1
use std::collections::HashMap;
2

            
3
use finance::split::Split;
4
use finance::transaction::Transaction;
5

            
6
use crate::format::{
7
    AccountData, BASE_OFFSET, CommodityData, ContextType, ENTITY_HEADER_SIZE, EntityFlags,
8
    EntityHeader, EntityType, GLOBAL_HEADER_SIZE, GlobalHeader, OUTPUT_HEADER_SIZE, Operation,
9
    OutputHeader, SplitData, TAG_DATA_SIZE, TagData, TransactionData,
10
};
11

            
12
13680
fn transaction_to_data(tx: &Transaction) -> TransactionData {
13
13680
    TransactionData {
14
13680
        post_date: tx.post_date.timestamp_millis(),
15
13680
        enter_date: tx.enter_date.timestamp_millis(),
16
13680
        split_count: 0,
17
13680
        tag_count: 0,
18
13680
        is_multi_currency: 0,
19
13680
        reserved: [0; 23],
20
13680
    }
21
13680
}
22

            
23
24890
fn split_to_data(split: &Split, account_name_offset: u32, account_name_len: u32) -> SplitData {
24
    SplitData {
25
24890
        account_id: *split.account_id.as_bytes(),
26
24890
        commodity_id: *split.commodity_id.as_bytes(),
27
24890
        value_num: split.value_num,
28
24890
        value_denom: split.value_denom,
29
24890
        reconcile_state: split.reconcile_state.map_or(0, u8::from),
30
24890
        reserved: [0; 7],
31
24890
        reconcile_date: split
32
24890
            .reconcile_date
33
24890
            .map_or(0, |d: chrono::DateTime<chrono::Utc>| d.timestamp_millis()),
34
24890
        account_name_offset,
35
24890
        account_name_len,
36
    }
37
24890
}
38

            
39
pub struct MemorySerializer {
40
    context_type: ContextType,
41
    primary_entity_type: EntityType,
42
    primary_entity_idx: u32,
43
    entities: Vec<SerializedEntity>,
44
    strings_pool: Vec<u8>,
45
    string_cache: HashMap<String, (u32, u16)>,
46
}
47

            
48
struct SerializedEntity {
49
    header: EntityHeader,
50
    data: Vec<u8>,
51
}
52

            
53
/// Header fields shared by every `add_*` entry: identity, parenting, and
54
/// the two flag bits (`is_primary`, `is_context`). Pulled out so each
55
/// add_* fn signature stays under clippy's `too_many_arguments` cap.
56
#[derive(Debug, Clone, Copy)]
57
pub struct EntityHeaderArgs {
58
    pub id: [u8; 16],
59
    pub parent_idx: i32,
60
    pub is_primary: bool,
61
    pub is_context: bool,
62
}
63

            
64
/// Body fields specific to a transaction entity. Combined with
65
/// [`EntityHeaderArgs`] by [`MemorySerializer::add_transaction`].
66
#[derive(Debug, Clone, Copy)]
67
pub struct TransactionArgs {
68
    pub post_date: i64,
69
    pub enter_date: i64,
70
    pub split_count: u32,
71
    pub tag_count: u32,
72
    pub is_multi_currency: bool,
73
}
74

            
75
/// Body fields specific to a split entity. `account_name` borrows from the
76
/// caller and is interned into the strings pool by
77
/// [`MemorySerializer::add_split`] so a trigger script can read the posting
78
/// account's display name via `SPLIT-ACCOUNT-NAME`.
79
#[derive(Debug, Clone, Copy)]
80
pub struct SplitArgs<'a> {
81
    pub account_id: [u8; 16],
82
    pub commodity_id: [u8; 16],
83
    pub value_num: i64,
84
    pub value_denom: i64,
85
    pub reconcile_state: u8,
86
    pub reconcile_date: i64,
87
    pub account_name: &'a str,
