0

I'm using Sha256 to hash multiple values. A value can be an enum, I am wondering how I can hash it

use sha2::Sha256

enum EnumType{
  A,
  B,
  C { value: u8 }
}

let enum_value = EnumType::A;
let mut hasher = Sha256::new();

// How to hash the enum?
// hasher.update(enum_value);

hasher.finalize()

The simplest way would be to assign a constant value for each enum value, but this seems unclean

fn get_enum_value(value: &EnumType)-> &[u8]{
    match value {
        EnumType::A => &[1u8],
        EnumType::B => &[2u8],
        EnumType::C { value } => &[3u8, value]
    }
}

// ... //
hasher.update(get_enum_value(enum_value));
// ... //

Is there a better way?

Simon Tran
  • 1,461
  • 1
  • 11
  • 28

1 Answers1

1

Rust doesn't expose the memory layout of enums to the user, but Sha256 operates on a sequence of bytes, so at some point you have to specify how enums turn into bytes. You could do as you suggest and do it manually, or you could also use for example bincode or serde_json to serialize your structure for hashing.

lkolbly
  • 1,140
  • 2
  • 6