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
//! Crate v_escape provides a macro, `new!` that define a `struct` with
//! escaping functionality. These macros are optimized using simd by default,
//! but this can be alter using sub-attributes.
//!
//! # Quick start
//! In order to use v_escape you will have to call one of the two macros
//! to create a escape `struct`. In this example, when using the macro
//! `new!(MyEscape, "62->bar");` a new a `struct` `MyEscape`
//! will be created that every time its method `MyEscape::fmt` is called
//! will replace all characters `">"` with `"bar"`.
//!
//! ```
//! v_escape::new!(MyEscape; 62 -> "bar");
//!
//! # fn main() {
//! # let s = "foo>bar";
//! let escaped = escape(s);
//!
//! print!("{}", escaped);
//! # }
//! ```
//!
//! ## Pairs syntax
//! v_escape uses a simple syntax to replace characters
//! with their respective quotes. The tuple is named `Pair`,
//! and several can be defined, referred as `Pairs`. The syntax to define
//! `Pairs` consists of a character, followed
//! by the delimiter `->`, followed by the substitution quote
//! and the delimiter ` || ` (last delimiter is optional):
//!
//!    `([character]->[quote], )*`
//!
//! * `character` :   Character to substitute. Accepts`i8+` from `0` to `i8::MAX` and
//!                 accepts the following formats: decimal (49), hexadecimal (0x31),
//!                 octal (0o61) or character (#1).
//!                 Note: Numbers are read in ASCII: `#6->foo`
//!
//! * `quote` :   Characters that will replace `character`
//!
//! ```
//! v_escape::new!(MyEscape; 49 -> "bar");
//! # fn main() {
//! assert_eq!(escape("foo 1").to_string(), "foo bar");
//! # }
//! ```
//! ```
//! v_escape::new!(MyEscape; 0x31 -> "bar");
//! # fn main() {
//! assert_eq!(escape("foo 1").to_string(), "foo bar");
//! # }
//! ```
//! ```
//! v_escape::new!(MyEscape; 0o61 -> "bar");
//! # fn main() {
//! assert_eq!(escape("foo 1").to_string(), "foo bar");
//! # }
//! ```
//! ```
//! v_escape::new!(MyEscape; '1' -> "bar");
//! # fn main() {
//! assert_eq!(escape("foo 1").to_string(), "foo bar");
//! # }
//! ```
//!
//! In the following example more than 16 pairs are given, this exceeds simd's
//! boundary. If simd optimization is wanted, ranges must be enabled (default)
//! or an error will be thrown. It is possible to not use ranges but simd
//! optimization has to be disabled.
//!
//! ```
//! v_escape::new!(
//!     MyEscape;
//!     62->"b",  60->"f",  'B'->"b",  65->"f",  0o67->"b",  '6'->"f",  68->"b",
//!     71->"f",  72->"b",  73->"f",  74->"b",  75->"f",  76->"b",  77->"f",
//!     78->"b",  79->"f",  0x1A->"f"
//! );
//! # fn main() {
//! assert_eq!(escape("foo>bar<").to_string(), "foobbarf");
//! # }
//! ```
//!
//! For debugging purposes, sub-attribute `print`, can be set to `true`
//! to print generated code
//!
//! ```
//! v_escape::new!(MyEscape; 'o' -> "bar"; print = true);
//! # fn main() {
//! # assert_eq!(escape("foo").to_string(), "fbarbar");
//! # }
//! ```
//!
#![allow(unused_imports)]

pub use buf_min::Buffer;
pub use v_escape_derive::derive;

#[macro_use]
mod macros;
#[macro_use]
mod scalar;
#[macro_use]
mod ranges;
#[macro_use]
mod chars;

#[macro_export]
/// Generates struct `$name` with escaping functionality at `fmt`
///
/// It will get as input:
///
/// * $__name__: Name of escape class.
///
/// * $__pairs__: Pairs of `[character]->[quote] || [character]->[quote]` or
///              `[character]->[quote]`.
///
/// * $__t__: Optional boolean parameters (simd, avx, sse, print).
///     * __simd__:  If true (by default), simd optimizations are enabled. When false,
///         no matter value of avx, `sse4.2` will be used,
///     * __avx__:   If true (by default), avx optimization are enabled. When false,
///         `sse2`(if `ranges=true` and `simd=true`) or `scalar`(if `simd=false`) will be used.
///     * __ranges__:   If true (by default), ranges optimizations are enabled. When false,
///         `sse4.2`(if `simd=true`) or `scalar`(if `simd=false`) will be used.
///     * __print__: If true (false by default), prints out generated code to console.
///
/// and will:
///
/// 1. Import `std::fmt::{self, Display, Formatter}`
///
/// 2. Define basic struct with attribute `bytes` and `Escape`
///    derive functionality
///
/// 3. Implements for `$name` constructors `new` and `From<&'a str>`
///
/// 4. Implements trait `Display` for `$name` with escape functionality
///
/// 5. Implements function `escape(&str) -> $name`
///
/// #### Example
///
/// ```
/// v_escape::new!(MyEscape; 'o' -> "bar");
///
/// # fn main() {
/// assert_eq!(escape("foobar").to_string(), "fbarbarbar");
/// # }
/// ```
///
macro_rules! new {
    // Macro called without attributes
    ($name:ident; $($t:tt)+) => {
        $crate::derive!($($t)+);
        $crate::escape_new!($name);
    };
}

