Skip to content

Commit 9070619

Browse files
committed
Add scenario file for the1Riddle (version 1)
1 parent 5e7114a commit 9070619

1 file changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* A program that takes a value, eg 1 and returns its type
3+
* plus other types
4+
*
5+
* Note: the program does not accept strings
6+
*
7+
* How to use:
8+
* rezzcode@linux$ rustc get_type.rs
9+
* rezzcode@linux$ ./get_type.rs 4
10+
*
11+
* 4 is of type i32: 4 bytes
12+
* Other types:
13+
* Size of char: 4 bytes
14+
* Size of u32: 4 bytes
15+
* Size of f64: 8 bytes
16+
*/
17+
18+
use std::env; // For accessing command-line arguments
19+
use std::mem; // For retrieving size of types in bytes
20+
21+
fn main() {
22+
// Collect command-line arguments into a vector
23+
let args: Vec<String> = env::args().collect();
24+
25+
// Ensure exactly one argument (besides program name) is provided
26+
if args.len() != 2 {
27+
eprintln!("Please pass in a value: Usage: {} <value>", args[0]);
28+
return;
29+
}
30+
31+
let input = &args[1]; // The input string to be parsed
32+
33+
// Try parsing input as i32
34+
if let Ok(value) = input.parse::<i32>() {
35+
println!("{value} is of type i32: {} bytes", mem::size_of::<i32>());
36+
print_other_types("i32");
37+
}
38+
// Try parsing input as u32
39+
else if let Ok(value) = input.parse::<u32>() {
40+
println!("{value} is of type u32: {} bytes", mem::size_of::<u32>());
41+
print_other_types("u32");
42+
}
43+
// Try parsing input as f64
44+
else if let Ok(value) = input.parse::<f64>() {
45+
println!("{value} is of type f64: {} bytes", mem::size_of::<f64>());
46+
print_other_types("f64");
47+
}
48+
// If parsing as number fails, check if it's a single character
49+
else if input.chars().count() == 1 {
50+
let c = input.chars().next().unwrap(); // Safe unwrap after count check
51+
println!("{c} is of type char: {} bytes", mem::size_of::<char>());
52+
print_other_types("char");
53+
}
54+
// If all parsing attempts fail, print an error
55+
else {
56+
println!("Could not determine type of input: {}", input);
57+
}
58+
}
59+
60+
// Print sizes of types excluding the one that matched
61+
fn print_other_types(exclude: &str) {
62+
println!("Other types:");
63+
if exclude != "char" {
64+
println!("Size of char: {} bytes", mem::size_of::<char>());
65+
}
66+
if exclude != "i32" {
67+
println!("Size of i32: {} bytes", mem::size_of::<i32>());
68+
}
69+
if exclude != "u32" {
70+
println!("Size of u32: {} bytes", mem::size_of::<u32>());
71+
}
72+
if exclude != "f64" {
73+
println!("Size of f64: {} bytes", mem::size_of::<f64>());
74+
}
75+
}

0 commit comments

Comments
 (0)