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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! # RusTT
//! TT is a format used to serialize/deserialize data efficiently and fast.
//! TT can be used to transmit data between processes or over the network.
//! TT is designed to not transmit any unneccecary data and keep data sizes small
//! but still easily readable to the machine.
//! The TT data is structured like a key-value format, where keys can be any integer,
//! String or Byte sequence. A value can be that or a Sequence or a Map.
//!
//! At the moment only TTv3 is supported, so all encoding/decoding will be done using that.
//! When another version is supported the enum [`Version`] will be used to specify the
//! (de)serialization version.
//!
//! # untyped TT Values
//! In cases where you cannot define a static structure, there are [`ttv3::Key`]
//! and [`ttv3::Value`]. These enums define alll possible values for a key and value.
//!
//! Since TT can have floats as keys, they will be represented by [`ttv3::serde::TtF32`] or [`ttv3::serde::TtF64`],
//! wich is a wrapper around u32 and u64 to be able to use it in a [`ttv3::Value::Map`].
//! This is not how rust usualy works and should only be used within [`ttv3::Value`]
//! ```
//! # use serde_json::{Number, Map};
//! #
//! # #[allow(dead_code)]
//! enum Key {
//!		String(String),
//!		Bytes(Vec<u8>),
//!		I8(i8),
//!		I16(i16),
//!		I32(i32),
//!		I64(i64),
//!		U8(u8),
//!		U16(u16),
//!		U32(u32),
//!		U64(u64),
//!		Bool(bool),
//!		F32(rustt::ttv3::TtF32),
//!		F64(rustt::ttv3::TtF64),
//! }
//! ```
//!
//! ```
//! # use rustt::ttv3::{Key};
//! #
//! # #[allow(dead_code)]
//! enum Value {
//!		String(String),
//!		Bytes(Vec<u8>),
//!		I8(i8),
//!		I16(i16),
//!		I32(i32),
//!		I64(i64),
//!		U8(u8),
//!		U16(u16),
//!		U32(u32),
//!		U64(u64),
//!		Bool(bool),
//!		F32(rustt::ttv3::TtF32),
//!		F64(rustt::ttv3::TtF64),
//!		Map(std::collections::HashMap<Key, Value>),
//!		Vec(Vec<Value>),
//! }
//! ```
//!
//! # Parsing TT as strongly types data
//!
//! Serde provides macro's for serializing and deserializing data structures.
//! Rust TT is able to use these macros to do all the same things serde_json and the like
//! can do too. For performance reasons it you should use `serde_bytes` for `Vec<u8>` and `[u8]`.
//! If you do not do this other applications will read this as an array of bytes, and not as
//! a Byte Sequence. the distinction being, in TT a byte sequence is encoded just like a string
//! while a sequence of bytes is encoded like any other array.
//!
//! # Versions
//! TT comes in diverent versions. This crate only supports ttv3 as it is the most recent one.
//! Any upcomming tt versions will be supported, this is the reason there is a diferent module for ttv3
//! specific code. [`ttv3::Key`], [`ttv3::Value`] and [`ttv3::Error`] are all specific to ttv3
//! (except maybe [`ttv3::Error`]) so to keep this crate backwards comptible those are in a diferent submodule.

#![feature(optin_builtin_traits)]
#![feature(negative_impls)]

use serde::de as ser_de;
use serde::{Deserialize, Serialize};
use ttv3::serde::ser::ValueSerializer;
use ttv3::size::ValueSizer;
use ttv3::Error;

pub mod ttv3;

pub enum Version {
	V3,
}

/// Deserialize an instance of type `T` from an IO stream of TT.
///
/// The content of the IO stream is deserialized directly from the stream
/// without being buffered in memory by rustt. If you are reading from a file
/// it is recomended to use a buffer.
///
/// # Errors
///
/// If the data coming in doesnt match Type `T` an error will be returned
/// Any IO error will lso cause an error.
pub fn from_reader<T, R>(mut r: R) -> Result<T, Error>
where
	T: ser_de::DeserializeOwned,
	R: std::io::Read,
{
	if ttv3::read_byte(&mut r) != Some(3) {
		return Err(Error::new("Invalid input, can only decode v3 using serde"));
	}
	let mut discard: [u8; 1] = Default::default();
	r.read_exact(&mut discard)?;
	let mut deserializer = ttv3::serde::de_read::Deserializer::from_reader(&mut r);
	T::deserialize(&mut deserializer)
}

/// Deserialize an instance of type `T` from a TT byte slice
///
/// # Errors
///
/// If the data coming in doesnt match Type `T` an error will be returned
/// Any IO error will lso cause an error.
pub fn from_bytes<'a, T>(s: &'a [u8]) -> Result<T, Error>
where
	T: Deserialize<'a>,
{
	if s.len() < 2 {
		return Err(Error::new("Invalid input, not long enough"));
	}
	if s[0] != 3 {
		return Err(Error::new("Invalid input, can only decode v3 using serde"));
	}
	//ignore the Stream bit
	let mut deserializer = ttv3::serde::de::Deserializer::from_bytes(&s[2..]);
	T::deserialize(&mut deserializer)
}

/// Get the size of `T` serialized into bytes.
/// This shoul'd not be used publicly to pre-allocate for to_vec, this already
/// reserves enough space using this function.
///
/// # Errors
///
/// This only errors when `T`'s implementation of `Serialize` decides to fail.
pub fn to_size<T>(value: &T) -> usize
where
	T: Serialize,
{
	//+1 for the version, +1 for the key varint, +1 for the empty key type +1 for the S bit+reserved byte
	let mut sizer = ValueSizer {
		size: 1 + 1 + 1 + 1,
	};
	value.serialize(&mut sizer).unwrap();
	sizer.size
}

/// Serialize `T` into a byte vector.
///
/// # Errors
///
/// This only errors when `T`'s implementation of `Serialize` decides to fail.
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>, ttv3::Error>
where
	T: Serialize,
{
	let len = to_size(value);
	let mut vec: Vec<u8> = Vec::with_capacity(len);
	vec.insert(0, 3);
	vec.insert(1, 0);
	let mut serializer = ValueSerializer::new(&mut vec, ttv3::serde::Empty {});
	value.serialize(&mut serializer)?;
	Ok(vec)
}

#[cfg(test)]
mod tt_tests {

	use serde::{Deserialize, Serialize};

	use crate::ttv3::Key;
	use crate::ttv3::Value;

	#[test]
	fn enc_dec_string() {
		let data = "hello world💖";
		let bytes = crate::to_vec(&data).unwrap();
		let res = crate::from_bytes::<&str>(&bytes);
		assert_eq!(crate::to_size(&data), bytes.len());

		match res {
			Ok(s) => {
				assert_eq!(s, data);
			}
			Err(err) => {
				println!("{}", err);
				assert!(1 != 1, err);
			}
		}
	}

