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.
45pub use reference_doc_macro::ReferenceDoc;
67/// 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.
13fn get_reference_doc_markdown() -> String;
1415/// This method is called internally by the reference doc generator when
16 /// recursing to generate documentation for field types.
17fn get_reference_doc_markdown_with_options(
18 indent_headers_by: usize,
19 indent_with_spaces: usize,
20 ) -> String {
21let 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}
2829/// 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 {
32if 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}
3839fn indent_markdown_header_by(s: &str, n: usize) -> String {
40if s.starts_with("#") {
41"#".to_string().repeat(n) + &s
42 } else {
43 s.to_string()
44 }
45}
4647fn indent_lines_with_spaces(s: &str, n: usize) -> String {
48if n == 0 {
49 s.to_string()
50 } else {
51let 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}