reference_doc/
lib.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5pub use reference_doc_macro::ReferenceDoc;
6
7/// Trait added by using `derive(ReferenceDoc)]`.
8pub trait MarkdownReferenceDocGenerator {
9    /// Returns a Markdown representation of the reference docs for the
10    /// struct that is derived from `ReferenceDoc`. The returned Markdown
11    /// indents any `#` Markdown headers in individual field doc comments
12    /// to ensure a well structured final Markdown document.
13    fn get_reference_doc_markdown() -> String;
14
15    /// This method is called internally by the reference doc generator when
16    /// recursing to generate documentation for field types.
17    fn get_reference_doc_markdown_with_options(
18        indent_headers_by: usize,
19        indent_with_spaces: usize,
20    ) -> String {
21        let doc = Self::get_reference_doc_markdown();
22        indent_lines_with_spaces(
23            &indent_all_markdown_headers_by(&doc, indent_headers_by),
24            indent_with_spaces,
25        )
26    }
27}
28
29/// Helper function to indent markdown headers in `str` by `n` additional hash
30/// marks.
31fn indent_all_markdown_headers_by(s: &str, n: usize) -> String {
32    if n == 0 {
33        s.to_string()
34    } else {
35        s.split('\n').map(|part| indent_markdown_header_by(part, n)).collect::<Vec<_>>().join("\n")
36    }
37}
38
39fn indent_markdown_header_by(s: &str, n: usize) -> String {
40    if s.starts_with("#") {
41        "#".to_string().repeat(n) + &s
42    } else {
43        s.to_string()
44    }
45}
46
47fn indent_lines_with_spaces(s: &str, n: usize) -> String {
48    if n == 0 {
49        s.to_string()
50    } else {
51        let prefix = " ".to_string().repeat(n);
52        s.split('\n')
53            .map(|part| if part.is_empty() { "".to_string() } else { prefix.clone() + part })
54            .collect::<Vec<_>>()
55            .join("\n")
56    }
57}