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
use std::{
    collections::HashMap,
    fmt::Display,
    hash::{Hash, Hasher},
};

use serde::{Deserialize, Serialize};

#[cfg(test)]
mod test;
mod trait_impls;
mod traits;

///Measured in microseconds <p>
/// depending on source can be from unix epoch or some arbitrary start time
pub type FrcTimestamp = u64;
type Bytes = Vec<u8>;

pub fn now() -> FrcTimestamp {
    let now = std::time::SystemTime::now();
    let since_epoch = now.duration_since(std::time::UNIX_EPOCH).unwrap();
    since_epoch.as_micros() as FrcTimestamp
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FrcType {
    Boolean,
    Int,
    Double,
    Float,
    String,
    BoolArray,
    IntArray,
    FloatArray,
    DoubleArray,
    StringArray,
    Binary,
}
impl Display for FrcType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FrcType::Boolean => write!(f, "Boolean"),
            FrcType::Int => write!(f, "Int"),
            FrcType::Double => write!(f, "Double"),
            FrcType::Float => write!(f, "Float"),
            FrcType::String => write!(f, "String"),
            FrcType::BoolArray => write!(f, "BoolArray"),
            FrcType::IntArray => write!(f, "IntArray"),
            FrcType::FloatArray => write!(f, "FloatArray"),
            FrcType::DoubleArray => write!(f, "DoubleArray"),
            FrcType::StringArray => write!(f, "StringArray"),
            FrcType::Binary => write!(f, "Binary"),
        }
    }
}

