source_generator/vhdl/
library_list.rs

1use std::collections::HashMap;
2use itertools::Itertools;
3use crate::element::Element;
4use crate::vhdl::library::Library;
5use crate::vhdl::library_use::LibraryUse;
6
7#[derive(Clone)]
8pub struct LibraryList {
9    libraries : HashMap< String, Library >
10}
11
12impl LibraryList {
13    pub fn new() -> LibraryList {
14        LibraryList { libraries : HashMap::new() }
15    }
16
17    pub fn contains( & self, library_name : & str ) -> bool {
18        self.libraries.contains_key( library_name )
19    }
20
21    pub fn add_library( & mut self, library : Library ) {
22        if ! self.libraries.contains_key( library.get_name() ) {
23            self.libraries.insert( library.get_name().to_string(), library );
24        }
25    }
26
27    pub fn add_library_use( & mut self, library_use : LibraryUse ) {
28        let library_name = & library_use.get_library_name();
29        self.add_library( Library::new( library_name ) );
30
31        let library = self.get_library_mut( library_name );
32        library.add_use( library_use );
33    }
34
35    fn get_library_mut( & mut self, library_name : & str ) -> & mut Library {
36        self.libraries.get_mut( library_name ).unwrap()
37    }
38}
39
40impl Element for LibraryList {
41    fn to_source_code( & self, indent : usize ) -> String {
42        let mut source = String::new();
43
44        if self.libraries.is_empty() {
45            return source;
46        }
47
48        for name in self.libraries.keys().sorted() {
49            source.push_str( & self.libraries[ name ].to_source_code( indent ) );
50            source.push_str( "\n" )
51        }
52        return source;
53    }
54}
55
56//------------------------------------------------------------------------------
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    const LIBRARIES : &'static str = concat!( "library ieee;\n",
62        "    use ieee.std_logic_1164.all;\n",
63        "    use ieee.numeric_std.all;\n",
64        "\n",
65        "library test;\n",
66        "    use test.utility.all;\n",
67        "\n" );
68
69    /**
70     * Create a library list with three entries
71     */
72    #[test]
73    fn library_list() {
74        let mut library_list = LibraryList::new();
75        library_list.add_library_use( LibraryUse::new( "ieee", "std_logic_1164" ) );
76        library_list.add_library_use( LibraryUse::new( "ieee", "numeric_std" ) );
77        library_list.add_library_use( LibraryUse::new( "test", "utility" ) );
78
79        assert_eq!(
80            library_list.to_source_code( 0 ),
81            format!( "{}", LIBRARIES )
82        );
83    }
84}
85