From 95473f805bb5a4aa5fe65bd03c3d3bf79131adea Mon Sep 17 00:00:00 2001
From: Stephen <stephen@stephendownward.ca>
Date: Fri, 9 Oct 2020 21:11:13 -0300
Subject: [PATCH] Gracefully handle broken stdout

---
 src/lol.rs | 24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)

diff --git a/src/lol.rs b/src/lol.rs
index bad8a28..f03626e 100644
--- a/src/lol.rs
+++ b/src/lol.rs
@@ -1,6 +1,8 @@
 use colored::Color;
 use regex::{Regex, RegexBuilder};
 use std::f64::consts;
+use std::io::{stdout, Write};
+use std::process::exit;
 
 fn rainbow(freq: f64, i: f64) -> (u8, u8, u8) {
     let red = ((freq * i).sin() * 127.0) as i16 + 128;
@@ -23,10 +25,26 @@ pub fn print_rainbow(line: &str, freq: f64, seed: f64, spread: f64, invert: bool
         let color = Color::TrueColor { r, g, b };
 
         if invert {
-            print!("{}\x1B[{}m{}\x1B[49m", &c[1], color.to_bg_str(), &c[2]);
+            if stdout()
+                .write_all(
+                    format!("{}\x1B[{}m{}\x1B[49m", &c[1], color.to_bg_str(), &c[2]).as_bytes(),
+                )
+                .is_err()
+            {
+                exit(0);
+            }
         } else {
-            print!("{}\x1B[{}m{}\x1B[39m", &c[1], color.to_fg_str(), &c[2]);
+            if stdout()
+                .write_all(
+                    format!("{}\x1B[{}m{}\x1B[39m", &c[1], color.to_fg_str(), &c[2]).as_bytes(),
+                )
+                .is_err()
+            {
+                exit(0);
+            }
         }
     }
-    println!();
+    if stdout().write_all(&[b'\n']).is_err() {
+        exit(0);
+    }
 }
-- 
GitLab