#[macro_export]
#[doc(hidden)]
/// Escape implementation
///
/// Generates function new, and traits From and Display, for class `$name`
macro_rules! escape_new {
    ($name:ident) => {
        pub struct $name<'a> {
            bytes: &'a [u8],
        }

        impl<'a> $name<'a> {
            #[inline]
            pub fn new(bytes: &[u8]) -> $name {
                $name { bytes }
            }

            #[inline]
            pub fn f_escape(&self, buf: &mut [std::mem::MaybeUninit<u8>]) -> Option<usize> {
                #[allow(unused_unsafe)]
                unsafe {
                    _f_escape(self.bytes, buf)
                }
            }
        }

        impl<'a> From<&'a str> for $name<'a> {
            #[inline]
            fn from(s: &str) -> $name {
                $name {
                    bytes: s.as_bytes(),
                }
            }
        }

        #[inline]
        pub fn escape(s: &str) -> $name {
            $name::from(s)
        }

        impl<'a> std::fmt::Display for $name<'a> {
            fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
                #[allow(unused_unsafe)]
                unsafe {
                    _escape(self.bytes, fmt)
                }
            }
        }

        #[inline]
        pub fn escape_char(c: char) -> impl std::fmt::Display {
            struct EscapeChar(char);

            impl std::fmt::Display for EscapeChar {
                fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
                    chars::escape_char(self.0, fmt)
                }
            }

            EscapeChar(c)
        }

        #[inline]
        pub fn f_escape(s: &[u8], buf: &mut [std::mem::MaybeUninit<u8>]) -> Option<usize> {
            #[allow(unused_unsafe)]
            unsafe {
                _f_escape(s, buf)
            }
        }

        #[inline]
        pub fn f_escape_char(c: char, buf: &mut [std::mem::MaybeUninit<u8>]) -> Option<usize> {
            #[allow(unused_unsafe)]
            unsafe {
                chars::f_escape_char(c, buf)
            }
        }

        /// Escape byte slice to `Buffer`
        ///
        /// # SIGILL
        /// Can produce **SIGILL** if compile with `sse2` or `avx2` and execute without they
        /// Because not exist way to build multiple static allocations by type
        /// And it's very expensive check it in runtime
        /// https://github.com/rust-lang/rust/issues/57775
        #[inline]
        pub fn b_escape<B: $crate::Buffer>(s: &[u8], buf: &mut B) {
            #[allow(unused_unsafe)]
            unsafe {
                _b_escape(s, buf)
            }
        }

        /// Escape char to `buf-min::Buffer`
        #[inline]
        pub fn b_escape_char<B: $crate::Buffer>(s: char, buf: &mut B) {
            #[allow(unused_unsafe)]
            unsafe {
                chars::b_escape_char(s, buf)
            }
        }
    };
}

