1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! ## Smart-Read
//! 
//! Complex but easy ways to read user input
//! 
//! <br>
//! 
//! ### Anything that implements the `TryRead` trait can be used with smart-read's macros, and many implementations are already given
//! 
//! <br>
//! <br>
//! 
//! ## Types that implement TryRead:
//! 
//! <br>
//! 
//! ### Basics
//! 
//! ```
//! impl TryRead for ()
//! impl TryRead for NonEmptyInput
//! impl TryRead for NonWhitespaceInput
//! impl TryRead for Fn(&str) -> Result<(), String>
//! impl TryRead for BoolInput
//! impl TryRead for YesNoInput
//! impl TryRead for CharInput
//! impl TryRead for UsizeInput
//! impl TryRead for IsizeInput
//! impl TryRead for U8Input, U16Input, U32Input, U64Input, U128Input
//! impl TryRead for I8Input, I16Input, I32Input, I64Input, I128Input
//! impl TryRead for F32Input
//! impl TryRead for F64Input
//! ```
//! 
//! <br>
//! 
//! ### List Constraints
//! 
//! These allow you to specify which inputs are allowed. Example: `read!(&["a", "b", "c"])`
//! 
//! If the choices are wrapped in EnumerateInput, it returns the index of the chosen option
//! 
//! Special syntax: `read!(= 1, 2, 3)`
//! 
//! Implemented types:
//! ```
//! impl<T: Display + Clone + PartialEq> TryRead for &[T]
//! impl<T: Display + Clone + PartialEq> TryRead for &[T; _]
//! impl<T: Display + Clone + PartialEq> TryRead for Vec<T>
//! impl<T: Display + Clone + PartialEq> TryRead for VecDeque<T>
//! impl<T: Display + Clone + PartialEq> TryRead for LinkedList<T>
//! impl<T: Display + Clone + PartialEq> TryRead for EnumerateInput<&[T]>
//! impl<T: Display + Clone + PartialEq> TryRead for EnumerateInput<&[T; _]>
//! impl<T: Display + Clone + PartialEq> TryRead for EnumerateInput<Vec<T>>
//! impl<T: Display + Clone + PartialEq> TryRead for EnumerateInput<VecDeque<T>>
//! impl<T: Display + Clone + PartialEq> TryRead for EnumerateInput<LinkedList<T>>
//! ```
//! 
//! <br>
//! 
//! ### Range Constraints
//! 
//! These allow you to take a number within a specified range. Example: `read!(1. .. 100.)`, or `read!(10..)`, etc
//! 
//! Implemented types:
//! ```
//! impl<T: Display + FromStr + PartialOrd<T>> TryRead for Range<T>
//! impl<T: Display + FromStr + PartialOrd<T>> TryRead for RangeInclusive<T>
//! impl<T: Display + FromStr + PartialOrd<T>> TryRead for RangeTo<T>
//! impl<T: Display + FromStr + PartialOrd<T>> TryRead for RangeFrom<T>
//! impl<T: Display + FromStr + PartialOrd<T>> TryRead for RangeToInclusive<T>
//! ```
//! 
//! <br>
//! <br>
//! 
//! ## Extra Functionality:
//! 
//! In addition to the type of input, data can be added at the start of `read!()` / `prompt!()`. In order, these additions are:
//! 
//! <br>
//! 
//! ### Prompt Message
//! 
//! `prompt_value;` (only available with prompt!())
//! 
//! <br>
//! 
//! ### Custom Input
//! 
//! `input >>` (must implement crate's `IntoInput`)
//! 
//! <br>
//! 
//! ### Default Value
//! 
//! `[default_value]`
//! 
//! <br>
//! 
//! #### Example: &nbsp; `prompt!("Enter a color: "; prev_user_input >> ["red"] = "red", "green", "blue")`
//! 
//! <br>
//! <br>
//! 
//! If you have ideas for more functionality (including things that you've found to be useful for yourself), feel free to open an issue
//! 
//! <br>
//! <br>



#![feature(let_chains)]
#![allow(clippy::tabs_in_doc_comments)]
#![warn(clippy::todo, clippy::unwrap_used)]

use std::{error::Error, io::{Read, Write}};



