File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Author : cyrixninja
2
+ // Octal to Binary Converter : Converts Octal to Binary
3
+ // Wikipedia References : 1. https://en.wikipedia.org/wiki/Octal
4
+ // 2. https://en.wikipedia.org/wiki/Binary_number
5
+
6
+ fn octal_to_binary ( octal_str : & str ) -> Result < String , & ' static str > {
7
+ let octal_str = octal_str. trim ( ) ;
8
+
9
+ if octal_str. is_empty ( ) {
10
+ return Err ( "Empty" ) ;
11
+ }
12
+
13
+ if !octal_str. chars ( ) . all ( |c| c >= '0' && c <= '7' ) {
14
+ return Err ( "Non-octal Value" ) ;
15
+ }
16
+
17
+ // Convert octal to binary
18
+ let binary = octal_str
19
+ . chars ( )
20
+ . map ( |c| match c {
21
+ '0' => "000" ,
22
+ '1' => "001" ,
23
+ '2' => "010" ,
24
+ '3' => "011" ,
25
+ '4' => "100" ,
26
+ '5' => "101" ,
27
+ '6' => "110" ,
28
+ '7' => "111" ,
29
+ _ => unreachable ! ( ) ,
30
+ } )
31
+ . collect :: < String > ( ) ;
32
+
33
+ Ok ( binary)
34
+ }
35
+
36
+ #[ cfg( test) ]
37
+ mod tests {
38
+ use super :: * ;
39
+
40
+ #[ test]
41
+ fn test_empty_string ( ) {
42
+ let input = "" ;
43
+ let expected = Err ( "Empty" ) ;
44
+ assert_eq ! ( octal_to_binary( input) , expected) ;
45
+ }
46
+
47
+ #[ test]
48
+ fn test_invalid_octal ( ) {
49
+ let input = "89" ;
50
+ let expected = Err ( "Non-octal Value" ) ;
51
+ assert_eq ! ( octal_to_binary( input) , expected) ;
52
+ }
53
+
54
+ #[ test]
55
+ fn test_valid_octal ( ) {
56
+ let input = "123" ;
57
+ let expected = Ok ( "001010011" . to_string ( ) ) ;
58
+ assert_eq ! ( octal_to_binary( input) , expected) ;
59
+ }
60
+
61
+ }
You can’t perform that action at this time.
0 commit comments