impl Serialize for FrcType {
    fn serialize<S>(
        &self,
        serializer: S,
    ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
    where
        S: serde::Serializer,
    {
        if let Self::Binary = self {
            return serializer.serialize_str("raw");
        }
        serializer.serialize_str(&self.to_string().to_lowercase().replace("array", "[]"))
    }
}

impl<'a> Deserialize<'a> for FrcType {
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'a>>::Error>
    where
        D: serde::Deserializer<'a>,
    {
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "boolean" => Ok(FrcType::Boolean),
            "int" => Ok(FrcType::Int),
            "double" => Ok(FrcType::Double),
            "float" => Ok(FrcType::Float),
            "string" => Ok(FrcType::String),
            "json" => Ok(FrcType::String),
            "bool[]" => Ok(FrcType::BoolArray),
            "int[]" => Ok(FrcType::IntArray),
            "float[]" => Ok(FrcType::FloatArray),
            "double[]" => Ok(FrcType::DoubleArray),
            "string[]" => Ok(FrcType::StringArray),
            "raw" => Ok(FrcType::Binary),
            "rpc" => Ok(FrcType::Binary),
            "msgpack" => Ok(FrcType::Binary),
            "protobuf" => Ok(FrcType::Binary),
            _ => Err(serde::de::Error::custom(format!("Invalid FrcType: {}", s))),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Hash)]
#[serde(untagged)]
pub enum FrcBinaryFormats {
    ///Unspecified
    Raw(Bytes),
    ///MessagePack
    MsgPack(Bytes),
    ///Protobuf
    Protobuf(Bytes),
}
impl FrcBinaryFormats {
    pub fn get_bytes(&self) -> &Bytes {
        match self {
            FrcBinaryFormats::Raw(v) => v,
            FrcBinaryFormats::MsgPack(v) => v,
            FrcBinaryFormats::Protobuf(v) => v,
        }
    }
    pub fn to_bytes(self) -> Bytes {
        match self {
            FrcBinaryFormats::Raw(v) => v,
            FrcBinaryFormats::MsgPack(v) => v,
            FrcBinaryFormats::Protobuf(v) => v,
        }
    }
    pub fn len(&self) -> usize {
        match self {
            FrcBinaryFormats::Raw(v) => v.len(),
            FrcBinaryFormats::MsgPack(v) => v.len(),
            FrcBinaryFormats::Protobuf(v) => v.len(),
        }
    }
    pub fn format_str(&self) -> &str {
        match self {
            FrcBinaryFormats::Raw(_) => "Raw",
            FrcBinaryFormats::MsgPack(_) => "MsgPack",
            FrcBinaryFormats::Protobuf(_) => "Protobuf",
        }
    }
}
impl Display for FrcBinaryFormats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}: {} Bytes]", self.format_str(), self.len())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FrcValue {
    Boolean(bool),
    Int(i64),
    Double(f64),
    Float(f32),
    String(String),
    BooleanArray(Vec<bool>),
    IntArray(Vec<i64>),
    FloatArray(Vec<f32>),
    DoubleArray(Vec<f64>),
    StringArray(Vec<String>),
    Binary(FrcBinaryFormats),
}
impl Display for FrcValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FrcValue::Boolean(v) => write!(f, "{}", v),
            FrcValue::Int(v) => write!(f, "{}", v),
            FrcValue::Double(v) => write!(f, "{}", v),
            FrcValue::Float(v) => write!(f, "{}", v),
            FrcValue::String(v) => write!(f, "{}", v),
            FrcValue::BooleanArray(v) => write!(f, "{:?}", v),
            FrcValue::IntArray(v) => write!(f, "{:?}", v),
            FrcValue::FloatArray(v) => write!(f, "{:?}", v),
            FrcValue::DoubleArray(v) => write!(f, "{:?}", v),
            FrcValue::StringArray(v) => write!(f, "{:?}", v),
            FrcValue::Binary(v) => write!(f, "{}", v),
        }
    }
}
impl Hash for FrcValue {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            FrcValue::Boolean(v) => v.hash(state),
            FrcValue::Int(v) => v.hash(state),
            FrcValue::Double(v) => v.to_bits().hash(state),
            FrcValue::Float(v) => v.to_bits().hash(state),
            FrcValue::String(v) => v.hash(state),
            FrcValue::BooleanArray(v) => v.hash(state),
            FrcValue::IntArray(v) => v.hash(state),
            FrcValue::FloatArray(v) => v.iter().for_each(|v| v.to_bits().hash(state)),
            FrcValue::DoubleArray(v) => v.iter().for_each(|v| v.to_bits().hash(state)),
            FrcValue::StringArray(v) => v.hash(state),
            FrcValue::Binary(v) => v.hash(state),
        }
    }
}
impl FrcValue {
    ///Returns the type enum of the value, a more memory efficient way of checking the type
    pub fn get_type(&self) -> FrcType {
        match self {
            FrcValue::Boolean(_) => FrcType::Boolean,
            FrcValue::Int(_) => FrcType::Int,
            FrcValue::Double(_) => FrcType::Double,
            FrcValue::Float(_) => FrcType::Float,
            FrcValue::String(_) => FrcType::String,
            FrcValue::BooleanArray(_) => FrcType::BoolArray,
            FrcValue::IntArray(_) => FrcType::IntArray,
            FrcValue::FloatArray(_) => FrcType::FloatArray,
            FrcValue::DoubleArray(_) => FrcType::DoubleArray,
            FrcValue::StringArray(_) => FrcType::StringArray,
            FrcValue::Binary(_) => FrcType::Binary,
        }
    }
    ///Creates an empty Binary
    pub fn empty() -> Self {
        Self::Binary(FrcBinaryFormats::Raw(Vec::new()))
    }
    ///always false if not binary, array or string
    pub fn is_empty(&self) -> bool {
        match self {
            FrcValue::String(v) => v.is_empty(),
            FrcValue::BooleanArray(v) => v.is_empty(),
            FrcValue::IntArray(v) => v.is_empty(),
            FrcValue::DoubleArray(v) => v.is_empty(),
            FrcValue::FloatArray(v) => v.is_empty(),
            FrcValue::StringArray(v) => v.is_empty(),
            FrcValue::Binary(v) => v.len() == 0,
            _ => false,
        }
    }
    ///Binary is false
    pub fn is_array(&self) -> bool {
        match self {
            FrcValue::BooleanArray(_) => true,
            FrcValue::IntArray(_) => true,
            FrcValue::DoubleArray(_) => true,
            FrcValue::FloatArray(_) => true,
            FrcValue::StringArray(_) => true,
            _ => false,
        }
    }
    /// Consumes itself to a timestamped value with the current timestamp
    pub fn to_timestamped_now(self) -> FrcTimestampedValue {
        FrcTimestampedValue::new(now(), self)
    }
    /// Consumes itself to a timestamped value with the given timestamp
    pub fn to_timestamped(self, timestamp: FrcTimestamp) -> FrcTimestampedValue {
        FrcTimestampedValue::new(timestamp, self)
    }
    /// Clones itself to a timestamped value with the current timestamp
    pub fn as_timestamped_now(&self) -> FrcTimestampedValue {
        FrcTimestampedValue::new(now(), self.clone())
    }
    /// Clones itself to a timestamped value with the given timestamp
    pub fn as_timestamped(&self, timestamp: FrcTimestamp) -> FrcTimestampedValue {
        FrcTimestampedValue::new(timestamp, self.clone())
    }
    pub fn to_tagged(self) -> TaggedValue {
        TaggedValue {
            r#type: self.get_type(),
            value: self,
        }
    }
    ///creates a default value based on the type
    pub fn default_value(r#type: FrcType) -> Self {
        match r#type {
            FrcType::Boolean => FrcValue::Boolean(false),
            FrcType::Int => FrcValue::Int(0),
            FrcType::Double => FrcValue::Double(0.0),
            FrcType::Float => FrcValue::Float(0.0),
            FrcType::String => FrcValue::String(String::new()),
            FrcType::BoolArray => FrcValue::BooleanArray(Vec::new()),
            FrcType::IntArray => FrcValue::IntArray(Vec::new()),
            FrcType::FloatArray => FrcValue::FloatArray(Vec::new()),
            FrcType::DoubleArray => FrcValue::DoubleArray(Vec::new()),
            FrcType::StringArray => FrcValue::StringArray(Vec::new()),
            FrcType::Binary => FrcValue::Binary(FrcBinaryFormats::Raw(Vec::new())),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Hash)]
