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
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
/*!
This crate exposes a procedural macro that allows you to format bytestrings.
For more background on why you would want to do that,
[read this article](https://octobus.net/blog/2020-06-05-not-everything-is-utf8.html).
## Usage
Add this to your `Cargo.toml`:
```toml
[dependencies]
format-bytes = "0.1"
```
then use the macro like so:
```rust
use format_bytes::format_bytes;
fn main() {
assert_eq!(
format_bytes!(b"look at those {} bytes", &[0u8, 1, 2]),
b"look at those \x00\x01\x02 bytes"
);
}
```
See more examples of how it works on the documentation of
[`format_bytes!` itself](https://docs.rs/format-bytes/\*\/format_bytes/macro.format_bytes.html).
## Missing features
* Named arguments, but they should be added in a future version
* Python-like "f-string" functionality is not planned because of its more
complex implementation and limited actual benefit
* ``format!``-like padding helpers: if the need manifests itself, they might
appear
## Why not 1.0?
Not until named arguments have landed and the macro gets a bit of mileage (it
will be used in [Mercurial](https://www.mercurial-scm.org)).
*/
use fmt;
use io;
/// Creates a `Vec<u8>` using interpolation of runtime expressions.
///
/// The first argument `format_bytes!` receives is a format bytestring.
/// This must be a bytestring literal. The power of the formatting string
/// is in the `{}`s contained.
///
/// Additional arguments passed to `format_bytes!` replace the `{}`s
/// within the formatting bytestring in the order given. It only supports
/// positional arguments for now, but a future version should add support
/// for named arguments.
///
/// These additional arguments may have any type that implements
/// the [`DisplayBytes`] trait.
///
/// # Examples
///
/// ```
/// use format_bytes::format_bytes;
///
/// assert_eq!(format_bytes!(b""), b"");
/// assert_eq!(format_bytes!(b"here"), b"here");
/// assert_eq!(format_bytes!(b"this {{ escapes {{"), b"this {{ escapes {{");
/// assert_eq!(format_bytes!(b"also this {{}}"), b"also this {{}}");
/// assert_eq!(format_bytes!(b"this works {{{}}}", b"a"), b"this works {{a}}");
/// assert_eq!(
/// format_bytes!(b"look at those {} bytes", &[0u8, 1, 2]),
/// b"look at those \x00\x01\x02 bytes"
/// );
///
/// let bytes = vec![0u8, 1, 2];
///
/// assert_eq!(
/// format_bytes!(b"look at those {} bytes", bytes),
/// b"look at those \x00\x01\x02 bytes"
/// );
/// assert_eq!(
/// format_bytes!(b"{}.{}.{}.{}", 1_i32, 2_u8, 3_f32, &4),
/// b"1.2.3.4"
/// );
/// assert_eq!(
/// format_bytes!(b"what about this very very long message {}?", "here".as_bytes()),
/// b"what about this very very long message here?".to_vec()
/// );
/// assert_eq!(format_bytes!(b"{}", std::borrow::Cow::Borrowed("cow".as_bytes())), b"cow");
/// ```
pub use _write_bytes;
/// Like [`format_bytes!`], but writes to a stream given as an additional first argument.
///
/// The stream is an expression of any type that implements the [`DisplayBytes`] trait.
/// The macro returns [`std::io::Result<()>`](std::io::Result).
///
/// # Examples
///
/// ```
/// use format_bytes::write_bytes;
///
/// const BUFFER_LEN: usize = 20;
/// let mut buffer = [0_u8; BUFFER_LEN];
/// let mut slice = &mut buffer[..];
///
/// write_bytes!(&mut slice, b"{}", 3.14).unwrap();
///
/// // `impl std::io::Write for &mut [u8]` reassigns the slice to the unwritten remainder:
/// let written = BUFFER_LEN - slice.len();
/// assert_eq!(&buffer[..written], b"3.14");
/// ```
/// Let types decide how to format themselves for presentation to users in a byte-stream output.
///
/// Similar to `std::fmt::Display`, but the output stream is bytes instead of Unicode.
///
/// When output is presented to users, it is decoded with an unspecified character encoding
/// that is presumed to be ASCII-compatible.
///
/// Implementers should return any error from `output` (e.g. with the `?` operator),
/// and not emit other errors.
///
/// # Example
///
/// A typical `impl` for a struct with multiple fields might use the `write_bytes` macro:
///
/// ```
/// use format_bytes::{DisplayBytes, write_bytes};
///
/// struct Point2D { x: f32, y: f32 }
///
/// impl DisplayBytes for Point2D {
/// fn display_bytes(
/// &self,
/// out: &mut dyn std::io::Write,
/// ) -> std::io::Result<()> {
/// write_bytes!(out, b"x = {}, y = {}", self.x, self.y)
/// }
/// }
/// ```
impl_through_deref!
/// Forward to the inner type.
impl_for_byte_string!;
impl_for_arrays!
/// Adaptor for types that implement `std::fmt::Display`. The Unicode output is encoded as UTF-8.
///
/// # Example
///
/// ```rust
/// use format_bytes::{format_bytes, Utf8};
///
/// assert_eq!(format_bytes!(b"{}", Utf8("è_é")), b"\xc3\xa8_\xc3\xa9");
/// ```
;
impl_ascii_only!
/// Format a sequence of values with the given separator repeated
/// between any two consecutive values, but not at the start or end of the sequence.
///
/// The return value can be formatted with `DisplayBytes` *once*.
/// Formatting consumes the input iterator. Formatting again will produce an empty output.
///
/// # Example
///
/// ```
/// use format_bytes::{format_bytes, join};
///
/// let formatted = format_bytes!(b"Got {}.", join(&[4, 3, 2], b" and "));
/// assert_eq!(formatted, b"Got 4 and 3 and 2.");
/// ```