proc_strarray 1.7.0

Create const u8 array from str or byte str literal
Documentation
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
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
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
// Procedural macros collection for string operations.
//
// Copyright 2024 Radim Kolar <hsn@sendmail.cz>
// https://gitlab.com/hsn10/proc_strarray
//
// SPDX-License-Identifier: MIT OR Apache-2.0

#![forbid(unsafe_code)]
#![forbid(non_fmt_panics)]
#![deny(missing_docs)]
#![deny(rustdoc::missing_crate_level_docs)]
#![warn(rustdoc::missing_doc_code_examples)]
#![deny(rustdoc::invalid_codeblock_attributes)]
#![warn(rustdoc::broken_intra_doc_links)]
#![warn(rustdoc::private_intra_doc_links)]
#![warn(rustdoc::unescaped_backticks)]
#![allow(rustdoc::private_doc_tests)]
#![allow(unused_parens)]
#![allow(non_camel_case_types)]

//! Collection of procedural macros for str and bytestr operations.
//!
//! 1. generate const u8 array from str or bytestr literal
//! 1. repeat str or bytestr literal
//! 1. repeat str or bytestr literal as byte slice
//! 1. get length of str or bytestr literal
//! 1. generate byte slice from str or bytestr literal
//!
//! Macros have *0* variant which terminates str or bytestr literal with \\0

/* rust internal proc_macro API */
extern crate proc_macro;
use proc_macro::TokenStream;

/* importing syn + quote */
use syn::{parse_macro_input, LitByteStr, LitStr};
use syn::parse::{Parse, ParseStream};
use quote::quote;
use std::fmt;


//    str_array


/**
  Parsed arguments for str_array macro.
*/
#[derive(Debug)]
struct MacroArgumentsAR {
   /** name of generated array */
   id: String,
   /** source string or byte string */
   content: StrOrByte,
   /** length of source string, will be automatically determined if omitted */
   len: Option<usize>
}

impl Parse for MacroArgumentsAR {
   fn parse(input: ParseStream) -> syn::Result<Self> {
      use syn::Ident;
      use syn::Token;
      use syn::LitInt;
      let ident: Ident = input.parse()?;
      let _comma: Token![,] = input.parse()?;
      let payload: StrOrByte = input.parse()?;
      /* check if there is an optional string size specified as ",50" */
      let maybecomma: Result<Token![,],_> = input.parse();
      let maybesize: Result<LitInt,_> = input.parse();
      let maybeusizedlen =
      if maybesize.is_ok() && maybecomma.is_ok() {
         /* try to parse an optional length */
         maybesize.unwrap().base10_parse::<usize>()
      } else {
         Err(syn::Error::new(input.span(), "Failed to parse size as usize"))
      };
      match( maybeusizedlen ) {
         Err(e) =>
            if (maybecomma.is_ok()) {
              Err(e)
            } else {
               Ok(MacroArgumentsAR { id: ident.to_string(), content: payload, len: None })
            },
         Ok(expectedlen) => Ok(MacroArgumentsAR { id: ident.to_string(), content: payload, len: Some(expectedlen) })
      }
   }
}

/**
   Procedural macro `proc_strarray::str_array!` creates const u8 array
   from _str_ or _byte str_ literal.

   ### Usage
```rust
   // without specified length
   proc_strarray::str_array!(RESULT, "str literal");
   // with specified length
   proc_strarray::str_array!(RESULT2, "string", 6);
```
   ### Arguments
   1. name of created array
   1. str or byte str literal
   1. (optional) expected length of str literal. Length is only used
      for length check. It will not trim or extend an array.

   ### Example
```rust
    // This code will create const array of u8 named STRU from
    // content of "stru" str literal.
    use proc_strarray::str_array;
    // case 1: automatically determine array length.
    str_array!(STRU, "stru");
    // check if newly created array have length 4 and first character is 's'
    assert_eq!(STRU.len(), 4);
    assert_eq!(STRU[0], 's' as u8);
    // case 2: manually specify expected array length
    str_array!(STRU_len, "stru", 4);
    assert_eq!(STRU_len.len(), 4);
    // case 3: bytestr
    str_array!(STRU_byte, b"stru", 4);
    assert_eq!(STRU_byte.len(), 4);
```
*/
#[proc_macro]
pub fn str_array(tokens: TokenStream) -> TokenStream {
   let input: MacroArgumentsAR = parse_macro_input!(tokens as MacroArgumentsAR);
   let id = syn::Ident::new(&input.id, proc_macro2::Span::from(proc_macro::Span::call_site()));
   let u8s = input.content.as_bytes();
   let mut len = u8s.len();
   if let Some(expectedlen) = input.len {
      len = expectedlen;
   };

   proc_macro::TokenStream::from(
   quote! {
      const #id: [u8; #len] = [ #(#u8s),* ];
   })
}

