### Examples for #[fastout] Source: https://docs.rs/proconio-derive/%5E0.2.0 Illustrates the usage of the `fastout` attribute macro to enable buffered stdout, which can significantly improve performance for programs with large amounts of output. The example shows how `print!` and `println!` behave with `fastout` enabled. ```rust use proconio_derive::fastout; #[fastout] fn main() { print!("{}{}, ", 'h', "ello"); // "hello" (no newline) println!("{}!", "world"); // "world!\n" println!("{}", 123456789); // "123456789\n" } ``` -------------------------------- ### input_interactive usage example Source: https://docs.rs/proconio/latest/proconio/macro.input_interactive.html Example of how to use the input_interactive macro, showing its similarity to the input! macro with a custom source. ```rust let source = procontio::source::line::LineSource::new(BufReader::new(std::io::stdin())); input! { from &mut source, (mut) variable: type, ... } ``` -------------------------------- ### Reading values from a source Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Example demonstrating how to read a specified number of values from a source and sum them up. ```rust #![allow(unused_imports)] use proconio::source::AutoSource; use proconio::read_value; let mut source = AutoSource::from("2 3 4"); let mut sum = 0; for _ in 0..read_value!(from &mut source, usize) { sum += read_value!(from &mut source, u32); } assert_eq!(sum, 7); ``` -------------------------------- ### read_value usage examples Source: https://docs.rs/proconio/latest/proconio/macro.read_value.html Examples demonstrating how to use the read_value macro to read input. ```rust let variable = read_value!(type); let variable = read_value!(with runtime_readable); // or let variable = read_value!(from source, type); let variable = read_value!(from source, with runtime_readable); ``` -------------------------------- ### Input Array Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates reading an array of fixed size and a 2D array using the `input!` macro. ```rust let source = AutoSource::from("5 3 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5"); input! { from source, n: usize, m: usize, a: [i32; n], b: [[i32; n]; m] // no trailing comma is OK } assert_eq!(a, [1, 2, 3, 4, 5]); assert_eq!(b, [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]); ``` -------------------------------- ### Input Tuple Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates reading tuples of a fixed size using the `read_value!` macro. ```rust let mut source = AutoSource::from("4 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5"); let n = read_value!(from &mut source, usize); let t = read_value!(from &mut source, [(i32, i32, i32, i32, i32); n]); assert_eq!( t, [ (1, 2, 3, 4, 5), (1, 2, 3, 4, 5), (1, 2, 3, 4, 5), (1, 2, 3, 4, 5) ] ); ``` -------------------------------- ### Input Usize1 Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates reading values as `Usize1` (1-based indexing) using the `input!` macro. ```rust use crate::marker::Usize1; let mut source = AutoSource::from("4 1 2 3 4 5 6 7 8"); input! { from &mut source, n: usize, } for i in 0..n { input! { from &mut source, from: Usize1, to: Usize1 } assert_eq!(from, i * 2); assert_eq!(to, i * 2 + 1); } ``` -------------------------------- ### Example of #[fastout] usage Source: https://docs.rs/proconio/%5E0.4.0 Demonstrates how to use the `#[fastout]` attribute on the main function to make `print!` and `println!` faster. ```rust use proconio::fastout; #[fastout] fn main() { print!("{}{}, ", 'h', "ello"); // "hello" (no newline) println!("{}!", "world"); // "world!\n" println!("{}", 123456789); // "123456789\n" } ``` -------------------------------- ### Example Usage of VecReadable Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates reading a vector of `Usize1` values after reading the count `n`. ```rust let mut source = AutoSource::from("4 1 2 3 4"); let n = read_value!(from &mut source, usize); let v = read_value!(from &mut source, with VecReadable::::new(n)); assert_eq!(v, [0, 1, 2, 3]); ``` -------------------------------- ### Input Mut Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates reading a mutable variable `n` and then using it in a loop to read other values. ```rust let mut source = AutoSource::from("8 1 2 3 4 5 6 7 8"); input! { from &mut source, mut n: usize, } let mut sum = 0; while n > 0 { input!(from &mut source, x: u32); sum += x; n -= 1; } assert_eq!(sum, 36); ``` -------------------------------- ### LineSource from &str Source: https://docs.rs/proconio/latest/proconio/source/line/struct.LineSource.html Example of creating a LineSource from a string slice by wrapping it in BufReader. ```rust fn from(s: &'a str) -> LineSource> ``` -------------------------------- ### Example of #[fastout] usage Source: https://docs.rs/proconio/latest/proconio/index.html Demonstrates the usage of the #[fastout] attribute on the main function to speed up print! and println! macros. ```rust use proconio::fastout; #[fastout] fn main() { print!("{}{}, ", 'h', "ello"); // "hello" (no newline) println!("{}!", "world"); // "world!\n" println!("{}", 123456789); // "123456789\n" } ``` -------------------------------- ### Basic usage of #[fastout] in main Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html This example demonstrates the basic usage of the `#[fastout]` attribute on the `main` function to enable fast output. It includes a spawned thread to show how output might be handled in concurrent scenarios. ```rust #! use proconio::fastout; # fn some_function(_: String) -> impl Iterator { vec!["hello".to_string(), "world".to_string()].into_iter() } # fn some_proc(x: &str) -> &str { x } #[fastout] fn main() { let context = "some context".to_string(); let thread = std::thread::spawn(move || { // Use many println! and the order is very important // It's possible to aggregate the result and print it later, but it's not easy to read // and seems ugly. println!("this is header."); for (i, item) in some_function(context).enumerate() { print!("Item #{}: ", i); print!("{}", some_proc(&item)); println!("({})", item); } }); thread.join().unwrap(); } ``` -------------------------------- ### Using AutoSource with input! Source: https://docs.rs/proconio/latest/proconio/source/index.html This example demonstrates how to use `AutoSource` to read input from a string literal. It shows how to specify the source to be used in the `input!` macro. ```rust use proconio::source::auto::AutoSource; use proconio::input; let source = AutoSource::from("32 54 -23"); input! { from source, n: u8, m: u32, l: i32, } println!("{} {} {}", n, m, l); assert_eq!(n, 32); assert_eq!(m, 54); assert_eq!(l, -23); ``` -------------------------------- ### Input Variable Length Array (VLA) Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates reading a variable length array (VLA) using the `input!` macro. ```rust let source = AutoSource::from("5 3 1 2 3 2 1 2 4 1 2 3 4 0 6 1 2 3 4 5 6"); input! { from source, n: usize, a: [[i32]; n], } assert_eq!( a, vec![ vec![1, 2, 3], vec![1, 2], vec![1, 2, 3, 4], vec![], vec![1, 2, 3, 4, 5, 6], ] ); ``` -------------------------------- ### RuntimeReadable Trait Example Source: https://docs.rs/proconio/latest/src/proconio/source/mod.rs.html An example demonstrating the implementation and usage of the RuntimeReadable trait to read a directed graph where the number of nodes and edges are determined at runtime. ```rust use proconio::source::RuntimeReadable; use proconio::source::auto::AutoSource; use proconio::source::Source; use proconio::input; use proconio::marker::Usize1; use std::io::BufRead; struct DirectedGraph(usize, usize); impl RuntimeReadable for DirectedGraph { type Output = Vec>; fn read>(self, source: &mut S) -> Self::Output { let DirectedGraph(n, m) = self; input! { from source, edges: [(Usize1, Usize1); m], }; let mut g = vec![vec![]; n]; for e in edges { g[e.0].push(e.1); } g } } let mut source = AutoSource::from("2 3\n1 1\n1 2\n2 2\n"); input! { from source, n: usize, m: usize, g: with DirectedGraph(n, m), } ``` -------------------------------- ### Input Min as Isize1 Panic Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates that reading `isize::MIN` as `Isize1` causes a panic. ```rust use crate::marker::Isize1; let min_string = isize::MIN.to_string(); let mut source = AutoSource::from(&*min_string); input! { from &mut source, _v: Isize1, } ``` -------------------------------- ### Read Value Array Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates reading an array of fixed size and a 2D array using the `read_value!` macro. ```rust let mut source = AutoSource::from("5 3 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5"); let n = read_value!(from &mut source, usize); let m = read_value!(from &mut source, usize); let a = read_value!(from &mut source, [i32; n]); let b = read_value!(from &mut source, [[i32; n]; m]); assert_eq!(a, [1, 2, 3, 4, 5]); assert_eq!(b, [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]); ``` -------------------------------- ### Input Multiple Times Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates using the `input!` macro multiple times within a loop to read data incrementally. ```rust let mut source = AutoSource::from("4 1 2 3 4\n1 2\r\n\r\n3 4"); input! { from &mut source, n: usize, } for i in 0..n { input! { from &mut source, j: i32, k: i32, } assert_eq!(j, if i % 2 == 0 { 1 } else { 3 }); assert_eq!(k, if i % 2 == 0 { 2 } else { 4 }); } ``` -------------------------------- ### Combined Types Source: https://docs.rs/proconio/%5E0.4.0 Example of combining different types, including arrays of tuples. ```rust use proconio::input; input! { n: usize, m: usize, t: [([u32; m], i32); n], } ``` -------------------------------- ### Input Zero as Usize1 Panic Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates that reading a zero value as `Usize1` causes a panic. ```rust use crate::marker::Usize1; let mut source = AutoSource::from("0"); input! { from &mut source, _v: Usize1, } ``` -------------------------------- ### Read Value Variable Length Array (VLA) Example Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates reading a variable length array (VLA) using the `read_value!` macro. ```rust let mut source = AutoSource::from("5 3 1 2 3 2 1 2 4 1 2 3 4 0 6 1 2 3 4 5 6"); let n = read_value!(from &mut source, usize); let a = read_value!(from &mut source, [[i32]; n]); assert_eq!( a, vec![ vec![1, 2, 3], vec![1, 2], vec![1, 2, 3, 4], vec![], vec![1, 2, 3, 4, 5, 6], ] ); ``` -------------------------------- ### Using #[fastout] on a separate function Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html This example shows how to apply `#[fastout]` to a separate function (`process`) that is called from `main`. This is a valid use case, but it highlights the potential for deadlocks if `#[fastout]` is also applied to the caller in a multithreaded context. ```rust # #[cfg(feature = "derive")] # { use proconio::fastout; # fn some_function(_: String) -> impl Iterator { vec!["hello".to_string(), "world".to_string()].into_iter() } # fn some_proc(x: &str) -> &str { x } // You can add #[fastout] here #[fastout] fn process(context: String) { // It's completely OK since this #[fastout] is a thing inside `process()` println!("this is header."); for (i, item) in some_function(context).enumerate() { print!("Item #{}: ", i); print!("{}", some_proc(&item)); println!("({})", item); } } // You must not add #[fastout] here! It causes deadlock. // #[fastout] fn main() { let context = "some context".to_string(); let thread = std::thread::spawn(move || process(context)); thread.join().unwrap(); } # } ``` -------------------------------- ### Example of printing order issue with #[fastout] Source: https://docs.rs/proconio/%5E0.4.0 This code snippet illustrates a potential issue with printing order when using #[fastout] and calling other functions between print statements. ```rust fn foo() { println!("between"); } #[fastout] fn main() { println!("hello"); foo(); println!("world"); } ``` -------------------------------- ### Deriving `Readable` with `#[derive_readable]` Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html An example of using `#[derive_readable]` to make custom structs like `Weight`, `Cost`, and `Edge` readable by the `input!` macro. ```rust # #[cfg(feature = "derive")] # { # extern crate proconio; use proconio::input; # use proconio::source::auto::AutoSource; use proconio::derive_readable; // Unit struct can derive readable. This generates a no-op for the reading. Not ignoring // the read value, but simply skip reading process. You cannot use it to discard the input. #[derive_readable] #[derive(PartialEq, Debug)] struct Weight; #[derive_readable] #[derive(PartialEq, Debug)] struct Cost(i32); #[derive_readable] #[derive(Debug)] struct Edge { from: usize, to: proconio::marker::Usize1, // The real Edge::to has type usize. weight: Weight, cost: Cost, } fn main() { # let source = AutoSource::from("12 32 35"); input! { # from source, edge: Edge, } // if you enter "12 32 35" to the stdin, the values are as follows. assert_eq!(edge.from, 12); assert_eq!(edge.to, 31); assert_eq!(edge.weight, Weight); assert_eq!(edge.cost, Cost(35)); } # } ``` -------------------------------- ### read_value! macro usage Source: https://docs.rs/proconio/latest/index.html Example demonstrating the direct usage of the read_value! macro, typically when the value does not need to be stored in a variable. ```rust use proconio::source::auto::AutoSource; use proconio::read_value; let mut source = AutoSource::from("2 3 4"); let mut sum = 0; for _ in 0..read_value!(from &mut source, usize) { sum += read_value!(from &mut source, u32); } assert_eq!(sum, 7); ``` -------------------------------- ### Examples for #[derive_readable] Source: https://docs.rs/proconio-derive/%5E0.2.0 Demonstrates how to use the `derive_readable` attribute macro to automatically implement the `Readable` trait for custom structs, including unit structs, tuple structs, and structs with various field types. It shows how to read complex nested structures from standard input using `proconio::input!`. ```rust use proconio::input; use proconio_derive::derive_readable; // Unit struct can derive readable. This generates a no-op for the reading. Not ignoring // the read value, but simply skip reading process. You cannot use it to discard the input. #[derive_readable] #[derive(PartialEq, Debug)] struct Weight; #[derive_readable] #[derive(PartialEq, Debug)] struct Cost(i32); #[derive_readable] #[derive(Debug)] struct Edge { from: usize, to: proconio::marker::Usize1, // The real Edge::to has type usize. weight: Weight, cost: Cost, } fn main() { input! { edge: Edge, } // if you enter "12 32 35" to the stdin, the values are as follows. assert_eq!(edge.from, 12); assert_eq!(edge.to, 31); assert_eq!(edge.weight, Weight); assert_eq!(edge.cost, Cost(35)); } ``` -------------------------------- ### input! macro usage Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates the basic syntax for the `input!` macro, showing how to specify the input source, declare variables (mutable or immutable), and define their types, including support for `RuntimeReadable` types. ```rust input! { from source, (mut) variable: type, (mut) variable: with runtime_readable, ... } ``` -------------------------------- ### From<&str> implementation Source: https://docs.rs/proconio/latest/proconio/source/once/struct.OnceSource.html Demonstrates creating a OnceSource from a string slice. ```rust impl<'a> From<&'a str> for OnceSource> { fn from(s: &'a str) -> OnceSource> { // ... implementation details ... } } ``` -------------------------------- ### Basic Input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html The macro's user interface is basically the same with tanakh's input macro. ```rust # extern crate proconio; # use proconio::source::auto::AutoSource; use proconio::input; # let source = AutoSource::from("32 54 -23"); input! { # from source, n: u8, m: u32, l: i32, } // now you can use n, m and l as variable. println!("{} {} {}", n, m, l); # assert_eq!(n, 32); # assert_eq!(m, 54); # assert_eq!(l, -23); ``` -------------------------------- ### new function Source: https://docs.rs/proconio/latest/proconio/source/once/struct.OnceSource.html Creates a new OnceSource using a specified BufRead reader. ```rust pub fn new(source: R) -> OnceSource ``` -------------------------------- ### Search Tricks Source: https://docs.rs/proconio/latest/help.html Tips for using the search functionality in Rustdoc, including type prefixes and path searches. ```text Prefix searches with a type followed by a colon (e.g., `fn:`) to restrict the search to a given item kind. Accepted kinds are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`. Search functions by type signature (e.g., `vec -> usize` or `-> vec` or `String, enum:Cow -> bool`) You can look for items with an exact name by putting double quotes around your request: `"string"` Look for functions that accept or return slices and arrays by writing square brackets (e.g., `-> [u8]` or `[] -> Option`) Look for items inside another one by searching for a path: `vec::Vec` ``` -------------------------------- ### Keyboard Shortcuts Source: https://docs.rs/proconio/latest/help.html A list of keyboard shortcuts available in Rustdoc for navigation and interaction. ```text `?` Show this help dialog `S` / `/` Focus the search field `↑` Move up in search results `↓` Move down in search results `←` / `→` Switch result tab (when results focused) `⏎` Go to active search result `+` / `=` Expand all sections `-` Collapse all sections `_` Collapse all sections, including impl blocks ``` -------------------------------- ### DirectedGraph Implementation of RuntimeReadable Source: https://docs.rs/proconio/latest/proconio/source/trait.RuntimeReadable.html An example implementation of the RuntimeReadable trait for a DirectedGraph struct, demonstrating how to read graph data whose size is determined at runtime. ```rust struct DirectedGraph(usize, usize); impl RuntimeReadable for DirectedGraph { type Output = Vec>; fn read>(self, source: &mut S) -> Self::Output { let DirectedGraph(n, m) = self; input! { from source, edges: [(Usize1, Usize1); m], }; let mut g = vec![vec![]; n]; for e in edges { g[e.0].push(e.1); } g } } ``` -------------------------------- ### Basic Input Source: https://docs.rs/proconio/%5E0.4.0 Demonstrates reading basic integer types (u8, u32, i32) using the input! macro. ```rust use proconio::input; input! { n: u8, m: u32, l: i32, } // now you can use n, m and l as variable. println!("{} {} {}", n, m, l); ``` -------------------------------- ### input! macro test case: string and byte input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Test case for the input! macro with String, Chars, and Bytes types. ```Rust #[test] fn input_str() { use crate::marker::{Bytes, Chars}; let source = AutoSource::from(" string chars\nbytes"); input! { from source, string: String, chars: Chars, bytes: Bytes, } assert_eq!(string, "string"); assert_eq!(chars, ['c', 'h', 'a', 'r', 's']); assert_eq!(bytes, b"bytes"); } ``` -------------------------------- ### Resolving `#[fastout]` error with closures Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Example showing how to resolve the compilation error when using closures with `print!` or `println!` inside a `#[fastout]` function by returning the result from the thread. ```rust # #[cfg(feature = "derive")] # { use proconio::fastout; #[fastout] fn main() { let thread = std::thread::spawn(|| { let x = 3; x * x }); let y = thread.join().unwrap(); # assert_eq!(y, 9); println!("{}", y); } # } ``` -------------------------------- ### Reading Strings, Chars, and Bytes Source: https://docs.rs/proconio/%5E0.4.0 Shows how to read input into a String, Vec (Chars), and Vec (Bytes). ```rust use proconio::input; use proconio::marker::{Bytes, Chars}; input! { string: String, // read as String chars: Chars, // read as Vec bytes: Bytes, // read as Vec } // if you enter "string chars bytes" to the stdin, they are like this. assert_eq!(string, "string"); assert_eq!(chars, ['c', 'h', 'a', 'r', 's']); assert_eq!(bytes, b"bytes"); ``` -------------------------------- ### Input Macro Usage with RuntimeReadable Source: https://docs.rs/proconio/latest/proconio/source/trait.RuntimeReadable.html An example showing how to use the input! macro with a type that implements RuntimeReadable, like DirectedGraph, to read data whose dimensions are known at runtime. ```rust input! { n: usize, m: usize, g: with DirectedGraph(n, m), } ``` -------------------------------- ### Tuple Input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html You can read tuples: ```rust # extern crate proconio; # use proconio::source::auto::AutoSource; use proconio::input; # let source = AutoSource::from("1 2 3 4 5"); input! { # from source, t: (i32, i32, i32, i32, i32), } // if you enter "1 2 3 4 5" to the stdin, `t` is like this. assert_eq!(t, (1, 2, 3, 4, 5)); ``` -------------------------------- ### Potential printing order issue with #[fastout] Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html This example illustrates how `#[fastout]` can alter the printing order when other functions are called between print statements. The output might show 'between' before 'hello' and 'world' due to buffering. ```rust # #[cfg(feature = "derive")] # { # use proconio::fastout; fn foo() { println!("between"); } #[fastout] fn main() { println!("hello"); foo(); println!("world"); } # } ``` -------------------------------- ### Combined Input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html And you can freely combine these types. ```rust # extern crate proconio; # use proconio::source::auto::AutoSource; use proconio::input; # let source = AutoSource::from("4 3 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5"); input! { # from source, n: usize, ``` -------------------------------- ### Input Error: Different Format Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Test case for `input!` macro panicking when the input format is incorrect (empty). ```rust let mut source = AutoSource::from(""); input! { from &mut source, _n: i32, } ``` -------------------------------- ### String, Bytes, and Chars Input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Strings can be read as `Vec` or `Vec`. Use `Bytes` and `Chars` to do so: ```rust # extern crate proconio; # use proconio::source::auto::AutoSource; use proconio::input; use proconio::marker::{Bytes, Chars}; # let source = AutoSource::from(" string chars\nbytes"); input! { # from source, string: String, // read as String chars: Chars, // read as Vec bytes: Bytes, // read as Vec } // if you enter "string chars bytes" to the stdin, they are like this. assert_eq!(string, "string"); assert_eq!(chars, ['c', 'h', 'a', 'r', 's']); assert_eq!(bytes, b"bytes"); ``` -------------------------------- ### Mutable Variables Source: https://docs.rs/proconio/%5E0.4.0 Shows how to declare and use mutable variables with the input! macro. ```rust use proconio::input; input! { n: u32, mut m: u32, } m += n; // OK: m is mutable ``` -------------------------------- ### Multiple Input Calls Source: https://docs.rs/proconio/%5E0.4.0 Shows how to use the input! macro multiple times to read data across different calls, useful for multiple datasets. ```rust use proconio::input; input! { n: usize, } for i in 0..n { input! { m: usize, a: [i32; m], } } ``` -------------------------------- ### OnceSource Implementation Source: https://docs.rs/proconio/latest/src/proconio/source/once.rs.html Implementation of OnceSource for reading all input at once. ```Rust 1// Copyright 2019 statiolake 2// 3// Licensed under the Apache License, Version 2.0 or the MIT license , at your option. This file may not be copied, modified, or 6// distributed except according to those terms. 7 8use super::Source; 9use crate::source::tokens::Tokens; 10use std::io::BufRead; 11use std::marker::PhantomData; 12 13/// Source reading entire content for the first time. 14/// 15/// It is a wrapper for `BufRead`. You can create `OnceSource` from any type implementing 16/// `BufRead`. 17pub struct OnceSource { 18 tokens: Tokens, 19 20 // to consume `R`. Actually `OnceSource` is not need to have `R`, since reading is done in its 21 // constructor. This is for the consistency with `LineSource` (To use smoothly through `AutoSource`). 22 _read: PhantomData, 23} 24 25impl OnceSource { 26 /// Creates `Source` using specified reader of `BufRead`. 27 pub fn new(mut source: R) -> OnceSource { 28 let mut context = String::new(); 29 source 30 .read_to_string(&mut context) 31 .expect("failed to read from source; maybe an IO error."); 32 33 OnceSource { 34 tokens: context.into(), 35 _read: PhantomData, 36 } 37 } 38} 39 40impl Source for OnceSource { 41 /// Gets a next token. 42 fn next_token(&mut self) -> Option<&str> { 43 self.tokens.next_token() 44 } 45 46 /// Check if tokens are empty 47 fn is_empty(&mut self) -> bool { 48 self.tokens.is_empty() 49 } 50} 51 52use std::io::BufReader; 53 54/// You can create `OnceSource` from `&str`. Since `&[u8]` is a `Read`, `BufRead` can be easily 55/// created by wrapping using `BufReader`. 56impl<'a> From<&'a str> for OnceSource> { 57 fn from(s: &'a str) -> OnceSource> { 58 OnceSource::new(BufReader::new(s.as_bytes())) 59 } 60} ``` -------------------------------- ### Multiple `input!` calls Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates using the `input!` macro multiple times to read subsequent input, even if the previous read stopped mid-line. ```rust # extern crate proconio; # use proconio::source::auto::AutoSource; use proconio::input; # let mut source = AutoSource::from("4 2 1 2 2 3 4 2 1 2 2 3 4"); input! { # from &mut source, n: usize, } for i in 0..n { input! { # from &mut source, m: usize, a: [i32; m], } # assert_eq!(a[0], if i % 2 == 0 { 1 } else { 3 }); # assert_eq!(a[1], if i % 2 == 0 { 2 } else { 4 }); } ``` -------------------------------- ### Reading Arrays and Matrices Source: https://docs.rs/proconio/%5E0.4.0 Illustrates reading a 2D array (matrix) with specified dimensions. ```rust use proconio::input; input! { n: usize, m: usize, a: [[i32; n]; m] // `a` is Vec>, (m, n)-matrix. } ``` -------------------------------- ### Reading Tuples Source: https://docs.rs/proconio/%5E0.4.0 Demonstrates reading a tuple of integers. ```rust use proconio::input; input! { t: (i32, i32, i32, i32, i32), } // if you enter "1 2 3 4 5" to the stdin, `t` is like this. assert_eq!(t, (1, 2, 3, 4, 5)); ``` -------------------------------- ### Using `Usize1` and `Isize1` for 0-indexed conversion Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Shows how `Usize1` and `Isize1` markers automatically convert 1-indexed input values to 0-indexed array indices. ```rust # extern crate proconio; # use proconio::source::auto::AutoSource; use proconio::input; use proconio::marker::Usize1; # let mut source = AutoSource::from("4 1 3 3 4 6 1 5 3"); input! { # from &mut source, n: usize, edges: [(Usize1, Usize1); n], } // if you enter "4 1 3 3 4 6 1 5 3", the decremented value is stored. assert_eq!(edges[0], (0, 2)); assert_eq!(edges[1], (2, 3)); assert_eq!(edges[2], (5, 0)); assert_eq!(edges[3], (4, 2)); ``` -------------------------------- ### input! macro test case: empty input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Test case for the input! macro with empty input. ```Rust #[test] fn input_empty() { let source = AutoSource::from(""); input! { from source, } } ``` -------------------------------- ### Runtime Readable Input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Demonstrates implementing `RuntimeReadable` for a custom `VecReadable` struct to read a dynamic number of elements into a `Vec`. ```rust struct VecReadable { n: usize, _marker: PhantomData, } impl VecReadable { pub fn new(n: usize) -> Self { VecReadable { n, _marker: PhantomData, } } } impl crate::source::RuntimeReadable for VecReadable { type Output = Vec; fn read>( self, source: &mut S, ) -> Self::Output { let mut res = vec![]; for _ in 0..self.n { input! { from &mut *source, v: T, } res.push(v); } res } } let mut source = AutoSource::from("4 1 2 3 4"); input! { from &mut source, n: usize, v: with VecReadable::::new(n), } assert_eq!(v, [0, 1, 2, 3]); ``` -------------------------------- ### input! macro test case: number input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Test case for the input! macro with various number types. ```Rust #[test] fn input_number() { let source = AutoSource::from(" 32 54 -23\r\r\n\nfalse"); input! { from source, n: u8, m: u32, l: i32, } assert_eq!(n, 32); assert_eq!(m, 54); assert_eq!(l, -23); } ``` -------------------------------- ### Reading Jagged Arrays Source: https://docs.rs/proconio/%5E0.4.0 Demonstrates reading a jagged array where inner array sizes can differ, by omitting the inner length. ```rust use proconio::input; input! { n: usize, a: [[i32]; n], } // if you enter "3 3 1 2 3 0 2 1 2" to the stdin, the result is as follows. assert_eq!( a, vec![ vec![1, 2, 3], vec![], vec![1, 2], ] ); ``` -------------------------------- ### next_token_unwrap method Source: https://docs.rs/proconio/latest/proconio/source/line/struct.LineSource.html Method to force retrieval of the next whitespace-splitted token, panicking if none is available. ```rust fn next_token_unwrap(&mut self) -> &str ``` -------------------------------- ### Array or Matrix Input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html You can read an array or a matrix like this: ```rust # extern crate proconio; # use proconio::source::auto::AutoSource; use proconio::input; # let source = AutoSource::from("5 4 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5"); input! { # from source, n: usize, m: usize, a: [[i32; n]; m] // `a` is Vec>, (m, n)-matrix. } # assert_eq!( # a, # [ # [1, 2, 3, 4, 5], # [1, 2, 3, 4, 5], # [1, 2, 3, 4, 5], # [1, 2, 3, 4, 5] # ] # ); ``` -------------------------------- ### Macro definition for input! Source: https://docs.rs/proconio/latest/proconio/macro.input.html The complete definition of the proconio input macro. ```rust macro_rules! input { (@from [$source:expr] @rest) => { ... }; (@from [$source:expr] @rest mut $($rest:tt)*) => { ... }; (@from [$source:expr] @rest $($rest:tt)*) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @rest $var:tt: $($rest:tt)*) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [] @rest with $($rest:tt)*) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [$($kind:tt)*] @rest) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [$($kind:tt)*] @rest, $($rest:tt)*) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [] @rest [$($tt:tt)*] $($rest:tt)*) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [] @rest ($($tt:tt)*) $($rest:tt)*) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [] @rest $ty:ty, $($rest:tt)*) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [] @rest $ty:ty) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @dyn_kind [$($dyn_kind:tt)*] @rest) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @dyn_kind [$($dyn_kind:tt)*] @rest, $($rest:tt)*) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @dyn_kind [$($dyn_kind:tt)*] @rest $dyn_readable:expr) => { ... }; (@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @dyn_kind [$($dyn_kind:tt)*] @rest $dyn_readable:expr, $($rest:tt)*) => { ... }; (@from $($tt:tt)*) => { ... }; (from $source:expr, $($rest:tt)*) => { ... }; ($($rest:tt)*) => { ... }; } ``` -------------------------------- ### Single TT Pattern Input Source: https://docs.rs/proconio/latest/src/proconio/lib.rs.html Shows how to use a single "tt" pattern for input, destructuring a tuple and reading a fixed-size array. ```rust fn input_single_tt_pattern() { let mut source = AutoSource::from("3 42 0\n1 2 3\n"); input! { from &mut source, (n, mut k): (usize, usize), _: usize, xs: [u32; n], } k += 1; assert_eq!(n, 3); assert_eq!(k, 43); assert_eq!(xs, [1, 2, 3]); } ``` -------------------------------- ### LineSource Constructor Source: https://docs.rs/proconio/latest/proconio/source/line/struct.LineSource.html Function to create a new LineSource instance from any type implementing BufRead. ```rust pub fn new(reader: R) -> LineSource ```