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 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
// Copyright 2019 statiolake <statiolake@gmail.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be copied, modified, or
// distributed except according to those terms.
#![allow(clippy::needless_doctest_main, clippy::print_literal)]
//! Easy IO library for competitive programming.
//!
//! `proconio` provides an easy way to read values from stdin (or other source). The main is
//! `input!` macro.
//!
//! # Examples
//!
//! The macro's user interface is basically the same with [tanakh's input
//! macro](https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8).
//!
//! ```
//! # 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);
//! ```
//!
//! In above code, variables n, m and l are declared and stored values are read from stdin.
//!
//! You can declare mutable variables like below:
//!
//! ```
//! # extern crate proconio;
//! # use proconio::source::auto::AutoSource;
//! use proconio::input;
//! # let source = AutoSource::from("32 54");
//!
//! input! {
//! # from source,
//! n: u32,
//! mut m: u32,
//! }
//!
//! m += n; // OK: m is mutable
//! # assert_eq!(n, 32);
//! # assert_eq!(m, 86);
//! ```
//!
//! You can read an array or a matrix like this:
//!
//! ```
//! # 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<Vec<i32>>, (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]
//! # ]
//! # );
//! ```
//!
//! If the first input is the length of the array, you can omit the length. This is the only way
//! to read jagged array (an array of arrays of which the member arrays can be of different sizes)
//! at once. (Of course you can use `input!` multiple times in for-loop to read such an array
//! since `input!` can be used multiple times.)
//!
//! ```
//! # extern crate proconio;
//! # use proconio::source::auto::AutoSource;
//! use proconio::input;
//! # let source = AutoSource::from("3 3 1 2 3 0 2 1 2");
//!
//! input! {
//! # from source,
//! 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],
//! ]
//! );
//! ```
//!
//! Strings can be read as `Vec<u8>` or `Vec<char>`. Use `Bytes` and `Chars` to do so:
//!
//! ```
//! # 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<char>
//! bytes: Bytes, // read as Vec<u8>
//! }
//!
//! // 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");
//! ```
//!
//! You can read tuples:
//!
//! ```
//! # 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));
//! ```
//!
//! And you can freely combine these types.
//!
//! ```
//! # 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,
//! m: usize,
//! t: [([u32; m], i32); n],
//! }
//! # assert_eq!(
//! # t,
//! # [
//! # (vec![1,1,1],1),
//! # (vec![2,2,2],2),
//! # (vec![3,3,3],3),
//! # (vec![4,4,4],4),
//! # ]
//! # );
//! ```
//!
//! You can use `input!` macro multiple times. For the second time, `input!` macro reads rest of
//! input. It works even if the first input stops at the middle of a line. The subsequent reads
//! will be started at the rest of the line. This may be helpful for problems where multiple
//! datasets are given once.
//!
//! ```
//! # 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 });
//! }
//! ```
//!
//! In addition to `Chars` and `Bytes`, `Usize1` and `Isize1` are also special types. They are
//! read as `usize` and `isize` respectively, but the read value is decremented. It enables us to
//! automatically convert 1-indexed vertices numbers to 0-indexed array indices.
//!
//! ```
//! # 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));
//! ```
//!
//! `Usize1` and `Isize1` doesn't hold actual value, so you cannot have value of the type. Thus,
//! they are only useful inside `input!` or `#[derive_readable]`. You can think the reason these
//! types exist is to tell "how to read the value". This how-to can be defined through `Readable`
//! trait. This trait doesn't require the output type to be the same with the implementor.
//! `Usize1` is implementing `Readable` trait, and there the type of read value is defined as
//! `usize`. You can implement `Readable` for your own type to read values in customized way.
//!
//! Finally, you can make your own types `Readable` using `#[derive_readable]` attribute. Types
//! used in the struct are automatically translated to their output types, so a member declared as
//! `Usize1` has type `usize` as real struct.
//!
//! **Note:** Using `#[derive_readable]` requires `derive` feature enabled. To do so, open your
//! Cargo.toml and modify the line of proconio from:
//!
//! ```toml
//! proconio = "=(version)"
//! ```
//!
//! to:
//!
//! ```toml
//! proconio = { version = "=(version)", features = ["derive"] }
//! ```
//!
//! Example of `#[derive_readable]`:
//!
//! ```
//! # #[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));
//! }
//! # }
//! ```
//!
//! # `#[fastout]`
//!
//! If you import `proconio::fastout`, you can use `#[fastout]` attribute. Adding this attribute
//! to your `main()`, your `print!` and `println!` become faster.
//!
//! **Note:** Using `#[proconio::fastout]` requires `derive` feature enabled. To do so, open your
//! Cargo.toml and modify the line of proconio from:
//!
//! ```toml
//! proconio = "=(version)"
//! ```
//!
//! to:
//!
//! ```toml
//! proconio = { version = "=(version)", features = ["derive"] }
//! ```
//!
//! Example of `#[fastout]`:
//!
//! ```
//! # #[cfg(feature = "derive")]
//! # {
//! # extern crate proconio;
//! use proconio::fastout;
//!
//! #[fastout]
//! fn main() {
//! print!("{}{}, ", 'h', "ello"); // "hello" (no newline)
//! println!("{}!", "world"); // "world!\n"
//! println!("{}", 123456789); // "123456789\n"
//! }
//! # }
//! ```
//!
//! ## Closures having `print!` or `println!` in `#[fastout]` function
//!
//! You cannot create a closure containing `print!` or `println!` in `#[fastout]` function. This
//! is because the closure becomes thread-unsafe since the closure refers the unlocked stdout
//! introduced by `#[fastout]` attribute. If this were not prohibited, an invalid usage of such a
//! closure would produce a very complex error messages. For example, `std::thread::spawn()`,
//! which requires its argument closure to be thread-safe, causes a confusing error.
//!
//! Yes, it is too conservative to make all of such closures compilation error because it is
//! actually no problem to use such a closure only inside a single thread. This is related to a
//! limitation in `#[fastout]` implementation.
//!
//! For more technical details, see documentation for `#[fastout]` in `proconio-derive`.
//!
//! ### How to resolve this error
//!
//! Consider you want to run this code:
//!
//! ```compile_fail
//! use proconio::fastout;
//!
//! #[fastout]
//! fn main() {
//! let thread = std::thread::spawn(|| {
//! let x = 3;
//! let y = x * x;
//! println!("{}", y);
//! });
//!
//! thread.join().unwrap();
//! }
//! ```
//!
//! You will get an error like below.
//!
//! ```text
//! error: Closures in a #[fastout] function cannot contain `print!` or `println!` macro
//!
//! note: If you want to run your entire logic in a thread having extended size of stack, you can
//! define a new function instead. See documentation (https://.....) for more details.
//!
//! note: This is because if you use this closure with `std::thread::spawn()` or any other
//! functions requiring `Send` for an argument closure, the compiler emits an error about thread
//! unsafety for our internal implementations. If you are using the closure just in a single
//! thread, it's actually no problem, but we cannot check the trait bounds at the macro-expansion
//! time. So for now, all closures having `print!` or `println!` is prohibited regardless of the
//! `Send` requirements.
//! --> src/test.rs:10:9
//! |
//! 10 | println!("{}", y);
//! | ^^^^^^^
//! ```
//!
//! If your `print!` is relying on the calculation in the thread, you can instead return the result
//! from the thread.
//!
//! ```
//! # #[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);
//! }
//! # }
//! ```
//!
//! If you are doing so complex job that it's too difficult to returning the results from your
//! closure...
//!
//! ```compile_fail
//! use proconio::fastout;
//!
//! # fn some_function(_: String) -> impl Iterator<Item = String> { 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();
//! }
//! ```
//!
//! ...you can use a function instead.
//!
//! ```
//! # #[cfg(feature = "derive")]
//! # {
//! use proconio::fastout;
//!
//! # fn some_function(_: String) -> impl Iterator<Item = String> { 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();
//! }
//! # }
//! ```
//!
//! **Important Note:** If you *spawn a new thread* which runs another function annotated with
//! `#[fastout]`, you must not add `#[fastout]` to the caller. If you add `#[fastout]` in caller
//! too, then the caller has the lock for the stdout, and so callee cannot acquire the lock forever
//! --- deadlock. This is not the case when the caller and callee is executed in the same thread,
//! since the lock of stdout is reentrant. We cannot warn about this kind of deadlock since we
//! don't know annotations attached to the function to be called. (In the above example, we can't
//! know whether the function `process()` has `#[fastout]` attribute or not.)
//!
//! If your code is so complex that you cannot avoid deadlock, you should give up using
//! `#[fastout]` and simply use `println!` or manually handle your stdout in usual Rust way.
//!
//! ## Issues of printing order
//!
//! `#[fastout]` enables buffering to stdout, so if you print something in other functions between
//! two prints in main, the order of printing may differ. In other words, the below example
//!
//! ```
//! # #[cfg(feature = "derive")]
//! # {
//! # use proconio::fastout;
//! fn foo() { println!("between"); }
//! #[fastout]
//! fn main() {
//! println!("hello");
//! foo();
//! println!("world");
//! }
//! # }
//! ```
//!
//! *likely* prints like
//!
//! ```text
//! between
//! hello
//! world
//! ```
//!
//! If you don't like this behavior, you can remove #[fastout] from your `main()`.
//!
#[cfg(feature = "derive")]
pub use proconio_derive::*;
pub mod marker;
pub mod source;
use crate::source::{auto::AutoSource, line::LineSource};
use std::io::{BufReader, Stdin};
use std::sync::OnceLock;
use std::{
io::{self, BufRead},
sync::Mutex,
};
// Prepares a short path to `Readable` to enables rust-analyzer to infer `Readable::Output`.
#[doc(hidden)]
pub use crate::source::Readable as __Readable;
pub enum StdinSource<R: BufRead> {
Normal(AutoSource<R>), // for input!
Interactive(LineSource<R>), // for for input_interactive!
Unknown(LineSource<R>), // for is_stdin_empty() without input! or input_interactive!
}
impl<R: BufRead> source::Source<R> for StdinSource<R> {
fn next_token(&mut self) -> Option<&str> {
match self {
StdinSource::Normal(source) => source.next_token(),
StdinSource::Interactive(source) => source.next_token(),
StdinSource::Unknown(source) => source.next_token(),
}
}
fn is_empty(&mut self) -> bool {
match self {
StdinSource::Normal(source) => source.is_empty(),
StdinSource::Interactive(source) => source.is_empty(),
StdinSource::Unknown(source) => source.is_empty(),
}
}
}
#[doc(hidden)]
pub static STDIN_SOURCE: OnceLock<Mutex<StdinSource<BufReader<Stdin>>>> = OnceLock::new();
/// read input from stdin.
///
/// basic syntax is:
/// ```text
/// input! {
/// from source, // optional: if you omitted, stdin is used by default.
/// (mut) variable: type, // mut is optional: mut makes the variable mutable.
/// ...
/// }
/// ```
/// the trailing comma is optional. `source` can be anything implementing `Source`. This macro
/// moves out the specified source. If you want to prevent moving, you can use `&mut source` since
/// `&mut S` where `S: Source` also implements `Source`.
#[macro_export]
macro_rules! input {
// terminator
(@from [$source:expr] @rest) => {};
// parse mutability
(@from [$source:expr] @rest mut $($rest:tt)*) => {
$crate::input! {
@from [$source]
@mut [mut]
@rest $($rest)*
}
};
(@from [$source:expr] @rest $($rest:tt)*) => {
$crate::input! {
@from [$source]
@mut []
@rest $($rest)*
}
};
// parse variable pattern
(@from [$source:expr] @mut [$($mut:tt)?] @rest $var:tt: $($rest:tt)*) => {
$crate::input! {
@from [$source]
@mut [$($mut)*]
@var $var
@kind []
@rest $($rest)*
}
};
// parse kind (type)
(@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [$($kind:tt)*] @rest) => {
let $($mut)* $var = $crate::read_value!(@source [$source] @kind [$($kind)*]);
};
(@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [$($kind:tt)*] @rest, $($rest:tt)*) => {
$crate::input!(@from [$source] @mut [$($mut)*] @var $var @kind [$($kind)*] @rest);
$crate::input!(@from [$source] @rest $($rest)*);
};
(@from [$source:expr] @mut [$($mut:tt)?] @var $var:tt @kind [$($kind:tt)*] @rest $tt:tt $($rest:tt)*) => {
$crate::input!(@from [$source] @mut [$($mut)*] @var $var @kind [$($kind)* $tt] @rest $($rest)*);
};
(from $source:expr, $($rest:tt)*) => {
#[allow(unused_variables, unused_mut)]
let mut s = $source;
$crate::input! {
@from [&mut s]
@rest $($rest)*
}
};
($($rest:tt)*) => {
let mut locked_stdin = $crate::STDIN_SOURCE
.get_or_init(|| {
std::sync::Mutex::new($crate::StdinSource::Normal(
$crate::source::auto::AutoSource::new(std::io::BufReader::new(std::io::stdin())),
))
})
.lock()
.expect(concat!(
"failed to lock the stdin; please re-run this program. ",
"If this issue repeatedly occur, this is a bug in `proconio`. ",
"Please report this issue from ",
"<https://github.com/statiolake/proconio-rs/issues>."
));
$crate::input! {
@from [&mut *locked_stdin]
@rest $($rest)*
}
drop(locked_stdin); // release the lock
};
}
/// read input from stdin interactively.
///
/// this macro is alias of:
/// ```text
/// let source = procontio::source::line::LineSource::new(BufReader::new(std::io::stdin()))
/// input! {
/// from &mut source,
/// (mut) variable: type,
/// ...
/// }
/// ```
/// read the documet of [input!](input) for further information.
#[macro_export]
macro_rules! input_interactive {
($($rest:tt)*) => {
let mut locked_stdin = $crate::STDIN_SOURCE
.get_or_init(|| {
std::sync::Mutex::new($crate::StdinSource::Interactive(
$crate::source::line::LineSource::new(std::io::BufReader::new(std::io::stdin())),
))
})
.lock()
.expect(concat!(
"failed to lock the stdin; please re-run this program. ",
"If this issue repeatedly occur, this is a bug in `proconio`. ",
"Please report this issue from ",
"<https://github.com/statiolake/proconio-rs/issues>."
));
$crate::input! {
from &mut *locked_stdin,
$($rest)*
}
drop(locked_stdin); // release the lock
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! read_value {
// array and variable length array
(@source [$source:expr] @kind [[$($kind:tt)*]]) => {
$crate::read_value!(@array @source [$source] @kind [] @rest $($kind)*)
};
(@array @source [$source:expr] @kind [$($kind:tt)*] @rest) => {{
let len = <usize as $crate::__Readable>::read($source);
$crate::read_value!(@source [$source] @kind [[$($kind)*; len]])
}};
(@array @source [$source:expr] @kind [$($kind:tt)*] @rest ; $($rest:tt)*) => {
$crate::read_value!(@array @source [$source] @kind [$($kind)*] @len [$($rest)*])
};
(@array @source [$source:expr] @kind [$($kind:tt)*] @rest $tt:tt $($rest:tt)*) => {
$crate::read_value!(@array @source [$source] @kind [$($kind)* $tt] @rest $($rest)*)
};
(@array @source [$source:expr] @kind [$($kind:tt)*] @len [$($len:tt)*]) => {{
let len = $($len)*;
(0..len)
.map(|_| $crate::read_value!(@source [$source] @kind [$($kind)*]))
.collect::<Vec<_>>()
}};
// tuple
(@source [$source:expr] @kind [($($kinds:tt)*)]) => {
$crate::read_value!(@tuple @source [$source] @kinds [] @current [] @rest $($kinds)*)
};
(@tuple @source [$source:expr] @kinds [$([$($kind:tt)*])*] @current [] @rest) => {
(
$($crate::read_value!(@source [$source] @kind [$($kind)*]),)*
)
};
(@tuple @source [$source:expr] @kinds [$($kinds:tt)*] @current [$($curr:tt)*] @rest) => {
$crate::read_value!(@tuple @source [$source] @kinds [$($kinds)* [$($curr)*]] @current [] @rest)
};
(@tuple @source [$source:expr] @kinds [$($kinds:tt)*] @current [$($curr:tt)*] @rest, $($rest:tt)*) => {
$crate::read_value!(@tuple @source [$source] @kinds [$($kinds)* [$($curr)*]] @current [] @rest $($rest)*)
};
(@tuple @source [$source:expr] @kinds [$($kinds:tt)*] @current [$($curr:tt)*] @rest $tt:tt $($rest:tt)*) => {
$crate::read_value!(@tuple @source [$source] @kinds [$($kinds)*] @current [$($curr)* $tt] @rest $($rest)*)
};
// unreachable
(@source [$source:expr] @kind []) => {
compile_error!(concat!("Reached unreachable statement while parsing macro input. ", "This is a bug in `proconio`. ", "Please report this issue from ", "<https://github.com/statiolake/proconio-rs/issues>."));
};
// normal other
(@source [$source:expr] @kind [$kind:ty]) => {
<$kind as $crate::__Readable>::read($source)
}
}
/// Checks if some of tokens are left on stdin.
///
/// This is useful when the number of test cases is not specified like ICPC problems.
///
/// ```text
/// loop {
/// if is_stdin_empty() {
/// break;
/// }
///
/// // do the normal logic
/// input! { ... }
/// }
/// ```
pub fn is_stdin_empty() -> bool {
use source::Source;
let mut lock = STDIN_SOURCE
.get_or_init(|| {
Mutex::new(StdinSource::Unknown(LineSource::new(BufReader::new(
io::stdin(),
))))
})
.lock()
.expect(concat!(
"failed to lock the stdin; please re-run this program. ",
"If this issue repeatedly occur, this is a bug in `proconio`. ",
"Please report this issue from ",
"<https://github.com/statiolake/proconio-rs/issues>."
));
lock.is_empty()
}
#[cfg(test)]
mod tests {
use crate::source::auto::AutoSource;
#[test]
fn input_empty() {
let source = AutoSource::from("");
input! {
from source,
}
}
#[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);
}
#[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");
}
#[test]
fn input_array() {
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]]);
}
#[test]
fn input_vla() {
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],
]
);
}
#[test]
fn input_tuple() {
let source = AutoSource::from("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,
t: [(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)
]
);
}
#[test]
fn input_multiple_times() {
let mut source = AutoSource::from("4 1 2 3 4\n1 2\r\n\r\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 });
}
}
#[test]
fn input_iusize1() {
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);
}
}
#[test]
#[should_panic]
fn input_zero_as_usize1() {
use crate::marker::Usize1;
let mut source = AutoSource::from("0");
input! {
from &mut source,
_v: Usize1,
}
}
#[test]
#[should_panic]
fn input_min_as_isize1() {
use crate::marker::Isize1;
let min_string = std::isize::MIN.to_string();
let mut source = AutoSource::from(&*min_string);
input! {
from &mut source,
_v: Isize1,
}
}
#[test]
fn input_mut() {
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);
}
#[test]
fn input_with_complex_type() {
let mut source = AutoSource::from("Hello\n2\n3 1 2 3\n4 5 ab\n4");
input! {
from &mut source,
hello: crate::marker::Bytes,
from: crate::marker::Usize1,
vla: [crate::marker::Isize1],
tuple: (crate::marker::Usize1, crate::marker::Isize1, crate::marker::Chars),
unit: (crate::marker::Usize1),
}
assert_eq!(hello, b"Hello");
assert_eq!(from, 1);
assert_eq!(vla, [0, 1, 2]);
assert_eq!(tuple, (3, 4, vec!['a', 'b']));
assert_eq!(unit, (3,));
}
#[test]
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]);
}
#[test]
#[should_panic]
fn input_err_different_type() {
let mut source = AutoSource::from("3.2\n");
input! {
from &mut source,
_n: i32,
}
}
#[test]
#[should_panic]
fn input_err_different_format() {
let mut source = AutoSource::from("");
input! {
from &mut source,
_n: i32,
}
}
}