	#[test]
	fn enc_dec_hello_world() {
		let mut map: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();
		map.insert(&"hello", &"world💖");

		let data = crate::to_vec(&map).unwrap();
		let resmap = crate::from_bytes::<std::collections::HashMap<&str, &str>>(&data);
		assert_eq!(crate::to_size(&map), data.len());

		match resmap {
			Ok(m) => {
				let res_sub_str = m.get("hello").unwrap();
				assert_eq!(res_sub_str, &"world💖");
			}
			Err(err) => {
				println!("{}", err);
				assert!(1 != 1, err);
			}
		}
	}
	#[test]
	fn enc_dec_worst_case() {
		let mut map: std::collections::HashMap<&str, Value> = std::collections::HashMap::new();
		map.insert(&"Da5ta", Value::String("n0thing".to_string()));

		let mut submap: std::collections::HashMap<Key, Value> = std::collections::HashMap::new();
		submap.insert(
			Key::String("more".to_string()),
			Value::String("d5ata89".to_string()),
		);

		map.insert(&"Data2", Value::Map(submap));

		let vec: Vec<Value> = vec![
			Value::String("hey".to_string()),
			Value::String("jude".to_string()),
		];
		map.insert(&"Data4", Value::Vec(vec));

		map.insert(&"1", Value::Bytes(vec![1, 2]));

		map.insert(&"2", Value::F64(0.64));

		map.insert(&"3", Value::I64(99));

		map.insert(&"4", Value::Bool(true));

		let data = crate::to_vec(&map).unwrap();
		let resmap = crate::from_bytes::<std::collections::HashMap<&str, Value>>(&data);
		assert_eq!(crate::to_size(&map), data.len());

		match resmap {
			Ok(m) => {
				match m.get("Da5ta") {
					Some(data2) => match data2 {
						Value::String(s) => assert_eq!(s, "n0thing"),
						_ => {
							println!("wrong datatype for Da5ta");
							assert!(1 != 1);
						}
					},
					None => {
						println!("Could not find key Da5ta!!!");
						assert!(1 != 1);
					}
				};
				match m.get("Data2") {
					Some(data2) => match data2 {
						Value::Map(m) => match m.get(&Key::String("more".to_string())) {
							Some(s) => match s {
								Value::String(s) => assert_eq!(s, &"d5ata89"),
								_ => {
									println!("wrong datatype for Da5ta");
									assert!(1 != 1);
								}
							},
							None => {
								println!("Could not find key Data2.more!!!");
								assert!(1 != 1);
							}
						},
						_ => {
							println!("wrong datatype for Data2");
							assert!(1 != 1);
						}
					},
					None => {
						println!("Could not find key Data2!!!");
						assert!(1 != 1);
					}
				};
				match m.get("Data4") {
					Some(data4) => match data4 {
						Value::Vec(v) => match v.len() {
							2 => {
								match &v[0] {
									Value::String(s) => assert_eq!(s, "hey"),
									_ => {
										println!("wrong datatype for Da5ta[0]");
										assert!(1 != 1);
									}
								};
								match &v[1] {
									Value::String(s) => assert_eq!(s, "jude"),
									_ => {
										println!("wrong datatype for Da5ta[0]");
										assert!(1 != 1);
									}
								};
							}
							_ => {
								println!("wrong length of vec Data4");
								assert!(1 != 1);
							}
						},
						_ => {
							println!("wrong datatype for Data4");
							assert!(1 != 1);
						}
					},
					None => {
						println!("Could not find key Data4!!!");
						assert!(1 != 1);
					}
				};
				match m.get("1") {
					Some(one) => match one {
						Value::Bytes(bytes) => assert_eq!(bytes, &vec![1, 2]),
						_ => {
							println!("wrong datatype for 1!!!");
							assert!(1 != 1);
						}
					},
					None => {
						println!("Could not find key 1!!!");
						assert!(1 != 1);
					}
				}
				match m.get("2") {
					Some(one) => match one {
						Value::F64(f) => assert_eq!(f, &0.64),
						_ => {
							println!("wrong datatype for 2!!!");
							assert!(1 != 1);
						}
					},
					None => {
						println!("Could not find key 2!!!");
						assert!(1 != 1);
					}
				}
				match m.get("3") {
					Some(one) => match one {
						Value::I64(f) => assert_eq!(f, &99),
						_ => {
							println!("wrong datatype for 3!!!");
							assert!(1 != 1);
						}
					},
					None => {
						println!("Could not find key 3!!!");
						assert!(1 != 1);
					}
				}
				match m.get("4") {
					Some(one) => match one {
						Value::Bool(f) => assert_eq!(f, &true),
						_ => {
							println!("wrong datatype for 4!!!");
							assert!(1 != 1);
						}
					},
					None => {
						println!("Could not find key 4!!!");
						assert!(1 != 1);
					}
				}
			}
			Err(err) => {
				println!("{}", err);
				assert!(1 != 1, err);
			}
		}
	}

	#[derive(Deserialize, Serialize, Debug)]
	enum A {
		A,
		B(u8),
		C(u8, u8),
		D { a: u8, b: u8 },
	}
	#[test]
	fn enc_dec_c_enum() {
		let input = A::A;
		let data = crate::to_vec(&input).unwrap();
		let res: A = crate::from_bytes(&data).unwrap();
		match res {
			A::A => {}
			A::B(_) => panic!("wrong enum type: B expected: A"),
			A::C(_, _) => panic!("wrong enum type: C expected: A"),
			A::D { a: _, b: _ } => panic!("wrong enum type: D expected: A"),
		}
	}