#[macro_export]
#[doc(hidden)]
/// cfg_if for escape function
macro_rules! cfg_escape {
    (false, $($t:tt)+) => {
        $crate::cfg_escape!(fn);
    };
    (true, $($t:tt)+) => {
        #[cfg(target_arch = "x86_64")]
        #[inline(always)]
        // https://github.com/BurntSushi/rust-memchr/blob/master/src/x86/mod.rs#L9-L29
        fn _escape(bytes: &[u8], fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
            use std::mem;
            use std::sync::atomic::{AtomicUsize, Ordering};
            use std::fmt::{self, Formatter};
            static mut FN: fn(&[u8], &mut Formatter) -> fmt::Result = detect;

            fn detect(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result {
                let fun = $crate::cfg_escape!(if $($t)+);

                let slot = unsafe { &*(&FN as *const _ as *const AtomicUsize) };
                slot.store(fun, Ordering::Relaxed);
                unsafe {
                    mem::transmute::<usize, fn(&[u8], &mut Formatter) -> fmt::Result>(fun)(
                        bytes, fmt,
                    )
                }
            }

            unsafe {
                let slot = &*(&FN as *const _ as *const AtomicUsize);
                let fun = slot.load(Ordering::Relaxed);
                mem::transmute::<usize, fn(&[u8], &mut Formatter) -> fmt::Result>(fun)(bytes, fmt)
            }
        }

        #[cfg(not(target_arch = "x86_64"))]
        $crate::cfg_escape!(fn);
    };
    (fn) => {
        #[inline(always)]
        fn _escape(bytes: &[u8], fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
            scalar::escape(bytes, fmt)
        }
    };
    (if true) => {
        if is_x86_feature_detected!("avx2") {
            ranges::avx::escape as usize
        } else if is_x86_feature_detected!("sse2") {
            ranges::sse::escape as usize
        } else {
            scalar::escape as usize
        }
    };
    (if false) => {
        if is_x86_feature_detected!("sse2") {
            ranges::sse::escape as usize
        } else {
            scalar::escape as usize
        }
    };
}

#[macro_export]
#[doc(hidden)]
/// cfg_if for escape function
macro_rules! cfg_escape_ptr {
    (false, $($t:tt)+) => {
        $crate::cfg_escape_ptr!(fn);
    };
    (true, $($t:tt)+) => {
        #[cfg(target_arch = "x86_64")]
        #[inline(always)]
        #[allow(unreachable_code)]
        // https://github.com/BurntSushi/rust-memchr/blob/master/src/x86/mod.rs#L9-L29
        pub unsafe fn _f_escape(bytes: &[u8], buf: &mut [std::mem::MaybeUninit<u8>]) -> Option<usize> {
            use std::mem;
            use std::sync::atomic::{AtomicUsize, Ordering};
            static mut FN: fn(&[u8], &mut [std::mem::MaybeUninit<u8>]) -> Option<usize> = detect;

            fn detect(bytes: &[u8], buf: &mut [std::mem::MaybeUninit<u8>]) -> Option<usize> {
                let fun = $crate::cfg_escape_ptr!(if $($t)+);

                let slot = unsafe { &*(&FN as *const _ as *const AtomicUsize) };
                slot.store(fun, Ordering::Relaxed);
                unsafe {
                    mem::transmute::<usize, fn(&[u8], &mut [std::mem::MaybeUninit<u8>]) -> Option<usize>>(fun)(
                        bytes, buf,
                    )
                }
            }

            unsafe {
                let slot = &*(&FN as *const _ as *const AtomicUsize);
                let fun = slot.load(Ordering::Relaxed);
                mem::transmute::<usize, fn(&[u8], &mut [std::mem::MaybeUninit<u8>]) -> Option<usize>>(fun)(bytes, buf)
            }
        }

        #[cfg(not(target_arch = "x86_64"))]
        $crate::cfg_escape_ptr!(fn);
    };
    (fn) => {
        #[inline(always)]
        pub unsafe fn _f_escape(bytes: &[u8], buf: &mut [std::mem::MaybeUninit<u8>]) -> Option<usize> {
            scalar::f_escape(bytes, buf)
        }
    };
    (if true) => {
        if is_x86_feature_detected!("avx2") {
            ranges::avx::f_escape as usize
        } else if is_x86_feature_detected!("sse2") {
            ranges::sse::f_escape as usize
        } else {
            scalar::f_escape as usize
        }
    };
    (if false) => {
        if is_x86_feature_detected!("sse2") {
            ranges::sse::f_escape as usize
        } else {
            scalar::f_escape as usize
        }
    };
}

#[macro_export]
#[doc(hidden)]
/// cfg_if for escape function
macro_rules! cfg_escape_bytes {
    (false, $($t:tt)+) => {
        $crate::cfg_escape_bytes!(fn);
    };
    (true, $($t:tt)+) => {
        #[cfg(target_arch = "x86_64")]
        #[inline(always)]
        pub unsafe fn _b_escape<B: $crate::Buffer>(bytes: &[u8], buf: &mut B) {
            $crate::cfg_escape_bytes!(if $($t)+, bytes, buf)
        }

        #[cfg(not(all(target_arch = "x86_64", not(b_escape_nosimd))))]
        $crate::cfg_escape_bytes!(fn);
    };
    (fn) => {
        #[inline(always)]
        pub unsafe fn _b_escape<B: $crate::Buffer>(bytes: &[u8], buf: &mut B) {
            scalar::b_escape(bytes, buf)
        }
    };
    (if true, $bytes:ident, $buf:ident) => {{
        #[cfg(not(v_escape_avx))] {
            #[cfg(not(v_escape_sse))] {
                scalar::b_escape($bytes, $buf)
            }
            #[cfg(v_escape_sse)] {
                ranges::sse::b_escape($bytes, $buf)
            }
        }
        #[cfg(v_escape_avx)] {
            ranges::avx::b_escape($bytes, $buf)
        }
    }};
    (if false, $bytes:ident, $buf:ident) => {{
        #[cfg(not(v_escape_sse))] {
            scalar::b_escape($bytes, $buf)
        }
        #[cfg(v_escape_sse)] {
            ranges::sse::b_escape($bytes, $buf)
        }
    }};
}

#[cfg(doctest)]
mod test_readme {
    macro_rules! external_doc_test {
        ($x:expr) => {
            #[doc = $x]
            extern "C" {}
        };
    }

    external_doc_test!(include_str!("../../README.md"));
}