1use crate::{KuteError, Result, Version, VocabularyId};
2use serde::{Deserialize, Serialize};
3use std::io::{Read, Write};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
7#[serde(rename_all = "snake_case")]
8pub enum Modality {
9 Text,
10 Binary,
11 Structured,
12 Events,
13 Other,
14}
15
16#[derive(Clone, Debug, PartialEq, Eq)]
22pub enum Payload {
23 Bytes(Vec<u8>),
24 Symbols(Vec<String>),
25}
26
27impl Payload {
28 pub fn kind(&self) -> PayloadKind {
29 match self {
30 Payload::Bytes(_) => PayloadKind::Bytes,
31 Payload::Symbols(_) => PayloadKind::Symbols,
32 }
33 }
34
35 pub fn len(&self) -> usize {
37 match self {
38 Payload::Bytes(b) => b.len(),
39 Payload::Symbols(s) => s.len(),
40 }
41 }
42
43 pub fn is_empty(&self) -> bool {
44 self.len() == 0
45 }
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum PayloadKind {
51 Bytes,
52 Symbols,
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct CanonicalInput {
58 pub modality: Modality,
59 pub payload: Payload,
60}
61
62impl CanonicalInput {
63 pub fn bytes(modality: Modality, bytes: impl Into<Vec<u8>>) -> Self {
64 Self { modality, payload: Payload::Bytes(bytes.into()) }
65 }
66
67 pub fn text(text: &str) -> Self {
68 Self::bytes(Modality::Text, text.as_bytes())
69 }
70
71 pub fn symbols<I, S>(symbols: I) -> Self
72 where
73 I: IntoIterator<Item = S>,
74 S: Into<String>,
75 {
76 Self {
77 modality: Modality::Events,
78 payload: Payload::Symbols(symbols.into_iter().map(Into::into).collect()),
79 }
80 }
81}
82
83#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
88pub struct TokenSequence {
89 pub vocabulary_id: VocabularyId,
90 pub vocabulary_version: Version,
91 pub vocabulary_digest: String,
92 pub modality: Modality,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub adapter: Option<String>,
95 pub ids: Vec<u32>,
96}
97
98#[derive(Serialize, Deserialize)]
99struct ContainerHeader {
100 vocabulary_id: VocabularyId,
101 vocabulary_version: Version,
102 vocabulary_digest: String,
103 modality: Modality,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
105 adapter: Option<String>,
106 count: u64,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
109 id_bytes: Option<u8>,
110}
111
112const MAGIC: &[u8; 5] = b"KUTE\x01";
113const MAGIC_COMPRESSED: &[u8; 5] = b"KUTE\x02";
115const MAX_HEADER: usize = 64 * 1024;
116const MAX_INFLATE_RATIO: u64 = 1040;
119
120impl TokenSequence {
121 pub fn to_bytes(&self) -> Result<Vec<u8>> {
124 let mut out = self.start_container(MAGIC, None, self.ids.len() * 2)?;
125 for &id in &self.ids {
126 let mut v = id;
127 loop {
128 let byte = (v & 0x7f) as u8;
129 v >>= 7;
130 if v == 0 {
131 out.push(byte);
132 break;
133 }
134 out.push(byte | 0x80);
135 }
136 }
137 Ok(out)
138 }
139
140 fn start_container(&self, magic: &[u8; 5], id_bytes: Option<u8>, body_hint: usize) -> Result<Vec<u8>> {
141 let header = serde_json::to_vec(&ContainerHeader {
142 vocabulary_id: self.vocabulary_id.clone(),
143 vocabulary_version: self.vocabulary_version.clone(),
144 vocabulary_digest: self.vocabulary_digest.clone(),
145 modality: self.modality,
146 adapter: self.adapter.clone(),
147 count: self.ids.len() as u64,
148 id_bytes,
149 })?;
150 if header.len() > MAX_HEADER {
151 return Err(KuteError::LimitExceeded("token sequence header exceeds 64 KiB".into()));
152 }
153 let mut out = Vec::with_capacity(magic.len() + 4 + header.len() + body_hint);
154 out.extend_from_slice(magic);
155 out.extend_from_slice(&(header.len() as u32).to_le_bytes());
156 out.extend_from_slice(&header);
157 Ok(out)
158 }
159
160 pub fn to_bytes_compressed(&self) -> Result<Vec<u8>> {
165 let max = self.ids.iter().copied().max().unwrap_or(0);
166 let width: usize = match max {
167 0..=0xff => 1,
168 0x100..=0xffff => 2,
169 0x1_0000..=0xff_ffff => 3,
170 _ => 4,
171 };
172 let mut plain = Vec::with_capacity(self.ids.len() * width);
173 for &id in &self.ids {
174 plain.extend_from_slice(&id.to_le_bytes()[..width]);
175 }
176 let out = self.start_container(MAGIC_COMPRESSED, Some(width as u8), plain.len() / 2)?;
177 let mut encoder = flate2::write::ZlibEncoder::new(out, flate2::Compression::best());
178 encoder.write_all(&plain)?;
179 Ok(encoder.finish()?)
180 }
181
182 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
185 let bad = |why: &str| KuteError::InvalidInput(format!("not a valid .kute token sequence: {why}"));
186 if bytes.len() < MAGIC.len() + 4 {
187 return Err(bad("missing KUTE magic"));
188 }
189 let compressed = match &bytes[..MAGIC.len()] {
190 m if m == MAGIC => false,
191 m if m == MAGIC_COMPRESSED => true,
192 _ => return Err(bad("missing KUTE magic")),
193 };
194 let mut pos = MAGIC.len();
195 let header_len = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) as usize;
196 pos += 4;
197 if header_len > MAX_HEADER {
198 return Err(bad("header longer than 64 KiB"));
199 }
200 let header_end = pos.checked_add(header_len).filter(|&e| e <= bytes.len()).ok_or_else(|| bad("truncated header"))?;
201 let header: ContainerHeader = serde_json::from_slice(&bytes[pos..header_end]).map_err(|e| bad(&format!("header: {e}")))?;
202 pos = header_end;
203 let remaining = bytes.len() - pos;
204 let ids = if compressed {
205 let width = match header.id_bytes {
206 Some(w @ 1..=4) => w as usize,
207 _ => return Err(bad("compressed container needs id_bytes between 1 and 4")),
208 };
209 let expected = header.count.checked_mul(width as u64).ok_or_else(|| bad("token count overflows"))?;
210 if expected > (remaining as u64).saturating_mul(MAX_INFLATE_RATIO) {
211 return Err(bad("declared token count exceeds what the data can hold"));
212 }
213 let mut decoder = flate2::read::ZlibDecoder::new(&bytes[pos..]);
214 let mut plain = Vec::with_capacity(expected as usize);
215 (&mut decoder).take(expected + 1).read_to_end(&mut plain).map_err(|e| bad(&format!("compressed ids: {e}")))?;
218 if plain.len() as u64 != expected {
219 return Err(bad("token count does not match the header"));
220 }
221 if decoder.total_in() != remaining as u64 {
222 return Err(bad("data after the compressed ids"));
223 }
224 plain
225 .chunks_exact(width)
226 .map(|c| {
227 let mut le = [0u8; 4];
228 le[..width].copy_from_slice(c);
229 u32::from_le_bytes(le)
230 })
231 .collect()
232 } else {
233 if header.id_bytes.is_some() {
234 return Err(bad("id_bytes belongs to the compressed format only"));
235 }
236 Self::read_varints(&bytes[pos..], header.count).map_err(bad)?
237 };
238 Ok(Self {
239 vocabulary_id: header.vocabulary_id,
240 vocabulary_version: header.vocabulary_version,
241 vocabulary_digest: header.vocabulary_digest,
242 modality: header.modality,
243 adapter: header.adapter,
244 ids,
245 })
246 }
247
248 fn read_varints(bytes: &[u8], count: u64) -> std::result::Result<Vec<u32>, &'static str> {
249 let bad = |why: &'static str| why;
250 let mut pos = 0;
251 if count > bytes.len() as u64 {
252 return Err(bad("declared token count exceeds the data present"));
253 }
254 let mut ids = Vec::with_capacity(count as usize);
255 while pos < bytes.len() {
256 let mut value: u32 = 0;
257 let mut shift = 0u32;
258 loop {
259 let byte = *bytes.get(pos).ok_or_else(|| bad("truncated token id"))?;
260 pos += 1;
261 let low = (byte & 0x7f) as u32;
262 if shift == 28 && low > 0x0f {
263 return Err(bad("token id overflows 32 bits"));
264 }
265 value |= low << shift;
266 if byte & 0x80 == 0 {
267 break;
268 }
269 shift += 7;
270 if shift > 28 {
271 return Err(bad("token id overflows 32 bits"));
272 }
273 }
274 ids.push(value);
275 }
276 if ids.len() as u64 != count {
277 return Err(bad("token count does not match the header"));
278 }
279 Ok(ids)
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 fn seq(ids: Vec<u32>) -> TokenSequence {
288 TokenSequence {
289 vocabulary_id: VocabularyId::parse("kute:test").unwrap(),
290 vocabulary_version: Version::new(1, 0, 0),
291 vocabulary_digest: "sha256:00".into(),
292 modality: Modality::Text,
293 adapter: Some("text".into()),
294 ids,
295 }
296 }
297
298 #[test]
299 fn container_round_trip() {
300 let s = seq(vec![0, 1, 127, 128, 255, 16_384, 1_048_576, u32::MAX]);
301 let bytes = s.to_bytes().unwrap();
302 assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
303 let empty = seq(vec![]);
304 assert_eq!(TokenSequence::from_bytes(&empty.to_bytes().unwrap()).unwrap(), empty);
305 }
306
307 #[test]
308 fn compressed_container_round_trip() {
309 for ids in [vec![], vec![7], vec![0, 255], vec![0, 256, 65_535], vec![65_536, 3], vec![1, u32::MAX], (0..5000).map(|i| i % 97).collect()] {
310 let s = seq(ids);
311 let bytes = s.to_bytes_compressed().unwrap();
312 assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
313 }
314 let repetitive = seq((0..20_000).map(|i| 300 + i % 50).collect());
315 assert!(repetitive.to_bytes_compressed().unwrap().len() * 10 < repetitive.to_bytes().unwrap().len());
316 }
317
318 #[test]
319 fn compressed_container_rejects_damage() {
320 let s = seq((0..400).map(|i| 1000 + i % 13).collect());
321 let bytes = s.to_bytes_compressed().unwrap();
322 for cut in 0..bytes.len() {
323 assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
324 }
325 let mut extra = bytes.clone();
326 extra.push(0);
327 assert!(TokenSequence::from_bytes(&extra).is_err());
328 let text = String::from_utf8_lossy(&bytes).to_string();
331 assert!(text.contains("\"count\":400"));
332 for claim in ["401", "399", "999999999999"] {
333 let mut forged = Vec::new();
334 let header_len = u32::from_le_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]) as usize;
335 let header = String::from_utf8(bytes[9..9 + header_len].to_vec()).unwrap().replace("\"count\":400", &format!("\"count\":{claim}"));
336 forged.extend_from_slice(&bytes[..5]);
337 forged.extend_from_slice(&(header.len() as u32).to_le_bytes());
338 forged.extend_from_slice(header.as_bytes());
339 forged.extend_from_slice(&bytes[9 + header_len..]);
340 assert!(TokenSequence::from_bytes(&forged).is_err(), "count {claim}");
341 }
342 let mut flipped = bytes.clone();
343 let last = flipped.len() - 6;
344 flipped[last] ^= 0x40;
345 assert!(TokenSequence::from_bytes(&flipped).is_err());
346 }
347
348 #[test]
349 fn container_rejects_damage() {
350 let bytes = seq(vec![1, 2, 300, 70_000]).to_bytes().unwrap();
351 for cut in 0..bytes.len() {
352 assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
353 }
354 let mut extra = bytes.clone();
355 extra.push(0x05);
356 assert!(TokenSequence::from_bytes(&extra).is_err());
357 let mut overflow = seq(vec![]).to_bytes().unwrap();
358 overflow.extend_from_slice(&[0xff, 0xff, 0xff, 0xff, 0x7f]);
359 assert!(TokenSequence::from_bytes(&overflow).is_err());
360 assert!(TokenSequence::from_bytes(b"not a kute file").is_err());
361 }
362}