Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust compare Option<Vec<u8>> with Option<&[u8]>

Tags:

rust

Is there an elegant way to compare Option<Vec<u8>> for equality with Option<&[u8]>? (Or equivalently with Result instead of Option.)

like image 702
Timmmm Avatar asked Oct 14 '19 10:10

Timmmm


Video Answer


2 Answers

Maybe it's suboptimal, but this code seems to compile:

fn cmp(first: Option<Vec<u8>>, second: Option<&[u8]>) -> bool {
    first.as_ref().map(Vec::as_ref) == second
}

Playground

There are two key transformations here:

  1. The first Option holds the owned value, the second - a reference. So we should go from Option<T> (or &Option<T>) to Option<&T>, and this is achieved using the as_ref method of Option.

  2. The first Option now holds &Vec<u8>, and we're going to compare it to &[u8]. This is handled again by the as_ref method, now defined on the AsRef<[u8]> trait and implemented on Vec.

like image 186
Cerberus Avatar answered Oct 21 '22 21:10

Cerberus


You just need to convert Option<Vec<u8>> to Option<&[u8]>, using as_ref() and Index trait:

fn foo(a: Option<Vec<u8>>, b: Option<&[u8]>) -> bool {
    a.as_ref().map(|x| &x[..]) == b
}

As of Rust 1.40, you can use as_deref():

fn foo(a: Option<Vec<u8>>, b: Option<&[u8]>) -> bool {
    a.as_deref() == b
}
like image 44
Stargateur Avatar answered Oct 21 '22 23:10

Stargateur