Conversation
KodrAus
left a comment
There was a problem hiding this comment.
I thought I'd just leave a bunch of comments around idioms you might find interesting.
| // | ||
| // Create new release entries | ||
| impl ReleaseEntry { | ||
| pub fn from_file(path: &str) -> Result<ReleaseEntry, Box<Error>> { |
There was a problem hiding this comment.
This could be fn from_file<P: AsRef<std::path::Path>>(path: P). That way we can accept anything that can be referenced as a Path, which includes owned and borrowed strings, paths and OS strings.
For reference, that's what the sig for File::open looks like.
| pub fn from_file(path: &str) -> Result<ReleaseEntry, Box<Error>> { | ||
| let mut sha256_sum = Sha256::new(); | ||
| { | ||
| let file = try!(File::open(path)); |
There was a problem hiding this comment.
There's a ? operator that can be used instead of the try! macro.
So this line could be let file = File::open(path)?;
|
|
||
| let p = Path::new(path); | ||
| let stat = try!(fs::metadata(path)); | ||
| let file = p.file_name().unwrap(); |
There was a problem hiding this comment.
Should be able to use ? instead of unwrapping.
There was a problem hiding this comment.
If P: AsRef<Path> then you could do p.as_ref().file_name()? and you could remove line 54.
|
|
||
| let mut ret = ReleaseEntry { | ||
| sha256: [0; 32], | ||
| filename_or_url: file.to_str().unwrap().to_owned(), |
| sha256: [0; 32], | ||
| filename_or_url: file.to_str().unwrap().to_owned(), | ||
| length: stat.len(), | ||
| version: Version::parse("0.0.0").unwrap(), |
| ret.sha256[i] = sha[i]; | ||
| } | ||
|
|
||
| return Ok(ret); |
There was a problem hiding this comment.
In Rust, the last expression statement in a block is the return. If that statement doesn't end with ; then its value is returned, otherwise () is.
So this could simply be Ok(ret).
If it was Ok(ret); then you'd get an error.
| // | ||
|
|
||
| impl ReleaseEntry { | ||
| fn sha256_to_string(&self) -> String { |
There was a problem hiding this comment.
I think this could be self.sha256.into_iter().map(|x| format!("{:02x}", x)).collect().
Because collect is magic.
| }); | ||
| } | ||
|
|
||
| fn escape_filename(&self) -> String { |
There was a problem hiding this comment.
Not sure how much you care about allocations here, but you might find the Cow type interesting. It would let you express a return type here that might be borrowed (in case SCHEME.is_match) or owned (in case it needs to be encoded).
It would basically look like:
fn escape_filename(&self) -> Cow<str> {
if match {
Cow::Borrowed(&self.filename_or_url)
} else {
Cow::Owned(utf8_percent_encode(&self.filename_or_url))
}
}
Finish up the methods from ReleaseEntry:
TODO: