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
//! Defines the saving and loading of the entire `surml` file.
use std::fs::File;
use std::io::{Read, Write};

use crate::{
    safe_eject_internal,
    safe_eject,
    storage::header::Header,
    errors::error::{
        SurrealError,
        SurrealErrorStatus
    }
};


/// The `SurMlFile` struct represents the entire `surml` file.
/// 
/// # Fields
/// * `header` - The header of the `surml` file containing data such as key bindings for inputs and normalisers.
/// * `model` - The PyTorch model in C.
pub struct SurMlFile {
    pub header: Header,
    pub model: Vec<u8>,
}


impl SurMlFile {

    /// Creates a new `SurMlFile` struct with an empty header.
    /// 
    /// # Arguments
    /// * `model` - The PyTorch model in C.
    /// 
    /// # Returns
    /// A new `SurMlFile` struct with no columns or normalisers.
    pub fn fresh(model: Vec<u8>) -> Self {
        Self {
            header: Header::fresh(),
            model
        }
    }

    /// Creates a new `SurMlFile` struct.
    /// 
    /// # Arguments
    /// * `header` - The header of the `surml` file containing data such as key bindings for inputs and normalisers.
    /// * `model` - The PyTorch model in C.
    /// 
    /// # Returns
    /// A new `SurMlFile` struct.
    pub fn new(header: Header, model: Vec<u8>) -> Self {
        Self {
            header,
            model,
        }
    }

    /// Creates a new `SurMlFile` struct from a vector of bytes.
    /// 
    /// # Arguments
    /// * `bytes` - A vector of bytes representing the header and the model.
    /// 
    /// # Returns
    /// A new `SurMlFile` struct.
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, SurrealError> {
        // check to see if there is enough bytes to read
        if bytes.len() < 4 {
            return Err(
                SurrealError::new(
                    "Not enough bytes to read".to_string(),
                    SurrealErrorStatus::BadRequest
                )
            );
        }
        let mut header_bytes = Vec::new();
        let mut model_bytes = Vec::new();

        // extract the first 4 bytes as an integer to get the length of the header
        let mut buffer = [0u8; 4];
        buffer.copy_from_slice(&bytes[0..4]);
        let integer_value = u32::from_be_bytes(buffer);

        // check to see if there is enough bytes to read
        if bytes.len() < (4 + integer_value as usize) {
            return Err(
                SurrealError::new(
                    "Not enough bytes to read for header, maybe the file format is not correct".to_string(),
                    SurrealErrorStatus::BadRequest
                )
            );
        }

        // Read the next integer_value bytes for the header
        header_bytes.extend_from_slice(&bytes[4..(4 + integer_value as usize)]);

        // Read the remaining bytes for the model
        model_bytes.extend_from_slice(&bytes[(4 + integer_value as usize)..]);

        // construct the header and C model from the bytes
        let header = Header::from_bytes(header_bytes)?;
        let model = model_bytes;
        Ok(Self {
            header,
            model,
        })
    }

    /// Creates a new `SurMlFile` struct from a file.
    /// 
    /// # Arguments
    /// * `file_path` - The path to the `surml` file.
    /// 
    /// # Returns
    /// A new `SurMlFile` struct.
    pub fn from_file(file_path: &str) -> Result<Self, SurrealError> {
        let mut file = safe_eject!(File::open(file_path), SurrealErrorStatus::NotFound);

        // extract the first 4 bytes as an integer to get the length of the header
        let mut buffer = [0u8; 4];
        safe_eject!(file.read_exact(&mut buffer), SurrealErrorStatus::BadRequest);
        let integer_value = u32::from_be_bytes(buffer);

        // Read the next integer_value bytes for the header
        let mut header_buffer = vec![0u8; integer_value as usize];
        safe_eject!(file.read_exact(&mut header_buffer), SurrealErrorStatus::BadRequest);

        // Create a Vec<u8> to store the data
        let mut model_buffer = Vec::new();

        // Read the rest of the file into the buffer
        safe_eject!(file.take(usize::MAX as u64).read_to_end(&mut model_buffer), SurrealErrorStatus::BadRequest);

        // construct the header and C model from the bytes
        let header = Header::from_bytes(header_buffer)?;
        Ok(Self {
            header,
            model: model_buffer,
        })
    }

    /// Converts the header and the model to a vector of bytes.
    /// 
    /// # Returns
    /// A vector of bytes representing the header and the model.
    pub fn to_bytes(&self) -> Vec<u8> {
        // compile the header into bytes.
        let (num, header_bytes) = self.header.to_bytes();
        let num_bytes = i32::to_be_bytes(num).to_vec();
        
        // combine the bytes into a single vector
        let mut combined_vec: Vec<u8> = Vec::new();
        combined_vec.extend(num_bytes);
        combined_vec.extend(header_bytes);
        combined_vec.extend(self.model.clone());
        return combined_vec
    }

    /// Writes the header and the model to a `surml` file.
    /// 
    /// # Arguments
    /// * `file_path` - The path to the `surml` file.
    /// 
    /// # Returns
    /// An `io::Result` indicating whether the write was successful.
    pub fn write(&self, file_path: &str) -> Result<(), SurrealError> {
        let combined_vec = self.to_bytes();

        // write the bytes to a file
        let mut file = safe_eject_internal!(File::create(file_path));
        safe_eject_internal!(file.write(&combined_vec));
        Ok(())
    }
}


#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_write() {
        let mut header = Header::fresh();
        header.add_column(String::from("squarefoot"));
        header.add_column(String::from("num_floors"));
        header.add_output(String::from("house_price"), None);

        let mut file = File::open("./stash/linear_test.onnx").unwrap();

        let mut model_bytes = Vec::new();
        file.read_to_end(&mut model_bytes).unwrap();

        let surml_file = SurMlFile::new(header, model_bytes);
        surml_file.write("./stash/test.surml").unwrap();

        let _ = SurMlFile::from_file("./stash/test.surml").unwrap();
    }

    #[test]
    fn test_write_forrest() {

        let header = Header::fresh();

        let mut file = File::open("./stash/forrest_test.onnx").unwrap();

        let mut model_bytes = Vec::new();
        file.read_to_end(&mut model_bytes).unwrap();

        let surml_file = SurMlFile::new(header, model_bytes);
        surml_file.write("./stash/forrest.surml").unwrap();

        let _ = SurMlFile::from_file("./stash/forrest.surml").unwrap();

    }

    #[test]
    fn test_empty_buffer() {
        let bytes = vec![0u8; 0];
        match SurMlFile::from_bytes(bytes) {
            Ok(_) => assert!(false),
            Err(error) => {
                assert_eq!(error.status, SurrealErrorStatus::BadRequest);
                assert_eq!(error.to_string(), "Not enough bytes to read");
            }
        }
    }
}