eao197

Фрагменты Rust-овского кода, найденные в ЖЖ theiced-а.

Jan 30th, 2019
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.78 KB | None | 0 0
  1. //
  2. // Оригинальный код
  3. //
  4. pub fn format_duration(duration: Duration) -> String {
  5.     let total_seconds = duration.as_secs();
  6.  
  7.     let hours = total_seconds / 3600;
  8.     let minutes = (total_seconds % 3600) / 60;
  9.     let seconds = total_seconds % 60;
  10.  
  11.     let hours_label = match hours {
  12.         1 => "hour",
  13.         _ => "hours"
  14.     };
  15.  
  16.     let minutes_label = match minutes {
  17.         1 => "minute",
  18.         _ => "minutes"
  19.     };
  20.  
  21.     let seconds_label = match seconds {
  22.         1 => "second",
  23.         _ => "seconds"
  24.     };
  25.  
  26.     let mut text = String::new();
  27.  
  28.     if hours > 0 {
  29.         push_value_and_label(&mut text, hours, hours_label);
  30.     }
  31.  
  32.     if minutes > 0 {
  33.         if !text.is_empty() {
  34.             text.push(' ');
  35.         }
  36.  
  37.         push_value_and_label(&mut text, minutes, minutes_label);
  38.     }
  39.  
  40.     if !text.is_empty() {
  41.         text.push(' ');
  42.     }
  43.  
  44.     push_value_and_label(&mut text, seconds, seconds_label);
  45.  
  46.     text
  47. }
  48.  
  49. fn push_value_and_label(text: &mut String, value: u64, label: &str) {
  50.     write!(text, "{} {}", value, label).unwrap();
  51. }
  52.  
  53. //
  54. // Предложенный альтернативный вариант
  55. //
  56. fn summon_satan(seconds: u64) -> String {
  57.     let labels = vec!["hour", "minute", "second"];
  58.     let parts = vec![seconds / 3600, (seconds % 3600) / 60, seconds % 60];
  59.     let index = parts.iter().position(|&p| p != 0).unwrap_or(2);
  60.     let parts_n_labels = parts[index..].iter().zip(labels[index..].iter());
  61.     let strs = parts_n_labels.map(|(&part, &label)| format!("{} {}{}", part, label, if part == 1 { "" } else { "s" }));
  62.     return strs.collect::<Vec<String>>().join(" ");
  63. }
  64.  
  65. // Источники:
  66. // https://theiced.livejournal.com/499970.html
  67. // https://theiced.livejournal.com/500541.html
Advertisement
Add Comment
Please, Sign In to add comment