@@ -27,7 +27,7 @@ enum IntoColorError {
2727 IntConversion ,
2828}
2929
30- // I AM NOT DONE
30+
3131
3232// Your task is to complete this implementation and return an Ok result of inner
3333// type Color. You need to create an implementation for a tuple of three
@@ -41,20 +41,82 @@ enum IntoColorError {
4141impl TryFrom < ( i16 , i16 , i16 ) > for Color {
4242 type Error = IntoColorError ;
4343 fn try_from ( tuple : ( i16 , i16 , i16 ) ) -> Result < Self , Self :: Error > {
44+ let red : u8 = match tuple. 0 . try_into ( ) {
45+ Ok ( red) => red,
46+ Err ( _) => return Err ( Self :: Error :: IntConversion ) ,
47+ } ;
48+ let green: u8 = match tuple. 1 . try_into ( ) {
49+ Ok ( green) => green,
50+ Err ( _) => return Err ( Self :: Error :: IntConversion ) ,
51+ } ;
52+ let blue : u8 = match tuple. 2 . try_into ( ) {
53+ Ok ( blue) => blue,
54+ Err ( _) => return Err ( Self :: Error :: IntConversion ) ,
55+ } ;
56+ Ok (
57+ Color {
58+ red,
59+ green,
60+ blue
61+ }
62+ )
63+
4464 }
4565}
4666
4767// Array implementation
4868impl TryFrom < [ i16 ; 3 ] > for Color {
4969 type Error = IntoColorError ;
5070 fn try_from ( arr : [ i16 ; 3 ] ) -> Result < Self , Self :: Error > {
71+ let red : u8 = match arr[ 0 ] . try_into ( ) {
72+ Ok ( red) => red,
73+ Err ( _) => return Err ( Self :: Error :: IntConversion ) ,
74+ } ;
75+ let green: u8 = match arr[ 1 ] . try_into ( ) {
76+ Ok ( green) => green,
77+ Err ( _) => return Err ( Self :: Error :: IntConversion ) ,
78+ } ;
79+ let blue : u8 = match arr[ 2 ] . try_into ( ) {
80+ Ok ( blue) => blue,
81+ Err ( _) => return Err ( Self :: Error :: IntConversion ) ,
82+ } ;
83+ Ok (
84+ Color {
85+ red,
86+ green,
87+ blue
88+ }
89+ )
5190 }
5291}
5392
5493// Slice implementation
5594impl TryFrom < & [ i16 ] > for Color {
5695 type Error = IntoColorError ;
5796 fn try_from ( slice : & [ i16 ] ) -> Result < Self , Self :: Error > {
97+ if slice. len ( ) !=3 {
98+ return Err ( Self :: Error :: BadLen ) ;
99+ }
100+ let red : u8 = match slice[ 0 ] . try_into ( ) {
101+ Ok ( red) => red,
102+ Err ( _) => return Err ( Self :: Error :: IntConversion ) ,
103+ } ;
104+ let green: u8 = match slice[ 1 ] . try_into ( ) {
105+ Ok ( green) => green,
106+ Err ( _) => return Err ( Self :: Error :: IntConversion ) ,
107+ } ;
108+ let blue : u8 = match slice[ 2 ] . try_into ( ) {
109+ Ok ( blue) => blue,
110+ Err ( _) => return Err ( Self :: Error :: IntConversion ) ,
111+ } ;
112+ Ok (
113+ Color {
114+ red,
115+ green,
116+ blue
117+ }
118+ )
119+
58120 }
59121}
60122
0 commit comments