-3

bytes32是一种在 Vyper 中是 32 位宽的字节数组的类型。以下来自https://github.com/ethereum/vyper/blob/master/docs/types.rst#32-bit-wide-byte-array


32 位宽字节数组

关键字: bytes32 这是一个 32 位宽的字节数组,在其他方面类似于字节数组。

例子:

# Declaration
hash: bytes32
# Assignment
self.hash = _hash

运营商

====================================  ============================================================
Keyword                               Description
====================================  ============================================================
``len(x)``                            Return the length as an integer.
``sha3(x)``                           Return the sha3 hash as bytes32.
``concat(x, ...)``                    Concatenate multiple inputs.
``slice(x, start=_start, len=_len)``  Return a slice of ``_len`` starting at ``_start``.
====================================  ============================================================

其中x是字节数组,_start以及_len是整数值。


我想知道如何在 Rust 中创建这样的 bytes32 作为自定义类型。要创建自定义类型,您使用结构,它是一个数组,但我不确定定义数组的最佳方法是什么。我想过这样做:

struct Bytes32 {
    bytes32: [0b00000000; 4]
}

但这显然不是理想的,例如可读性,你必须使用一个特定的值,0b00000000.

4

1 回答 1

-1

您可以使用自定义struct.

我做了一个简单的例子。您应该调整它并为输入和输出制作一个包装器。

#[derive(Eq, PartialEq)]
struct Bytes32 {
    pub store: Vec<[u8; 4]>,
}

impl Ord for Bytes32 {
    fn cmp(&self, other: &Bytes32) -> Ordering {
        for _i in 0..3 {
            if other.store[_i] > self.store[_i] {
                return Ordering::Greater;
            }
            if other.store[_i] < self.store[_i] {
                return Ordering::Less;
            }
        }
        Ordering::Equal
    }
}

impl PartialOrd for Bytes32 {
    fn partial_cmp(&self, other: &Bytes32) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
于 2018-03-26T05:42:30.747 回答