feat: Rewrite try_from_into (#393)

This commit is contained in:
IkaR49 2020-05-16 00:02:57 +03:00 committed by GitHub
parent d6c0a688e6
commit 763aa6e378
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 91 additions and 61 deletions

View File

@ -17,6 +17,7 @@ struct Person {
// 3. Extract the first element from the split operation and use it as the name // 3. Extract the first element from the split operation and use it as the name
// 4. If the name is empty, then return an error // 4. If the name is empty, then return an error
// 5. Extract the other element from the split operation and parse it into a `usize` as the age // 5. Extract the other element from the split operation and parse it into a `usize` as the age
// with something like `"4".parse::<usize>()`.
// If while parsing the age, something goes wrong, then return an error // If while parsing the age, something goes wrong, then return an error
// Otherwise, then return a Result of a Person object // Otherwise, then return a Result of a Person object
impl FromStr for Person { impl FromStr for Person {

View File

@ -5,98 +5,126 @@
use std::convert::{TryInto, TryFrom}; use std::convert::{TryInto, TryFrom};
#[derive(Debug)] #[derive(Debug)]
struct Person { struct Color {
name: String, red: u8,
age: usize, green: u8,
blue: u8,
} }
// I AM NOT DONE // I AM NOT DONE
// Your task is to complete this implementation // Your task is to complete this implementation
// in order for the line `let p = Person::try_from("Mark,20")` to compile // and return an Ok result of inner type Color.
// and return an Ok result of inner type Person. // You need create implementation for a tuple of three integer,
// Please note that you'll need to parse the age component into a `usize` // an array of three integer and slice of integer.
// with something like `"4".parse::<usize>()`. The outcome of this needs to
// be handled appropriately.
// //
// Steps: // Note, that implementation for tuple and array will be checked at compile-time,
// 1. If the length of the provided string is 0, then return an error // but slice implementation need check slice length!
// 2. Split the given string on the commas present in it // Also note, that chunk of correct rgb color must be integer in range 0..=255.
// 3. Extract the first element from the split operation and use it as the name
// 4. If the name is empty, then return an error. // Tuple implementation
// 5. Extract the other element from the split operation and parse it into a `usize` as the age impl TryFrom<(i16, i16, i16)> for Color {
// If while parsing the age, something goes wrong, then return an error
// Otherwise, then return a Result of a Person object
impl TryFrom<&str> for Person {
type Error = String; type Error = String;
fn try_from(s: &str) -> Result<Self, Self::Error> { fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
}
}
// Array implementation
impl TryFrom<[i16; 3]> for Color {
type Error = String;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
}
}
// Slice implementation
impl TryFrom<&[i16]> for Color {
type Error = String;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
} }
} }
fn main() { fn main() {
// Use the `from` function // Use the `from` function
let p1 = Person::try_from("Mark,20"); let c1 = Color::try_from((183, 65, 14));
// Since From is implemented for Person, we should be able to use Into println!("{:?}", c1);
let p2: Result<Person, _> = "Gerald,70".try_into();
println!("{:?}", p1); // Since From is implemented for Color, we should be able to use Into
println!("{:?}", p2); let c2: Result<Color, _> = [183, 65, 14].try_into();
println!("{:?}", c2);
let v = vec![183, 65, 14];
// With slice we should use `from` function
let c3 = Color::try_from(&v[..]);
println!("{:?}", c3);
// or take slice within round brackets and use Into
let c4: Result<Color, _> = (&v[..]).try_into();
println!("{:?}", c4);
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_bad_convert() { #[should_panic]
// Test that error is returned when bad string is provided fn test_tuple_out_of_range_positive() {
let p = Person::try_from(""); let _ = Color::try_from((256, 1000, 10000)).unwrap();
assert!(p.is_err());
}
#[test]
fn test_good_convert() {
// Test that "Mark,20" works
let p = Person::try_from("Mark,20");
assert!(p.is_ok());
let p = p.unwrap();
assert_eq!(p.name, "Mark");
assert_eq!(p.age, 20);
} }
#[test] #[test]
#[should_panic] #[should_panic]
fn test_panic_empty_input() { fn test_tuple_out_of_range_negative() {
let p: Person = "".try_into().unwrap(); let _ = Color::try_from((-1, -10, -256)).unwrap();
} }
#[test] #[test]
#[should_panic] fn test_tuple_correct() {
fn test_panic_bad_age() { let c: Color = (183, 65, 14).try_into().unwrap();
let p = Person::try_from("Mark,twenty").unwrap(); assert_eq!(c.red, 183);
assert_eq!(c.green, 65);
assert_eq!(c.blue, 14);
} }
#[test] #[test]
#[should_panic] #[should_panic]
fn test_missing_comma_and_age() { fn test_array_out_of_range_positive() {
let _: Person = "Mark".try_into().unwrap(); let _: Color = [1000, 10000, 256].try_into().unwrap();
}
#[test]
#[should_panic]
fn test_array_out_of_range_negative() {
let _: Color = [-10, -256, -1].try_into().unwrap();
}
#[test]
fn test_array_correct() {
let c: Color = [183, 65, 14].try_into().unwrap();
assert_eq!(c.red, 183);
assert_eq!(c.green, 65);
assert_eq!(c.blue, 14);
} }
#[test] #[test]
#[should_panic] #[should_panic]
fn test_missing_age() { fn test_slice_out_of_range_positive() {
let _: Person = "Mark,".try_into().unwrap(); let arr = [10000, 256, 1000];
let _ = Color::try_from(&arr[..]).unwrap();
} }
#[test] #[test]
#[should_panic] #[should_panic]
fn test_missing_name() { fn test_slice_out_of_range_negative() {
let _ : Person = ",1".try_into().unwrap(); let arr = [-256, -1, -10];
let _ = Color::try_from(&arr[..]).unwrap();
}
#[test]
fn test_slice_correct() {
let v = vec![183, 65, 14];
let c = Color::try_from(&v[..]).unwrap();
assert_eq!(c.red, 183);
assert_eq!(c.green, 65);
assert_eq!(c.blue, 14);
} }
#[test] #[test]
#[should_panic] #[should_panic]
fn test_missing_name_and_age() { fn test_slice_excess_length() {
let _: Person = ",".try_into().unwrap(); let v = vec![0, 0, 0, 0];
} let _ = Color::try_from(&v[..]).unwrap();
#[test]
#[should_panic]
fn test_missing_name_and_invalid_age() {
let _: Person = ",one".try_into().unwrap();
} }
} }

View File

@ -799,5 +799,6 @@ name = "from_str"
path = "exercises/conversions/from_str.rs" path = "exercises/conversions/from_str.rs"
mode = "test" mode = "test"
hint = """ hint = """
If you've already solved try_from_into.rs, then this is almost a copy-paste. The implementation of FromStr should return an Ok with a Person object,
Otherwise, go ahead and solve try_from_into.rs first.""" or an Err with a string if the string is not valid.
This is a some like an `try_from_into` exercise."""