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
//! Crate v_escape provides two macros, `new_escape!` and `new_escape_sized!`,
//! that define a `struct` with escaping functionalities. 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_escape!(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"`.
//! ```
//! #[macro_use]
//! extern crate v_escape;
//!
//! new_escape_sized!(MyEscape, "62->bar");
//!
//! # fn main() {
//! # let s = "foo>bar";
//! let escaped = MyEscape::from(s);
//!
//! print!("#{} : {}", escaped.size(), escaped);
//! # }
//! ```
//!
//! To check if rust version has simd functionality. The following code
//! has to be added to file `build.rs`.
//!
//! ```ignore
//! use version_check::is_min_version;
//!
//! fn main() {
//! enable_simd_optimizations();
//! }
//!
//! fn enable_simd_optimizations() {
//! if !is_min_version("1.27.0").map_or(false, |(yes, _)| yes) {
//! println!("cargo:rustc-cfg=v_escape_nosimd");
//! }
//! }
//! ```
//!
//! ## 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, refered 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`
//!
//! ```
//! # #[macro_use]
//! # extern crate v_escape;
//! new_escape_sized!(MyEscape, "49->bar");
//! # fn main() {
//! assert_eq!(MyEscape::from("foo 1").to_string(), "foo bar");
//! # }
//! ```
//! ```
//! # #[macro_use]
//! # extern crate v_escape;
//! new_escape_sized!(MyEscape, "0x31->bar");
//! # fn main() {
//! assert_eq!(MyEscape::from("foo 1").to_string(), "foo bar");
//! # }
//! ```
//! ```
//! # #[macro_use]
//! # extern crate v_escape;
//! new_escape_sized!(MyEscape, "0o61->bar");
//! # fn main() {
//! assert_eq!(MyEscape::from("foo 1").to_string(), "foo bar");
//! # }
//! ```
//! ```
//! # #[macro_use]
//! # extern crate v_escape;
//! new_escape_sized!(MyEscape, "#1->bar");
//! # fn main() {
//! assert_eq!(MyEscape::from("foo 1").to_string(), "foo bar");
//! # }
//! ```
//!
//! The sub-attribute `sse`, true by default, can process a maximum
//! of 16 `Pairs`. If more `Pairs` are needed, sse optimizations has
//! to be deactivated using sub-attribute `sse = false`
//!
//! ```
//! # #[macro_use]
//! # extern crate v_escape;
//! new_escape_sized!(
//! MyEscape,
//! "62->b || 60->f || A->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",
//! sse = false
//! );
//! # fn main() {
//! assert_eq!(MyEscape::from("foo>bar<").to_string(), "foobbarf");
//! # }
//! ```
//!
//! Optimization for avx requires the creation of ranges. If the
//! distance between the escaped characters is very large,
//! sub-attribute `avx = false` should be disabled
//!
//! ```
//! # #[macro_use]
//! # extern crate v_escape;
//! new_escape!(MyEscape, "0-> || 33->foo || 66->bar || 127->", avx = false);
//! # fn main() {
//! assert_eq!(MyEscape::from("fooBbar").to_string(), "foobarbar");
//! # }
//! ```
//!
//! For debugging purposes, sub-attribute `print`, can be set to `true`
//! to print generated code
//!
//! ```
//! # #[macro_use]
//! # extern crate v_escape;
//! new_escape_sized!(MyEscape, "o->bar", print = true);
//! # fn main() {
//! # assert_eq!(MyEscape::from("foo").to_string(), "fbarbar");
//! # }
//! ```
//!
#![allow(unused_imports)]
use v_escape_derive::Escape;
#[macro_use]
mod loops;
#[macro_use]
mod macros;
#[macro_use]
mod scalar;
#[macro_use]
mod sse;
#[macro_use]
mod avx;
#[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, 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,
/// `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 fmt, Display and Formatter.
///
/// 2. Define basic struct with attribute `bytes` and escaping
/// derive functionality.
///
/// 3. Implements a constructor `new` and traits `Display` and
/// `From<&'a str>` to struct `$name` (using `_v_escape_escape_new` macro).
///
/// The generated struct `$name` can escape a string using function `from`
/// and can be displayed as in the example.
///
/// #### Example
///
/// ```
/// #[macro_use]
/// extern crate v_escape;
///
/// new_escape_sized!(MyEscape, "o->bar", print=true);
///
/// # fn main() {
/// # let s = "foobar";
/// let escaped = MyEscape::from(s);
///
/// print!("{}", escaped);
/// # }
/// ```
///
macro_rules! new_escape {
// Macro called without attributes
($name:ident, $pairs:expr) => {
use std::fmt::{self, Display, Formatter};
// Adding code generated by Derive with Escape and escape
#[derive(Escape)]
#[escape(pairs = $pairs)]
pub struct $name<'a> {
bytes: &'a [u8],
}
// Implementing function new and traits Display and From
_v_escape_escape_new!($name);
};
// Macro called with attributes
($name:ident, $pairs:expr, $($t:tt)+) => {
use std::fmt::{self, Display, Formatter};
// Adding code generated by Derive with Escape and escape
// passing attributes to function escape
#[derive(Escape)]
#[escape(pairs = $pairs, $($t)+)]
pub struct $name<'a> {
bytes: &'a [u8],
}
// Implementing function new and traits Display and From
_v_escape_escape_new!($name);
};
}
#[macro_export]
/// Generates struct `$name` with escaping functionality at `fmt` and `size` method
///
/// Not use with empty quote `"i8->"`
///
/// Follows same process as new_escape, but with a function
/// called size implemented at the end of the defined struct.
///
/// 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, print).
/// * __simd__: If true (by default), `simd` optimizations are enabled
/// (if `avx=true`) or `sse4.2` (if `avx=false`). When false,
/// `scalar` will be used.
/// * __avx__: Disabling `avx` optimizations (`true` by default).
/// * __sse__: Disabling `sse` optimizations (`true` by default).
/// * __print__: If `true` (`false` by default), prints out generated code to console.
///
/// | | `avx=true` | `avx=false` |
/// |--:|----------|-----------|
/// | __`simd=true`__ | `simd` (default) | `sse4.2` |
/// | __`simd=false`__ | `scalar` | `scalar` |
///
/// and will:
///
/// 1. Import `fmt`, `Display` and `Formatter`.
///
/// 2. Define basic struct with attribute `bytes` and escaping
/// derive functionality.
///
/// 3. Implements a constructor `new` and traits `Display` and
/// `From<&'a str>` to struct `$name` (using `_v_escape_escape_new` macro).
///
/// The generated struct `$name` can escape a string using function
/// `from` and the escaped string can be displayed as well as the
/// size of it as in the example:
///
///
/// ```
/// #[macro_use]
/// extern crate v_escape;
///
/// new_escape_sized!(MyEscape, "o->bar || ");
///
/// # fn main() {
/// # let s = "foo>bar";
/// let escaped = MyEscape::from(s);
///
/// print!("#{} : {}", escaped.size(), escaped);
/// # }
/// ```
///
macro_rules! new_escape_sized {
// Macro called without attributes
($name:ident, $pairs:expr) => {
use std::fmt::{self, Display, Formatter};
// Adding code generated by Derive with Escape and escape
#[derive(Escape)]
#[escape(pairs = $pairs, sized = true)]
pub struct $name<'a> {
bytes: &'a [u8],
}
// Implementing function new and traits Display and From
_v_escape_escape_new!($name);
// Implementing function size
impl<'a> $name<'a> {
pub fn size(&self) -> usize {
#[allow(unused_unsafe)]
unsafe {
_size(self.bytes)
}
}
}
};
// Macro called with attributes
($name:ident, $pairs:expr, $($t:tt)+) => {
use std::fmt::{self, Display, Formatter};
// Adding code generated by Derive with Escape and escape
// passing attributes to function escape
#[derive(Escape)]
#[escape(pairs = $pairs, sized = true, $($t)+)]
pub struct $name<'a> {
bytes: &'a [u8],
}
// Implementing function new and traits Display and From
_v_escape_escape_new!($name);
// Implementing function size
impl<'a> $name<'a> {
pub fn size(&self) -> usize {
#[allow(unused_unsafe)]
unsafe {
_size(self.bytes)
}
}
}
};
}
#[macro_export]
#[doc(hidden)]
/// Escape implementation
///
/// Generates function new, and traits From and Display, for class `$name`
macro_rules! _v_escape_escape_new {
($name:ident) => {
#[allow(dead_code)]
impl<'a> $name<'a> {
pub fn new(bytes: &[u8]) -> $name {
$name { bytes }
}
}
impl<'a> From<&'a str> for $name<'a> {
fn from(s: &str) -> $name {
$name {
bytes: s.as_bytes(),
}
}
}
#[inline]
pub fn escape(s: &str) -> $name {
$name::from(s)
}
impl<'a> Display for $name<'a> {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
#[allow(unused_unsafe)]
unsafe {
_escape(self.bytes, fmt)
}
}
}
};
}
#[macro_export]
#[doc(hidden)]
/// cfg_if for escape function
macro_rules! _v_escape_cfg_escape {
(false, $a:expr, $b:expr) => {
_v_escape_cfg_escape!(fn);
};
(true, false, false) => {
_v_escape_cfg_escape!(fn);
};
(true, $($t:tt)+) => {
#[cfg(all(
target_arch = "x86_64",
not(all(target_os = "windows", v_escape_nosimd))
))]
#[inline(always)]
// https://github.com/BurntSushi/rust-memchr/blob/master/src/x86/mod.rs#L9-L29
fn _escape(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result {
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
static mut FN: fn(&[u8], &mut Formatter) -> fmt::Result = detect;
fn detect(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result {
let fun = _v_escape_cfg_escape!(if $($t)+);
let slot = unsafe { &*(&FN as *const _ as *const AtomicUsize) };
slot.store(fun as usize, 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(all(
target_arch = "x86_64",
not(all(target_os = "windows", v_escape_nosimd))
)))]
_v_escape_cfg_escape!(fn);
};
(fn) => {
#[inline(always)]
fn _escape(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result {
scalar::escape(bytes, fmt)
}
};
(if false, true) => {
if is_x86_feature_detected!("sse4.2") {
sse::escape as usize
} else {
scalar::escape as usize
}
};
(if true, true) => {
if is_x86_feature_detected!("avx2") {
avx::escape as usize
} else if is_x86_feature_detected!("sse4.2") {
sse::escape as usize
} else {
scalar::escape as usize
}
};
(if true, false) => {
if is_x86_feature_detected!("avx2") {
avx::escape as usize
} else {
scalar::escape as usize
}
};
}
#[macro_export]
#[doc(hidden)]
/// cfg_if for size function
macro_rules! _v_escape_cfg_sized {
(false, $a:expr, $b:expr) => {
_v_escape_cfg_sized!(fn);
};
(true, false, false) => {
_v_escape_cfg_sized!(fn);
};
(true, $($t:tt)+) => {
#[cfg(all(
target_arch = "x86_64",
not(all(target_os = "windows", v_escape_nosimd))
))]
#[inline(always)]
// https://github.com/BurntSushi/rust-memchr/blob/master/src/x86/mod.rs#L9-L29
fn _size(bytes: &[u8]) -> usize {
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
static mut FN: fn(&[u8]) -> usize = detect;
fn detect(bytes: &[u8]) -> usize {
let fun = _v_escape_cfg_sized!(if $($t)+);
let slot = unsafe { &*(&FN as *const _ as *const AtomicUsize) };
slot.store(fun as usize, Ordering::Relaxed);
unsafe { mem::transmute::<usize, fn(&[u8]) -> usize>(fun)(bytes) }
}
unsafe {
let slot = &*(&FN as *const _ as *const AtomicUsize);
let fun = slot.load(Ordering::Relaxed);
mem::transmute::<usize, fn(&[u8]) -> usize>(fun)(bytes)
}
}
#[cfg(not(all(
target_arch = "x86_64",
not(all(target_os = "windows", v_escape_nosimd))
)))]
_v_escape_cfg_sized!(fn);
};
(fn) => {
#[inline(always)]
fn _size(bytes: &[u8]) -> usize {
scalar::size(bytes)
}
};
(if false, true) => {
if is_x86_feature_detected!("sse4.2") {
sse::size as usize
} else {
scalar::size as usize
}
};
(if true, true) => {
if is_x86_feature_detected!("avx2") {
avx::size as usize
} else if is_x86_feature_detected!("sse4.2") {
sse::size as usize
} else {
scalar::size as usize
}
};
(if true, false) => {
if is_x86_feature_detected!("avx2") {
avx::size as usize
} else {
scalar::size as usize
}
};
}