/// Contains implementations for `()`, `UsizeInput`, `NonEmptyInput`, etc
pub mod basics;
/// Contains implementations for `Vec<T>`, `read!(= a, b, c)`, etc
pub mod list_constraints;
/// Contains implementations for `Range<T>`, `RangeFrom<T>`, etc
pub mod range_constraints;

/// Easy way to use existing functionality. If you want to extend functionality instead, you can do `use smart_read::*;`
pub mod prelude {
	pub use super::{
		read,
		try_read,
		prompt,
		try_prompt,
		basics::*,
		list_constraints::*,
		range_constraints::*,
	};
}





// ================================ Macros ================================ //



/// ## Reads a line of text, a number, etc
#[macro_export]
macro_rules! read {
	($($args:tt)*) => {
		smart_read::try_read!($($args)*).unwrap()
	}
}

/// Same as read!(), but returns a result
#[macro_export]
macro_rules! try_read {
	
	($($args:tt)*) => {{|| -> smart_read::BoxResult<_> {
		use smart_read::{TryRead, parse_input_arg, stdin_as_input};
		let args = parse_input_arg!($($args)*);
		let (read_args, readline_struct) = args.finalize();
		readline_struct.try_read_line(read_args)
	}()}};
	
}



/// Same as read!(), but also prints a prompt
#[macro_export]
macro_rules! prompt {
	($($args:tt)*) => {
		smart_read::try_prompt!($($args)*).unwrap()
	}
}

/// Same as prompt!(), but returns a result
#[macro_export]
macro_rules! try_prompt {
	
	($prompt:expr) => {smart_read::try_prompt!($prompt;)};
	
	($prompt:expr; $($args:tt)*) => {{|| -> smart_read::BoxResult<_> {
		use smart_read::{TryRead, parse_input_arg, stdin_as_input};
		let mut args = parse_input_arg!($($args)*);
		args.set_prompt = Some($prompt.to_string());
		let (read_args, readline_struct) = args.finalize();
		readline_struct.try_read_line(read_args)
	}()}};
	
}



#[macro_export]
#[doc(hidden)]
macro_rules! parse_input_arg {
	
	() => {{
		use smart_read::MacroArgs;
		let mut output = MacroArgs::default();
		output.set_readline_struct = Some(());
		output
	}};
	
	($input:tt >> $($args:tt)*) => {{
		use smart_read::{Input, IntoInput, MacroArgs, parse_default_arg};
		smart_read::MacroArgs {
			set_input: Some($input.into_input()),
			set_prompt: None,
			set_default: None,
			set_readline_struct: None,
		}.extend(parse_default_arg!($($args)*))
	}};
	
	($($args:tt)*) => {smart_read::parse_default_arg!($($args)*)}
	
}



#[macro_export]
#[doc(hidden)]
macro_rules! parse_default_arg {
	
	() => {{
		use smart_read::MacroArgs;
		let mut output = MacroArgs::default();
		output.set_readline_struct = Some(());
		output
	}};
	
	([$default:expr] $($args:tt)*) => {{
		use smart_read::{MacroArgs, parse_final_args};
		smart_read::MacroArgs {
			set_input: None,
			set_prompt: None,
			set_default: Some($default.into()),
			set_readline_struct: None,
		}.extend(parse_final_args!($($args)*))
	}};
	
	($($args:tt)*) => {smart_read::parse_final_args!($($args)*)}
	
}



#[macro_export]
#[doc(hidden)]
macro_rules! parse_final_args {
	
	() => {{
		let mut output = smart_read::MacroArgs::default();
		output.set_readline_struct = Some(());
		output
	}};
	
	(= $($choice:expr),*) => {{
		let choices = vec!($($choice,)*);
		smart_read::MacroArgs {
			set_input: None,
			set_prompt: None,
			set_default: None,
			set_readline_struct: Some(choices),
		}
	}};
	
	($readline_struct:expr) => {{
		smart_read::MacroArgs {
			set_input: None,
			set_prompt: None,
			set_default: None,
			set_readline_struct: Some($readline_struct),
		}
	}}
	
}





// ================================ TYPES ================================ //



/// Just `Result<T, Box<dyn Error>>`, mostly for internal use
pub type BoxResult<T> = Result<T, Box<dyn Error>>;



/// This is what powers the whole crate. Any struct that implements this can be used with the macros
pub trait TryRead {
	type Output;
	fn try_read_line(&self, read_args: TryReadArgs<Self::Output>) -> BoxResult<Self::Output>;
}



