|
| 1 | +use book::metadata::BookMetadata; |
| 2 | +use book::chapter::Chapter; |
| 3 | + |
| 4 | + |
| 5 | +/// The `Book` struct contains the metadata and chapters for one language of the book. |
| 6 | +/// Multiple `Book` structs are combined in the `MDBook` struct to support multi-language books. |
| 7 | +pub struct Book { |
| 8 | + metadata: BookMetadata, |
| 9 | + |
| 10 | + preface: Vec<Chapter>, |
| 11 | + chapters: Vec<Chapter>, |
| 12 | + appendix: Vec<Chapter>, |
| 13 | +} |
| 14 | + |
| 15 | +impl Book { |
| 16 | + /// Creates a new book with the given title, chapters are added with the `add_chapter` method |
| 17 | + pub fn new(title: &str) -> Self { |
| 18 | + Book { |
| 19 | + metadata: BookMetadata::new(title), |
| 20 | + |
| 21 | + preface: Vec::new(), |
| 22 | + chapters: Vec::new(), |
| 23 | + appendix: Vec::new(), |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + /// Adds a new chapter at the end of the book |
| 28 | + pub fn add_chapter(&mut self, chapter: Chapter) -> &mut Self { |
| 29 | + self.chapters.push(chapter); |
| 30 | + self |
| 31 | + } |
| 32 | + |
| 33 | + /// Adds a new preface chapter to the book, the preface chapters are in the order they were added |
| 34 | + pub fn add_preface_chapter(&mut self, chapter: Chapter) -> &mut Self { |
| 35 | + self.preface.push(chapter); |
| 36 | + self |
| 37 | + } |
| 38 | + |
| 39 | + /// Adds a new appendix chapter to the book, they are in de order they are added |
| 40 | + pub fn add_appendix_chapter(&mut self, chapter: Chapter) -> &mut Self { |
| 41 | + self.appendix.push(chapter); |
| 42 | + self |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + /// This method takes a slice `&[x, y, z]` as parameter and returns the corresponding chapter. |
| 47 | + /// For example, to retrieve chapter 2.3 we would use: |
| 48 | + /// ``` |
| 49 | + /// #extern crate mdbook; |
| 50 | + /// #use mdbook::book::Book; |
| 51 | + /// #fn main() { |
| 52 | + /// #let book = Book::new("Test"); |
| 53 | + /// let chapter_2_3 = book.get_chapter(&[2, 3]); |
| 54 | + /// #} |
| 55 | + /// ``` |
| 56 | + pub fn get_chapter(&self, section: &[usize]) -> Option<&Chapter> { |
| 57 | + match section.len() { |
| 58 | + 0 => None, |
| 59 | + 1 => self.chapters.get(section[0]), |
| 60 | + _ => { |
| 61 | + self.chapters |
| 62 | + .get(section[0]) |
| 63 | + .and_then(|ch| ch.get_sub_chapter(§ion[1..])) |
| 64 | + }, |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + /// Returns a mutable reference to the metadata for modification |
| 69 | + pub fn mut_metadata(&mut self) -> &mut BookMetadata { |
| 70 | + &mut self.metadata |
| 71 | + } |
| 72 | + |
| 73 | + // Returns a reference to the metadata |
| 74 | + pub fn metadata(&self) -> &BookMetadata { |
| 75 | + &self.metadata |
| 76 | + } |
| 77 | +} |
0 commit comments