Skip to content

Instantly share code, notes, and snippets.

@wperron
Created November 21, 2022 15:35
Show Gist options
  • Save wperron/b516f63dceb9fc25cabd65ad001c8a02 to your computer and use it in GitHub Desktop.
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.
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