/**
   Procedural macro `proc_strarray::str_array0!` creates *zero terminated*
   const u8 array from _str_ or _byte str_ literal.

   Macro is same as `str_array!` but it will append \\0 to result.
   Optional array length *must* include terminating \\0.

   ### See also
   - [`str_array!`](macro.str_array.html): Creates a non-zero terminated const u8 array from a str literal.
```rust
    // Create const array of u8 named STRU from content of "stru" str literal.
    use proc_strarray::str_array0;
    // case 1: without specifying length
    str_array0!(STRU, "stru");
    // check if created array have length 4 + 1 \\0 and first character is 's'
    assert_eq!(STRU.len(), 4+1);
    assert_eq!(STRU[0], 's' as u8);
    assert_eq!(STRU[4], 0);
    // case 2: with specifying length
    str_array0!(STRU2, "stru", 5);
    // check if newly created array have length 5
    assert_eq!(STRU.len(), 5);
    // case 3: bytestr
    str_array0!(STRU_byte, b"stru", 5);
    assert_eq!(STRU_byte.len(), 4 + 1);
```
*/
#[proc_macro]
pub fn str_array0(tokens: TokenStream) -> TokenStream {
   let input: MacroArgumentsAR = parse_macro_input!(tokens as MacroArgumentsAR);
   let id = syn::Ident::new(&input.id, proc_macro::Span::call_site().into());
   let u8s = input.content.add0().as_bytes();
   let mut len = u8s.len();
   if let Some(expectedlen) = input.len {
      len = expectedlen;
   };
   proc_macro::TokenStream::from(
   quote! {
            const #id: [ u8; #len ] = [ #(#u8s),* ];
   })
}


//    str_len


/**
   Procedural macro `proc_strarray::str_len!` returns length of str or
   byte str literal.

   ### See also
   - [`str_len0!`](macro.str_len0.html): returns length of zero terminated
   str or byte str literal.

   ### Example
```rust
    // Get length of str or byte str.
    use proc_strarray::str_len;
    const PMD85: usize = str_len!("PMD-85-2");
    assert_eq!(PMD85, 8);
    const IQ151: usize = str_len!(b"IQ-151");
    assert_eq!(IQ151, 6);
```
*/
#[proc_macro]
pub fn str_len(tokens: TokenStream) -> TokenStream {
   let input = parse_macro_input!(tokens as StrOrByte);
   let len = input.as_bytes().len();
   proc_macro::TokenStream::from(
   quote! {
      #len
   })
}

/**
   Procedural macro `proc_strarray::str_len0!` returns length of
   *zero terminated* str or byte str literal.

   ### See also
   - [`str_len!`](macro.str_len.html): returns length of str literal.

   ### Example
```rust
    // This code will create const usize and assign length of supplied string to it.
    use proc_strarray::str_len0;
    const PMD85: usize = str_len0!("PMD-85");
    assert_eq!(PMD85, 7);
    const IQ151: usize = str_len0!(b"IQ-151");
    assert_eq!(IQ151, 6+1);
```
*/
#[proc_macro]
pub fn str_len0(tokens: TokenStream) -> TokenStream {
   let input = parse_macro_input!(tokens as StrOrByte);
   let len = 1 + input.as_bytes().len();

   proc_macro::TokenStream::from(
   quote! {
      #len
   })
}


//    str_repeat


/** holds LitStr or LitByteStr */
enum StrOrByte {
   str(LitStr),
   byte(LitByteStr)
}

impl fmt::Debug for StrOrByte {
   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
      match self {
         StrOrByte::str(lit_str) => write!(f, "Str({:?})", lit_str.value()),
         StrOrByte::byte(lit_byte_str) => write!(f, "Byte({:?})", std::str::from_utf8(&lit_byte_str.value()).map_err(|_| fmt::Error)?),
      }
   }
}

impl PartialEq<StrOrByte> for StrOrByte {
   fn eq(&self, other: &Self) -> bool {
      match (self, other) {
         (StrOrByte::str(a), StrOrByte::str(b)) => a.value() == b.value(),
         (StrOrByte::byte(a), StrOrByte::byte(b)) => a.value() == b.value(),
          _ => false,
       }
   }
}

