pw_tokenizer/
lib.rs

1// Copyright 2023 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15//! `pw_tokenizer` - Efficient string handling and printf style encoding.
16//!
17//! Logging is critical, but developers are often forced to choose between
18//! additional logging or saving crucial flash space. The `pw_tokenizer` crate
19//! helps address this by replacing printf-style strings with binary tokens
20//! during compilation. This enables extensive logging with substantially less
21//! memory usage.
22//!
23//! For a more in depth explanation of the systems design and motivations,
24//! see [Pigweed's pw_tokenizer module documentation](https://pigweed.dev/pw_tokenizer/).
25//!
26//! # Examples
27//!
28//! Pigweed's tokenization database uses `printf` style strings internally so
29//! those are supported directly.
30//!
31//! ```
32//! use pw_tokenizer::tokenize_printf_to_buffer;
33//!
34//! let mut buffer = [0u8; 1024];
35//! let len = tokenize_printf_to_buffer!(&mut buffer, "The answer is %d", 42)?;
36//!
37//! // 4 bytes used to encode the token and one to encode the value 42.  This
38//! // is a **3.5x** reduction in size compared to the raw string!
39//! assert_eq!(len, 5);
40//! # Ok::<(), pw_status::Error>(())
41//! ```
42//!
43//! We also support Rust's `core::fmt` style syntax.  These format strings are
44//! converted to `printf` style at compile time to maintain compatibly with the
45//! rest of the Pigweed tokenizer ecosystem.  The below example produces the
46//! same token and output as the above one.
47//!
48//! ```
49//! use pw_tokenizer::tokenize_core_fmt_to_buffer;
50//!
51//! let mut buffer = [0u8; 1024];
52//! let len = tokenize_core_fmt_to_buffer!(&mut buffer, "The answer is {}", 42 as i32)?;
53//! assert_eq!(len, 5);
54//! # Ok::<(), pw_status::Error>(())
55//! ```
56#![cfg_attr(feature = "nightly", feature(type_alias_impl_trait))]
57#![cfg_attr(not(feature = "std"), no_std)]
58#![deny(missing_docs)]
59
60use pw_status::Result;
61
62#[doc(hidden)]
63pub mod internal;
64
65#[doc(hidden)]
66// Creating a __private namespace allows us a way to get to the modules
67// we need from macros by doing:
68//     use $crate::__private as __pw_tokenizer_crate;
69//
70// This is how proc macro generated code can reliably reference back to
71// `pw_tokenizer` while still allowing a user to import it under a different
72// name.
73pub mod __private {
74    pub use pw_bytes::concat_static_strs;
75    pub use pw_format_core::{PrintfFormatter, PrintfHexFormatter, PrintfUpperHexFormatter};
76    pub use pw_status::Result;
77    pub use pw_stream::{Cursor, Seek, WriteInteger, WriteVarint};
78    pub use pw_tokenizer_core::hash_string;
79    pub use pw_tokenizer_macro::{
80        _token, _tokenize_core_fmt_to_buffer, _tokenize_core_fmt_to_writer,
81        _tokenize_printf_to_buffer, _tokenize_printf_to_writer,
82    };
83
84    pub use crate::*;
85}
86
87/// Return the [`u32`] token for the specified string and add it to the token
88/// database.
89///
90/// This is where the magic happens in `pw_tokenizer`!   ... and by magic
91/// we mean hiding information in a special linker section that ends up in the
92/// final elf binary but does not get flashed to the device.
93///
94/// Two things are accomplished here:
95/// 1) The string is hashed into its stable `u32` token.  This is the value that
96///    is returned from the macro.
97/// 2) A [token database entry](https://pigweed.dev/pw_tokenizer/design.html#binary-database-format)
98///    is generated, assigned to a unique static symbol, placed in a linker
99///    section named `pw_tokenizer.entries.<TOKEN_HASH>`.  A
100///    [linker script](https://pigweed.googlesource.com/pigweed/pigweed/+/refs/heads/main/pw_tokenizer/pw_tokenizer_linker_sections.ld)
101///    is responsible for picking these symbols up and aggregating them into a
102///    single `.pw_tokenizer.entries` section in the final binary.
103///
104/// # Example
105/// ```
106/// use pw_tokenizer::token;
107///
108/// let token = token!("hello, \"world\"");
109/// assert_eq!(token, 3537412730);
110/// ```
111///
112/// Currently there is no support for encoding tokens to specific domains
113/// or with "fixed lengths" per [`pw_tokenizer_core::hash_bytes_fixed`].
114#[macro_export]
115macro_rules! token {
116    ($string:literal) => {{
117        use $crate::__private as __pw_tokenizer_crate;
118        $crate::__private::_token!($string)
119    }};
120}
121
122/// Tokenize a `core::fmt` style format string and arguments to an [`AsMut<u8>`]
123/// buffer.  The format string is converted in to a `printf` and added token to
124/// the token database.
125///
126/// See [`token`] for an explanation on how strings are tokenized and entries
127/// are added to the token database.  The token's domain is set to `""`.
128///
129/// Returns a [`pw_status::Result<usize>`] the number of bytes written to the buffer.
130///
131/// `tokenize_to_buffer!` supports concatenation of format strings as described
132/// in [`pw_format::macros::FormatAndArgs`].
133///
134/// # Errors
135/// - [`pw_status::Error::OutOfRange`] - Buffer is not large enough to fit
136///   tokenized data.
137/// - [`pw_status::Error::InvalidArgument`] - Invalid buffer was provided.
138///
139/// # Example
140///
141/// ```
142/// use pw_tokenizer::tokenize_core_fmt_to_buffer;
143///
144/// // Tokenize a format string and argument into a buffer.
145/// let mut buffer = [0u8; 1024];
146/// let len = tokenize_core_fmt_to_buffer!(&mut buffer, "The answer is {}", 42 as i32)?;
147///
148/// // 4 bytes used to encode the token and one to encode the value 42.
149/// assert_eq!(len, 5);
150///
151/// // The format string can be composed of multiple strings literals using
152/// // the custom`PW_FMT_CONCAT` operator.
153/// let len = tokenize_core_fmt_to_buffer!(&mut buffer, "Hello " PW_FMT_CONCAT "Pigweed")?;
154///
155/// // Only a single 4 byte token is emitted after concatenation of the string
156/// // literals above.
157/// assert_eq!(len, 4);
158/// # Ok::<(), pw_status::Error>(())
159/// ```
160#[macro_export]
161macro_rules! tokenize_core_fmt_to_buffer {
162    ($buffer:expr, $($format_string:literal)PW_FMT_CONCAT+ $(, $args:expr)* $(,)?) => {{
163      use $crate::__private as __pw_tokenizer_crate;
164      __pw_tokenizer_crate::_tokenize_core_fmt_to_buffer!($buffer, $($format_string)PW_FMT_CONCAT+, $($args),*)
165    }};
166}
167
168/// Tokenize a printf format string and arguments to an [`AsMut<u8>`] buffer
169/// and add the format string's token to the token database.
170///
171/// See [`token`] for an explanation on how strings are tokenized and entries
172/// are added to the token database.  The token's domain is set to `""`.
173///
174/// Returns a [`pw_status::Result<usize>`] the number of bytes written to the buffer.
175///
176/// `tokenize_to_buffer!` supports concatenation of format strings as described
177/// in [`pw_format::macros::FormatAndArgs`].
178///
179/// # Errors
180/// - [`pw_status::Error::OutOfRange`] - Buffer is not large enough to fit
181///   tokenized data.
182/// - [`pw_status::Error::InvalidArgument`] - Invalid buffer was provided.
183///
184/// # Example
185///
186/// ```
187/// use pw_tokenizer::tokenize_printf_to_buffer;
188///
189/// // Tokenize a format string and argument into a buffer.
190/// let mut buffer = [0u8; 1024];
191/// let len = tokenize_printf_to_buffer!(&mut buffer, "The answer is %d", 42)?;
192///
193/// // 4 bytes used to encode the token and one to encode the value 42.
194/// assert_eq!(len, 5);
195///
196/// // The format string can be composed of multiple strings literals using
197/// // the custom`PW_FMT_CONCAT` operator.
198/// let len = tokenize_printf_to_buffer!(&mut buffer, "Hello " PW_FMT_CONCAT "Pigweed")?;
199///
200/// // Only a single 4 byte token is emitted after concatenation of the string
201/// // literals above.
202/// assert_eq!(len, 4);
203/// # Ok::<(), pw_status::Error>(())
204/// ```
205#[macro_export]
206macro_rules! tokenize_printf_to_buffer {
207    ($buffer:expr, $($format_string:literal)PW_FMT_CONCAT+ $(, $args:expr)* $(,)?) => {{
208      use $crate::__private as __pw_tokenizer_crate;
209      __pw_tokenizer_crate::_tokenize_printf_to_buffer!($buffer, $($format_string)PW_FMT_CONCAT+, $($args),*)
210    }};
211}
212
213/// Deprecated alias for [`tokenize_printf_to_buffer!`].
214#[macro_export]
215macro_rules! tokenize_to_buffer {
216    ($buffer:expr, $($format_string:literal)PW_FMT_CONCAT+ $(, $args:expr)* $(,)?) => {{
217      $crate::tokenize_printf_to_buffer!($buffer, $($format_string)PW_FMT_CONCAT+, $($args),*)
218    }};
219}
220
221/// Tokenize a `core::fmt` format string and arguments to a [`MessageWriter`].
222/// The format string is converted in to a `printf` and added token to the token
223/// database.
224///
225/// `tokenize_core_fmt_to_writer!` and the accompanying [`MessageWriter`] trait
226/// provide an optimized API for use cases like logging where the output of the
227/// tokenization will be written to a shared/ambient resource like stdio, a
228/// UART, or a shared buffer.
229///
230/// See [`token`] for an explanation on how strings are tokenized and entries
231/// are added to the token database.  The token's domain is set to `""`.
232///
233/// Returns a [`pw_status::Result<()>`].
234///
235/// `tokenize_core_fmt_to_writer!` supports concatenation of format strings as
236///  described in [`pw_format::macros::FormatAndArgs`].
237///
238/// # Errors
239/// - [`pw_status::Error::OutOfRange`] - [`MessageWriter`] does not have enough
240///   space to fit tokenized data.
241/// - others - `tokenize_core_fmt_to_writer!` will pass on any errors returned
242///   by the [`MessageWriter`].
243///
244/// # Code Size
245///
246/// This data was collected by examining the disassembly of a test program
247/// built for a Cortex M0.
248///
249/// | Tokenized Message   | Per Call-site Cost (bytes) |
250/// | --------------------| -------------------------- |
251/// | no arguments        | 10                         |
252/// | one `i32` argument  | 18                         |
253///
254/// # Example
255///
256/// ```
257/// use pw_status::Result;
258/// use pw_stream::{Cursor, Write};
259/// use pw_tokenizer::{MessageWriter, tokenize_core_fmt_to_writer};
260///
261/// const BUFFER_LEN: usize = 32;
262///
263/// // Declare a simple MessageWriter that uses a [`pw_status::Cursor`] to
264/// // maintain an internal buffer.
265/// struct TestMessageWriter {
266///   cursor: Cursor<[u8; BUFFER_LEN]>,
267/// }
268///
269/// impl MessageWriter for TestMessageWriter {
270///   fn new() -> Self {
271///       Self {
272///           cursor: Cursor::new([0u8; BUFFER_LEN]),
273///       }
274///   }
275///
276///   fn write(&mut self, data: &[u8]) -> Result<()> {
277///       self.cursor.write_all(data)
278///   }
279///
280///   fn remaining(&self) -> usize {
281///       self.cursor.remaining()
282///   }
283///
284///   fn finalize(self) -> Result<()> {
285///       let len = self.cursor.position();
286///       // 4 bytes used to encode the token and one to encode the value 42.
287///       assert_eq!(len, 5);
288///       Ok(())
289///   }
290/// }
291///
292/// // Tokenize a format string and argument into the writer.  Note how we
293/// // pass in the message writer's type, not an instance of it.
294/// let len = tokenize_core_fmt_to_writer!(TestMessageWriter, "The answer is {}", 42 as i32)?;
295/// # Ok::<(), pw_status::Error>(())
296/// ```
297#[macro_export]
298macro_rules! tokenize_core_fmt_to_writer {
299    ($ty:ty, $($format_string:literal)PW_FMT_CONCAT+ $(, $args:expr)* $(,)?) => {{
300      use $crate::__private as __pw_tokenizer_crate;
301      __pw_tokenizer_crate::_tokenize_core_fmt_to_writer!($ty, $($format_string)PW_FMT_CONCAT+, $($args),*)
302    }};
303}
304
305/// Tokenize a `printf` format string and arguments to a [`MessageWriter`] and
306/// add the format string's token to the token database.
307///
308/// `tokenize_printf_fmt_to_writer!` and the accompanying [`MessageWriter`] trait
309/// provide an optimized API for use cases like logging where the output of the
310/// tokenization will be written to a shared/ambient resource like stdio, a
311/// UART, or a shared buffer.
312///
313/// See [`token`] for an explanation on how strings are tokenized and entries
314/// are added to the token database.  The token's domain is set to `""`.
315///
316/// Returns a [`pw_status::Result<()>`].
317///
318/// `tokenize_core_fmt_to_writer!` supports concatenation of format strings as
319///  described in [`pw_format::macros::FormatAndArgs`].
320///
321/// # Errors
322/// - [`pw_status::Error::OutOfRange`] - [`MessageWriter`] does not have enough
323///   space to fit tokenized data.
324/// - others - `tokenize_printf_to_writer!` will pass on any errors returned
325///   by the [`MessageWriter`].
326///
327/// # Code Size
328///
329/// This data was collected by examining the disassembly of a test program
330/// built for a Cortex M0.
331///
332/// | Tokenized Message   | Per Call-site Cost (bytes) |
333/// | --------------------| -------------------------- |
334/// | no arguments        | 10                         |
335/// | one `i32` argument  | 18                         |
336///
337/// # Example
338///
339/// ```
340/// use pw_status::Result;
341/// use pw_stream::{Cursor, Write};
342/// use pw_tokenizer::{MessageWriter, tokenize_printf_to_writer};
343///
344/// const BUFFER_LEN: usize = 32;
345///
346/// // Declare a simple MessageWriter that uses a [`pw_status::Cursor`] to
347/// // maintain an internal buffer.
348/// struct TestMessageWriter {
349///   cursor: Cursor<[u8; BUFFER_LEN]>,
350/// }
351///
352/// impl MessageWriter for TestMessageWriter {
353///   fn new() -> Self {
354///       Self {
355///           cursor: Cursor::new([0u8; BUFFER_LEN]),
356///       }
357///   }
358///
359///   fn write(&mut self, data: &[u8]) -> Result<()> {
360///       self.cursor.write_all(data)
361///   }
362///
363///   fn remaining(&self) -> usize {
364///       self.cursor.remaining()
365///   }
366///
367///   fn finalize(self) -> Result<()> {
368///       let len = self.cursor.position();
369///       // 4 bytes used to encode the token and one to encode the value 42.
370///       assert_eq!(len, 5);
371///       Ok(())
372///   }
373/// }
374///
375/// // Tokenize a format string and argument into the writer.  Note how we
376/// // pass in the message writer's type, not an instance of it.
377/// let len = tokenize_printf_to_writer!(TestMessageWriter, "The answer is %d", 42)?;
378/// # Ok::<(), pw_status::Error>(())
379/// ```
380#[macro_export]
381macro_rules! tokenize_printf_to_writer {
382    ($ty:ty, $($format_string:literal)PW_FMT_CONCAT+ $(, $args:expr)* $(,)?) => {{
383      use $crate::__private as __pw_tokenizer_crate;
384      __pw_tokenizer_crate::_tokenize_printf_to_writer!($ty, $($format_string)PW_FMT_CONCAT+, $($args),*)
385    }};
386}
387
388/// Deprecated alias for [`tokenize_printf_to_writer!`].
389#[macro_export]
390macro_rules! tokenize_to_writer {
391  ($ty:ty, $($format_string:literal)PW_FMT_CONCAT+ $(, $args:expr)* $(,)?) => {{
392    $crate::tokenize_printf_to_writer!($ty, $($format_string)PW_FMT_CONCAT+, $($args),*)
393  }};
394}
395
396/// A trait used by [`tokenize_to_writer!`] to output tokenized messages.
397///
398/// For more details on how this type is used, see the [`tokenize_to_writer!`]
399/// documentation.
400pub trait MessageWriter {
401    /// Returns a new instance of a `MessageWriter`.
402    fn new() -> Self;
403
404    /// Append `data` to the message.
405    fn write(&mut self, data: &[u8]) -> Result<()>;
406
407    /// Return the remaining space in this message instance.
408    ///
409    /// If there are no space constraints, return `usize::MAX`.
410    fn remaining(&self) -> usize;
411
412    /// Finalize message.
413    ///
414    /// `finalize()` is called when the tokenized message is complete.
415    fn finalize(self) -> Result<()>;
416}
417
418#[cfg(test)]
419// Untyped prints code rely on as casts to annotate type information.
420#[allow(clippy::unnecessary_cast)]
421#[allow(clippy::literal_string_with_formatting_args)]
422mod tests {
423    use super::*;
424    extern crate self as pw_tokenizer;
425    use std::cell::RefCell;
426
427    use pw_stream::{Cursor, Write};
428
429    // This is not meant to be an exhaustive test of tokenization which is
430    // covered by `pw_tokenizer_core`'s unit tests.  Rather, this is testing
431    // that the `tokenize!` macro connects to that correctly.
432    #[test]
433    fn test_token() {}
434
435    macro_rules! tokenize_to_buffer_test {
436      ($expected_data:expr, $buffer_len:expr, $printf_fmt:literal, $core_fmt:literal $(, $args:expr)* $(,)?) => {{
437        if $printf_fmt != "" {
438          let mut buffer = [0u8; $buffer_len];
439          let len = tokenize_printf_to_buffer!(&mut buffer, $printf_fmt, $($args),*).unwrap();
440          assert_eq!(
441              &buffer[..len],
442              $expected_data,
443              "printf style input does not produce expected output",
444          );
445        }
446        if $core_fmt != "" {
447           let mut buffer = [0u8; $buffer_len];
448           let len = tokenize_core_fmt_to_buffer!(&mut buffer, $core_fmt, $($args),*).unwrap();
449           assert_eq!(
450               &buffer[..len],
451               $expected_data,
452              "core::fmt style input does not produce expected output",
453           );
454        }
455      }}
456    }
457
458    macro_rules! tokenize_to_writer_test {
459      ($expected_data:expr, $buffer_len:expr, $printf_fmt:literal, $core_fmt:literal $(, $args:expr)* $(,)?) => {{
460        // The `MessageWriter` API is used in places like logging where it
461        // accesses an shared/ambient resource (like stdio or an UART).  To test
462        // it in a hermetic way we declare test specific `MessageWriter` that
463        // writes it's output to a scoped static variable that can be checked
464        // after the test is run.
465
466        // Since these tests are not multi-threaded, we can use a thread_local!
467        // instead of a mutex.
468        thread_local!(static TEST_OUTPUT: RefCell<Option<Vec<u8>>> = RefCell::new(None));
469
470        struct TestMessageWriter {
471            cursor: Cursor<[u8; $buffer_len]>,
472        }
473
474        impl MessageWriter for TestMessageWriter {
475          fn new() -> Self {
476              Self {
477                  cursor: Cursor::new([0u8; $buffer_len]),
478              }
479          }
480
481          fn write(&mut self, data: &[u8]) -> Result<()> {
482              self.cursor.write_all(data)
483          }
484
485          fn remaining(&self) -> usize {
486              self.cursor.remaining()
487          }
488
489          fn finalize(self) -> Result<()> {
490              let write_len = self.cursor.position();
491              let data = self.cursor.into_inner();
492              TEST_OUTPUT.with(|output| *output.borrow_mut() = Some(data[..write_len].to_vec()));
493
494              Ok(())
495          }
496        }
497
498        if $printf_fmt != "" {
499          TEST_OUTPUT.with(|output| *output.borrow_mut() = None);
500          tokenize_printf_to_writer!(TestMessageWriter, $printf_fmt, $($args),*).unwrap();
501          TEST_OUTPUT.with(|output| {
502              assert_eq!(
503                  *output.borrow(),
504                  Some($expected_data.to_vec()),
505              )
506          });
507        }
508
509        if $core_fmt != "" {
510          TEST_OUTPUT.with(|output| *output.borrow_mut() = None);
511          tokenize_core_fmt_to_writer!(TestMessageWriter, $core_fmt, $($args),*).unwrap();
512          TEST_OUTPUT.with(|output| {
513              assert_eq!(
514                  *output.borrow(),
515                  Some($expected_data.to_vec()),
516              )
517          });
518        }
519      }}
520    }
521
522    macro_rules! tokenize_test {
523        ($expected_data:expr, $buffer_len:expr, $printf_fmt:literal, $core_fmt:literal $(, $args:expr)* $(,)?) => {{
524            tokenize_to_buffer_test!($expected_data, $buffer_len, $printf_fmt, $core_fmt, $($args),*);
525            tokenize_to_writer_test!($expected_data, $buffer_len, $printf_fmt, $core_fmt, $($args),*);
526        }};
527    }
528
529    #[test]
530    fn bare_string_encodes_correctly() {
531        tokenize_test!(
532            &[0xe0, 0x92, 0xe0, 0xa], // expected buffer
533            64,                       // buffer size
534            "Hello Pigweed",          // printf style
535            "Hello Pigweed",          // core::fmt style
536        );
537    }
538
539    #[test]
540    fn test_decimal_format() {
541        // "as casts" are used for the integer arguments below.  They are only
542        // need for the core::fmt style arguments but are added so that we can
543        // check that the printf and core::fmt style equivalents encode the same.
544        tokenize_test!(
545            &[0x52, 0x1c, 0xb0, 0x4c, 0x2], // expected buffer
546            64,                             // buffer size
547            "The answer is %d!",            // printf style
548            "The answer is {}!",            // core::fmt style
549            1 as i32
550        );
551
552        tokenize_test!(
553            &[0x36, 0xd0, 0xfb, 0x69, 0x1], // expected buffer
554            64,                             // buffer size
555            "No! The answer is %d!",        // printf style
556            "No! The answer is {}!",        // core::fmt style
557            -1 as i32
558        );
559
560        tokenize_test!(
561            &[0xa4, 0xad, 0x50, 0x54, 0x0],               // expected buffer
562            64,                                           // buffer size
563            "I think you'll find that the answer is %d!", // printf style
564            "I think you'll find that the answer is {}!", // core::fmt style
565            0 as i32
566        );
567    }
568
569    #[test]
570    fn test_misc_integer_format() {
571        // %d, %i, %o, %u, %x, %X all encode integers the same.
572        tokenize_test!(
573            &[0x52, 0x1c, 0xb0, 0x4c, 0x2], // expected buffer
574            64,                             // buffer size
575            "The answer is %d!",            // printf style
576            "",                             // no equivalent core::fmt style
577            1
578        );
579
580        // Because %i is an alias for %d, it gets converted to a %d by the
581        // `pw_format` macro infrastructure.
582        tokenize_test!(
583            &[0x52, 0x1c, 0xb0, 0x4c, 0x2], // expected buffer
584            64,                             // buffer size
585            "The answer is %i!",            // printf style
586            "",                             // no equivalent core::fmt style
587            1
588        );
589
590        tokenize_test!(
591            &[0x5d, 0x70, 0x12, 0xb4, 0x2], // expected buffer
592            64,                             // buffer size
593            "The answer is %o!",            // printf style
594            "",                             // no equivalent core::fmt style
595            1u32
596        );
597
598        tokenize_test!(
599            &[0x63, 0x58, 0x5f, 0x8f, 0x2], // expected buffer
600            64,                             // buffer size
601            "The answer is %u!",            // printf style
602            "",                             // no equivalent core::fmt style
603            1u32
604        );
605
606        tokenize_test!(
607            &[0x66, 0xcc, 0x05, 0x7d, 0x2], // expected buffer
608            64,                             // buffer size
609            "The answer is %x!",            // printf style
610            "",                             // no equivalent core::fmt style
611            1u32
612        );
613
614        tokenize_test!(
615            &[0x46, 0x4c, 0x16, 0x96, 0x2], // expected buffer
616            64,                             // buffer size
617            "The answer is %X!",            // printf style
618            "",                             // no equivalent core::fmt style
619            1u32
620        );
621    }
622
623    #[test]
624    fn test_string_format() {
625        tokenize_test!(
626            b"\x25\xf6\x2e\x66\x07Pigweed", // expected buffer
627            64,                             // buffer size
628            "Hello: %s!",                   // printf style
629            "",                             // no equivalent core::fmt style
630            "Pigweed"
631        );
632    }
633
634    #[test]
635    fn test_string_format_overflow() {
636        tokenize_test!(
637            b"\x25\xf6\x2e\x66\x83Pig", // expected buffer
638            8,                          // buffer size
639            "Hello: %s!",               // printf style
640            "",                         // no equivalent core::fmt style
641            "Pigweed"
642        );
643    }
644
645    #[test]
646    fn test_char_format() {
647        tokenize_test!(
648            &[0x2e, 0x52, 0xac, 0xe4, 0xa0, 0x1], // expected buffer
649            64,                                   // buffer size
650            "Hello: %cigweed",                    // printf style
651            "",                                   // no equivalent core::fmt style
652            "P".as_bytes()[0]
653        );
654    }
655
656    #[test]
657    fn test_untyped_format() {
658        tokenize_test!(
659            &[0x63, 0x58, 0x5f, 0x8f, 0x2], // expected buffer
660            64,                             // buffer size
661            "The answer is %u!",            // printf style
662            "The answer is {}!",            // core::fmt style
663            1 as u32
664        );
665
666        tokenize_test!(
667            &[0x36, 0xd0, 0xfb, 0x69, 0x1], // expected buffer
668            64,                             // buffer size
669            "No! The answer is %v!",        // printf style
670            "No! The answer is {}!",        // core::fmt style
671            -1 as i32
672        );
673
674        tokenize_test!(
675            b"\x25\xf6\x2e\x66\x07Pigweed", // expected buffer
676            64,                             // buffer size
677            "Hello: %v!",                   // printf style
678            "Hello: {}!",                   // core::fmt style
679            "Pigweed" as &str
680        );
681    }
682
683    #[test]
684    fn test_field_width_and_zero_pad_format() {
685        tokenize_test!(
686            &[0x3a, 0xc2, 0x1a, 0x05, 0xfc, 0xab, 0x06], // expected buffer
687            64,                                          // buffer size
688            "Lets go to the %x",                         // printf style
689            "Lets go to the {:x}",                       // core::fmt style
690            0xcafe as u32
691        );
692
693        tokenize_test!(
694            &[0xf3, 0x16, 0x03, 0x99, 0xfc, 0xab, 0x06], // expected buffer
695            64,                                          // buffer size
696            "Lets go to the %8x",                        // printf style
697            "Lets go to the {:8x}",                      // core::fmt style
698            0xcafe as u32
699        );
700
701        tokenize_test!(
702            &[0x44, 0xce, 0xa3, 0x7e, 0xfc, 0xab, 0x06], // expected buffer
703            64,                                          // buffer size
704            "Lets go to the %08x",                       // printf style
705            "Lets go to the {:08x}",                     // core::fmt style
706            0xcafe as u32
707        );
708    }
709
710    #[test]
711    fn tokenizer_supports_concatenated_printf_format_strings() {
712        // Since the no argument and some arguments cases are handled differently
713        // by `tokenize_to_buffer!` we need to test both.
714        let mut buffer = [0u8; 64];
715        let len =
716            tokenize_printf_to_buffer!(&mut buffer, "Hello" PW_FMT_CONCAT " Pigweed").unwrap();
717        assert_eq!(&buffer[..len], &[0xe0, 0x92, 0xe0, 0xa]);
718
719        let len = tokenize_printf_to_buffer!(&mut buffer, "Hello: " PW_FMT_CONCAT "%cigweed",
720          "P".as_bytes()[0])
721        .unwrap();
722        assert_eq!(&buffer[..len], &[0x2e, 0x52, 0xac, 0xe4, 0xa0, 0x1]);
723    }
724
725    #[test]
726    fn tokenizer_supports_concatenated_core_fmt_format_strings() {
727        // Since the no argument and some arguments cases are handled differently
728        // by `tokenize_to_buffer!` we need to test both.
729        let mut buffer = [0u8; 64];
730        let len =
731            tokenize_core_fmt_to_buffer!(&mut buffer, "Hello" PW_FMT_CONCAT " Pigweed").unwrap();
732        assert_eq!(&buffer[..len], &[0xe0, 0x92, 0xe0, 0xa]);
733
734        let len = tokenize_core_fmt_to_buffer!(&mut buffer, "The answer is " PW_FMT_CONCAT "{}!",
735          1 as i32)
736        .unwrap();
737        assert_eq!(&buffer[..len], &[0x52, 0x1c, 0xb0, 0x4c, 0x2]);
738    }
739}