NLinker

scanf interop

Jul 3rd, 2018
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.96 KB | None | 0 0
  1. const STDIN_FILENO: i32 = 0;
  2. const STDOUT_FILENO: i32 = 1;
  3.  
  4. enum FILE {}
  5.  
  6. extern {
  7.     #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
  8.     link_name = "fputs$UNIX2003")]
  9.     fn fputs(s: *const u8, stream: *mut FILE)-> i32;
  10.     fn fgets(buf: *mut u8, n: i32, stream: *mut FILE) -> *mut u8;
  11.     fn fdopen(fd: i32, mode: *const u8) -> *mut FILE;
  12. }
  13.  
  14. fn main() {
  15.     let mut chars: [u8; 15] = unsafe { std::mem::zeroed() };
  16.  
  17.     unsafe {
  18.         let input = fdopen(STDIN_FILENO, "r\0".as_ptr());
  19.         if fgets(chars.as_mut_ptr(), chars.len() as i32, input) == std::ptr::null_mut() {
  20.             panic!();
  21.         }
  22.  
  23.         let mut n: u32 = 0;
  24.  
  25.         for &c in chars.iter() {
  26.             if c == b'\n' {
  27.                 break;
  28.             }
  29.             n = n * 10 + (c - b'0') as u32;
  30.         }
  31.  
  32.         let mut tuples = std::iter::repeat(String::new())
  33.             .take(101)
  34.             .collect::<Vec<_>>();
  35.  
  36.         for _ in 0..n {
  37.             chars = std::mem::zeroed();
  38.             if fgets(chars.as_mut_ptr(), chars.len() as i32, input) == std::ptr::null_mut() {
  39.                 panic!();
  40.             }
  41.  
  42.             let mut j = chars.len() - 1;
  43.  
  44.             while !chars[j].is_ascii_digit() {
  45.                 j -= 1;
  46.             }
  47.  
  48.             let chars_count = j + 2; // 123\n
  49.  
  50.             let mut m = 0u8;
  51.             let mut multiplier = 1;
  52.  
  53.             while chars[j] != b' ' {
  54.                 let digit = chars[j] - b'0';
  55.                 m += digit  * multiplier;
  56.                 if j == 0 || multiplier == 100{
  57.                     break;
  58.                 }
  59.                 j -= 1;
  60.                 multiplier *= 10;
  61.             }
  62.  
  63.             tuples[100 - m as usize].push_str(std::str::from_utf8_unchecked(&chars[0..chars_count]));
  64.         }
  65.  
  66.         let output = fdopen(STDOUT_FILENO, "w\0".as_ptr());
  67.         for g in &mut tuples {
  68.             g.push('\0');
  69.             fputs(g.as_ptr(), output);
  70.         }
  71.     };
  72. }
Add Comment
Please, Sign In to add comment