hello/src/lib.rs

93 lines2,303 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Greet people from the command line1//! Greetings.
2
Extract argument parsing into parse_args in lib.rs3/// Parsed command-line options.
4#[derive(Debug, Default, PartialEq, Eq)]
5pub struct Options {
6 /// The name to greet, if one was given.
7 pub name: Option<String>,
8}
9
10/// Parses command-line arguments (excluding the program name).
11///
12/// Arguments starting with `--` are treated as flags and skipped; the name is
13/// the first remaining argument.
14pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Options {
15 let name = args.into_iter().find(|arg| !arg.starts_with("--"));
16 Options { name }
17}
18
Greet people from the command line19/// The greeting for `name`.
20pub fn greeting(name: &str) -> String {
Handle empty and whitespace-only names, trim whitespace from input21 let trimmed = name.trim();
22 let display_name = if trimmed.is_empty() { "world" } else { trimmed };
23 format!("Hello, {display_name}!")
Greet people from the command line24}
25
Add farewell function alongside greeting26/// The farewell for `name`.
27pub fn farewell(name: &str) -> String {
28 let trimmed = name.trim();
29 let display_name = if trimmed.is_empty() { "world" } else { trimmed };
30 format!("Goodbye, {display_name}!")
31}
32
Greet people from the command line33#[cfg(test)]
34mod tests {
35 use super::*;
36
Extract argument parsing into parse_args in lib.rs37 fn args(list: &[&str]) -> Vec<String> {
38 list.iter().map(|s| s.to_string()).collect()
39 }
40
41 #[test]
42 fn parse_args_no_args() {
43 assert_eq!(parse_args(args(&[])).name, None);
44 }
45
46 #[test]
47 fn parse_args_name() {
48 assert_eq!(parse_args(args(&["Ada"])).name.as_deref(), Some("Ada"));
49 }
50
51 #[test]
52 fn parse_args_skips_leading_flag() {
53 assert_eq!(
54 parse_args(args(&["--unknown", "Ada"])).name.as_deref(),
55 Some("Ada")
56 );
57 }
58
Greet people from the command line59 #[test]
60 fn greets_by_name() {
61 assert_eq!(greeting("Ada"), "Hello, Ada!");
62 }
Handle empty and whitespace-only names, trim whitespace from input63
64 #[test]
65 fn greets_world_with_empty_string() {
66 assert_eq!(greeting(""), "Hello, world!");
67 }
68
69 #[test]
70 fn greets_world_with_whitespace_only() {
71 assert_eq!(greeting(" "), "Hello, world!");
72 }
73
74 #[test]
75 fn trims_whitespace_from_name() {
76 assert_eq!(greeting(" Ada "), "Hello, Ada!");
77 }
Add farewell function alongside greeting78
79 #[test]
80 fn says_goodbye_by_name() {
81 assert_eq!(farewell("Ada"), "Goodbye, Ada!");
82 }
83
84 #[test]
85 fn says_goodbye_to_world_when_blank() {
86 assert_eq!(farewell(" "), "Goodbye, world!");
87 }
88
89 #[test]
90 fn farewell_trims_whitespace() {
91 assert_eq!(farewell(" Ada "), "Goodbye, Ada!");
92 }
Greet people from the command line93}