ruipacheco
ruipacheco

Reputation: 16402

How can I compare a slice to a byte string literal?

I have a method that tried to match a slice of [u8] to a number of byte string literals:

pub(crate) fn from_slice(slice: &[u8]) -> Option<SqlStateCode> {
    match slice {
      b"3030303030" => Some(SqlStateCode::SuccessfulCompletion),
      b"3031303030" => Some(SqlStateCode::Warning),
      b"3031303043" => Some(SqlStateCode::DynamicResultSetsReturned),
      _=> None
    }
}

Except it won't work unless I replace the byte string literal with an array:

[30, 31, 30, 30, 43] => Some(SqlStateCode::DynamicResultSetsReturned)

Is there a way to make this work with the literal?

Upvotes: 1

Views: 1069

Answers (1)

Skgland
Skgland

Reputation: 982

Your byte string literals are incorrect; the byte sting literal b"3031303043" does not correspond to the slice [30, 31, 30, 30, 43] but rather to the slice [51, 48, 51, 49, 51, 48, 51, 48, 52, 51].

This is because each character in the literal is replaced with its ASCII value in the slice.

The corresponding byte string literal for [30, 31, 30, 30, 43] using hex escape sequences for the control characters would be b"\x1E\x1F\x1E\x1E+".

Upvotes: 6

Related Questions