frewsxcv / rust-crates-index

Rust library for retrieving and interacting with the crates.io index
https://docs.rs/crates-index/
Apache License 2.0
72 stars 37 forks source link

Support: How do I convert a checksum into a String? #43

Closed UebelAndre closed 4 years ago

UebelAndre commented 4 years ago

I have the following code and am trying to return the checksum as a String but cannot figure it out. Would anyone know how to do this?

pub fn fetch_crate_checksum(index_url: &String, name: &String, version: &String) -> Result<String> {
  let index = crates_index::BareIndex::from_url(index_url.as_str())?;

  let crate_index = index
    .open_or_clone()?
    .crate_(name)
    .ok_or(anyhow!("Failed to find crate '{}' in index", name))?;

  let crate_version = crate_index
    .versions()
    .iter()
    .enumerate()
    .find(|(_, ver)| ver.version() == version)
    .ok_or(anyhow!(
      "Failed to find version {} for crate {}",
      version,
      name
    ))?
    .1;

   // crate_version.checksum() <- TODO
}
kornelski commented 4 years ago

Use the hex crate.

UebelAndre commented 4 years ago

Thanks!! This is the function I wrote

pub fn fetch_crate_checksum(index_url: &String, name: &String, version: &String) -> Result<String> {
  let index = crates_index::BareIndex::from_url(index_url.as_str())?;

  let crate_index = index
    .open_or_clone()?
    .crate_(name)
    .ok_or(anyhow!("Failed to find crate '{}' in index", name))?;

  let crate_version = crate_index
    .versions()
    .iter()
    .enumerate()
    .find(|(_, ver)| ver.version() == version)
    .ok_or(anyhow!(
      "Failed to find version {} for crate {}",
      version,
      name
    ))?
    .1;

  Ok(crate_version.checksum().to_vec()[..].to_hex())
}

In case anyone is interested in the future 😄

kornelski commented 4 years ago

You can skip .to_vec() part. You only need to change fixed-width array to a slice.

UebelAndre commented 4 years ago

Oh cool! Thanks for the tip and sorry for posting a newb question 😅 for some reason I couldn't wrap my head around the representation of checksum().