/// This contains all possible information about the read / prompt
pub struct TryReadArgs<Output> {
	pub input: Input,
	pub prompt: Option<String>,
	pub default: Option<Output>,
}



/// Specifies the source of user input
/// 
/// If should_stop is None, it defaults to stopping once \n is read
/// 
/// If clean_output is None, it defaults to removing a trailing \n (if found) then a trailing \r (if found)
pub struct Input {
	pub iter: Box<dyn Iterator<Item = BoxResult<u8>>>,
	pub needs_std_flush: bool,
	pub should_stop: Option<fn(&[u8]) -> bool>,
	pub clean_output: Option<fn(Vec<u8>) -> Vec<u8>>,
}

impl Input {
	/// Needs to be called to prevent prints before the read appearing after the read
	pub fn flush_std_if_needed(&self) -> BoxResult<()>{
		if self.needs_std_flush {std::io::stdout().flush()?;}
		Ok(())
	}
}



/// Allows a type to be used as input. Example:
/// 
/// ```
/// pub struct TerminalInput;
/// impl IntoInput for TerminalInput {
/// 	...
/// }
/// 
/// read!(TerminalInput >>);
/// ```
pub trait IntoInput {
	fn into_input(self) -> Input;
}

impl<T: Into<String>> IntoInput for T {
	fn into_input(self) -> Input {
		Input {
			iter: Box::new(self.into().into_bytes().into_iter().map(Ok)),
			needs_std_flush: false,
			should_stop: None,
			clean_output: None,
		}
	}
}



#[doc(hidden)]
#[derive(Default)]
pub struct MacroArgs<Output, Struct: TryRead> {
	pub set_input: Option<Input>,
	pub set_prompt: Option<String>,
	pub set_default: Option<Output>,
	pub set_readline_struct: Option<Struct>,
}

impl<Output, Struct: TryRead> MacroArgs<Output, Struct> {
	pub fn extend(mut self, other: MacroArgs<Output, Struct>) -> Self {
		if other.set_input.is_some() {
			self.set_input = other.set_input;
		}
		if other.set_prompt.is_some() {
			self.set_prompt = other.set_prompt;
		}
		if other.set_default.is_some() {
			self.set_default = other.set_default;
		}
		if other.set_readline_struct.is_some() {
			self.set_readline_struct = other.set_readline_struct;
		}
		self
	}
	pub fn finalize(self) -> (TryReadArgs<Output>, Struct) {
		let read_data = TryReadArgs {
			input: match self.set_input {
				Some(v) => v,
				None => stdin_as_input(),
			},
			prompt: self.set_prompt,
			default: self.set_default,
		};
		(read_data, self.set_readline_struct.unwrap_or_else(|| panic!("Internal macro error, MacroArgs.set_readline_struct is None")))
	}
}





// ================================ FUNCTIONS ================================ //



/// Utility function, mostly for internal use
pub fn read_string(input: &mut Input) -> BoxResult<String> {
	
	fn default_should_stop(input: &[u8]) -> bool {input.last() == Some(&10)}
	let should_stop = input.should_stop.unwrap_or(default_should_stop);
	fn default_clean_output(mut output: Vec<u8>) -> Vec<u8> {
		if output.last() == Some(&10) {output.pop();} // pop \n
		if output.last() == Some(&13) {output.pop();} // pop \r
		output
	}
	let clean_output = input.clean_output.unwrap_or(default_clean_output);
	
	input.flush_std_if_needed()?;
	let mut output = vec!();
	loop {
		let Some(next) = input.iter.next() else {break};
		output.push(next?);
		if should_stop(&output) {break}
	}
	let output = clean_output(output);
	let output = String::from_utf8(output)?;
	
	Ok(output)
}



/// Utility function, mostly for internal use
pub fn stdin_as_input() -> Input {
	let output = std::io::stdin()
		.bytes()
		.map(|b|
			b.map_err(|e| Box::new(e) as Box<dyn Error>)
		);
	Input {
		iter: Box::new(output),
		needs_std_flush: true,
		should_stop: None,
		clean_output: None,
	}
}



/// Tiny utility function, clears the terminal output
pub fn clear_term() {
	print!("{esc}c", esc = 27 as char);
}