impl PartialEq<&str> for StrOrByte {
   fn eq(&self, other: &&str) -> bool {
      match self {
         StrOrByte::str(lit_str) => lit_str.value() == *other,
         _ => false
      }
   }
}

impl PartialEq<&[u8]> for StrOrByte {
   fn eq(&self, other: &&[u8]) -> bool {
      match self {
         StrOrByte::byte(lit_byte) => lit_byte.value() == *other,
         _ => false
      }
   }
}

impl Parse for StrOrByte {
   fn parse(input: ParseStream) -> syn::Result<Self> {
      if input.peek(LitStr) {
         let lit_str: LitStr = input.parse()?;
         Ok(StrOrByte::str(lit_str))
      } else {
         let lit_bytestr: LitByteStr = input.parse()?;
         Ok(StrOrByte::byte(lit_bytestr))
      }
   }
}

impl quote::ToTokens for StrOrByte {
   fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
      match self {
         StrOrByte::str(lit_str) => lit_str.to_tokens(tokens),
         StrOrByte::byte(lit_byte_str) => lit_byte_str.to_tokens(tokens),
      }
   }
}

impl StrOrByte {
    fn repeat(&self, times: usize) -> Self {
        match self {
            StrOrByte::str(lit_str) => {
                let repeated = lit_str.value().repeat(times);
                StrOrByte::str(LitStr::new(&repeated, lit_str.span()))
            },
            StrOrByte::byte(lit_byte_str) => {
                let repeated_bytes = lit_byte_str.value().repeat(times);
                StrOrByte::byte(LitByteStr::new(&repeated_bytes, lit_byte_str.span()))
            },
        }
    }
    fn add0(&self) -> Self {
        match self {
            StrOrByte::str(lit_str) => {
                let with_null = format!("{}\0", lit_str.value());
                StrOrByte::str(LitStr::new(&with_null, lit_str.span()))
            },
            StrOrByte::byte(lit_byte_str) => {
                let mut with_null = lit_byte_str.value().clone();
                with_null.push(0 as u8);
                StrOrByte::byte(LitByteStr::new(&with_null, lit_byte_str.span()))
            },
        }
    }
    fn as_bytes(&self) -> Vec<u8> {
        match self {
            StrOrByte::str(lit_str) => lit_str.value().as_bytes().to_vec(),
            StrOrByte::byte(lit_byte_str) => lit_byte_str.value()
      }
   }
}

#[derive(Debug)]
struct MacroArgumentsRP {
   content: StrOrByte,
   times: usize
}

impl Parse for MacroArgumentsRP {
   fn parse(input: ParseStream) -> syn::Result<Self> {
      use syn::Token;
      use syn::LitInt;
      let payload: StrOrByte = input.parse()?;
      let _comma: Token![,] = input.parse()?;
      let times: usize = input.parse::<LitInt>()?.base10_parse::<usize>()?;
      Ok(MacroArgumentsRP { content: payload, times })
   }
}

/**
   Procedural macro `proc_strarray::str_repeat!` repeats str or byte str
   literal n times.

   ### Arguments
   1. str or byte str literal
   1. unsigned number of repetitions

```rust
    // This code will repeat string "AB" 4 times.
    use proc_strarray::str_repeat;
    const S: &str = str_repeat!("AB", 4);
    assert_eq!(S.len(), 8);
    assert_eq!(S, "ABABABAB");
    // repeat byte str
    const B: &[u8] = str_repeat!(b"zx", 4);
    assert_eq!(B.len(), 8);
    assert_eq!(B, b"zxzxzxzx");
```
*/
#[proc_macro]
pub fn str_repeat(tokens: TokenStream) -> TokenStream {
   let input: MacroArgumentsRP = parse_macro_input!(tokens as MacroArgumentsRP);
   let payload = input.content.repeat(input.times);

   proc_macro::TokenStream::from(
   quote! {
     #payload
   })
}

