Trait core::ops::Shift

pub trait Shift {
    /// Bit shift left by an amount.
    ///
    /// # Arguments
    ///
    /// * `other`: [u64] - The amount to bit shift by.
    ///
    /// # Returns
    ///
    /// * [Self] - The result of the value bit shifted to the left.
    ///
    /// # Examples
    ///
    /// ```sway
    /// struct MyStruct {
    ///     val: u64,
    /// }
    ///
    /// impl Shift for MyStruct {
    ///     fn lsh(self, other: u64) -> Self {
    ///         let val = self.val << other;
    ///         Self {
    ///             val
    ///         }
    ///     }
    /// }
    ///
    /// fn foo() {
    ///     let struct1 = MyStruct { val: 10 };
    ///     let result_struct = struct1 << 3;
    ///     assert(result_struct.val == 80);
    /// }
    /// ```
    fn lsh(self, other: u64) -> Self;
    /// Bit shift right by an amount.
    ///
    /// # Arguments
    ///
    /// * `other`: [u64] - The amount to bit shift by.
    ///
    /// # Returns
    ///
    /// * [Self] - The result of the value bit shifted to the right.
    ///
    /// # Examples
    ///
    /// ```sway
    /// struct MyStruct {
    ///     val: u64,
    /// }
    ///
    /// impl Shift for MyStruct {
    ///     fn rsh(self, other: u64) -> Self {
    ///         let val = self.val >> other;
    ///         Self {
    ///             val
    ///         }
    ///     }
    /// }
    ///
    /// fn foo() {
    ///     let struct1 = MyStruct { val: 10 };
    ///     let result_struct = struct1 >> 1;
    ///     assert(result_struct.val == 5);
    /// }
    /// ```
    fn rsh(self, other: u64) -> Self;
}
Expand description

Trait to bit shift a value.

Required Methods

Bit shift left by an amount.

Arguments

  • other: [u64] - The amount to bit shift by.

Returns

  • [Self] - The result of the value bit shifted to the left.

Examples

struct MyStruct {
    val: u64,
}

impl Shift for MyStruct {
    fn lsh(self, other: u64) -> Self {
        let val = self.val << other;
        Self {
            val
        }
    }
}

fn foo() {
    let struct1 = MyStruct { val: 10 };
    let result_struct = struct1 << 3;
    assert(result_struct.val == 80);
}

Bit shift right by an amount.

Arguments

  • other: [u64] - The amount to bit shift by.

Returns

  • [Self] - The result of the value bit shifted to the right.

Examples

struct MyStruct {
    val: u64,
}

impl Shift for MyStruct {
    fn rsh(self, other: u64) -> Self {
        let val = self.val >> other;
        Self {
            val
        }
    }
}

fn foo() {
    let struct1 = MyStruct { val: 10 };
    let result_struct = struct1 >> 1;
    assert(result_struct.val == 5);
}