Skip to main content

Width

Struct Width 

Source
pub struct Width(/* private fields */);
Expand description

A bit width in 1..=512. Invalid widths cannot be constructed.

Implementations§

Source§

impl Width

Source

pub const MAX_BITS: u16 = 512

The largest supported width.

Source

pub const W1: Width

1 bit (the width of comparisons and select conditions).

Source

pub const W8: Width

8 bits.

Source

pub const W16: Width

16 bits.

Source

pub const W32: Width

32 bits.

Source

pub const W64: Width

64 bits.

Source

pub const W128: Width

128 bits.

Source

pub const W256: Width

256 bits.

Source

pub const W512: Width

512 bits.

Source

pub const fn new(bits: u16) -> Result<Width, WidthError>

A width of bits bits, if bits is in 1..=512.

Examples found in repository?
examples/valeria_rule_audit.rs (line 26)
7fn main() {
8    let strategy = if std::env::args().any(|a| a == "--deobfuscate") {
9        Strategy::deobfuscate()
10    } else {
11        Strategy::standard()
12    };
13    let engine = Engine::builder()
14        .builtin()
15        .strategy(strategy)
16        .build()
17        .unwrap();
18    let mut invalid = false;
19    for line in io::stdin().lock().lines() {
20        let line = line.unwrap();
21        let fields: Vec<_> = line.split('\t').collect();
22        if fields.len() != 4 {
23            panic!("expected id/width/input/reference");
24        }
25        let mut cx = Context::new();
26        let options = ParseOptions::width(Width::new(fields[1].parse().unwrap()).unwrap());
27        let result = (|| -> Result<_, Box<dyn std::error::Error>> {
28            let input = cx.parse(fields[2], &options)?;
29            let reference = cx.parse(fields[3], &options)?;
30            let before = cx.tree_size(input)?;
31            if !agrees(&mut cx, &[input, reference])? {
32                return Ok((
33                    "invalid-reference",
34                    before,
35                    before,
36                    cx.tree_size(reference)?,
37                    cx.display(input).to_string().replace(['\n', '\t'], " "),
38                    cx.display(reference).to_string().replace(['\n', '\t'], " "),
39                ));
40            }
41            let output = engine.simplify(&mut cx, input)?.expr;
42            let want = engine.simplify(&mut cx, reference)?.expr;
43            let after = cx.tree_size(output)?;
44            let target = cx.tree_size(want)?;
45            let status = if !agrees(&mut cx, &[input, reference, output, want])? {
46                "invalid-output"
47            } else if output == want {
48                "covered"
49            } else if after > target {
50                "gap"
51            } else {
52                "different-form"
53            };
54            Ok((
55                status,
56                before,
57                after,
58                target,
59                cx.display(output).to_string().replace(['\n', '\t'], " "),
60                cx.display(want).to_string().replace(['\n', '\t'], " "),
61            ))
62        })();
63        match result {
64            Ok((status, before, after, target, output, want)) => {
65                invalid |= status.starts_with("invalid-");
66                println!(
67                    "{}\t{}\t{status}\t{before}\t{after}\t{target}\t{output}\t{want}",
68                    fields[0], fields[1]
69                );
70            }
71            Err(error) => {
72                invalid = true;
73                println!(
74                    "{}\t{}\terror\t{}",
75                    fields[0],
76                    fields[1],
77                    error.to_string().replace(['\n', '\t'], " ")
78                );
79            }
80        }
81    }
82    if invalid {
83        std::process::exit(1);
84    }
85}
Source

pub const fn bits(self) -> u16

The number of bits.

Examples found in repository?
examples/valeria_rule_audit.rs (line 96)
88fn agrees(cx: &mut Context, roots: &[bitwright::Expr]) -> Result<bool, bitwright::Error> {
89    for seed in 0..32_u64 {
90        let env = FnEnv(|key: &SymbolKey, width: Width| {
91            let mut state = format!("{key:?}")
92                .bytes()
93                .fold(seed.wrapping_mul(0x9e3779b97f4a7c15), |state, byte| {
94                    state.wrapping_mul(0x100000001b3) ^ u64::from(byte)
95                });
96            let limbs: Vec<_> = (0..width.bits().div_ceil(64))
97                .map(|_| {
98                    state = state.wrapping_add(0x9e3779b97f4a7c15);
99                    let mut value = state;
100                    value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
101                    value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb);
102                    value ^ (value >> 31)
103                })
104                .collect();
105            Some(match seed {
106                0 => BitVec::zero(width),
107                1 => BitVec::ones(width),
108                _ => BitVec::wrapping_from_limbs(width, &limbs),
109            })
110        });
111        let values = cx.eval(roots, &env)?;
112        if values.iter().any(|v| *v != values[0]) {
113            return Ok(false);
114        }
115    }
116    Ok(true)
117}
Source

pub const fn is_narrow(self) -> bool

Whether values of this width use the native (<= 128 bits) fast path.

Trait Implementations§

Source§

impl Clone for Width

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Width

Source§

impl Debug for Width

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Width

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Width

Source§

impl Hash for Width

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Width

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for Width

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for Width

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl StructuralPartialEq for Width

Source§

impl TryFrom<u16> for Width

Source§

type Error = WidthError

The type returned in the event of a conversion error.
Source§

fn try_from(bits: u16) -> Result<Self, WidthError>

Performs the conversion.

Auto Trait Implementations§

§

impl Freeze for Width

§

impl RefUnwindSafe for Width

§

impl Send for Width

§

impl Sync for Width

§

impl Unpin for Width

§

impl UnsafeUnpin for Width

§

impl UnwindSafe for Width

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.