/**
   Procedural macro `proc_strarray::str_repeat0!` repeats str or bytestr
   literal n times and adds zero termination.

```rust
    // This code will repeat string "AB" 2 times.
    use proc_strarray::str_repeat0;
    const S: &str = str_repeat0!("AB", 2);
    assert_eq!(S.len(), 5);
    assert_eq!(S.chars().take(4).collect::<String>(), "ABAB");
    assert_eq!(S.chars().nth(4).unwrap(), 0 as char);
    // repeat byte str
    const B: &[u8] = str_repeat0!(b"zx", 2);
    assert_eq!(B.len(), 5);
    assert_eq!(B, b"zxzx\0");
```
*/
#[proc_macro]
pub fn str_repeat0(tokens: TokenStream) -> TokenStream {
   let input: MacroArgumentsRP = parse_macro_input!(tokens as MacroArgumentsRP);
   let payload = input.content.repeat(input.times).add0();

   proc_macro::TokenStream::from(
   quote! {
     #payload
   })
}

//    str_repeat_bytes

/**
   Procedural macro `proc_strarray::str_repeat_bytes!` repeats str or byte str
   literal as byte slice.

   Arguments are same as `str_repeat!` only returned type is byte slice.

   ### See also
   - [`str_repeat!`](macro.str_repeat.html): repeat str or bytestr literal.

```rust
    // This code will repeat string "AB" 2 times.
    use proc_strarray::str_repeat_bytes;
    const S: &[u8] = str_repeat_bytes!("AB", 2);
    assert_eq!(S.len(), 4);
    assert_eq!(S, b"ABAB");
```
*/
#[proc_macro]
pub fn str_repeat_bytes(tokens: TokenStream) -> TokenStream {
   let input: MacroArgumentsRP = parse_macro_input!(tokens as MacroArgumentsRP);
   let bytes = input.content.repeat(input.times).as_bytes();

   proc_macro::TokenStream::from(
   quote! { &[#(#bytes),*] }
   )
}

/**
   Procedural macro `proc_strarray::str_repeat_bytes0!` repeats str or byte str
   literal as byte slice with added \\0.

   Arguments are same as `str_repeat0!` only returned type is byte slice.

   ### See also
   - [`str_repeat!`](macro.str_repeat.html): repeat str or bytestr literal.
   - [`str_repeat0!`](macro.str_repeat0.html): repeat str or bytestr literal
     with added \\0

```rust
    // This code will repeat string "AB" 2 times.
    use proc_strarray::str_repeat_bytes0;
    const S: &[u8] = str_repeat_bytes0!("AB", 2);
    assert_eq!(S.len(), 5);
    assert_eq!(S, b"ABAB\0");
```
*/
#[proc_macro]
pub fn str_repeat_bytes0(tokens: TokenStream) -> TokenStream {
   let input: MacroArgumentsRP = parse_macro_input!(tokens as MacroArgumentsRP);
   let bytes = input.content.repeat(input.times).add0().as_bytes();

   proc_macro::TokenStream::from(
   quote! { &[#(#bytes),*] }
   )
}

/**
Convert string or bytestring literals to byte slice.

```rust
use proc_strarray::str_bytes;
const A: &[u8] = str_bytes!("A");
const B: &[u8] = str_bytes!(b"A");
assert_eq!(A.len(),1);
assert_eq!(B.len(),1);
```
*/
#[proc_macro]
pub fn str_bytes(tokens: TokenStream) -> TokenStream {
   let input = parse_macro_input!(tokens as StrOrByte);
   let bytes = input.as_bytes();
   proc_macro::TokenStream::from(
   quote! { &[#(#bytes),*] }
   )
}

/**
Convert string or byte string literals to zero terminated byte slice.

```rust
use proc_strarray::str_bytes0;
const A: &[u8] = str_bytes0!("A");
const B: &[u8] = str_bytes0!(b"A");
assert_eq!(A.len(),2);
assert_eq!(B.len(),2);
```
*/
#[proc_macro]
pub fn str_bytes0(tokens: TokenStream) -> TokenStream {
   let input = parse_macro_input!(tokens as StrOrByte);
   let bytes = input.add0().as_bytes();
   proc_macro::TokenStream::from(
   quote! { &[#(#bytes),*] }
   )
}

#[cfg(test)]
#[path= "./macro_tests.rs"]
mod tests;

#[cfg(test)]
#[path= "./macro_parseAR_tests.rs"]
mod ARparsetests;

#[cfg(test)]
#[path= "./macro_parseRP_tests.rs"]
mod RPparsetests;

#[cfg(test)]
#[path= "./macro_strorbyte_tests.rs"]
mod SoBparsetests;

#[cfg(doctest)]
#[path= "./macro_sized_tests.rs"]
mod sizedtests;

#[cfg(doctest)]
#[path= "./macro_0sized_tests.rs"]
mod zerosizedtests;