Created
November 21, 2022 15:35
-
-
Save wperron/b516f63dceb9fc25cabd65ad001c8a02 to your computer and use it in GitHub Desktop.
Write a function that takes a string of slashes (\ and /) and returns all of those slashes drawn downwards in a line connecting them.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{io::stdout, io::Write}; | |
fn main() { | |
indent_slashes(&mut stdout(), "\\\\\\\\//\\\\\\////").unwrap(); | |
} | |
/// takes a string of slashes (\ and /) and returns all of those slashes drawn | |
/// downwards in a line connecting them. | |
/// | |
/// Example: | |
/// | |
/// ``` | |
/// $ verticalSlashes('\\\//\/\\') | |
/// \ | |
/// \ | |
/// \ | |
/// / | |
/// / | |
/// \ | |
/// / | |
/// \ | |
/// \ | |
/// $ verticalSlashes('\\\\') | |
/// \ | |
/// \ | |
/// \ | |
/// \ | |
/// ``` | |
fn indent_slashes<W: Write>(w: &mut W, pat: &str) -> std::io::Result<()> { | |
let mut indent = 0; | |
for c in pat.chars() { | |
match c { | |
'\\' => { | |
write!(w, "{}\\\n", " ".repeat(indent))?; | |
indent += 1; | |
} | |
'/' => { | |
if indent == 0 { | |
return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)); | |
} | |
indent -= 1; | |
write!(w, "{}/\n", " ".repeat(indent))?; | |
} | |
_ => return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)), | |
} | |
} | |
Ok(()) | |
} | |
#[cfg(test)] | |
mod tests { | |
use std::io::{stderr, BufWriter}; | |
use super::*; | |
#[test] | |
fn happy_path() { | |
let expected = "\\ | |
\\ | |
\\ | |
/ | |
/ | |
\\ | |
\\ | |
/ | |
"; | |
let mut buf = BufWriter::new(vec![]); | |
indent_slashes(&mut buf, "\\\\\\//\\\\/").unwrap(); | |
assert_eq!(expected.as_bytes(), buf.buffer()); | |
} | |
#[test] | |
fn overflow() { | |
assert!(indent_slashes(&mut stderr(), "\\/////").is_err()) | |
} | |
#[test] | |
fn buffer_full() { | |
let mut buf: &mut [u8] = &mut [0; 8]; | |
assert!(indent_slashes(&mut buf, "\\/\\\\\\\\///").is_err()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment