blockchainparity-iosubstrate

How do you modify the bytes in a `Hash` in Parity Substrate?


Given some Hash value that is generated within a substrate runtime, how do I modify or access the individual bytes of that hash?


Solution

  • The Hash trait Output has the AsRef and AsMut traits which allows you to interact with the hash as a byteslice ([u8]):

    pub trait Hash: 'static + MaybeSerializeDebug + Clone + Eq + PartialEq {
        type Output: Member + MaybeSerializeDebug + AsRef<[u8]> + AsMut<[u8]>;
    
        // ... removed for brevity
    }
    

    Using the as_ref() or as_mut() on a hash will return a slice of bytes which you can use as normal:

    For example:

    // Iterate over a hash
    let hash1 = <T as system::Trait>::Hashing::hash(1);
    for hash_byte in hash1.as_ref().iter() {
        // ... do something
    }
    

    or

    // Add one to the first byte of a hash
    let mut hash2 = <T as system::Trait>::Hashing::hash(2);
    hash2.as_mut()[0] += 1;