aj_io_tools/input.rs
1//! Copyright 2023 Dallas
2//!
3//! Licensed under the Apache License, Version 2.0 (the "License");
4//! you may not use this file except in compliance with the License.
5//! You may obtain a copy of the License at
6//!
7//! <http://www.apache.org/licenses/LICENSE-2.0>
8//!
9//! Unless required by applicable law or agreed to in writing, software
10//! distributed under the License is distributed on an "AS IS" BASIS,
11//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//! See the License for the specific language governing permissions and
13//! limitations under the License.
14
15use std::io::{stdin, stdout, Write};
16use std::str::FromStr;
17
18/// Scans the input to the console by first
19/// printing an invitation message to the console.
20///
21/// # Params
22/// * `message: &str` - Invitation message
23/// to the console.
24///
25/// # Returns
26/// * [`String`] object.
27///
28/// # Panics
29/// If somehow failed to read line with
30/// `stdin().read_line()` function.
31///
32/// # Examples
33/// ```
34/// use aj_io_tools::read_line;
35///
36/// let input = read_line("What's your name: ");
37///
38/// match input.as_str() {
39/// "Aleksey" => println!("You're Aleksey, glad to hear you!"),
40/// _ => println!("You're not Aleksey, but anuway I'm glad to hear you!")
41/// }
42/// ```
43pub fn read_line(message: &str) -> String {
44 print!("{message}");
45
46 stdout()
47 .flush()
48 .unwrap();
49
50 let mut input = String::new();
51
52 stdin()
53 .read_line(&mut input)
54 .expect("failed to read line.");
55
56 input.trim()
57 .to_owned()
58}
59
60/// Scans the input to the console by first
61/// printing an invitation message to the console
62/// and finally parsing it into a specific type,
63/// declared in turbofish.
64///
65/// # Params
66/// * `message: &str` - Invitation message
67/// to the console.
68///
69/// # Returns
70/// * Turbofish typed (`T`) object.
71///
72/// # Panics
73/// If somehow failed to read line with
74/// `stdin().read_line()` function.
75///
76/// # Examples
77/// ```
78/// use aj_io_tools::read_line_as;
79///
80/// let input = read_line_as::<u8>("How old are you: ");
81///
82/// match input {
83/// 23 => println!("Wow, your life is just starting!"),
84/// _ => println!("Wow, your life is just starting, but you're not 23!")
85/// }
86/// ```
87pub fn read_line_as<T: Default + FromStr>(message: &str) -> T {
88 let input = read_line(message);
89
90 match input.parse::<T>() {
91 Ok(n) => n,
92 Err(_) => T::default()
93 }
94}