Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Difference From blather-0.10.1 To blather-0.11.0
2024-09-22
| ||
14:26 | Release maintenance. Leaf check-in: f9ffae0254 user: jan tags: blather-0.11.0, trunk | |
12:02 | Docs. check-in: 69ffa6c624 user: jan tags: trunk | |
09:18 | Remove PartialEq from Error. Change Error::IO to carry std::io::Error. Lots of pedantic clippy fixes. check-in: 28c3fe56c4 user: jan tags: trunk | |
2024-08-06
| ||
13:06 | Relase maintenance. check-in: fcdac3ca7e user: jan tags: blather-0.10.1, trunk | |
13:02 | Happy clippy. check-in: 1a365cef19 user: jan tags: trunk | |
Changes to Cargo.toml.
1 2 | [package] name = "blather" | | > > > > > > > | | | | | > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | [package] name = "blather" version = "0.11.0" edition = "2021" license = "0BSD" # https://crates.io/category_slugs categories = [ "network-programming" ] keywords = [ "line-based", "protocol", "tokio", "codec" ] repository = "https://repos.qrnch.tech/pub/blather" description = "A talkative line-based protocol" exclude = [ ".fossil-settings", ".efiles", ".fslckout", "bacon.toml", "rustfmt.toml", "www" ] # https://doc.rust-lang.org/cargo/reference/manifest.html#the-badges-section [badges] maintenance = { status = "actively-developed" } [dependencies] bytes = { version = "1.7.2" } futures = { version = "0.3.30" } tokio = { version = "1.40.0" } tokio-stream = { version = "0.1.16" } tokio-util = { version= "0.7.12", features = ["codec"] } [dev-dependencies] tokio = { version = "1.40.0", features = ["macros", "net"] } tokio-test = { version = "0.4.4" } [package.metadata.docs.rs] rustdoc-args = ["--generate-link-to-definition"] [lints.clippy] all = { level = "deny", priority = -1 } pedantic = { level = "warn", priority = -1 } nursery = { level = "warn", priority = -1 } cargo = { level = "warn", priority = -1 } # vim: set ft=toml et sw=2 ts=2 sts=2 cinoptions=2 tw=79 : |
Added bacon.toml.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | # This is a configuration file for the bacon tool # # Bacon repository: https://github.com/Canop/bacon # Complete help on configuration: https://dystroy.org/bacon/config/ # You can also check bacon's own bacon.toml file # as an example: https://github.com/Canop/bacon/blob/main/bacon.toml default_job = "clippy-all" [jobs.check] command = ["cargo", "check", "--color", "always"] need_stdout = false [jobs.check-all] command = ["cargo", "check", "--all-targets", "--color", "always"] need_stdout = false # Run clippy on the default target [jobs.clippy] command = [ "cargo", "clippy", "--color", "always", ] need_stdout = false # Run clippy on all targets # To disable some lints, you may change the job this way: # [jobs.clippy-all] # command = [ # "cargo", "clippy", # "--all-targets", # "--color", "always", # "--", # "-A", "clippy::bool_to_int_with_if", # "-A", "clippy::collapsible_if", # "-A", "clippy::derive_partial_eq_without_eq", # ] # need_stdout = false [jobs.clippy-all] command = [ "cargo", "clippy", "--all-targets", "--color", "always", ] need_stdout = false # This job lets you run # - all tests: bacon test # - a specific test: bacon test -- config::test_default_files # - the tests of a package: bacon test -- -- -p config [jobs.test] command = [ "cargo", "test", "--color", "always", "--", "--color", "always", # see https://github.com/Canop/bacon/issues/124 ] need_stdout = true [jobs.doc] command = ["cargo", "doc", "--color", "always", "--no-deps"] need_stdout = false # If the doc compiles, then it opens in your browser and bacon switches # to the previous job [jobs.doc-open] command = ["cargo", "doc", "--color", "always", "--no-deps", "--open"] need_stdout = false on_success = "back" # so that we don't open the browser at each change # You can run your application and have the result displayed in bacon, # *if* it makes sense for this crate. # Don't forget the `--color always` part or the errors won't be # properly parsed. # If your program never stops (eg a server), you may set `background` # to false to have the cargo run output immediately displayed instead # of waiting for program's end. [jobs.run] command = [ "cargo", "run", "--color", "always", # put launch parameters for your program behind a `--` separator ] need_stdout = true allow_warnings = true background = true # This parameterized job runs the example of your choice, as soon # as the code compiles. # Call it as # bacon ex -- my-example [jobs.ex] command = ["cargo", "run", "--color", "always", "--example"] need_stdout = true allow_warnings = true # You may define here keybindings that would be specific to # a project, for example a shortcut to launch a specific job. # Shortcuts to internal functions (scrolling, toggling, etc.) # should go in your personal global prefs.toml file instead. [keybindings] # alt-m = "job:my-job" c = "job:clippy-all" # comment this to have 'c' run clippy on only the default target |
Changes to src/codec.rs.
︙ | ︙ | |||
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | tg: Telegram, params: Params, kvlines: KVLines, state: CodecState, remain: u64 } impl fmt::Debug for Codec { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Codec").field("state", &self.state).finish() } } impl Default for Codec { fn default() -> Self { | > | | 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | tg: Telegram, params: Params, kvlines: KVLines, state: CodecState, remain: u64 } #[allow(clippy::missing_fields_in_debug)] impl fmt::Debug for Codec { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Codec").field("state", &self.state).finish() } } impl Default for Codec { fn default() -> Self { Self::new() } } /// A Codec used to encode and decode the blather protocol. /// /// # Notes |
︙ | ︙ | |||
118 119 120 121 122 123 124 | /// conn.codec_mut().expect_bytes(len); /// } /// ``` impl Codec { /// Create a new `Codec`. It will default to having not practical limit to /// the maximum line length and it will expect a [`Telegram`] buffer to /// arrive as the first frame. | > | | | > | | > | | | | 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | /// conn.codec_mut().expect_bytes(len); /// } /// ``` impl Codec { /// Create a new `Codec`. It will default to having not practical limit to /// the maximum line length and it will expect a [`Telegram`] buffer to /// arrive as the first frame. #[must_use] pub fn new() -> Self { Self { next_line_index: 0, max_line_length: usize::MAX, tg: Telegram::new_uninit(), params: Params::new(), kvlines: KVLines::new(), state: CodecState::Telegram, remain: 0 } } /// Create a new `Codec` with a specific maximum line length. The default /// state will be to expect a [`Telegram`]. #[must_use] pub fn new_with_max_length(max_line_length: usize) -> Self { Self { max_line_length, ..Self::new() } } /// Get the current maximum line length. #[must_use] pub const fn max_line_length(&self) -> usize { self.max_line_length } /// Determine how far into the buffer we'll search for a newline. If /// there's no `max_length` set, we'll read to the end of the buffer. fn find_newline(&self, buf: &BytesMut) -> (usize, Option<usize>) { let read_to = cmp::min(self.max_line_length.saturating_add(1), buf.len()); let newline_offset = buf[self.next_line_index..read_to] .iter() .position(|b| *b == b'\n'); (read_to, newline_offset) } /// This is called when `decode_telegram_lines` has encountered an eol, /// determined that the string is longer than zero characters, and thus /// passed the line to this function to process it. /// /// The first line received is a telegram topic. This is a required line. /// Following lines are parameter lines, which are a single space character /// separated key/value pairs. fn decode_telegram_line(&mut self, line: &str) -> Result<(), Error> { if self.tg.get_topic().is_empty() { self .tg .set_topic(line) .map_err(|e| Error::Protocol(e.to_string()))?; } else { let idx = line.find(' '); if let Some(idx) = idx { |
︙ | ︙ | |||
262 263 264 265 266 267 268 | let line = utf8(without_carriage_return(line))?; // Empty line marks end of Telegram if line.is_empty() { // mem::take() can replace a member of a struct. // (This requires Default to be implemented for the object being // taken). | > > | < | > | 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | let line = utf8(without_carriage_return(line))?; // Empty line marks end of Telegram if line.is_empty() { // mem::take() can replace a member of a struct. // (This requires Default to be implemented for the object being // taken). let newtg = Telegram::new_uninit(); //return Ok(Some(mem::take(&mut self.tg))); return Ok(Some(mem::replace(&mut self.tg, newtg))); } self.decode_telegram_line(line)?; } else { // Returning Ok(None) instructs the FramedRead that more data is // needed. return Ok(None); } } } |
︙ | ︙ | |||
299 300 301 302 303 304 305 | // The application can override this when needed. self.state = CodecState::Telegram; // mem::take() can replace a member of a struct. // (This requires Default to be implemented for the object being // taken). return Ok(Some(mem::take(&mut self.params))); | < > | | | | | < | 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | // The application can override this when needed. self.state = CodecState::Telegram; // mem::take() can replace a member of a struct. // (This requires Default to be implemented for the object being // taken). return Ok(Some(mem::take(&mut self.params))); } let idx = line.find(' '); if let Some(idx) = idx { let (k, v) = line.split_at(idx); let v = &v[1..v.len()]; self.params.add_param(k, v)?; } } else { // Need more data return Ok(None); } } } |
︙ | ︙ | |||
339 340 341 342 343 344 345 | // The application can override this when needed. self.state = CodecState::Telegram; // mem::take() can replace a member of a struct. // (This requires Default to be implemented for the object being // taken). return Ok(Some(mem::take(&mut self.kvlines))); | < > | | | | | < | > > > | 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | // The application can override this when needed. self.state = CodecState::Telegram; // mem::take() can replace a member of a struct. // (This requires Default to be implemented for the object being // taken). return Ok(Some(mem::take(&mut self.kvlines))); } let idx = line.find(' '); if let Some(idx) = idx { let (k, v) = line.split_at(idx); let v = &v[1..v.len()]; self.kvlines.append(k, v); } } else { // Need more data return Ok(None); } } } /// Set the decoder to treat the next `size` bytes as raw bytes to be /// received in chunks as `Bytes`. /// /// # Decoder behavior /// The decoder will return an [`Input::Chunk(buf, remain)`](Input::Chunk) to /// the application each time a new chunk has been received. In addition to /// the actual chunk the number of bytes remaining will be returned. The /// remaining bytes value is adjusted to subtract the currently returned /// chunk, which means that the application can detect the end of the /// buffer by checking if the remaining value is zero. /// /// Once the entire buffer has been received by the `Decoder` it will revert /// to expect an [`Input::Telegram`]. /// /// # Errors /// [`Error::InvalidSize`] means the `size` parameter was set to `0`. pub fn expect_chunks(&mut self, size: u64) -> Result<(), Error> { if size == 0 { return Err(Error::InvalidSize("The size must not be zero".to_string())); } //println!("Expecting bin {}", size); self.state = CodecState::Chunks; |
︙ | ︙ | |||
392 393 394 395 396 397 398 399 400 401 402 403 404 405 | /// # Decoder behavior /// Once a complete buffer has been successfully reaceived the `Decoder` will /// return an [`Input::Bytes(b)`](Input::Bytes) where `b` is a /// [`bytes::Bytes`] containing the entire buffer. /// /// Once the entire buffer has been received by the `Decoder` it will revert /// to expect an [`Input::Telegram`]. pub fn expect_bytes(&mut self, size: usize) -> Result<(), Error> { if size == 0 { return Err(Error::InvalidSize("The size must not be zero".to_string())); } self.state = CodecState::Bytes; // unwrap() should be safe, unless running on a platform where | > > > > | 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | /// # Decoder behavior /// Once a complete buffer has been successfully reaceived the `Decoder` will /// return an [`Input::Bytes(b)`](Input::Bytes) where `b` is a /// [`bytes::Bytes`] containing the entire buffer. /// /// Once the entire buffer has been received by the `Decoder` it will revert /// to expect an [`Input::Telegram`]. /// /// # Errors /// [`Error::InvalidSize`] means the `size` parameter was set to `0`. #[allow(clippy::missing_panics_doc)] pub fn expect_bytes(&mut self, size: usize) -> Result<(), Error> { if size == 0 { return Err(Error::InvalidSize("The size must not be zero".to_string())); } self.state = CodecState::Bytes; // unwrap() should be safe, unless running on a platform where |
︙ | ︙ | |||
422 423 424 425 426 427 428 | pub fn expect_params(&mut self) { self.state = CodecState::Params; } /// Tell the Decoder to expect lines ordered key/value pairs. /// /// # Decoder behavior | | > > > | | 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | pub fn expect_params(&mut self) { self.state = CodecState::Params; } /// Tell the Decoder to expect lines ordered key/value pairs. /// /// # Decoder behavior /// On successful completion the Framed `StreamExt::next()` will return an /// [`Input::KVLines(kvlines)`](Input::KVLines) once a complete `KVLines` /// buffer has been received. /// /// Once the entire buffer has been received by the `Decoder` it will revert /// to expect an [`Input::Telegram`]. pub fn expect_kvlines(&mut self) { self.state = CodecState::KVLines; } /// Skip a requested number of bytes. /// /// # Decoder behavior /// On successful completion the decoder will have ignored the specified /// number of byes, reverts back to waiting for a [`Input::Telegram`] and /// returns [`Input::SkipDone`]. /// /// # Errors /// [`Error::InvalidSize`] means the `size` parameter was set to `0`. pub fn skip(&mut self, size: u64) -> Result<(), Error> { if size == 0 { return Err(Error::InvalidSize("The size must not be zero".to_string())); } self.state = CodecState::Skip; self.remain = size; Ok(()) } } fn utf8(buf: &[u8]) -> Result<&str, io::Error> { std::str::from_utf8(buf).map_err(|_| { io::Error::new( io::ErrorKind::InvalidData, "Unable to decode input as UTF8" ) }) } fn without_carriage_return(s: &[u8]) -> &[u8] { if s.last() == Some(&b'\r') { &s[..s.len() - 1] } else { s } } |
︙ | ︙ | |||
535 536 537 538 539 540 541 | self.state = CodecState::Telegram; } // Return a buffer and the amount of data remaining, this buffer // included. The application can check if remain is 0 to determine // if it has received all the expected binary data. // | | > | < < < | 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 | self.state = CodecState::Telegram; } // Return a buffer and the amount of data remaining, this buffer // included. The application can check if remain is 0 to determine // if it has received all the expected binary data. // // .unwrap() is safe here, because read_to is guaranteed to // be within the bounds of an usize due to the `cmp::min()` above. let len = usize::try_from(read_to).unwrap(); Ok(Some(Input::Chunk(buf.split_to(len).freeze(), self.remain))) } CodecState::Bytes => { // This is guaranteed to work, because expect_bytes() takes in an // usize. let remain: usize = self.remain.try_into().unwrap(); if buf.len() < remain { Ok(None) |
︙ | ︙ | |||
563 564 565 566 567 568 569 | if buf.is_empty() { return Ok(None); // Need more data } // Read as much data as available or requested and write it to our // output. let read_to = cmp::min(self.remain, buf.len() as u64); | > > > | | 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | if buf.is_empty() { return Ok(None); // Need more data } // Read as much data as available or requested and write it to our // output. let read_to = cmp::min(self.remain, buf.len() as u64); // unwrap() is okay here, due to the cmd::min() above let len = usize::try_from(read_to).unwrap(); let _ = buf.split_to(len); self.remain -= read_to; if self.remain != 0 { return Ok(None); // Need more data } // Revert to the default of expecting a telegram. |
︙ | ︙ | |||
602 603 604 605 606 607 608 | type Error = crate::err::Error; fn encode( &mut self, params: &Params, buf: &mut BytesMut ) -> Result<(), Error> { | | | | | | 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | type Error = crate::err::Error; fn encode( &mut self, params: &Params, buf: &mut BytesMut ) -> Result<(), Error> { params.encoder_write(buf); Ok(()) } } impl Encoder<&HashMap<String, String>> for Codec { type Error = crate::err::Error; fn encode( &mut self, data: &HashMap<String, String>, buf: &mut BytesMut ) -> Result<(), Error> { // Calculate the amount of space required let mut sz = 0; for (k, v) in data { // key space + whitespace + value space + eol sz += k.len() + 1 + v.len() + 1; } // Terminating empty line sz += 1; //println!("Writing {} bin data", data.len()); buf.reserve(sz); for (k, v) in data { buf.put(k.as_bytes()); buf.put_u8(b' '); buf.put(v.as_bytes()); buf.put_u8(b'\n'); } buf.put_u8(b'\n'); Ok(()) } } impl Encoder<&KVLines> for Codec { type Error = crate::err::Error; fn encode( &mut self, kvlines: &KVLines, buf: &mut BytesMut ) -> Result<(), Error> { kvlines.encoder_write(buf); Ok(()) } } impl Encoder<Bytes> for Codec { type Error = crate::err::Error; |
︙ | ︙ |
Changes to src/codec/utils.rs.
︙ | ︙ | |||
27 28 29 30 31 32 33 | /// Receive a [`Telegram`] from a `Frame`'d stream. /// /// The callback in `validate` can be used to inspect the received `Telegram` /// and choose whether to return/ignore it or return a fatal error. /// /// If the connection is closed this function will return `Ok(None)`. | > | | | | | 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | /// Receive a [`Telegram`] from a `Frame`'d stream. /// /// The callback in `validate` can be used to inspect the received `Telegram` /// and choose whether to return/ignore it or return a fatal error. /// /// If the connection is closed this function will return `Ok(None)`. #[allow(clippy::missing_errors_doc)] pub async fn expect_telegram<C, F>( frmio: &mut Framed<C, Codec>, validate: F ) -> Result<Option<Telegram>, Error> where C: AsyncRead + Unpin + Send, F: Fn(&Telegram) -> Outcome + Send { loop { let Some(frm) = frmio.next().await else { // Got None, which (probably) means the connection has ended. break Ok(None); }; let frm = match frm { |
︙ | ︙ |
Changes to src/err.rs.
1 2 3 4 5 6 7 | //! Error types and error management functions. use std::fmt; use tokio::io; /// Error that `blather` can emit. | | | | | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | //! Error types and error management functions. use std::fmt; use tokio::io; /// Error that `blather` can emit. #[derive(Debug)] pub enum Error { /// The input format of a buffer was incorrect. BadFormat(String), /// Something occurred which was unexpected in the current state. BadState(String), /// The specified size is invalid, or invalid in a specific context. InvalidSize(String), /// A `std::io` or `tokio::io` error has occurred. IO(std::io::Error), /// The requiested key was not found. KeyNotFound(String), /// Unable to serialize a buffer. SerializeError(String), /// A "protcol error" implies that the Framed decoder detected an error /// while parsing incoming data. Protocol(String) } impl std::error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::BadFormat(s) => write!(f, "Bad format; {s}"), Self::BadState(s) => { write!(f, "Encountred an unexpected/bad state: {s}") } Self::InvalidSize(s) => write!(f, "Invalid size; {s}"), Self::IO(e) => write!(f, "I/O error; {e}"), Self::KeyNotFound(s) => write!(f, "Parameter '{s}' not found"), Self::Protocol(s) => write!(f, "Protocol error; {s}"), Self::SerializeError(s) => write!(f, "Unable to serialize; {s}") } } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Self::IO(err) } } // vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 : |
Changes to src/lib.rs.
︙ | ︙ | |||
9 10 11 12 13 14 15 | //! The most central communication buffer is [`Telegram`], which //! consists of a _topic_ and zero or more key/value pairs, where each key must //! be unique. //! //! ``` //! use blather::Telegram; //! | | | | 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //! The most central communication buffer is [`Telegram`], which //! consists of a _topic_ and zero or more key/value pairs, where each key must //! be unique. //! //! ``` //! use blather::Telegram; //! //! let mut tg = Telegram::new("AddUser"); //! //! tg.add_param("Name", "Frank Foobar"); //! tg.add_param("Job", "Secret Agent"); //! tg.add_param("Age", "42"); //! //! assert_eq!(tg.get_topic(), "AddUser"); //! assert_eq!(tg.get_str("Name").unwrap(), "Frank Foobar"); //! assert_eq!(tg.get_param::<u8>("Age").unwrap(), 42); //! ``` //! //! ## Params //! These are simple key/value pairs, which can be seen as `HashMap`'s with //! some restrictions on key names. |
︙ | ︙ |
Changes to src/types/kvlines.rs.
1 2 3 4 5 6 | //! A key/value pair list with stable ordering and non-unique keys. use std::fmt; use bytes::{BufMut, BytesMut}; | < < > < | < > | > | > > | | | < < > | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | //! A key/value pair list with stable ordering and non-unique keys. use std::fmt; use bytes::{BufMut, BytesMut}; /// Representation of a key/value pair in `KVLines`. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct KeyValue { key: String, value: String } /// Ordered list of key/value pairs, with no uniqueness constraint for the /// keys. #[derive(Debug, Clone, Default)] pub struct KVLines { lines: Vec<KeyValue> } impl KVLines { /// Create a new empty parameters object. #[must_use] pub fn new() -> Self { Self::default() } /// Reset all the lines. pub fn clear(&mut self) { self.lines.clear(); } /// Get a reference to the inner vector of [`KeyValue`]'s. #[must_use] pub const fn get_inner(&self) -> &Vec<KeyValue> { &self.lines } /// Append a key/value entry to the end of the list. #[allow(clippy::needless_pass_by_value)] pub fn append(&mut self, key: impl ToString, value: impl ToString) { self.lines.push(KeyValue { key: key.to_string(), value: value.to_string() }); } /// Calculate the size of the buffer in serialized form. /// Each entry will be a newline terminated utf-8 line. /// Last line will be a single newline character. #[must_use] pub fn calc_buf_size(&self) -> usize { let mut size = 0; for n in &self.lines { size += n.key.len() + 1; // including ' ' size += n.value.len() + 1; // including '\n' } size + 1 // terminating '\n' } /// Serialize object into a `Vec<u8>` buffer suitable for transmission. #[must_use] pub fn serialize(&self) -> Vec<u8> { let mut buf = Vec::new(); for n in &self.lines { let k = n.key.as_bytes(); let v = n.value.as_bytes(); for a in k { buf.push(*a); } buf.push(b' '); for a in v { buf.push(*a); } buf.push(b'\n'); } buf.push(b'\n'); buf } /// Write the Params to a buffer. pub fn encoder_write(&self, buf: &mut BytesMut) { // Calculate the required buffer size let size = self.calc_buf_size(); // Reserve space buf.reserve(size); // Write data to output buffer for n in &self.lines { buf.put(n.key.as_bytes()); buf.put_u8(b' '); buf.put(n.value.as_bytes()); buf.put_u8(b'\n'); } buf.put_u8(b'\n'); } /// Consume the Params buffer and return the internal key/value list as a /// `Vec<KeyValue>` #[must_use] pub fn into_inner(self) -> Vec<KeyValue> { self.lines } } impl From<Vec<KeyValue>> for KVLines { fn from(lines: Vec<KeyValue>) -> Self { Self { lines } } } impl From<Vec<(String, String)>> for KVLines { fn from(lines: Vec<(String, String)>) -> Self { let mut out = Self { lines: Vec::new() }; for (key, value) in lines { out.append(key, value); } out } } |
︙ | ︙ |
Changes to src/types/params.rs.
︙ | ︙ | |||
22 23 24 25 26 27 28 29 | #[derive(Debug, Clone, Default)] pub struct Params { hm: HashMap<String, String> } impl Params { /// Create a new empty parameters object. pub fn new() -> Self { | > < | < > > | > | > > > > | | | > > > | 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | #[derive(Debug, Clone, Default)] pub struct Params { hm: HashMap<String, String> } impl Params { /// Create a new empty parameters object. #[must_use] pub fn new() -> Self { Self::default() } /// Reset all the key/values in `Params` object. pub fn clear(&mut self) { self.hm.clear(); } /// Return the number of key/value pairs in the parameter buffer. #[must_use] pub fn len(&self) -> usize { self.hm.len() } /// Returns `true` if the `Params` collection does not contain any key/value /// pairs. #[must_use] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Return reference to inner `HashMap`. #[must_use] pub const fn get_inner(&self) -> &HashMap<String, String> { &self.hm } /// Add a parameter to the parameter. /// /// The `key` and `value` parameters are generic over the trait `ToString`, /// allowing a polymorphic behavior. /// /// # Examples /// ``` /// use blather::Params; /// /// let mut params = Params::new(); /// params.add_param("integer", 42).unwrap(); /// params.add_param("string", "hello").unwrap(); /// ``` /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. #[allow(clippy::needless_pass_by_value)] pub fn add_param( &mut self, key: impl ToString, value: impl ToString ) -> Result<(), Error> { let key = key.to_string(); validate_param_key(&key)?; self.hm.insert(key, value.to_string()); Ok(()) } /// Add a string parameter to the parameter. /// /// # Notes /// - This method exists for parity with a C++ interface and is a less /// flexible version of [`add_param()`](Self::add_param), which application /// should use instead. /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. pub fn add_str(&mut self, key: &str, value: &str) -> Result<(), Error> { self.add_param(key, value) } /// Add parameter where the value is generated from an iterator over /// strings, where entries are comma-separated. |
︙ | ︙ | |||
114 115 116 117 118 119 120 121 122 123 124 125 126 | /// assert_eq!(params.get_str("CatToo"), Some("meow,paws,tail")); /// /// let mut hs = HashSet::new(); /// hs.insert("Elena"); /// hs.insert("Drake"); /// params.add_strit("Uncharted", hs.into_iter()).unwrap(); /// ``` pub fn add_strit<I, S>(&mut self, key: &str, c: I) -> Result<(), Error> where I: IntoIterator<Item = S>, S: AsRef<str> { let mut sv = Vec::new(); | > > > | | | > > > | | | < < < > | > > > > > | > > | | < | | < | > > > | < > | > > > > | > > | | < | | < | | | > > > > | 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | /// assert_eq!(params.get_str("CatToo"), Some("meow,paws,tail")); /// /// let mut hs = HashSet::new(); /// hs.insert("Elena"); /// hs.insert("Drake"); /// params.add_strit("Uncharted", hs.into_iter()).unwrap(); /// ``` /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. pub fn add_strit<I, S>(&mut self, key: &str, c: I) -> Result<(), Error> where I: IntoIterator<Item = S>, S: AsRef<str> { let mut sv = Vec::new(); for o in c { sv.push(o.as_ref().to_string()); } self.add_param(key, sv.join(","))?; Ok(()) } /// Add a boolean parameter. /// /// # Examples /// ``` /// use blather::Params; /// /// let mut params = Params::new(); /// params.add_bool("should_be_true", true).unwrap(); /// params.add_bool("should_be_false", false).unwrap(); /// assert!(matches!(params.get_bool("should_be_true"), Ok(true))); /// assert!(matches!(params.get_bool("should_be_false"), Ok(false))); /// ``` /// /// # Notes /// - Applications should not make assumptions about the specific string /// value added by this function. Do not treat boolean values as strings; /// use the [`get_bool()`](Self::get_bool) method instead. /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. pub fn add_bool( &mut self, key: impl ToString, value: bool ) -> Result<(), Error> { let v = if value { "True" } else { "False" }; self.add_param(key, v) } /// Returns `true` if the parameter with `key` exists. Returns `false` /// otherwise. #[must_use] pub fn have(&self, key: &str) -> bool { self.hm.contains_key(key) } /// Get a parameter and convert it to a requested type, fail if key isn't /// found. /// /// # Examples /// ``` /// use blather::{Params, Error}; /// /// let mut params = Params::new(); /// params.add_param("arthur", 42); /// let fourtytwo = params.get_param::<u32>("arthur").unwrap(); /// assert_eq!(fourtytwo, 42); /// let nonexist = params.get_param::<u32>("ford"); /// let expect = Error::KeyNotFound(String::from("ford")); /// assert!(matches!(nonexist, Err(expect))); /// ``` /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. /// [`Error::BadFormat`] means the input parameters are invalid. pub fn get_param<T: FromStr>(&self, key: &str) -> Result<T, Error> { self.get_str(key).map_or_else( || Err(Error::KeyNotFound(key.to_string())), |val| { T::from_str(val).map_or_else( |_| { Err(Error::BadFormat(format!( "Unable to parse value from parameter '{key}'" ))) }, |v| Ok(v) ) } ) } /// Get a parameter and convert it to a requested type, return a default /// value if key isn't found. /// /// # Examples /// ``` /// use blather::Params; /// /// let mut params = Params::new(); /// let val = params.get_param_def::<u32>("nonexist", 11); /// assert!(matches!(val, Ok(11))); /// ``` /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. /// [`Error::BadFormat`] means the input parameters are invalid. pub fn get_param_def<T: FromStr>( &self, key: &str, def: T ) -> Result<T, Error> { self.get_str(key).map_or_else( || Ok(def), |val| { T::from_str(val).map_or_else( |_| { Err(Error::BadFormat(format!( "Unable to parse value from parameter '{key}'" ))) }, |v| Ok(v) ) } ) } /// Get string representation of a value for a requested key. /// Returns `None` if the key is not found in the inner storage. Returns /// `Some(&str)` if parameter exists. #[must_use] pub fn get_str(&self, key: &str) -> Option<&str> { let kv = self.hm.get_key_value(key); if let Some((_k, v)) = kv { return Some(v); } None } |
︙ | ︙ | |||
248 249 250 251 252 253 254 255 256 257 258 259 260 261 | /// /// let params = Params::new(); /// let e = params.get_str_def("nonexist", "elena"); /// assert_eq!(e, "elena"); /// ``` // Lifetimes of self and def don't really go hand-in-hand, but we bound them // together for the sake of the return value's lifetime. pub fn get_str_def<'a>(&'a self, key: &str, def: &'a str) -> &'a str { let kv = self.hm.get_key_value(key); if let Some((_k, v)) = kv { v } else { def } | > | 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | /// /// let params = Params::new(); /// let e = params.get_str_def("nonexist", "elena"); /// assert_eq!(e, "elena"); /// ``` // Lifetimes of self and def don't really go hand-in-hand, but we bound them // together for the sake of the return value's lifetime. #[must_use] pub fn get_str_def<'a>(&'a self, key: &str, def: &'a str) -> &'a str { let kv = self.hm.get_key_value(key); if let Some((_k, v)) = kv { v } else { def } |
︙ | ︙ | |||
273 274 275 276 277 278 279 280 281 282 | /// assert_eq!(params.get_int::<usize>("Num").unwrap(), 7); /// ``` /// /// # Notes /// - This method exists primarily to achive some sort of parity with a /// corresponding C++ library. It is recommended that applications use /// [`Params::get_param()`](Self::get_param) instead. // This method should really have some integer trait bound, but it doesn't // seem to exist in the standard library. pub fn get_int<T: FromStr>(&self, key: &str) -> Result<T, Error> { | > > > > | > > | | < | | < | > > > | < > > > > | > > | | < | | < | | | > > > > > > | 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | /// assert_eq!(params.get_int::<usize>("Num").unwrap(), 7); /// ``` /// /// # Notes /// - This method exists primarily to achive some sort of parity with a /// corresponding C++ library. It is recommended that applications use /// [`Params::get_param()`](Self::get_param) instead. /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. /// [`Error::BadFormat`] means the input parameters are invalid. // This method should really have some integer trait bound, but it doesn't // seem to exist in the standard library. pub fn get_int<T: FromStr>(&self, key: &str) -> Result<T, Error> { self.get_str(key).map_or_else( || Err(Error::KeyNotFound(key.to_string())), |val| { T::from_str(val).map_or_else( |_| { Err(Error::BadFormat(format!( "Unable to parse numeric value from parameter '{key}'" ))) }, |v| Ok(v) ) } ) } /// Try to get the value of a key and interpret it as an integer. If the key /// does not exist then return a default value supplied by the caller. /// /// # Examples /// ``` /// use blather::Params; /// /// let mut params = Params::new(); /// params.add_param("num", 11); /// assert_eq!(params.get_int_def::<u32>("num", 5).unwrap(), 11); /// assert_eq!(params.get_int_def::<u32>("nonexistent", 17).unwrap(), 17); /// ``` /// /// # Notes /// - It is recommended that application use /// [`Params::get_param_def()`](Self::get_param_def) instead. /// /// # Errors /// [`Error::BadFormat`] means the value's format is invalid. pub fn get_int_def<T: FromStr>( &self, key: &str, def: T ) -> Result<T, Error> { self.get_str(key).map_or_else( || Ok(def), |val| { T::from_str(val).map_or_else( |_| { Err(Error::BadFormat(format!( "Unable to parse numeric value from parameter '{key}'" ))) }, |v| Ok(v) ) } ) } /// Get a boolean value; return error if key wasn't found. /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. pub fn get_bool(&self, key: &str) -> Result<bool, Error> { if let Some(v) = self.get_str(key) { let v = v.to_ascii_lowercase(); match v.as_ref() { "y" | "yes" | "t" | "true" | "1" => { return Ok(true); } |
︙ | ︙ | |||
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | } } Err(Error::KeyNotFound(key.to_string())) } /// Get a boolean value; return a default value if key wasn't found. pub fn get_bool_def(&self, key: &str, def: bool) -> Result<bool, Error> { match self.get_bool(key) { Ok(v) => Ok(v), Err(Error::KeyNotFound(_)) => Ok(def), Err(e) => Err(e) } } /// Parse the value of a key as a comma-separated list of strings and return /// it. Only non-empty entries are returned. /// /// # Examples /// ``` /// use blather::Params; /// /// let mut params = Params::new(); /// params.add_param("csv", "elena,chloe,drake"); /// let sv = params.get_strvec("csv").unwrap(); /// assert_eq!(sv, vec!["elena", "chloe", "drake"]); /// ``` pub fn get_strvec(&self, key: &str) -> Result<Vec<String>, Error> { let mut ret = Vec::new(); if let Some(v) = self.get_str(key) { let split = v.split(','); for s in split { if !s.is_empty() { ret.push(s.to_string()); } } } Ok(ret) } /// Parse the value of a key as a comma-separated list of uniqie strings and | > > > > > > > > > > > > > > > > > > | > > > > > | | | | < | < | > | | | 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 | } } Err(Error::KeyNotFound(key.to_string())) } /// Get a boolean value; return a default value if key wasn't found. /// /// # Errors pub fn get_bool_def(&self, key: &str, def: bool) -> Result<bool, Error> { match self.get_bool(key) { Ok(v) => Ok(v), Err(Error::KeyNotFound(_)) => Ok(def), Err(e) => Err(e) } } /* /// Get a value and call a closure to map the value to another. pub fn get_map<F, T>(&self, key: &str, f: F) -> Result<T, Error> where F: FnOnce(&str) -> Result<T, Error> { if let Some(val) = self.get_str(key) { f(val) } else { Err(Error::KeyNotFound(key.to_string())) } } */ /// Parse the value of a key as a comma-separated list of strings and return /// it. Only non-empty entries are returned. /// /// # Examples /// ``` /// use blather::Params; /// /// let mut params = Params::new(); /// params.add_param("csv", "elena,chloe,drake"); /// let sv = params.get_strvec("csv").unwrap(); /// assert_eq!(sv, vec!["elena", "chloe", "drake"]); /// ``` /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. pub fn get_strvec(&self, key: &str) -> Result<Vec<String>, Error> { let mut ret = Vec::new(); if let Some(v) = self.get_str(key) { let split = v.split(','); for s in split { if !s.is_empty() { ret.push(s.to_string()); } } } Ok(ret) } /// Parse the value of a key as a comma-separated list of uniqie strings and /// return them in a `HashSet`. Only non-empty entries are returned. /// /// # Examples /// ``` /// use blather::Params; /// /// let mut params = Params::new(); /// params.add_param("set", "elena,chloe"); /// let set = params.get_hashset("set").unwrap(); /// assert_eq!(set.len(), 2); /// assert_eq!(set.contains("elena"), true); /// assert_eq!(set.contains("chloe"), true); /// assert_eq!(set.contains("drake"), false); /// ``` /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. pub fn get_hashset(&self, key: &str) -> Result<HashSet<String>, Error> { let mut ret = HashSet::new(); if let Some(v) = self.get_str(key) { let split = v.split(','); for s in split { if !s.is_empty() { ret.insert(s.to_string()); } } } Ok(ret) } /// Calculate the size of the buffer in serialized form. /// Each entry will be a newline terminated utf-8 line. /// Last line will be a single newline character. #[must_use] pub fn calc_buf_size(&self) -> usize { let mut size = 0; for (key, value) in &self.hm { size += key.len() + 1; // including ' ' size += value.len() + 1; // including '\n' } size + 1 // terminating '\n' } /// Serialize `Params` buffer into a vector of bytes for transmission. #[must_use] pub fn serialize(&self) -> Vec<u8> { let mut buf = Vec::new(); for (key, value) in &self.hm { let k = key.as_bytes(); let v = value.as_bytes(); for a in k { buf.push(*a); } buf.push(b' '); for a in v { buf.push(*a); } buf.push(b'\n'); } buf.push(b'\n'); buf } /// Write the Params to a buffer. pub fn encoder_write(&self, buf: &mut BytesMut) { // Calculate the required buffer size let size = self.calc_buf_size(); // Reserve space buf.reserve(size); // Write data to output buffer for (key, value) in &self.hm { buf.put(key.as_bytes()); buf.put_u8(b' '); buf.put(value.as_bytes()); buf.put_u8(b'\n'); } buf.put_u8(b'\n'); } /// Consume the `Params` buffer and return its internal `HashMap`. #[must_use] pub fn into_inner(self) -> HashMap<String, String> { self.hm } } impl From<HashMap<String, String>> for Params { fn from(hm: HashMap<String, String>) -> Self { Self { hm } } } impl fmt::Display for Params { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut kvlist = Vec::new(); for (key, value) in &self.hm { kvlist.push(format!("{key}={value}")); } write!(f, "{{{}}}", kvlist.join(",")) } } // vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 : |
Changes to src/types/telegram.rs.
︙ | ︙ | |||
15 16 17 18 19 20 21 | use super::{params::Params, validators::validate_topic}; /// Representation of a Telegram; a buffer which contains a _topic_ and a set /// of key/value parameters. /// /// Internally the key/value parameters are represented by a [`Params`] /// structure. | | | | | < < | < | < < < | | | < < < < < < < < | | | | < | | < < < | < < < < < | > | | | | | | > < > | < | < | > | < | | | > > > | < < < < | | > | | < < < | < < | > > > | | | < > > > < | | > > > < > > > < > < > > > < > > > < > > > > < > < | > > > < | > > > < > > > < > > > < > > > > > > > < > < | < < > > > | < < < < < < < > > > > > > > < | > > > | < | < < > > > > > > > | | < < < < < < < < | < > > | < < < < < < < < < < < < < < | | 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | use super::{params::Params, validators::validate_topic}; /// Representation of a Telegram; a buffer which contains a _topic_ and a set /// of key/value parameters. /// /// Internally the key/value parameters are represented by a [`Params`] /// structure. #[derive(Debug, Clone)] pub struct Telegram { topic: String, params: Params } impl Telegram { /// Create a new telegram object. /// /// # Panics /// The `topic` must be valid. #[must_use] #[allow(clippy::needless_pass_by_value)] pub fn new(topic: impl ToString) -> Self { let topic = topic.to_string(); assert!(validate_topic(&topic).is_ok()); Self { topic, params: Params::default() } } /// Internal factory function for creating a `Telegram` with an empty topic. /// /// This is intended to be used only by the codec. pub(crate) fn new_uninit() -> Self { Self { topic: String::new(), params: Params::default() } } /// Return the number of key/value parameters in the Telegram object. /// /// # Examples /// ``` /// use blather::Telegram; /// /// let mut tg = Telegram::new("SomeTopic"); /// assert_eq!(tg.num_params(), 0); /// tg.add_param("cat", "meow"); /// assert_eq!(tg.num_params(), 1); /// ``` /// /// # Notes /// This is a wrapper around [`Params::len()`](crate::Params::len). #[must_use] pub fn num_params(&self) -> usize { self.params.len() } /// Get a reference to the internal parameters object. #[must_use] pub const fn get_params(&self) -> &Params { &self.params } /// Get a mutable reference to the inner [`Params`] object. /// /// ``` /// use blather::Telegram; /// /// let mut tg = Telegram::new("Topic"); /// tg.add_param("cat", "meow"); /// assert_eq!(tg.num_params(), 1); /// tg.get_params_mut().clear(); /// assert_eq!(tg.num_params(), 0); /// ``` pub fn get_params_mut(&mut self) -> &mut Params { &mut self.params } /// Get a reference the the parameter's internal `HashMap`. /// /// Note: The inner representation of the Params object may change in the /// future. #[must_use] pub const fn get_params_inner(&self) -> &HashMap<String, String> { self.params.get_inner() } /// Set topic for telegram. /// /// Overwrites current topic is one has already been set. /// /// # Examples /// ``` /// use blather::{Telegram, Error}; /// /// let mut tg = Telegram::new("SomeTopic"); /// assert!(matches!(tg.set_topic("Hello"), Ok(()))); /// /// let e = Error::BadFormat("Invalid topic character".to_string()); /// assert!(matches!(tg.set_topic("Hell o"), Err(e))); /// ``` /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. pub fn set_topic(&mut self, topic: &str) -> Result<(), Error> { validate_topic(topic)?; self.topic = topic.to_string(); Ok(()) } /// Get a reference to the topic string, or None if topic is not been set. /// /// # Examples /// ``` /// use blather::{Telegram, Error}; /// /// let tg = Telegram::new("SomeTopic"); /// assert_eq!(tg.get_topic(), "SomeTopic"); /// ``` #[must_use] pub fn get_topic(&self) -> &str { self.topic.as_ref() } /// Add a parameter to the telegram. /// /// The `key` and `value` parameters are generic over the trait `ToString`, /// allowing a polymorphic behavior. /// /// # Examples /// ``` /// use blather::Telegram; /// /// let mut tg = Telegram::new("Hello"); /// tg.add_param("integer", 42).unwrap(); /// tg.add_param("string", "hello").unwrap(); /// ``` /// /// # Notes /// - This is a thin wrapper around /// [`Params::add_param()`](crate::Params::add_param). /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. pub fn add_param( &mut self, key: impl ToString, value: impl ToString ) -> Result<(), Error> { self.params.add_param(key, value) } /// Add a string parameter to the telegram. /// /// # Notes /// - This function exists primarily for parity with a C++ library; it is /// just a wrapper around [`add_param()`](Self::add_param), which is /// recommended over `add_str()`. /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. pub fn add_str(&mut self, key: &str, value: &str) -> Result<(), Error> { self.add_param(key, value) } /// Add parameter where the value is generated from an iterator over a /// string container, where entries will be comma-separated. /// /// ``` /// use blather::Telegram; /// /// let mut tg = Telegram::new("SomeTopic"); /// tg.add_strit("Cat", &["meow", "paws", "tail"]).unwrap(); /// assert!(matches!(tg.get_str("Cat"), Some("meow,paws,tail"))); /// ``` /// /// # Notes /// - This is a thin wrapper for /// [`Params::add_strit()`](crate::Params::add_strit). /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. pub fn add_strit<I, S>(&mut self, key: &str, c: I) -> Result<(), Error> where I: IntoIterator<Item = S>, S: AsRef<str> { self.params.add_strit(key, c) } /// Add a boolean value to Telegram object. /// /// # Notes /// - This is a thin wrapper around /// [`Params::add_bool()`](crate::Params::add_bool). /// /// # Errors /// [`Error::BadFormat`] means the input parameters are invalid. pub fn add_bool<K: ToString>( &mut self, key: K, value: bool ) -> Result<(), Error> { self.params.add_bool(key, value) } /// Check whether a parameter exists in Telegram object. /// /// Returns `true` is the key exists, and `false` otherwise. #[must_use] pub fn have_param(&self, key: &str) -> bool { self.params.have(key) } /// Get a parameter. Fail if the parameter does not exist. /// /// # Notes /// - This is a thin wrapper around /// [`Params::get_param()`](crate::Params::get_param). /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. pub fn get_param<T: FromStr>(&self, key: &str) -> Result<T, Error> { self.params.get_param(key) } /// Get a parameter. Return a default value if the parameter does not /// exist. /// /// # Notes /// - This is a thin wrapper around /// [`Params::get_param_def()`](crate::Params::get_param_def). /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. pub fn get_param_def<T: FromStr>( &self, key: &str, def: T ) -> Result<T, Error> { self.params.get_param_def(key, def) } /// Get a string representation of a parameter. Return `None` is parameter /// does not exist. /// /// # Notes /// - This is a thin wrapper around /// [`Params::get_str()`](crate::Params::get_str) /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. #[must_use] pub fn get_str(&self, key: &str) -> Option<&str> { self.params.get_str(key) } /// Get a string representation of a parameter. Returns a default value is /// the parameter does not exist. /// /// # Notes /// - This is a thin wrapper around /// [`Params::get_str_def()`](crate::Params::get_str_def) #[must_use] pub fn get_str_def<'a>(&'a self, key: &str, def: &'a str) -> &'a str { self.params.get_str_def(key, def) } /// Get an integer representation of a parameter. /// /// ``` /// use blather::Telegram; /// /// let mut tg = Telegram::new("SomeTopic"); /// tg.add_param("Num", 7); /// assert_eq!(tg.get_int::<usize>("Num").unwrap(), 7); /// ``` /// /// # Notes /// - This function uses the `FromStr` trait on the return-type so it /// technically isn't limited to integers. /// - The method exists to mimic a C++ library. It is recommeded that /// applications use [`Telegram::get_param()`](Self::get_param) instead. /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. pub fn get_int<T: FromStr>(&self, key: &str) -> Result<T, Error> { self.params.get_int(key) } /// Try to get the parameter value of a key and interpret it as an integer. /// If the key does not exist then return a default value supplied by the /// caller. /// /// ``` /// use blather::Telegram; /// /// let mut tg = Telegram::new("SomeTopic"); /// tg.add_param("num", 11); /// assert_eq!(tg.get_int_def::<u32>("num", 5).unwrap(), 11); /// assert_eq!(tg.get_int_def::<u32>("nonexistent", 17).unwrap(), 17); /// ``` /// /// # Errors /// [`Error::BadFormat`] means the value's format is invalid. pub fn get_int_def<T: FromStr>( &self, key: &str, def: T ) -> Result<T, Error> { self.params.get_int_def(key, def) } /// Return a boolean value. Return error if parameter does not exist. /// /// If a value exist but can not be parsed as a boolean value the error /// `Error::BadFormat` will be returned. /// /// # Notes /// - This is a thing wrapper around /// [`Params::get_bool()`](crate::Params::get_bool). /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. pub fn get_bool(&self, key: &str) -> Result<bool, Error> { self.params.get_bool(key) } /// Return a boolean value. Return a default value if parameter does not /// exist. /// /// # Notes /// - This is a thing wrapper around /// [`Params::get_bool()`](crate::Params::get_bool). /// /// # Errors /// [`Error::BadFormat`] means the value's format is invalid. pub fn get_bool_def(&self, key: &str, def: bool) -> Result<bool, Error> { self.params.get_bool_def(key, def) } /// Parse the value of a key as a comma-separated list of strings and return /// it as a `Vec<String>`. Only non-empty entries are returned. /// /// # Notes /// - This is a thin wrapper around /// [`Params::get_strvec()`](crate::Params::get_strvec). /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. pub fn get_strvec(&self, key: &str) -> Result<Vec<String>, Error> { self.params.get_strvec(key) } /// Parse the value of a key as a comma-separated list of strings and return /// it as a `HashSet<String>`. Only non-empty entries are returned. /// /// # Notes /// - This is a thin wrapper around /// [`Params::get_hashset()`](crate::Params::get_hashset). /// /// # Errors /// [`Error::KeyNotFound`] means the requested parameter does not exist. /// [`Error::BadFormat`] means the value's format is invalid. pub fn get_hashset(&self, key: &str) -> Result<HashSet<String>, Error> { self.params.get_hashset(key) } /// Calculate the size of a serialized version of this Telegram object. /// If no topic has been set it is simply ignored. In the future this might /// change to something more dramatic, like a panic. Telegrams should always /// contain a topic when transmitted. /// /// Each line is terminated by a newline character. /// The last line consists of a single newline character. #[must_use] pub fn calc_buf_size(&self) -> usize { // Calculate the required buffer size let mut size = 0; size += self.topic.len() + 1; // including '\n' // Note that the Params method reserves the final terminating newline. size + self.params.calc_buf_size() } /// Serialize `Telegram` into a vector of bytes for transmission. /// /// # Errors /// [`Error::BadFormat`] the `Telegram` is missing a topic. pub fn serialize(&self) -> Result<Vec<u8>, Error> { let mut buf = Vec::new(); if self.topic.is_empty() { return Err(Error::BadFormat("Missing heading".to_string())); } // Copy topic let b = self.topic.as_bytes(); for a in b { buf.push(*a); } buf.push(b'\n'); for (key, value) in self.get_params_inner() { let k = key.as_bytes(); let v = value.as_bytes(); for a in k { buf.push(*a); } buf.push(b' '); for a in v { buf.push(*a); } buf.push(b'\n'); } buf.push(b'\n'); Ok(buf) } /// Write the Telegram to a `BytesMut` buffer. /// /// # Errors /// [`Error::SerializeError`] the `Telegram` is missing a topic. pub fn encoder_write(&self, buf: &mut BytesMut) -> Result<(), Error> { if self.topic.is_empty() { return Err(Error::SerializeError("Missing Telegram topic".to_string())); } // Calculate the required buffer size let size = self.calc_buf_size(); // Reserve space buf.reserve(size); // Write data to output buffer buf.put(self.topic.as_bytes()); buf.put_u8(b'\n'); for (key, value) in self.get_params_inner() { buf.put(key.as_bytes()); buf.put_u8(b' '); buf.put(value.as_bytes()); buf.put_u8(b'\n'); } buf.put_u8(b'\n'); Ok(()) } /// Consume the Telegram buffer and return the internal parameters object. #[must_use] pub fn into_params(self) -> Params { self.params } /// Unwrap the `Telegram` into a topic and `Params`. #[must_use] pub fn unwrap_topic_params(self) -> (String, Params) { (self.topic, self.params) } } impl From<String> for Telegram { fn from(topic: String) -> Self { Self { topic, params: Params::default() } } } impl TryFrom<(&str, Params)> for Telegram { type Error = Error; /// # Panics /// The topic must be valid. fn try_from(t: (&str, Params)) -> Result<Self, Self::Error> { let mut tg = Self::new(t.0.to_string()); tg.params = t.1; Ok(tg) } } impl fmt::Display for Telegram { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.topic, self.params) } } // vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 : |
Changes to src/types/validators.rs.
︙ | ︙ | |||
60 61 62 63 64 65 66 | #[test] fn ok_topic_1() { assert!(validate_topic("Foobar").is_ok()); } #[test] fn empty_topic() { | < | > > | < < | > > | < < | | > | < < | 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | #[test] fn ok_topic_1() { assert!(validate_topic("Foobar").is_ok()); } #[test] fn empty_topic() { let Err(Error::BadFormat(msg)) = validate_topic("") else { panic!("Unexpectedly not Error::BadFormat"); }; assert_eq!(msg, "Empty or broken topic"); } #[test] fn broken_topic_1() { let Err(Error::BadFormat(msg)) = validate_topic("foo bar") else { panic!("Unexpectedly not Error::BadFormat"); }; assert_eq!(msg, "Invalid topic character"); } #[test] fn broken_topic_2() { let Err(Error::BadFormat(msg)) = validate_topic(" foobar") else { panic!("Unexpectedly not Error::BadFormat"); }; assert_eq!(msg, "Invalid leading topic character"); } } // vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 : |
Changes to tests/conn_telegram.rs.
︙ | ︙ | |||
13 14 15 16 17 18 19 | mock.read(b"hello\n\n"); let mut frm = Framed::new(mock.build(), Codec::new()); while let Some(o) = frm.next().await { let o = o.unwrap(); if let codec::Input::Telegram(tg) = o { | | | 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | mock.read(b"hello\n\n"); let mut frm = Framed::new(mock.build(), Codec::new()); while let Some(o) = frm.next().await { let o = o.unwrap(); if let codec::Input::Telegram(tg) = o { assert_eq!(tg.get_topic(), "hello"); let params = tg.into_params(); let map = params.into_inner(); assert_eq!(map.len(), 0); } else { panic!("Not a Telegram"); } } |
︙ | ︙ | |||
37 38 39 40 41 42 43 | let mut frm = Framed::new(mock.build(), Codec::new()); while let Some(o) = frm.next().await { let o = o.unwrap(); match o { codec::Input::Telegram(tg) => { | | | 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | let mut frm = Framed::new(mock.build(), Codec::new()); while let Some(o) = frm.next().await { let o = o.unwrap(); match o { codec::Input::Telegram(tg) => { assert_eq!(tg.get_topic(), "hello"); let params = tg.into_params(); let map = params.into_inner(); assert_eq!(map.len(), 2); assert_eq!(map.get("murky_waters").unwrap(), "off"); assert_eq!(map.get("wrong_impression").unwrap(), "cows"); } _ => { |
︙ | ︙ |
Changes to tests/params.rs.
︙ | ︙ | |||
58 59 60 61 62 63 64 | #[test] fn display() { let mut params = Params::new(); params.add_str("foo", "bar").unwrap(); | | | 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | #[test] fn display() { let mut params = Params::new(); params.add_str("foo", "bar").unwrap(); let s = format!("{params}"); assert_eq!(s, "{foo=bar}"); } #[test] fn ser_size() { let mut params = Params::new(); |
︙ | ︙ | |||
89 90 91 92 93 94 95 | assert_eq!(num, 42); } #[test] fn broken_key() { let mut param = Params::new(); | < | > > | < < | > > | < | > > | > | | | 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | assert_eq!(num, 42); } #[test] fn broken_key() { let mut param = Params::new(); let Err(Error::BadFormat(msg)) = param.add_str("hell o", "world") else { panic!("Unexpectedly not Error::BadFormat"); }; assert_eq!(msg, "Invalid key character"); } #[test] fn empty_key() { let mut param = Params::new(); let Err(Error::BadFormat(msg)) = param.add_str("", "world") else { panic!("Unexpectedly not Error::BadFormat"); }; assert_eq!(msg, "Empty or broken key"); } #[test] fn boolvals() { let mut params = Params::new(); params.add_bool("abool", true).unwrap(); params.add_bool("abooltoo", false).unwrap(); let Ok(true) = params.get_bool("abool") else { panic!("Unexpectedly not Ok(true)"); }; let Ok(false) = params.get_bool("abooltoo") else { panic!("Unexpectedly not Ok(false)"); }; } // vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 : |
Changes to tests/telegram.rs.
1 2 3 4 5 | use blather::{Error, Params, Telegram}; #[test] fn simple() { | | < < | | | | | | < | | | | | | | | | | | | | | | | < | | > | < < | < | > > | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | use blather::{Error, Params, Telegram}; #[test] fn simple() { let mut tg = Telegram::new("SomeTopic"); assert_eq!(tg.get_topic(), "SomeTopic"); tg.add_str("Foo", "bar").unwrap(); assert_eq!(tg.get_str("Foo").unwrap(), "bar"); assert_eq!(tg.get_str("Moo"), None); } #[test] fn exist() { let mut tg = Telegram::new("SomeTopic"); tg.add_str("foo", "bar").unwrap(); assert!(tg.have_param("foo")); assert!(!tg.have_param("nonexistent")); } #[test] fn integer() { let mut tg = Telegram::new("SomeTopic"); assert_eq!(tg.get_topic(), "SomeTopic"); tg.add_str("Num", "64").unwrap(); assert_eq!(tg.get_int::<u16>("Num").unwrap(), 64); } #[test] fn size() { let mut tg = Telegram::new("SomeTopic"); tg.add_param("Num", 7_usize).unwrap(); assert_eq!(tg.get_int::<usize>("Num").unwrap(), 7); } #[test] fn intoparams() { let mut tg = Telegram::new("SomeTopic"); tg.add_str("Foo", "bar").unwrap(); assert_eq!(tg.get_str("Foo").unwrap(), "bar"); assert_eq!(tg.get_str("Moo"), None); let params = tg.into_params(); let val = params.get_str("Foo"); assert_eq!(val.unwrap(), "bar"); } #[test] fn display() { let mut tg = Telegram::new("hello"); tg.add_param("foo", "bar").unwrap(); let s = format!("{tg}"); assert_eq!(s, "hello:{foo=bar}"); } #[test] fn ser_size() { let mut tg = Telegram::new("hello"); tg.add_str("foo", "bar").unwrap(); tg.add_str("moo", "cow").unwrap(); let sz = tg.calc_buf_size(); assert_eq!(sz, 6 + 8 + 8 + 1); } #[test] fn def_int() { let mut tg = Telegram::new("SomeTopic"); tg.add_str("Num", "11").unwrap(); assert_eq!(tg.get_int_def::<u16>("Num", 17).unwrap(), 11); let num = tg.get_int_def::<u32>("nonexistent", 42).unwrap(); assert_eq!(num, 42); } #[test] fn bad_topic_leading() { let mut tg = Telegram::new("Hello"); let Err(Error::BadFormat(msg)) = tg.set_topic(" SomeTopic") else { panic!("Unexpectedly not Error::BadFormat"); }; assert_eq!(msg, "Invalid leading topic character"); } #[test] fn bad_topic() { let mut tg = Telegram::new("Hello"); let Err(Error::BadFormat(msg)) = tg.set_topic("Some Topic") else { panic!("Unexpectedly not Error::BadFormat"); }; assert_eq!(msg, "Invalid topic character"); } #[test] fn create_from_tuple() { let mut params = Params::new(); params.add_str("my", "word").unwrap(); |
︙ | ︙ |
Changes to tests/tg_to_expect.rs.
︙ | ︙ | |||
16 17 18 19 20 21 22 | let Some(o) = frm.next().await else { panic!("No frame"); }; let o = o.unwrap(); if let codec::Input::Telegram(tg) = o { | | | 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | let Some(o) = frm.next().await else { panic!("No frame"); }; let o = o.unwrap(); if let codec::Input::Telegram(tg) = o { assert_eq!(tg.get_topic(), "hello"); assert_eq!(tg.get_int::<usize>("len").unwrap(), 4); frm.codec_mut().expect_bytes(4).unwrap(); } else { panic!("Not a Telegram"); } while let Some(o) = frm.next().await { |
︙ | ︙ |
Changes to www/changelog.md.
1 2 3 4 5 6 | # Change Log ⚠️ indicates a breaking change. ## [Unreleased] | | > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | # Change Log ⚠️ indicates a breaking change. ## [Unreleased] [Details](/vdiff?from=blather-0.11.0&to=trunk) ### Added ### Changed ### Removed --- ## [0.11.0] - 2024-09-22 [Details](/vdiff?from=blather-0.10.1&to=blather-0.11.0) ### Changed - ⚠️ `Error::IO` carries with it `std::io::Error` rather than a string representation of the error. ### Removed - ⚠️ `Error` no longer implements `PartialEq`. - ⚠️ `Telegram::clear()` was removed because there's no "default" topic. - Remove `From<Params>` for `Telegram` (since it needs a topic now). --- ## [0.10.1] - 2024-08-06 [Details](/vdiff?from=blather-0.10.0&to=blather-0.10.1) ### Added |
︙ | ︙ |