1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
extern crate serde;
extern crate terminal_size;

#[macro_use]
extern crate serde_derive;

/// Contains things related to displaying things in a terminal. Minimally that is. See the aesthetic module for making things look decent.
pub mod disp {
    use std::fmt;

    /// Prints anything that has a std::fmt::Display trait.
    pub fn print<T>(text: T) where T: fmt::Display {
        println!("{}", text);
        return;
    }

    /// Prints a newline.
    pub fn newline() {
        println!("");
        return;
    }

    /// Prints anything with the std::fmt::Debug trait. Useful for printing different collections.
    pub fn print_debug<T>(data: T) where T: fmt::Debug {
        println!("{:?}", data);
        return;
    }
}

/// The range module. [DEPRECATED]
pub mod range {
    /// Returns a Vec with a range of elements. [DEPRECATED]
    pub fn range(x: u32, y: u32) -> Vec<u32> {
        // Make a new counter. Probably bad practice and should be fixed.
        let mut iterator = x;

        // Create a Vec and assign it each number in the provided range and return.
        let mut list = Vec::new();
        list.push(iterator);
        while iterator != y {
            iterator += 1;
            list.push(iterator);
        }
        return list;
    }
}

/// Contains things related to getting args.
pub mod arg {
    use std::env;

    /// Returns a Vec of all arguments sent to the program.
    pub fn get_args() -> Vec<String> {
        let args = env::args().collect();
        return args;
    }
}

/// Contains some random things that might be useful when working with strings.
pub mod stringutil {
    use std::string::String;

    /// Extract the char at a specific location in a string.
    pub fn get_char_pos(string: &String, char_loc: usize) -> char {
        let char_vec: &Vec<char> = &string.chars().collect();
        return char_vec[char_loc];
    }

    /// Get a empty newline string. Purely for making code look prettier.
    pub fn newline() -> String {
        let newline = String::from("\n");
        return newline;
    }
}

/// The appinfo module. Contains stuff related to the APPINFO standard this library uses. Providing a valid appinfo may be required for some functions in the future.
/// Meant to be set as a constant at the beginning of the main source file.
pub mod appinfo {
    /// A simple struct for storing appinfo data.
    #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
    pub struct AppInfo {
        pub name: &'static str,
        pub author: &'static str,
        pub repository: &'static str,
        pub crate_link: &'static str,
    }

    /// Implements for the struct AppInfo.
    impl AppInfo {
        /// Generate a new, empty appinfo.
        pub fn new() -> AppInfo {
            let appinfo: AppInfo = AppInfo {name: "", author: "", repository: "", crate_link: ""};
            return appinfo;
        }
    }
}

/// Point: Define a point on a 2D canvas.
pub mod point {
    #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
    pub struct Point {
        pub x: i32,
        pub y: i32,
    }

    impl Point {
        pub fn new() -> Point {
            let point: Point = Point {x: 0, y: 0};
            return point;
        }
    }
}

/// Coordinate: Define a point on a 3D canvas.
pub mod coordinate {
    #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
    pub struct Coordinate {
        pub x: i32,
        pub y: i32,
        pub z: i32,
    }

    impl Coordinate {
        pub fn new() -> Coordinate {
            let coordinate: Coordinate = Coordinate {x: 0, y: 0, z: 0};
            return coordinate;
        }
    }
}

/// Stuff related to making shapes. Both 2D and 3D.
pub mod shape {
    pub mod quadrilateral {
        use point::Point;

        #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
        pub struct Quadrilateral {
            pub corner: [Point; 4],
        }

        impl Quadrilateral {
            pub fn new() -> Quadrilateral {
                let quadrilateral: Quadrilateral = Quadrilateral {corner: [Point {x: 0, y: 0}; 4]};
                return quadrilateral;
            }
        }
    }

    pub mod hexahedron {
        use coordinate::Coordinate;

        #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
        pub struct Hexahedron {
            pub corner: [Coordinate; 8],
        }

        impl Hexahedron {
            pub fn new() -> Hexahedron {
                let hexahedron: Hexahedron = Hexahedron {corner: [Coordinate {x: 0, y: 0, z: 0}; 8]};
                return hexahedron;
            }
        }
    }
}

/// Stuff for error handling and exiting smoothly.
pub mod error {
    use std::process;
    use ::disp::print;
    use ::stringutil;

    /// Defines an error.
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct Error {
        pub errormessage: String,
        pub exitcode: u8,
        pub exit: bool,
    }

    /// Construct an error which exits.
    pub fn const_error(errormessage: &'static str, exitcode: u8) -> Error {
        let error = Error {errormessage: String::from(errormessage), exitcode: exitcode, exit: true};
        return error;
    }

