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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use serde::{Serialize, Deserialize};
use std::fmt::{Debug, Display};
use std::fs::{self, File};
use std::io::{BufReader, BufWriter, Read, Write};
use std::net::{TcpStream, UdpSocket, ToSocketAddrs, SocketAddr};
use std::path::{Path, PathBuf};
use crate::bytes::{Bytes, IntoBytes};
use crate::error::{Error, ErrorKind};
use crate::packet::{Packet, PacketKind, FromPacket, IntoPacket};
use crate::ron::{FromRon, ToRon};
/// Default struct to store data sent or received.
///
/// # Fields
/// * `metadata` -- has to implement [MetaDataType].
/// * `content` -- has to implement [ContentType].
/// * `end_data` -- marks end of [Message] during transmission, but can also hold some data.
///
/// Usually is used by declaring custom `type`.
/// ```
/// # struct MyMetaData;
/// # struct MyContent;
/// # use nardol::message::Message;
/// type MyMessage = Message<MyMetaData, MyContent>;
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message<M, C> {
metadata: M,
content: C,
end_data: Packet,
}
impl<M, C> Default for Message<M, C>
where
M: Default,
C: Default {
fn default() -> Self {
Message {
metadata: M::default(),
content: C::default(),
end_data: Packet::default(),
}
}
}
impl<M, C> Display for Message<M, C>
where
M: Serialize,
C: Serialize {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let formatted = self.to_ron_pretty(None).expect("Failed to parse a Message to RON.");
write!(f, "{}", &formatted)
}
}
impl<'a, M, C> ToRon for Message<M, C>
where
M: Serialize,
C: Serialize {}
impl<'a, M, C> FromRon<'a> for Message<M, C>
where
M: Deserialize<'a>,
C: Deserialize<'a> {}
impl<'a, M, C> Message<M, C>
where
M: Default + Clone + Debug + MetaDataType<'a>,
C: Default + Clone + Debug + ContentType<'a, M, C> {
/// Creates an empty [Message].
///
/// Usually created as mutable and later given data.
///
/// ```
/// use nardol::packet::{Packet, PacketKind};
/// # // -------------------------------------------------------------------------------------------------------------------------
/// # // This is done, so I get rid of those errors from cargo test.
/// # use nardol::error::NardolError;
/// # use nardol::message::{MetaDataType, ContentType};
/// # use nardol::ron::{ToRon, FromRon};
/// # use std::path::PathBuf;
/// # use std::net::TcpStream;
/// # use serde::{Serialize, Deserialize};
/// # #[derive(Clone, Debug, Default, Serialize, Deserialize)]
/// # pub struct MyMetaData;
/// #
/// # impl MyMetaData {
/// # pub fn new() -> Self { MyMetaData {} }
/// # }
/// # impl FromRon<'_> for MyMetaData {}
/// # impl ToRon for MyMetaData {}
/// # impl std::fmt::Display for MyMetaData {
/// # fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "") } }
/// # impl MetaDataType<'_> for MyMetaData {
/// # fn send(self, stream: &mut TcpStream) -> Result<Self, NardolError> { Ok(MyMetaData::new()) }
/// # fn receive(stream: &mut TcpStream, location: Option<PathBuf>) -> Result<Self, NardolError> { Ok(MyMetaData::new()) }
/// # }
/// #
/// # #[derive(Clone, Debug, Default, Serialize, Deserialize)]
/// # pub struct MyContent;
/// #
/// # impl FromRon<'_> for MyContent {}
/// # impl ToRon for MyContent {}
/// # impl std::fmt::Display for MyContent{
/// # fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "") } }
/// # impl ContentType<'_, MyMetaData, MyContent> for MyContent {
/// # fn send(self, stream: &mut TcpStream, metadata: MyMetaData) -> Result<(), NardolError> { Ok(()) }
/// # fn receive(stream: &mut TcpStream, metadata: &MyMetaData, path: Option<PathBuf>) -> Result<(Self, Packet), NardolError> {
/// # Ok((MyContent::new(), Packet::default()))
/// # }
/// # }
/// # impl MyContent {
/// # pub fn new() -> Self { MyContent }
/// # }
/// # // -------------------------------------------------------------------------------------------------------------------------
/// use nardol::bytes::Bytes;
///
/// type MyMessage = nardol::message::Message<MyMetaData, MyContent>;
///
/// let mut message = MyMessage::new();
///
/// message.set_metadata(MyMetaData::new());
/// message.set_content(MyContent::new());
/// message.set_end_data(Packet::new(PacketKind::End, Bytes::new()));
/// #
/// ```
pub fn new() -> Self {
Self::default()
}
/// Sends `Self` via [`stream`](std::net::TcpStream).
///
/// Takes an ownership of `self`.
///
/// This uses send methods implemented by `metadata` and `content`.
///
/// This will return [Ok] with an empty [tuple] inside if succeeds to send `self`, otherwise returns [NardolError].
pub fn send(self, stream: &mut TcpStream) -> Result<(), Error> {
// MetaDataType needs to return valid metadata, if they need to be used while sending content,
// otherwise it can just return an empty, invalid metadata.
let metadata = self.metadata.send(stream)?;
self.content.send(stream, metadata)?;
self.end_data.send(stream)?;
Ok(())
}
/// Receives a [Message] from [`stream`](std::net::TcpStream).
///
/// * `location` -- an optional path to location on the device, that can be used to store
/// received data inside methods implemented by `metadata` and `content`.
pub fn receive(stream: &mut TcpStream, location: Option<PathBuf>) -> Result<Self, Error> {
let mut message = Self::default();
let metadata = M::receive(stream, location.clone())?;
// Since end of content is marked by end_data packet, it needs to be returned with content.
let (content, end_data) = C::receive(stream, &metadata, location)?;
message.set_metadata(metadata);
message.set_content(content);
message.set_end_data(end_data);
Ok(message)
}
/// Sends [`content`](Bytes) via `stream`.
///
/// This method can be used in implementation of [ContentType].
pub fn send_content(stream: &mut TcpStream, content: Bytes) -> Result<(), Error> {
let content_split = Packet::split_to_max_packet_size(content);
// Write all content packets to stream.
for packet_content in content_split.into_iter() {
let packet = Packet::new(PacketKind::Content, packet_content);
packet.send(stream)?;
}
Ok(())
}
/// Receives [`content`](Bytes) and `end_data` [Packet] from `stream`.
///
/// This method can be used in implementation of [ContentType].
pub fn receive_content(stream: &mut TcpStream) -> Result<(Bytes, Packet), Error> {
let mut content = Bytes::new();
// loop until end_data packet is received.
loop {
let mut packet = Packet::receive(stream)?;
match packet.kind() {
PacketKind::Empty => {
return Err(Error::new(
ErrorKind::InvalidPacketKind,
Some("Expected content packet, got empty.".to_string())));
},
PacketKind::MetaData
| PacketKind::MetaDataEnd => {
return Err(Error::new(
ErrorKind::InvalidPacketKind,
Some("Expected content packet, got metadata.".to_string())));
},
PacketKind::Content => {
content.append(packet.content_mut());
},
PacketKind::End => {
let end_data = packet;
return Ok((content, end_data));
},
PacketKind::Unit => {
return Err(Error::new(
ErrorKind::InvalidPacketKind,
Some("Expected content packet, got unit.".to_string())));
}
PacketKind::Unknown => {
return Err(Error::new(
ErrorKind::UnknownPacketKind,
None))
},
}
}
}
/// Sends a file from [`path`](Path) via a [`stream`](TcpStream).
///
/// This method differs from other send methods as this does not load whole file into memory,
/// but it gradually reads file sends part with size equal to [MAX_CONTENT_SIZE](Packet::max_content_size).
pub fn send_file(stream: &mut TcpStream, path: &Path) -> Result<(), Error> {
let file = match File::open(path) {
Ok(file) => file,
Err(e) => return Err(Error::new(
ErrorKind::OpeningFileFailed,
Some(format!("{}", e)))),
};
// Get information about to how many packet the file will be split.
let n_of_content_packets = Packet::number_of_packets(file
.metadata()
.unwrap()
.len() as usize);
let mut reader = BufReader::new(file);
// Starts at 1 and ends inclusively at n_of_content_packets so the whole file is read.
for part in 1..=n_of_content_packets {
let mut buff: Vec<u8>;
if part == n_of_content_packets {
// Read last part of file.
buff = Vec::new();
if let Err(e) = reader.read_to_end(&mut buff) {
return Err(Error::new(
ErrorKind::ReadingFromFileFailed,
Some(format!("Failed to read last content packet from file.\n({})",
e))));
}
} else {
// Create a buffer with exact buffer size.
buff = vec![0_u8; Packet::max_content_size() as usize];
// This read_exact instead of read is really important, valid content is
// guaranteed by getting correct size of file and then checking if end of file was reached.
if let Err(e) = reader.read_exact(&mut buff) {
return Err(Error::new(
ErrorKind::ReadingFromFileFailed,
Some(format!("Failed to read content packet from file.\n({})", e))));
}
}
let packet = Packet::new(PacketKind::Content, buff.into_Bytes());
packet.send(stream)?;
}
Ok(())
}
/// Receives a file from [`stream`](TcpStream) and saves it to [`location`](Path) with `file_name`.
///
/// This method differs from other receive methods as this does not load whole file into memory,
/// but it gradually receives part of file and saves it.
pub fn receive_file(stream: &mut TcpStream,
location: &Path, file_name: String,
) -> Result<(usize, Packet), Error> {
let mut path = location.to_path_buf();
path.push(&file_name);
let file = match File::create(path) {
Ok(file) => file,
Err(e) => {
return Err(Error::new(
ErrorKind::CreatingFileFailed,
Some(format!("Could not create a file: {}.\n({})", file_name, e))));
},
};
let mut writer = BufWriter::new(file);
let mut number_of_packets = 0;
// Loop to receive packets until end_data packet comes.
loop {
let packet = Packet::receive(stream)?;
match packet.kind() {
PacketKind::Empty => {
return Err(Error::new(
ErrorKind::InvalidPacketKind,
Some("Expected content packet, got empty.".to_string())));
},
PacketKind::MetaData
| PacketKind::MetaDataEnd => {
return Err(Error::new(
ErrorKind::InvalidPacketKind,
Some("Expected content packet, got metadata.".to_string())));
},
PacketKind::Content => {
// Write to file.
if let Err(e) = writer.write(&packet.content_move().into_vec()) {
return Err(Error::new(
ErrorKind::WritingToFileFailed,
Some(format!("Could not write to file. ({})", e))));
}
},
PacketKind::End => {
writer.flush().unwrap();
let end_data = packet;
return Ok((number_of_packets, end_data));
},
PacketKind::Unit => {
return Err(Error::new(
ErrorKind::InvalidPacketKind,
Some("Expected content packet, got unit.".to_string())));
}
PacketKind::Unknown => {
return Err(Error::new(
ErrorKind::UnknownPacketKind,
None))
},
}
number_of_packets += 1;
}
}
/// Saves `Self` into `location`.
pub fn save(&self, location: &Path) {
let message_ron = self.to_ron().unwrap();
fs::create_dir_all(location.parent().unwrap()).unwrap();
let mut file = fs::OpenOptions::new().create(true).write(true).open(location).unwrap();
file.write_fmt(format_args!("{}", message_ron)).unwrap();
}
// Implementation of setters and getters for Message.
/// Returns `metadata`.
///
/// Metadata are cloned.
pub fn metadata(&self) -> M {
self.metadata.clone()
}
/// Returns a reference to `metadata`.
pub fn metadata_ref(&'a self) -> &'a M {
&self.metadata
}
/// Returns a mutable reference to `metadata`.
pub fn metadata_mut(&'a mut self) -> &'a mut M {
&mut self.metadata
}
/// Takes ownership of `Self` and return owned `metadata`.
pub fn metadata_move(self) -> M {
self.metadata
}
/// Returns a 'cloned' content.
pub fn content(&self) -> C {
self.content.clone()
}
/// Return a reference to `content`.
pub fn content_ref(&self) -> &C {
&self.content
}
/// Return a mutable reference to `content`.
pub fn content_mut(&mut self) -> &mut C {
&mut self.content
}
/// Takes ownership of `Self` and return owned `content`.
pub fn content_move(self) -> C {
self.content
}
/// Returns `end_data`.
///
/// `end_data` are cloned.
pub fn end_data(&self) -> Packet {
self.end_data.clone()
}
/// Sets [Message] `metadata` to given.
pub fn set_metadata(&mut self, metadata: M) {
self.metadata = metadata;
}
/// Sets [Message] `content` to given.
pub fn set_content(&mut self, content: C) {
self.content = content;
}
/// Sets [Message] `end_data` to given packet, this [Packet] should have `kind` [PacketKind::End].
pub fn set_end_data(&mut self, end_data: Packet) {
self.end_data = end_data;
}
}