	#[test]
	fn enc_dec_value_enum() {
		let input = A::B(6);
		let data = crate::to_vec(&input).unwrap();
		let res: A = crate::from_bytes(&data).unwrap();
		match res {
			A::A => panic!("wrong enum type: A expected: D"),
			A::B(b) => match b {
				6 => {}
				_ => panic!("wrong value for A::B: {} expected: 6", b),
			},
			A::C(_, _) => panic!("wrong enum type: C expected: A"),
			A::D { a: _, b: _ } => panic!("wrong enum type: D expected: A"),
		}
	}

	#[test]
	fn enc_dec_tuple_enum() {
		let input = A::C(6, 8);
		let data = crate::to_vec(&input).unwrap();
		let res: A = crate::from_bytes(&data).unwrap();
		match res {
			A::A => panic!("wrong enum type: A expected: D"),
			A::B(_) => panic!("wrong enum type: B expected: A"),
			A::C(h, j) => {
				match h {
					6 => {}
					_ => panic!("wrong value for a: {} expected: 6", h),
				};
				match j {
					8 => {}
					_ => panic!("wrong value for b: {} expected: 8", h),
				};
			}
			A::D { a: _, b: _ } => panic!("wrong enum type: D expected: A"),
		}
	}

	#[test]
	fn enc_dec_struct_enum() {
		let input = A::D { a: 5, b: 8 };
		let data = crate::to_vec(&input).unwrap();
		let res: A = crate::from_bytes(&data).unwrap();
		match res {
			A::A => panic!("wrong enum type: A expected: D"),
			A::B(_) => panic!("wrong enum type: B expected: D"),
			A::C(_, _) => panic!("wrong enum type: C expected: D"),
			A::D { a: h, b: j } => {
				match h {
					5 => {}
					_ => panic!("wrong value for a: {} expected: 5", h),
				};
				match j {
					8 => {}
					_ => panic!("wrong value for b: {} expected: 8", h),
				}
			}
		}
	}

	#[test]
	fn enc_dec_c_enum_read() {
		let input = A::A;
		let data = crate::to_vec(&input).unwrap();
		let res: A = crate::from_bytes(&data).unwrap();
		match res {
			A::A => {}
			A::B(_) => panic!("wrong enum type: B expected: A"),
			A::C(_, _) => panic!("wrong enum type: C expected: A"),
			A::D { a: _, b: _ } => panic!("wrong enum type: D expected: A"),
		}
	}

	#[test]
	fn enc_dec_value_enum_read() {
		let input = A::B(6);
		let data = crate::to_vec(&input).unwrap();
		let res: A = crate::from_bytes(&data).unwrap();
		match res {
			A::A => panic!("wrong enum type: A expected: D"),
			A::B(b) => match b {
				6 => {}
				_ => panic!("wrong value for A::B: {} expected: 6", b),
			},
			A::C(_, _) => panic!("wrong enum type: C expected: A"),
			A::D { a: _, b: _ } => panic!("wrong enum type: D expected: A"),
		}
	}

	#[test]
	fn enc_dec_tuple_enum_read() {
		let input = A::C(6, 8);
		let data = crate::to_vec(&input).unwrap();
		let res: A = crate::from_bytes(&data).unwrap();
		match res {
			A::A => panic!("wrong enum type: A expected: D"),
			A::B(_) => panic!("wrong enum type: B expected: A"),
			A::C(h, j) => {
				match h {
					6 => {}
					_ => panic!("wrong value for a: {} expected: 6", h),
				};
				match j {
					8 => {}
					_ => panic!("wrong value for b: {} expected: 8", h),
				};
			}
			A::D { a: _, b: _ } => panic!("wrong enum type: D expected: A"),
		}
	}

	#[test]
	fn enc_dec_struct_enum_read() {
		let input = A::D { a: 5, b: 8 };
		let data = crate::to_vec(&input).unwrap();
		let res: A = crate::from_reader(&data as &[u8]).unwrap();
		match res {
			A::A => panic!("wrong enum type: A expected: D"),
			A::B(_) => panic!("wrong enum type: B expected: D"),
			A::C(_, _) => panic!("wrong enum type: C expected: D"),
			A::D { a: h, b: j } => {
				match h {
					5 => {}
					_ => panic!("wrong value for a: {} expected: 5", h),
				};
				match j {
					8 => {}
					_ => panic!("wrong value for b: {} expected: 8", h),
				}
			}
		}
	}
}