    /// Construct an error that doesn't exit. Really just a error template.
    pub fn const_error_noexit(errormessage: &'static str) -> Error {
        let error = Error {errormessage: String::from(errormessage), exitcode: 1, exit: false};
        return error;
    }

    /// Takes an error and prints everything in a nice standarized format.
    pub fn error(error: Error) {
        print([String::from("Error: "), error.errormessage, stringutil::newline()].concat());

        // Exit if the exit var is set to true.
        if error.exit {
            process::exit(error.exitcode as i32);
        }
        return;
    }
}

/// Everything related to argument parsing and help texts.
pub mod argumentparser {
    /// Defines a argument.
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct Argument {
        pub identifier: char,
        pub description: String,
    }

    /// Everything related to help texts.
    pub mod help {
        use std::string::String;
        use ::argumentparser::Argument;
        use ::aesthetic::border;
        use ::disp::print;
        use ::stringutil;

        /// Takes a Vec of all valid Arguments and an usage paramater and turns it into a help text and prints it.
        pub fn help(usage: &'static str, arg_array: Vec<Argument>) {

            // Make a new Vec to store each line of the help text.
            let mut help: Vec<String> = Vec::new();

            // Add the border, template and the usage text.
            help.push([border::horizontal(String::from("-")), stringutil::newline()].concat());
            help.push([String::from("Usage:\n    "), String::from(usage), stringutil::newline()].concat());
            help.push(String::from("Flags:"));

            // Add every argument.
            for argument in arg_array {
                help.push([String::from("    -"), argument.identifier.to_string(), String::from(" # "), argument.description].concat());
            }

            // Add a newline at the end.
            help.push(stringutil::newline());

            // Then finally print everything.
            for line in &help {
                print(&line);
            }
            return;
        }
    }

    /// A simple argument parser. In it's current state. You probably want to use clap instead.
    pub mod parse {
        use std::collections::HashMap;
        use ::argumentparser::Argument;

        pub fn parseargs(argstring: String, valid_arg_array: Vec<Argument>) -> HashMap<String, bool> {
            // Make a new HashMap to store if an argument is given.
            let mut arg_bool_list = HashMap::new();

            // Set every argument to false as a base,
            for validarg in &valid_arg_array {
                arg_bool_list.insert(validarg.identifier.to_string(), false);
            }

            // Check every character in the provided argument string if it's valid. And if so, set it's entry to true.
            for arg in argstring.chars() {
                for validarg in &valid_arg_array {
                    if arg == validarg.identifier {
                        arg_bool_list.remove(&validarg.identifier.to_string());
                        arg_bool_list.insert(validarg.identifier.to_string(), true);
                    }

                }
            }
            return arg_bool_list;
        }
    }
}

/// This module is used for making your terminal applications look better.
pub mod aesthetic {
    pub mod border {
        use std::iter;
        use terminal_size::terminal_size;

        /// Create an horizontal border with the length of the terminal.
        pub fn horizontal(border_char: String) -> String {
            // Get the width of the terminal.
            let term_size = terminal_size().unwrap();
            let term_width: usize = (term_size.0).0 as usize;

            // Create a infinite generator of the character provided and take as many as the terminal fits.
            let border = iter::repeat(border_char).take(term_width).collect::<String>();
            return border;
        }
    }
}

#[cfg(test)]
mod tests {
    use ::range;
    use ::error;
    use ::aesthetic::border;
    use ::argumentparser;
    use ::argumentparser::Argument;

    #[test]
    fn range() {
        let testvec = range::range(0, 4);
        println!("{:?}", testvec);
    }

    #[test]
    fn error() {
        let error = error::const_error_noexit("This is a sample error, beep beep.");
        error::error(error);
    }

    #[test]
    fn bordertest() {
        let border = border::horizontal(String::from("-"));
        println!("{}", border);
    }

    #[test]
    fn arghelptest() {
        let usage = "[PROGRAM NAME] -[CATEGORIES AND SWITCHES]";
        let arg1: Argument = Argument { identifier: 'v', description: String::from("Prints the program version") };
        let arg2: Argument = Argument { identifier: 't', description: String::from("Prints \"Rust is the best language\"") };
        let mut arg_array: Vec<Argument> = Vec::new();
        arg_array.push(arg1);
        arg_array.push(arg2);
        argumentparser::help::help(usage, arg_array);
    }

    #[test]
    fn argparser() {
        let args = String::from("-vt");
        let arg1: Argument = Argument { identifier: 'v', description: String::from("Prints the program version") };
        let arg2: Argument = Argument { identifier: 't', description: String::from("Prints \"Rust is the best language\"") };
        let mut arg_array: Vec<Argument> = Vec::new();
        arg_array.push(arg1);
        arg_array.push(arg2);
        let ev = argumentparser::parse::parseargs(args, arg_array);
        println!("{:?}", ev);
    }
}