88
}
89

            
90
/// Body fields specific to an account entity. The `name` and `path`
91
/// borrow from the caller's scope and are interned into the strings
92
/// pool by [`MemorySerializer::add_account`].
93
#[derive(Debug, Clone, Copy)]
94
pub struct AccountArgs<'a> {
95
    pub parent_account_id: [u8; 16],
96
    pub name: &'a str,
97
    pub path: &'a str,
98
    pub tag_count: u32,
99
}
100

            
101
/// Body fields specific to a commodity entity.
102
#[derive(Debug, Clone, Copy)]
103
pub struct CommodityArgs<'a> {
104
    pub symbol: &'a str,
105
    pub name: &'a str,
106
    pub tag_count: u32,
107
}
108

            
109
/// Aggregate args for `add_transaction_from`: the source `Transaction`
110
/// plus the runtime-supplied counters and primary flag the test harness
111
/// can't infer from the row.
112
#[derive(Debug, Clone, Copy)]
113
pub struct TransactionFromArgs<'a> {
114
    pub transaction: &'a Transaction,
115
    pub is_primary: bool,
116
    pub split_count: u32,
117
    pub tag_count: u32,
118
    pub is_multi_currency: bool,
119
}
120

            
121
impl Default for MemorySerializer {
122
    fn default() -> Self {
123
        Self::new()
124
    }
125
}
126

            
127
impl MemorySerializer {
128
    #[must_use]
129
1637233
    pub fn new() -> Self {
130
1637233
        Self {
131
1637233
            context_type: ContextType::EntityCreate,
132
1637233
            primary_entity_type: EntityType::Transaction,
133
1637233
            primary_entity_idx: 0,
134
1637233
            entities: Vec::new(),
135
1637233
            strings_pool: Vec::new(),
136
1637233
            string_cache: HashMap::new(),
137
1637233
        }
138
1637233
    }
139

            
140
1637232
    pub fn set_context(&mut self, context_type: ContextType, primary_entity_type: EntityType) {
141
1637232
        self.context_type = context_type;
142
1637232
        self.primary_entity_type = primary_entity_type;
143
1637232
    }
144

            
145
431112
    pub fn set_primary(&mut self, entity_idx: u32) {
146
431112
        self.primary_entity_idx = entity_idx;
147
431112
    }
148

            
149
4175447
    pub fn add_string(&mut self, s: &str) -> (u32, u16) {
150
4175447
        if let Some(&cached) = self.string_cache.get(s) {
151
12351
            return cached;
152
4163096
        }
153
4163096
        let offset = self.strings_pool.len() as u32;
154
4163096
        let len = s.len() as u16;
155
4163096
        self.strings_pool.extend_from_slice(s.as_bytes());
156
4163096
        self.string_cache.insert(s.to_string(), (offset, len));
157
4163096
        (offset, len)
158
4175447
    }
159

            
160
826502
    pub fn add_transaction(&mut self, header: EntityHeaderArgs, args: TransactionArgs) -> u32 {
161
826502
        let flags = EntityFlags::make(header.is_primary, header.is_context);
162
826502
        let data = TransactionData {
163
826502
            post_date: args.post_date,
164
826502
            enter_date: args.enter_date,
165
826502
            split_count: args.split_count,
166
826502
            tag_count: args.tag_count,
167
826502
            is_multi_currency: u8::from(args.is_multi_currency),
168
826502
            reserved: [0; 23],
169
826502
        };
170
826502
        let entity_header = EntityHeader::new(
171
826502
            EntityType::Transaction,
172
826502
            Operation::Nop,
173
826502
            flags,
174
826502
            header.id,
175
826502
            header.parent_idx,
176
826502
            0,
177
826502
            data.to_bytes().len() as u32,
178
826502
        );
179
826502
        let idx = self.entities.len() as u32;
180
826502
        self.entities.push(SerializedEntity {
181
826502
            header: entity_header,
182
826502
            data: data.to_bytes().to_vec(),
183
826502
        });
184
826502
        idx
185
826502
    }
186

            
187
1648252
    pub fn add_split(&mut self, header: EntityHeaderArgs, args: SplitArgs) -> u32 {
188
1648252
        let flags = EntityFlags::make(header.is_primary, header.is_context);
189
1648252
        let (name_offset, _) = self.add_string(args.account_name);
190
1648252
        let data = SplitData {
191
1648252
            account_id: args.account_id,
192
1648252
            commodity_id: args.commodity_id,
193
1648252
            value_num: args.value_num,
194
1648252
            value_denom: args.value_denom,
195
1648252
            reconcile_state: args.reconcile_state,
196
1648252
            reserved: [0; 7],
197
1648252
            reconcile_date: args.reconcile_date,
198
1648252
            account_name_offset: name_offset,
199
1648252
            // The format gives the split account name a u32 length; take the full
200
1648252
            // byte length rather than `add_string`'s u16 (which would wrap a name
201
1648252
            // longer than 65535 bytes while the field claims u32 capacity).
202
1648252
            account_name_len: args.account_name.len() as u32,
203
1648252
        };
204
1648252
        let entity_header = EntityHeader::new(
205
1648252
            EntityType::Split,
206
1648252
            Operation::Nop,
207
1648252
            flags,
208
1648252
            header.id,
209
1648252
            header.parent_idx,
210
1648252
            0,
211
1648252
            data.to_bytes().len() as u32,
212
1648252
        );
213
1648252
        let idx = self.entities.len() as u32;
214
1648252
        self.entities.push(SerializedEntity {
215
1648252
            header: entity_header,
216
1648252
            data: data.to_bytes().to_vec(),
217
1648252
        });
218
1648252
        idx
219
1648252
    }
220

            
221
1250961
    pub fn add_tag(
222
1250961
        &mut self,
223
1250961
        id: [u8; 16],
224
1250961
        parent_idx: i32,
225
1250961
        is_primary: bool,
226
1250961
        is_context: bool,
227
1250961
        name: &str,
228
1250961
        value: &str,
229
1250961
    ) -> u32 {
230
1250961
        let flags = EntityFlags::make(is_primary, is_context);
231
1250961
        let (name_offset, name_len) = self.add_string(name);
232
1250961
        let (value_offset, value_len) = self.add_string(value);
233
1250961
        let data = TagData {
234
1250961
            name_offset,
235
1250961
            value_offset,
236
1250961
            name_len,
237
1250961
            value_len,
238
1250961
            reserved: [0; 4],
239
1250961
        };
240
1250961
        let header = EntityHeader::new(
241
1250961
            EntityType::Tag,
242
1250961
            Operation::Nop,
243
1250961
            flags,
244
1250961
            id,
245
1250961
            parent_idx,
246
1250961
            0,
247
1250961
            TAG_DATA_SIZE as u32,
248
1250961
        );
249
1250961
        let idx = self.entities.len() as u32;
250
1250961
        self.entities.push(SerializedEntity {
251
1250961
            header,
252
1250961
            data: data.to_bytes().to_vec(),
253
1250961
        });
254
1250961
        idx
255
1250961
    }
256

            
257
190
    pub fn add_account(&mut self, header: EntityHeaderArgs, args: AccountArgs<'_>) -> u32 {
258
190
        let flags = EntityFlags::make(header.is_primary, header.is_context);
259
190
        let (name_offset, name_len) = self.add_string(args.name);
260
190
        let (path_offset, path_len) = self.add_string(args.path);
261
190
        let data = AccountData {
262
190
            parent_account_id: args.parent_account_id,
263
190
            name_offset,
264
190
            path_offset,
265
190
            tag_count: args.tag_count,
266
190
            name_len,
267
190
            path_len,
268
190
            reserved: [0; 16],
269
190
        };
270
190
        let entity_header = EntityHeader::new(
271
190
            EntityType::Account,
272
190
            Operation::Nop,
273
190
            flags,
274
190
            header.id,
275
190
            header.parent_idx,
276
190
            0,
277
190
            data.to_bytes().len() as u32,
278
190
        );
279
190
        let idx = self.entities.len() as u32;
280
190
        self.entities.push(SerializedEntity {
281
190
            header: entity_header,
282
190
            data: data.to_bytes().to_vec(),
283
190
        });
284
190
        idx
285
190
    }
286

            
287
    pub fn add_commodity(&mut self, header: EntityHeaderArgs, args: CommodityArgs<'_>) -> u32 {
288
        let flags = EntityFlags::make(header.is_primary, header.is_context);
289
        let (symbol_offset, symbol_len) = self.add_string(args.symbol);
290
        let (name_offset, name_len) = self.add_string(args.name);
291
        let data = CommodityData {
292
            symbol_offset,
293
            name_offset,
294
            tag_count: args.tag_count,
295
            symbol_len,
296
            name_len,
297
            reserved: [0; 16],
298
        };
299
        let entity_header = EntityHeader::new(
300
            EntityType::Commodity,
301
            Operation::Nop,
302
            flags,
303
            header.id,
304
            header.parent_idx,
305
            0,
306
            data.to_bytes().len() as u32,
307
        );
308
        let idx = self.entities.len() as u32;
309
        self.entities.push(SerializedEntity {
310
            header: entity_header,
311
            data: data.to_bytes().to_vec(),
312
        });
313
        idx
314
    }
315

            
316
    #[must_use]
317
1
    pub fn entity_count(&self) -> u32 {
318
1
        self.entities.len() as u32
319
1
    }
320

            
321
13680
    pub fn add_transaction_from(&mut self, args: TransactionFromArgs<'_>) -> u32 {
322
13680
        let flags = EntityFlags::make(args.is_primary, false);
323
13680
        let mut data = transaction_to_data(args.transaction);
324
13680
        data.split_count = args.split_count;
325
13680
        data.tag_count = args.tag_count;
326
13680
        data.is_multi_currency = u8::from(args.is_multi_currency);
327
13680
        let header = EntityHeader::new(
328
13680
            EntityType::Transaction,
329
13680
            Operation::Nop,
330
13680
            flags,
331
13680
            *args.transaction.id.as_bytes(),
332
13680
            -1,
333
13680
            0,
334
13680
            data.to_bytes().len() as u32,
335
13680
        );
336
13680
        let idx = self.entities.len() as u32;
337
13680
        self.entities.push(SerializedEntity {
338
13680
            header,
339
13680
            data: data.to_bytes().to_vec(),
340
13680
        });
341
13680
        idx
342
13680
    }
343

            
344
24890
    pub fn add_split_from(&mut self, split: &Split, parent_idx: i32, account_name: &str) -> u32 {
345
24890
        let (name_offset, _) = self.add_string(account_name);
346
24890
        let data = split_to_data(split, name_offset, account_name.len() as u32);
347
24890
        let header = EntityHeader::new(
348
24890
            EntityType::Split,
349
24890
            Operation::Nop,
350
24890
            0,
351
24890
            *split.id.as_bytes(),
352
24890
            parent_idx,
353
24890
            0,
354
24890
            data.to_bytes().len() as u32,
355
24890
        );
356
24890
        let idx = self.entities.len() as u32;
357
24890
        self.entities.push(SerializedEntity {
358
24890
            header,
359
24890
            data: data.to_bytes().to_vec(),
360
24890
        });
361
24890
        idx
362
24890
    }
363

            
364
    #[must_use]
365
1637232
    pub fn finalize(mut self, output_size: u32) -> Vec<u8> {
366
1637232
        let entity_count = self.entities.len() as u32;
367
1637232
        let entities_offset = BASE_OFFSET + GLOBAL_HEADER_SIZE as u32;
368

            
369
1637232
        let mut entities_total_size = 0u32;
370
1637232
        for entity in &self.entities {
371
3764475
            entities_total_size += ENTITY_HEADER_SIZE as u32 + entity.data.len() as u32;
372
        }
373

            
374
1637232
        let strings_pool_offset = entities_offset + entities_total_size;
375
1637232
        let strings_pool_size = self.strings_pool.len() as u32;
376
1637232
        let output_offset = strings_pool_offset + strings_pool_size;
377

            
378
1637232
        let output_header = OutputHeader::new(entity_count);
379

            
380
1637232
        let mut global_header = GlobalHeader::new(
381
1637232
            self.context_type,
382
1637232
            self.primary_entity_type,
383
1637232
            entity_count,
384
1637232
            self.primary_entity_idx,
385
1637232
        );
386
1637232
        global_header.entities_offset = entities_offset;
387
1637232
        global_header.strings_pool_offset = strings_pool_offset;
388
1637232
        global_header.strings_pool_size = strings_pool_size;
389
1637232
        global_header.output_offset = output_offset;
390
1637232
        global_header.output_size = output_size;
391

            
392
1637232
        let total_size = GLOBAL_HEADER_SIZE
393
1637232
            + entities_total_size as usize
394
1637232
            + strings_pool_size as usize
395
1637232
            + output_size as usize;
396
1637232
        let mut buffer = vec![0u8; total_size];
397

            
398
1637232
        buffer[..GLOBAL_HEADER_SIZE].copy_from_slice(global_header.as_bytes());
399

            
400
1637232
        let headers_total = entity_count as usize * ENTITY_HEADER_SIZE;
401
1637232
        let mut data_offset = entities_offset + headers_total as u32;
402
1637232
        let mut write_pos = GLOBAL_HEADER_SIZE;
403

            
404
1637232
        for entity in &mut self.entities {
405
3764475
            entity.header.data_offset = data_offset;
406
3764475
            data_offset += entity.data.len() as u32;
407
        }
408

            
409
1637232
        for entity in &self.entities {
410
3764475
            let header_bytes = entity.header.to_bytes();
411
3764475
            buffer[write_pos..write_pos + ENTITY_HEADER_SIZE].copy_from_slice(&header_bytes);
412
3764475
            write_pos += ENTITY_HEADER_SIZE;
413
        }
414

            
415
1637232
        for entity in &self.entities {
416
3764475
            buffer[write_pos..write_pos + entity.data.len()].copy_from_slice(&entity.data);
417
3764475
            write_pos += entity.data.len();
418
        }
419

            
420
1637232
        buffer[write_pos..write_pos + self.strings_pool.len()].copy_from_slice(&self.strings_pool);
421
1637232
        write_pos += self.strings_pool.len();
422

            
423
1637232
        buffer[write_pos..write_pos + OUTPUT_HEADER_SIZE]
424
1637232
            .copy_from_slice(&output_header.to_bytes());
425

            
426
1637232
        buffer
427
1637232
    }
428
}
429

            
430
#[cfg(test)]
431
mod tests {
432
    use super::*;
433
    use crate::format::MAGIC_NOMI;
434

            
435
    #[test]
436
1
    fn test_serializer_basic() {
437
1
        let mut serializer = MemorySerializer::new();
438
1
        serializer.set_context(ContextType::EntityCreate, EntityType::Transaction);
439

            
440
1
        let tx_id = [1u8; 16];
441
1
        let tx_idx = serializer.add_transaction(
442
1
            EntityHeaderArgs {
443
1
                id: tx_id,
444
1
                parent_idx: -1,
445
1
                is_primary: true,
446
1
                is_context: false,
447
1
            },
448
1
            TransactionArgs {
449
1
                post_date: 1000,
450
1
                enter_date: 2000,
451
1
                split_count: 2,
452
1
                tag_count: 1,
453
1
                is_multi_currency: false,
454
1
            },
455
1
        );
456
1
        serializer.set_primary(tx_idx);
457

            
458
1
        let split_id = [2u8; 16];
459
1
        let account_id = [3u8; 16];
460
1
        let commodity_id = [4u8; 16];
461
1
        serializer.add_split(
462
1
            EntityHeaderArgs {
463
1
                id: split_id,
464
1
                parent_idx: tx_idx as i32,
465
1
                is_primary: false,
466
1
                is_context: false,
467
1
            },
468
1
            SplitArgs {
469
1
                account_id,
470
1
                commodity_id,
471
1
                value_num: -5000,
472
1
                value_denom: 100,
473
1
                reconcile_state: 0,
474
1
                reconcile_date: 0,
475
1
                account_name: "Assets:Test",
476
1
            },
477
1
        );
478

            
479
1
        let tag_id = [5u8; 16];
480
1
        serializer.add_tag(
481
1
            tag_id,
482
1
            tx_idx as i32,
483
1
            false,
484
1
            false,
485
1
            "note",
486
1
            "test transaction",
487
1
        );
488

            
489
1
        assert_eq!(serializer.entity_count(), 3);
490

            
491
1
        let buffer = serializer.finalize(1024);
492

            
493
1
        let header = GlobalHeader::from_bytes(&buffer).unwrap();
494
1
        assert_eq!(header.magic, MAGIC_NOMI);
495
1
        assert_eq!(header.input_entity_count, 3);
496
1
        assert_eq!(header.context_type, ContextType::EntityCreate as u8);
497
1
        assert_eq!(header.primary_entity_type, EntityType::Transaction as u8);
498
1
    }
499

            
500
    #[test]
501
1
    fn split_account_name_round_trips_through_strings_pool() {
502
1
        let mut ser = MemorySerializer::new();
503
1
        ser.set_context(ContextType::EntityCreate, EntityType::Transaction);
504
1
        let tx_idx = ser.add_transaction(
505
1
            EntityHeaderArgs {
506
1
                id: [1u8; 16],
507
1
                parent_idx: -1,
508
1
                is_primary: true,
509
1
                is_context: false,
510
1
            },
511
1
            TransactionArgs {
512
1
                post_date: 0,
513
1
                enter_date: 0,
514
1
                split_count: 1,
515
1
                tag_count: 0,
516
1
                is_multi_currency: false,
517
1
            },
518
1
        );
519
1
        ser.set_primary(tx_idx);
520
1
        ser.add_split(
521
1
            EntityHeaderArgs {
522
1
                id: [2u8; 16],
523
1
                parent_idx: tx_idx as i32,
524
1
                is_primary: false,
525
1
                is_context: false,
526
1
            },
527
1
            SplitArgs {
528
1
                account_id: [3u8; 16],
529
1
                commodity_id: [4u8; 16],
530
1
                value_num: -5000,
531
1
                value_denom: 100,
532
1
                reconcile_state: 0,
533
1
                reconcile_date: 0,
534
1
                account_name: "Metro",
535
1
            },
536
1
        );
537
1
        let buf = ser.finalize(1024);
538

            
539
1
        let header = GlobalHeader::from_bytes(&buf).unwrap();
540
        // Header offsets are absolute wasm addresses (BASE_OFFSET-relative); the
541
        // raw buffer starts at BASE_OFFSET, so index it after subtracting that.
542
1
        let base = BASE_OFFSET as usize;
543
        // Entity 1 is the split (entity 0 is the transaction).
544
1
        let split_header_off = header.entities_offset as usize - base + ENTITY_HEADER_SIZE;
545
1
        let split_header = EntityHeader::from_bytes(&buf[split_header_off..]).unwrap();
546
        let split =
547
1
            SplitData::from_bytes(&buf[split_header.data_offset as usize - base..]).unwrap();
548

            
549
        let name_start =
550
1
            header.strings_pool_offset as usize - base + split.account_name_offset as usize;
551
1
        let name = &buf[name_start..name_start + split.account_name_len as usize];
552
1
        assert_eq!(name, b"Metro");
553
1
    }
554

            
555
    #[test]
556
1
    fn test_string_deduplication() {
557
1
        let mut serializer = MemorySerializer::new();
558
1
        let (offset1, len1) = serializer.add_string("test");
559
1
        let (offset2, len2) = serializer.add_string("test");
560
1
        let (offset3, _) = serializer.add_string("other");
561

            
562
1
        assert_eq!(offset1, offset2);
563
1
        assert_eq!(len1, len2);
564
1
        assert_ne!(offset1, offset3);
565
1
    }
566
}