| 1 | #[cfg(not(feature = "std"))] |
| 2 | use alloc::{ |
| 3 | borrow::ToOwned, |
| 4 | collections::BTreeMap, |
| 5 | format, |
| 6 | string::{String, ToString}, |
| 7 | vec::Vec, |
| 8 | }; |
| 9 | #[cfg(feature = "std")] |
| 10 | use std::{collections::BTreeMap, vec::Vec}; |
| 11 | |
| 12 | use crate::{ |
| 13 | encoding::{Error, PrintableInteger, ToBencode}, |
| 14 | state_tracker::{StateTracker, StructureError, Token}, |
| 15 | }; |
| 16 | |
| 17 | /// The actual encoder. Unlike the decoder, this is not zero-copy, as that would |
| 18 | /// result in a horrible interface |
| 19 | #[derive(Default, Debug)] |
| 20 | pub struct Encoder { |
| 21 | state: StateTracker<Vec<u8>, Error>, |
| 22 | output: Vec<u8>, |
| 23 | } |
| 24 | |
| 25 | impl Encoder { |
| 26 | /// Create a new encoder |
| 27 | pub fn new() -> Self { |
| 28 | <Self as Default>::default() |
| 29 | } |
| 30 | |
| 31 | /// Set the max depth of the encoded object |
| 32 | #[must_use] |
| 33 | pub fn with_max_depth(mut self, max_depth: usize) -> Self { |
| 34 | self.state.set_max_depth(max_depth); |
| 35 | self |
| 36 | } |
| 37 | |
| 38 | /// Emit a single token to the encoder |
| 39 | pub(crate) fn emit_token(&mut self, token: Token) -> Result<(), Error> { |
| 40 | self.state.check_error()?; |
| 41 | self.state.observe_token(&token)?; |
| 42 | match token { |
| 43 | Token::List => self.output.push(b'l'), |
| 44 | Token::Dict => self.output.push(b'd'), |
| 45 | Token::String(s) => { |
| 46 | // Writing to a vec can't fail |
| 47 | let length = s.len().to_string(); |
| 48 | self.output.extend_from_slice(length.as_bytes()); |
| 49 | self.output.push(b':'); |
| 50 | self.output.extend_from_slice(s); |
| 51 | }, |
| 52 | Token::Num(num) => { |
| 53 | // Alas, this doesn't verify that the given number is valid |
| 54 | self.output.push(b'i'); |
| 55 | self.output.extend_from_slice(num.as_bytes()); |
| 56 | self.output.push(b'e'); |
| 57 | }, |
| 58 | Token::End => self.output.push(b'e'), |
| 59 | } |
| 60 | |
| 61 | Ok(()) |
| 62 | } |
| 63 | |
| 64 | /// Emit an arbitrary encodable object |
| 65 | pub fn emit<E: ToBencode>(&mut self, value: E) -> Result<(), Error> { |
| 66 | self.emit_with(|e| value.encode(e)) |
| 67 | } |
| 68 | |
| 69 | /// Emit a single object using an encoder |
| 70 | pub fn emit_with<F>(&mut self, value_cb: F) -> Result<(), Error> |
| 71 | where |
| 72 | F: FnOnce(SingleItemEncoder) -> Result<(), Error>, |
| 73 | { |
| 74 | let mut value_written = false; |
| 75 | let ret = value_cb(SingleItemEncoder { |
| 76 | encoder: self, |
| 77 | value_written: &mut value_written, |
| 78 | }); |
| 79 | |
| 80 | self.state.latch_err(ret)?; |
| 81 | |
| 82 | if !value_written { |
| 83 | return self |
| 84 | .state |
| 85 | .latch_err(Err(Error::from(StructureError::invalid_state( |
| 86 | "No value was emitted", |
| 87 | )))); |
| 88 | } |
| 89 | |
| 90 | Ok(()) |
| 91 | } |
| 92 | |
| 93 | /// Emit an integer |
| 94 | pub fn emit_int<T: PrintableInteger>(&mut self, value: T) -> Result<(), Error> { |
| 95 | // This doesn't use emit_token, as that would require that I write the integer to a |
| 96 | // temporary buffer and then copy it to the output; writing it directly saves at |
| 97 | // least one memory allocation |
| 98 | self.state.check_error()?; |
| 99 | // We observe an int here, as we need something that isn't a string (and therefore |
| 100 | // possibly valid as a key) but we also want to require as few state transitions as |
| 101 | // possible (for performance) |
| 102 | self.state.observe_token(&Token::Num(""))?; |
| 103 | self.output.push(b'i'); |
| 104 | self.output.extend_from_slice(value.to_string().as_bytes()); |
| 105 | self.output.push(b'e'); |
| 106 | Ok(()) |
| 107 | } |
| 108 | |
| 109 | /// Emit a string |
| 110 | pub fn emit_str(&mut self, value: &str) -> Result<(), Error> { |
| 111 | self.emit_token(Token::String(value.as_bytes())) |
| 112 | } |
| 113 | |
| 114 | /// Emit a byte array |
| 115 | pub fn emit_bytes(&mut self, value: &[u8]) -> Result<(), Error> { |
| 116 | self.emit_token(Token::String(value)) |
| 117 | } |
| 118 | |
| 119 | /// Emit a dictionary where you know that the keys are already |
| 120 | /// sorted. The callback must emit key/value pairs to the given |
| 121 | /// encoder in sorted order. If the key/value pairs may not be |
| 122 | /// sorted, [`emit_unsorted_dict`] should be used instead. |
| 123 | /// |
| 124 | /// [`emit_unsorted_dict`]: SingleItemEncoder::emit_unsorted_dict |
| 125 | /// |
| 126 | /// Example: |
| 127 | /// |
| 128 | /// ``` |
| 129 | /// # use bendy::encoding::{Encoder, Error}; |
| 130 | /// # |
| 131 | /// # fn main() -> Result<(), Error>{ |
| 132 | /// let mut encoder = Encoder::new(); |
| 133 | /// encoder.emit_dict(|mut e| { |
| 134 | /// e.emit_pair(b"a", "foo")?; |
| 135 | /// e.emit_pair(b"b", 2) |
| 136 | /// }) |
| 137 | /// # } |
| 138 | /// ``` |
| 139 | pub fn emit_dict<F>(&mut self, content_cb: F) -> Result<(), Error> |
| 140 | where |
| 141 | F: FnOnce(SortedDictEncoder) -> Result<(), Error>, |
| 142 | { |
| 143 | self.emit_token(Token::Dict)?; |
| 144 | content_cb(SortedDictEncoder { encoder: self })?; |
| 145 | self.emit_token(Token::End) |
| 146 | } |
| 147 | |
| 148 | /// Emit an arbitrary list. The callback should emit the contents |
| 149 | /// of the list to the given encoder. |
| 150 | /// |
| 151 | /// E.g., to emit the list `[1,2,3]`, you would write |
| 152 | /// |
| 153 | /// ``` |
| 154 | /// # use bendy::encoding::{Encoder, Error}; |
| 155 | /// # fn main() -> Result<(), Error> { |
| 156 | /// let mut encoder = Encoder::new(); |
| 157 | /// encoder.emit_list(|e| { |
| 158 | /// e.emit_int(1)?; |
| 159 | /// e.emit_int(2)?; |
| 160 | /// e.emit_int(3) |
| 161 | /// }) |
| 162 | /// # } |
| 163 | /// ``` |
| 164 | pub fn emit_list<F>(&mut self, list_cb: F) -> Result<(), Error> |
| 165 | where |
| 166 | F: FnOnce(&mut Encoder) -> Result<(), Error>, |
| 167 | { |
| 168 | self.emit_token(Token::List)?; |
| 169 | list_cb(self)?; |
| 170 | self.emit_token(Token::End) |
| 171 | } |
| 172 | |
| 173 | /// Emit a dictionary that may have keys out of order. This will write the dict |
| 174 | /// values to temporary memory, then sort them before adding them to the serialized |
| 175 | /// stream |
| 176 | /// |
| 177 | /// Example. |
| 178 | /// |
| 179 | /// ``` |
| 180 | /// # use bendy::encoding::{Encoder, Error}; |
| 181 | /// # |
| 182 | /// # fn main() -> Result<(), Error> { |
| 183 | /// let mut encoder = Encoder::new(); |
| 184 | /// encoder.emit_and_sort_dict(|e| { |
| 185 | /// // Unlike in the example for Encoder::emit_dict(), these keys aren't sorted |
| 186 | /// e.emit_pair(b"b", 2)?; |
| 187 | /// e.emit_pair(b"a", "foo") |
| 188 | /// }) |
| 189 | /// # } |
| 190 | /// ``` |
| 191 | pub fn emit_and_sort_dict<F>(&mut self, content_cb: F) -> Result<(), Error> |
| 192 | where |
| 193 | F: FnOnce(&mut UnsortedDictEncoder) -> Result<(), Error>, |
| 194 | { |
| 195 | let mut encoder = self.begin_unsorted_dict()?; |
| 196 | |
| 197 | content_cb(&mut encoder)?; |
| 198 | |
| 199 | self.end_unsorted_dict(encoder) |
| 200 | } |
| 201 | |
| 202 | /// Return the encoded string, if all objects written are complete |
| 203 | pub fn get_output(mut self) -> Result<Vec<u8>, Error> { |
| 204 | self.state.observe_eof()?; |
| 205 | Ok(self.output) |
| 206 | } |
| 207 | |
| 208 | pub(crate) fn begin_unsorted_dict(&mut self) -> Result<UnsortedDictEncoder, Error> { |
| 209 | // emit the dict token so that a pre-existing state error is reported early |
| 210 | self.emit_token(Token::Dict)?; |
| 211 | |
| 212 | Ok(UnsortedDictEncoder::new(self.state.remaining_depth())) |
| 213 | } |
| 214 | |
| 215 | pub(crate) fn end_unsorted_dict(&mut self, encoder: UnsortedDictEncoder) -> Result<(), Error> { |
| 216 | let content = encoder.done()?; |
| 217 | |
| 218 | for (k, v) in content { |
| 219 | self.emit_bytes(&k)?; |
| 220 | // We know that the output is a single object by construction |
| 221 | self.state.observe_token(&Token::Num(""))?; |
| 222 | self.output.extend_from_slice(&v); |
| 223 | } |
| 224 | |
| 225 | self.emit_token(Token::End)?; |
| 226 | |
| 227 | Ok(()) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /// An encoder that can only encode a single item. See [`Encoder`] |
| 232 | /// for usage examples; the only difference between these classes is |
| 233 | /// that `SingleItemEncoder` can only be used once. |
| 234 | pub struct SingleItemEncoder<'a> { |
| 235 | encoder: &'a mut Encoder, |
| 236 | /// Whether we attempted to write a value to the encoder. The value |
| 237 | /// of the referent of this field is meaningless if the encode method |
| 238 | /// failed. |
| 239 | value_written: &'a mut bool, |
| 240 | } |
| 241 | |
| 242 | impl<'a> SingleItemEncoder<'a> { |
| 243 | /// Emit an arbitrary encodable object |
| 244 | pub fn emit<E: ToBencode + ?Sized>(self, value: &E) -> Result<(), Error> { |
| 245 | value.encode(self) |
| 246 | } |
| 247 | |
| 248 | /// Emit a single object using an encoder |
| 249 | pub fn emit_with<F>(self, value_cb: F) -> Result<(), Error> |
| 250 | where |
| 251 | F: FnOnce(SingleItemEncoder) -> Result<(), Error>, |
| 252 | { |
| 253 | value_cb(self) |
| 254 | } |
| 255 | |
| 256 | /// Emit an integer |
| 257 | pub fn emit_int<T: PrintableInteger>(self, value: T) -> Result<(), Error> { |
| 258 | *self.value_written = true; |
| 259 | self.encoder.emit_int(value) |
| 260 | } |
| 261 | |
| 262 | /// Emit a string |
| 263 | pub fn emit_str(self, value: &str) -> Result<(), Error> { |
| 264 | *self.value_written = true; |
| 265 | self.encoder.emit_str(value) |
| 266 | } |
| 267 | |
| 268 | /// Emit a byte array |
| 269 | pub fn emit_bytes(self, value: &[u8]) -> Result<(), Error> { |
| 270 | *self.value_written = true; |
| 271 | self.encoder.emit_bytes(value) |
| 272 | } |
| 273 | |
| 274 | /// Emit an arbitrary list |
| 275 | pub fn emit_list<F>(self, list_cb: F) -> Result<(), Error> |
| 276 | where |
| 277 | F: FnOnce(&mut Encoder) -> Result<(), Error>, |
| 278 | { |
| 279 | *self.value_written = true; |
| 280 | self.encoder.emit_list(list_cb) |
| 281 | } |
| 282 | |
| 283 | /// Emit a sorted dictionary. If the input dictionary is unsorted, this will return an error. |
| 284 | pub fn emit_dict<F>(self, content_cb: F) -> Result<(), Error> |
| 285 | where |
| 286 | F: FnOnce(SortedDictEncoder) -> Result<(), Error>, |
| 287 | { |
| 288 | *self.value_written = true; |
| 289 | self.encoder.emit_dict(content_cb) |
| 290 | } |
| 291 | |
| 292 | /// Emit a dictionary that may have keys out of order. This will write the dict |
| 293 | /// values to temporary memory, then sort them before adding them to the serialized |
| 294 | /// stream |
| 295 | pub fn emit_unsorted_dict<F>(self, content_cb: F) -> Result<(), Error> |
| 296 | where |
| 297 | F: FnOnce(&mut UnsortedDictEncoder) -> Result<(), Error>, |
| 298 | { |
| 299 | *self.value_written = true; |
| 300 | self.encoder.emit_and_sort_dict(content_cb) |
| 301 | } |
| 302 | |
| 303 | /// Emit an arbitrary list. |
| 304 | /// |
| 305 | /// Attention: If this method is used while canonical output is required |
| 306 | /// the caller needs to ensure that the iterator has a defined order. |
| 307 | pub fn emit_unchecked_list( |
| 308 | self, |
| 309 | iterable: impl Iterator<Item = impl ToBencode>, |
| 310 | ) -> Result<(), Error> { |
| 311 | self.emit_list(|e| { |
| 312 | for item in iterable { |
| 313 | e.emit(item)?; |
| 314 | } |
| 315 | Ok(()) |
| 316 | }) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | /// Encodes a map with pre-sorted keys |
| 321 | pub struct SortedDictEncoder<'a> { |
| 322 | encoder: &'a mut Encoder, |
| 323 | } |
| 324 | |
| 325 | impl<'a> SortedDictEncoder<'a> { |
| 326 | /// Emit a key/value pair |
| 327 | pub fn emit_pair<E>(&mut self, key: &[u8], value: E) -> Result<(), Error> |
| 328 | where |
| 329 | E: ToBencode, |
| 330 | { |
| 331 | self.encoder.emit_token(Token::String(key))?; |
| 332 | self.encoder.emit(value) |
| 333 | } |
| 334 | |
| 335 | /// Equivalent to [`SortedDictEncoder::emit_pair()`], but forces the type of the value |
| 336 | /// to be a callback |
| 337 | pub fn emit_pair_with<F>(&mut self, key: &[u8], value_cb: F) -> Result<(), Error> |
| 338 | where |
| 339 | F: FnOnce(SingleItemEncoder) -> Result<(), Error>, |
| 340 | { |
| 341 | self.encoder.emit_token(Token::String(key))?; |
| 342 | self.encoder.emit_with(value_cb) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /// Helper to write a dictionary that may have keys out of order. This will buffer the |
| 347 | /// dict values in temporary memory, then sort them before adding them to the serialized |
| 348 | /// stream |
| 349 | pub struct UnsortedDictEncoder { |
| 350 | content: BTreeMap<Vec<u8>, Vec<u8>>, |
| 351 | error: Result<(), Error>, |
| 352 | remaining_depth: usize, |
| 353 | } |
| 354 | |
| 355 | impl UnsortedDictEncoder { |
| 356 | pub(crate) fn new(remaining_depth: usize) -> Self { |
| 357 | Self { |
| 358 | content: BTreeMap::new(), |
| 359 | error: Ok(()), |
| 360 | remaining_depth, |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | /// Emit a key/value pair |
| 365 | pub fn emit_pair<E>(&mut self, key: &[u8], value: E) -> Result<(), Error> |
| 366 | where |
| 367 | E: ToBencode, |
| 368 | { |
| 369 | self.emit_pair_with(key, |e| value.encode(e)) |
| 370 | } |
| 371 | |
| 372 | /// Emit a key/value pair where the value is produced by a callback |
| 373 | pub fn emit_pair_with<F>(&mut self, key: &[u8], value_cb: F) -> Result<(), Error> |
| 374 | where |
| 375 | F: FnOnce(SingleItemEncoder) -> Result<(), Error>, |
| 376 | { |
| 377 | let mut value_written = false; |
| 378 | |
| 379 | let mut encoder = Encoder::new().with_max_depth(self.remaining_depth); |
| 380 | |
| 381 | let ret = value_cb(SingleItemEncoder { |
| 382 | encoder: &mut encoder, |
| 383 | value_written: &mut value_written, |
| 384 | }); |
| 385 | |
| 386 | if ret.is_err() { |
| 387 | self.error = ret.clone(); |
| 388 | return ret; |
| 389 | } |
| 390 | |
| 391 | if !value_written { |
| 392 | self.error = Err(Error::from(StructureError::InvalidState { |
| 393 | state: "No value was emitted".to_owned(), |
| 394 | })); |
| 395 | } else { |
| 396 | self.error = encoder.state.observe_eof(); |
| 397 | } |
| 398 | |
| 399 | if self.error.is_err() { |
| 400 | return self.error.clone(); |
| 401 | } |
| 402 | |
| 403 | let encoded_object = encoder |
| 404 | .get_output() |
| 405 | .expect("Any errors should have been caught by observe_eof"); |
| 406 | |
| 407 | self.save_pair(key, encoded_object) |
| 408 | } |
| 409 | |
| 410 | #[cfg(feature = "serde")] |
| 411 | pub(crate) fn remaining_depth(&self) -> usize { |
| 412 | self.remaining_depth |
| 413 | } |
| 414 | |
| 415 | pub(crate) fn save_pair( |
| 416 | &mut self, |
| 417 | unencoded_key: &[u8], |
| 418 | encoded_value: Vec<u8>, |
| 419 | ) -> Result<(), Error> { |
| 420 | #[cfg(not(feature = "std"))] |
| 421 | use alloc::collections::btree_map::Entry; |
| 422 | #[cfg(feature = "std")] |
| 423 | use std::collections::btree_map::Entry; |
| 424 | |
| 425 | if self.error.is_err() { |
| 426 | return self.error.clone(); |
| 427 | } |
| 428 | |
| 429 | let vacancy = match self.content.entry(unencoded_key.to_owned()) { |
| 430 | Entry::Vacant(vacancy) => vacancy, |
| 431 | Entry::Occupied(occupation) => { |
| 432 | self.error = Err(Error::from(StructureError::InvalidState { |
| 433 | state: format!( |
| 434 | "Duplicate key {}", |
| 435 | String::from_utf8_lossy(occupation.key()) |
| 436 | ), |
| 437 | })); |
| 438 | return self.error.clone(); |
| 439 | }, |
| 440 | }; |
| 441 | |
| 442 | vacancy.insert(encoded_value); |
| 443 | |
| 444 | Ok(()) |
| 445 | } |
| 446 | |
| 447 | pub(crate) fn done(self) -> Result<BTreeMap<Vec<u8>, Vec<u8>>, Error> { |
| 448 | self.error?; |
| 449 | Ok(self.content) |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | #[cfg(test)] |
| 454 | mod test { |
| 455 | use super::*; |
| 456 | |
| 457 | #[test] |
| 458 | pub fn simple_encoding_works() { |
| 459 | let mut encoder = Encoder::new(); |
| 460 | encoder |
| 461 | .emit_dict(|mut e| { |
| 462 | e.emit_pair(b"bar", 25)?; |
| 463 | e.emit_pair_with(b"foo", |e| { |
| 464 | e.emit_list(|e| { |
| 465 | e.emit_str("baz")?; |
| 466 | e.emit_str("qux") |
| 467 | }) |
| 468 | }) |
| 469 | }) |
| 470 | .expect("Encoding shouldn't fail"); |
| 471 | assert_eq!( |
| 472 | &encoder |
| 473 | .get_output() |
| 474 | .expect("Complete object should have been written"), |
| 475 | &b"d3:bari25e3:fool3:baz3:quxee" |
| 476 | ); |
| 477 | } |
| 478 | |
| 479 | #[test] |
| 480 | fn emit_cb_must_emit() { |
| 481 | let mut encoder = Encoder::new(); |
| 482 | assert!(encoder.emit_with(|_| Ok(())).is_err()); |
| 483 | } |
| 484 | } |