1 /**
2  * Copyright:       Copyright (C) 2018 Gabriel Gheorghe, All Rights Reserved
3  * Authors:         $(Gabriel Gheorghe)
4  * License:         $(LINK2 https://www.gnu.org/licenses/gpl-3.0.txt, GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007)
5  * Source:          $(LINK2 https://github.com/GabyForceQ/LibertyEngine/blob/master/source/liberty/io/manager.d)
6  * Documentation:
7  * Coverage:
8 **/
9 module liberty.io.manager;
10 
11 import std.stdio : File;
12 
13 import liberty.logger.impl;
14 
15 /**
16  * Used for managing files and console input/output.
17 **/
18 final abstract class IOManager {  
19   /**
20    *
21   **/
22   static bool readFileToBuffer(string filePath, ref char[] buffer, string mode = "r")
23   in (mode == "r" || mode == "rb")
24   do {
25     // Try to open and read file
26     auto file = File(filePath, mode);
27     scope(exit) file.close;
28 
29     // Check file load
30     if (file.error) {
31       Logger.error("File couldn't be opened", typeof(this).stringof);
32       return false;
33     }
34     
35     // Get the file size
36     ulong fileSize = file.size;
37 
38     // Reduce the file size by any header bytes that might be present
39     fileSize -= file.tell;
40 
41     // Fill buffer
42     buffer = file.rawRead(new char[cast(size_t)fileSize]);
43 
44     return true;
45   }
46 
47   /**
48    *
49   **/
50   unittest {
51     char[] buf;
52 
53     if (!IOManager.readFileToBuffer("test_file.txt", buf))
54       assert(0, "Operation failed at reading!");
55 
56     assert(
57       buf == "Hello,\r\nDear engine!" ||
58       buf == "Hello,\nDear engine!", 
59       "Buffer does not containt the same data as file"
60     );
61   }
62 
63   /**
64    *
65   **/
66   static bool writeBufferToFile(string filePath, ref char[] buffer, string mode = "w")
67   in (mode == "w" || mode == "wb")
68   do {
69     // Try to open a file in write mode
70     auto file = File(filePath, mode);
71     scope(exit) file.close;
72 
73     // Check file load
74     if (file.error) {
75       Logger.error("File couldn't be created/opened", typeof(this).stringof);
76       return false;
77     }
78 
79     // Write to file
80     file.write(buffer);
81 
82     return true;
83   }
84 
85   /**
86    *
87   **/
88   unittest {
89     char[] buf = ['H', 'E', 'L', 'L', 'O', '7', '!'];
90     char[] buf2;
91 
92     if (!IOManager.writeBufferToFile("test_write_file.txt", buf))
93       assert(0, "Operation failed at writing!");
94 
95     if (!IOManager.readFileToBuffer("test_write_file.txt", buf2))
96       assert(0, "Operation failed at reading!");
97 
98     assert(
99       buf == buf2,
100       "Buffer2 does not containt the same data as Buffer1"
101     );
102   }
103 }