zamm_yang 0.0.3

A basic, experimental code generator
#[cfg(test)]
const CODE_WIDTH: usize = 30;
/// How many characters per line each autogenerated document should have.
#[cfg(not(test))]
const CODE_WIDTH: usize = 80;

/// Break up a one line documentation string into a multi-line docstring.
pub fn into_docstring(documentation: &str, indent_size: usize) -> String {
    let indent = " ".repeat(indent_size);
    // subtract 4 more from CODE_WIDTH to account for "/// " at the beginning of each line
    let lines = textwrap::fill(documentation, CODE_WIDTH - indent_size - 4);
    let mut comment = String::new();
    for line in lines.split("\n") {
        comment.push_str(format!("{}/// {}\n", indent, line.trim_end()).as_str());
    }
    comment.trim_end().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_short_docstring() {
        assert_eq!(
            into_docstring("A short description.", 0),
            "/// A short description."
        );
    }

    #[test]
    fn test_short_docstring_indent() {
        assert_eq!(
            into_docstring("A short description.", 4),
            "    /// A short description."
        );
    }

    #[test]
    fn test_short_docstring_trim() {
        assert_eq!(
            into_docstring("A short description.\t", 4),
            "    /// A short description."
        );
    }

    #[test]
    fn test_long_docstring() {
        assert_eq!(
            into_docstring(
                "A really long description. I mean, there's just so much to \
            document. Who has time for it all?",
                0
            ),
            r#"/// A really long description.
/// I mean, there's just so
/// much to document. Who has
/// time for it all?"#
        );
    }

    #[test]
    fn test_long_docstring_indent() {
        assert_eq!(
            into_docstring(
                "A really long description. I mean, there's just so much to \
            document. Who has time for it all?",
                4
            ),
            r#"    /// A really long
    /// description. I mean,
    /// there's just so much
    /// to document. Who has
    /// time for it all?"#
        );
    }

    #[test]
    fn test_long_docstring_indent_more() {
        assert_eq!(
            into_docstring(
                "A really long description. I mean, there's just so much to \
            document. Who has time for it all?",
                8
            ),
            r#"        /// A really long
        /// description. I
        /// mean, there's just
        /// so much to
        /// document. Who has
        /// time for it all?"#
        );
    }
}