pub struct TaggedValue {
    #[serde(rename = "type")]
    pub r#type: FrcType,
    pub value: FrcValue,
}
impl Display for TaggedValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}({})", self.r#type, self.value)
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Hash)]
pub struct FrcTimestampedValue {
    pub timestamp: FrcTimestamp,
    pub value: FrcValue,
}
impl Display for FrcTimestampedValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} at {}", self.value, self.timestamp)
    }
}
impl FrcTimestampedValue {
    pub fn new(timestamp: FrcTimestamp, value: FrcValue) -> Self {
        Self { timestamp, value }
    }
    pub fn get_type(&self) -> FrcType {
        self.value.get_type()
    }
    pub fn is_empty(&self) -> bool {
        self.value.is_empty()
    }
    pub fn is_array(&self) -> bool {
        self.value.is_array()
    }
    pub fn is_after_timestamp(&self, timestamp: FrcTimestamp) -> bool {
        self.timestamp > timestamp
    }
    pub fn is_after_other(&self, other: &Self) -> bool {
        self.timestamp > other.timestamp
    }
    pub fn is_before_timestamp(&self, timestamp: FrcTimestamp) -> bool {
        self.timestamp < timestamp
    }
    pub fn is_before_other(&self, other: &Self) -> bool {
        self.timestamp < other.timestamp
    }
    pub fn replace_timestamp(&mut self, timestamp: FrcTimestamp) {
        self.timestamp = timestamp;
    }
    pub fn replace_value(&mut self, value: FrcValue) {
        self.value = value;
    }
    pub fn replace(&mut self, other: Self) {
        self.timestamp = other.timestamp;
        self.value = other.value;
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrcTimeline(Vec<FrcTimestampedValue>);

impl IntoIterator for FrcTimeline {
    type Item = FrcTimestampedValue;
    type IntoIter = std::vec::IntoIter<Self::Item>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl FrcTimeline {
    pub fn new() -> Self {
        Self(Vec::new())
    }
    pub fn from_vec_sorted(vec: Vec<FrcTimestampedValue>) -> Self {
        Self(vec)
    }
    pub fn from_vec(mut vec: Vec<FrcTimestampedValue>) -> Self {
        vec.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
        Self(vec)
    }
    pub fn to_vec(self) -> Vec<FrcTimestampedValue> {
        self.0
    }
    pub fn is_all_same_type(&self) -> bool {
        if self.0.is_empty() {
            return true;
        }
        let first_type = self.0[0].get_type();
        self.0.iter().all(|v| v.get_type() == first_type)
    }
    pub fn is_all_same_type_as(&self, other: &Self) -> bool {
        if self.0.is_empty() || other.0.is_empty() {
            return true;
        }
        let first_type = self.0[0].get_type();
        let other_first_type = other.0[0].get_type();
        first_type == other_first_type && self.0.iter().all(|v| v.get_type() == first_type)
    }
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
    pub fn len(&self) -> usize {
        self.0.len()
    }
    ///if closest above will get the value with the closest timestamp that is after the given timestamp
    /// if closest above is false, will get the value with the closest timestamp that is before the given timestamp
    pub fn get_by_timestamp(
        &self,
        timestamp: u64,
        closest_after: bool,
    ) -> Option<&FrcTimestampedValue> {
        if closest_after {
            if timestamp < self.0[0].timestamp {
                return None;
            }
        } else {
            if timestamp > self.0[self.0.len() - 1].timestamp {
                return None;
            }
        }
        //use a bisect algorithm to find the closest value
        let mut low = 0;
        let mut high = self.0.len() - 1;
        while low <= high {
            let mid = (low + high) / 2;
            if self.0[mid].timestamp < timestamp {
                low = mid + 1;
            } else if self.0[mid].timestamp > timestamp {
                high = mid - 1;
            } else {
                return Some(&self.0[mid]);
            }
        }
        if low == self.0.len() {
            return None;
        }
        if closest_after {
            Some(&self.0[low])
        } else {
            Some(&self.0[low - 1])
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrcTableInstant {
    #[serde(flatten)]
    pub values: HashMap<String, FrcTimestampedValue>, //just now
}
impl Display for FrcTableInstant {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{{")?;
        for (i, (k, v)) in self.values.iter().enumerate() {
            if i != 0 {
                write!(f, ", ")?;
            }
            write!(f, "{}: {}", k, v)?;
        }
        write!(f, "}}")
    }
}
impl FrcTableInstant {
    pub fn new_slim() -> Self {
        Self {
            values: HashMap::new(),
        }
    }
    pub fn new() -> Self {
        Self {
            values: HashMap::new(),
        }
    }
    pub fn from_tuples(mut tuples: Vec<(impl ToString, FrcTimestampedValue)>) -> Self {
        let mut values = HashMap::new();
        tuples.reverse();
        for (k, v) in tuples {
            values.insert(k.to_string(), v);
        }
        Self { values }
    }
    pub fn set_field(&mut self, name: impl ToString, value: FrcTimestampedValue) {
        self.values.insert(name.to_string(), value);
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FrcTableHistory {
    #[serde(flatten)]
    pub values: HashMap<String, FrcTimeline>, //all values that have occured
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "table", rename_all = "lowercase")]
pub enum FrcTable {
    Snapshot(FrcTableInstant),
    History(FrcTableHistory),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrcObject {
    pub table: FrcTableInstant,
    #[serde(rename = "type")]
    pub r#type: String,
    pub schema: FrcObjectSchema,
    panic_on_type_mismatch: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FrcObjectSchema {
    #[serde(flatten)]
    pub values: HashMap<String, FrcType>,
}
impl FrcObjectSchema {
    pub fn from_tuples(tuples: Vec<(impl ToString, FrcType)>) -> Self {
        let mut values = HashMap::new();
        for (k, v) in tuples {
            values.insert(k.to_string(), v);
        }
        Self { values }
    }
}