ngdp-bpsv 0.4.3

BPSV (Blizzard Pipe-Separated Values) parser and writer for NGDP
Documentation
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! BPSV document representation

use crate::error::{Error, Result};
use crate::schema::BpsvSchema;
use crate::value::BpsvValue;
use std::collections::HashMap;

/// Common functionality for BPSV row types
pub trait BpsvRowOps {
    /// Get the number of values in this row
    fn len(&self) -> usize;

    /// Check if the row is empty
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get a raw string value by index
    fn get_raw(&self, index: usize) -> Option<&str>;

    /// Get a raw string value by field name using the schema
    fn get_raw_by_name(&self, field_name: &str, schema: &BpsvSchema) -> Option<&str> {
        schema
            .get_field(field_name)
            .and_then(|field| self.get_raw(field.index))
    }

    /// Convert row to a map of field names to raw values
    fn to_map(&self, schema: &BpsvSchema) -> Result<HashMap<String, String>> {
        if self.len() != schema.field_count() {
            return Err(Error::SchemaMismatch {
                expected: schema.field_count(),
                actual: self.len(),
            });
        }

        let mut map = HashMap::new();
        for (field_index, field) in schema.fields().iter().enumerate() {
            if let Some(value) = self.get_raw(field_index) {
                map.insert(field.name.clone(), value.to_string());
            }
        }
        Ok(map)
    }
}

/// A single row in a BPSV document with borrowed data
#[derive(Debug, Clone, PartialEq)]
pub struct BpsvRow<'a> {
    /// Raw string values as they appear in the BPSV (borrowed)
    raw_values: Vec<&'a str>,
    /// Typed values (lazy-loaded)
    typed_values: Option<Vec<BpsvValue>>,
}

impl BpsvRowOps for BpsvRow<'_> {
    fn len(&self) -> usize {
        if let Some(typed) = &self.typed_values {
            typed.len()
        } else {
            self.raw_values.len()
        }
    }

    fn get_raw(&self, index: usize) -> Option<&str> {
        self.raw_values.get(index).copied()
    }
}

impl<'a> BpsvRow<'a> {
    /// Create a new row from raw string slices
    pub fn new(values: Vec<&'a str>) -> Self {
        Self {
            raw_values: values,
            typed_values: None,
        }
    }

    /// Create a new row from typed values
    pub fn from_typed_values(values: Vec<BpsvValue>) -> BpsvRow<'static> {
        // For typed values, we need to allocate since we're creating new data
        BpsvRow {
            raw_values: vec![],
            typed_values: Some(values),
        }
    }

    /// Get the number of values in this row
    pub fn len(&self) -> usize {
        BpsvRowOps::len(self)
    }

    /// Check if the row is empty
    pub fn is_empty(&self) -> bool {
        BpsvRowOps::is_empty(self)
    }

    /// Get a raw string value by index
    pub fn get_raw(&self, index: usize) -> Option<&str> {
        BpsvRowOps::get_raw(self, index)
    }

    /// Get a raw string value by field name using the schema
    pub fn get_raw_by_name(&self, field_name: &str, schema: &BpsvSchema) -> Option<&str> {
        BpsvRowOps::get_raw_by_name(self, field_name, schema)
    }

    /// Get all raw values
    pub fn raw_values(&self) -> &[&'a str] {
        &self.raw_values
    }

    /// Parse and get typed values using the schema
    pub fn get_typed_values(&mut self, schema: &BpsvSchema) -> Result<&[BpsvValue]> {
        if self.typed_values.is_none() {
            if self.raw_values.len() != schema.field_count() {
                return Err(Error::SchemaMismatch {
                    expected: schema.field_count(),
                    actual: self.raw_values.len(),
                });
            }

            let mut typed = Vec::new();
            for (value, field) in self.raw_values.iter().zip(schema.fields()) {
                let typed_value = BpsvValue::parse(value, &field.field_type)?;
                typed.push(typed_value);
            }
            self.typed_values = Some(typed);
        }

        Ok(self.typed_values.as_ref().unwrap())
    }

    /// Get a typed value by index
    pub fn get_typed(&mut self, index: usize, schema: &BpsvSchema) -> Result<Option<&BpsvValue>> {
        let typed_values = self.get_typed_values(schema)?;
        Ok(typed_values.get(index))
    }

    /// Get a typed value by field name
    pub fn get_typed_by_name(
        &mut self,
        field_name: &str,
        schema: &BpsvSchema,
    ) -> Result<Option<&BpsvValue>> {
        if let Some(field) = schema.get_field(field_name) {
            self.get_typed(field.index, schema)
        } else {
            Err(Error::FieldNotFound {
                field: field_name.to_string(),
            })
        }
    }

    /// Convert row to a map of field names to raw values
    pub fn to_map(&self, schema: &BpsvSchema) -> Result<HashMap<String, String>> {
        BpsvRowOps::to_map(self, schema)
    }

    /// Convert row to a map of field names to typed values
    pub fn to_typed_map(&mut self, schema: &BpsvSchema) -> Result<HashMap<String, BpsvValue>> {
        let typed_values = self.get_typed_values(schema)?;
        let mut map = HashMap::new();

        for (field, value) in schema.fields().iter().zip(typed_values.iter()) {
            map.insert(field.name.clone(), value.clone());
        }
        Ok(map)
    }

    /// Convert to BPSV line format
    pub fn to_bpsv_line(&self) -> String {
        if let Some(typed) = &self.typed_values {
            typed
                .iter()
                .map(|v| v.to_bpsv_string())
                .collect::<Vec<_>>()
                .join("|")
        } else {
            self.raw_values.join("|")
        }
    }
}

/// An owned version of BpsvRow for when we need to store data
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OwnedBpsvRow {
    /// Raw string values as they appear in the BPSV
    pub raw_values: Vec<String>,
    /// Typed values (lazy-loaded)
    pub typed_values: Option<Vec<BpsvValue>>,
}

impl BpsvRowOps for OwnedBpsvRow {
    fn len(&self) -> usize {
        if let Some(typed) = &self.typed_values {
            typed.len()
        } else {
            self.raw_values.len()
        }
    }

    fn get_raw(&self, index: usize) -> Option<&str> {
        self.raw_values.get(index).map(|s| s.as_str())
    }
}

impl OwnedBpsvRow {
    /// Create a new row from owned string values
    pub fn new(values: Vec<String>) -> Self {
        Self {
            raw_values: values,
            typed_values: None,
        }
    }

    /// Create from a borrowed row
    pub fn from_borrowed(row: &BpsvRow<'_>) -> Self {
        Self {
            raw_values: row.raw_values.iter().map(|&s| s.to_string()).collect(),
            typed_values: row.typed_values.clone(),
        }
    }

    /// Convert to borrowed row
    pub fn as_borrowed(&self) -> BpsvRow<'_> {
        BpsvRow {
            raw_values: self.raw_values.iter().map(|s| s.as_str()).collect(),
            typed_values: self.typed_values.clone(),
        }
    }

    /// Get the number of values
    pub fn len(&self) -> usize {
        BpsvRowOps::len(self)
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        BpsvRowOps::is_empty(self)
    }

    /// Get a raw string value by index
    pub fn get_raw(&self, index: usize) -> Option<&str> {
        BpsvRowOps::get_raw(self, index)
    }

    /// Get a raw string value by field name using the schema
    pub fn get_raw_by_name(&self, field_name: &str, schema: &BpsvSchema) -> Option<&str> {
        BpsvRowOps::get_raw_by_name(self, field_name, schema)
    }

    /// Convert row to a map of field names to raw values
    pub fn to_map(&self, schema: &BpsvSchema) -> Result<HashMap<String, String>> {
        BpsvRowOps::to_map(self, schema)
    }
}

/// Represents a complete BPSV document with borrowed data
#[derive(Debug, Clone, PartialEq)]
pub struct BpsvDocument<'a> {
    /// The original content (for zero-copy)
    content: &'a str,
    /// The schema defining field structure
    schema: BpsvSchema,
    /// Sequence number (optional)
    sequence_number: Option<u32>,
    /// All data rows
    rows: Vec<BpsvRow<'a>>,
}

impl<'a> BpsvDocument<'a> {
    /// Create a new BPSV document
    pub fn new(content: &'a str, schema: BpsvSchema) -> Self {
        Self {
            content,
            schema,
            sequence_number: None,
            rows: Vec::new(),
        }
    }

    /// Parse a BPSV document from string content
    ///
    /// # Examples
    ///
    /// ```
    /// use ngdp_bpsv::BpsvDocument;
    ///
    /// let content = "Region!STRING:0|BuildId!DEC:4\n## seqn = 12345\nus|1234\neu|5678";
    ///
    /// let doc = BpsvDocument::parse(content)?;
    /// assert_eq!(doc.sequence_number(), Some(12345));
    /// assert_eq!(doc.rows().len(), 2);
    /// # Ok::<(), ngdp_bpsv::Error>(())
    /// ```
    pub fn parse(content: &'a str) -> Result<Self> {
        crate::parser::BpsvParser::parse(content)
    }

    /// Get the schema
    pub fn schema(&self) -> &BpsvSchema {
        &self.schema
    }

    /// Get the sequence number
    pub fn sequence_number(&self) -> Option<u32> {
        self.sequence_number
    }

    /// Set the sequence number
    pub fn set_sequence_number(&mut self, seqn: Option<u32>) {
        self.sequence_number = seqn;
    }

    /// Get all rows
    pub fn rows(&self) -> &[BpsvRow<'a>] {
        &self.rows
    }

    /// Get a mutable reference to all rows
    pub fn rows_mut(&mut self) -> &mut [BpsvRow<'a>] {
        &mut self.rows
    }

    /// Get the number of rows
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Check if the document has no data rows
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    /// Add a row from raw string slices
    pub fn add_row(&mut self, values: Vec<&'a str>) -> Result<()> {
        // Validate against schema
        let validated = self.schema.validate_row_refs(&values)?;
        self.rows.push(BpsvRow::new(validated));
        Ok(())
    }

    /// Add a row from typed values
    pub fn add_typed_row(&mut self, values: Vec<BpsvValue>) -> Result<()> {
        if values.len() != self.schema.field_count() {
            return Err(Error::SchemaMismatch {
                expected: self.schema.field_count(),
                actual: values.len(),
            });
        }

        // Validate compatibility
        for (value, field) in values.iter().zip(self.schema.fields()) {
            if !value.is_compatible_with(&field.field_type) {
                return Err(Error::InvalidValue {
                    field: field.name.clone(),
                    field_type: field.field_type.to_string(),
                    value: value.to_bpsv_string(),
                });
            }
        }

        self.rows.push(BpsvRow::from_typed_values(values));
        Ok(())
    }

    /// Get a row by index
    pub fn get_row(&self, index: usize) -> Option<&BpsvRow<'a>> {
        self.rows.get(index)
    }

    /// Get a mutable row by index
    pub fn get_row_mut(&mut self, index: usize) -> Option<&mut BpsvRow<'a>> {
        self.rows.get_mut(index)
    }

    /// Find rows where a field matches a specific value
    pub fn find_rows_by_field(&self, field_name: &str, value: &str) -> Result<Vec<usize>> {
        let field = self
            .schema
            .get_field(field_name)
            .ok_or_else(|| Error::FieldNotFound {
                field: field_name.to_string(),
            })?;

        let mut matching_indices = Vec::new();
        for (index, row) in self.rows.iter().enumerate() {
            if let Some(row_value) = row.get_raw(field.index) {
                if row_value == value {
                    matching_indices.push(index);
                }
            }
        }

        Ok(matching_indices)
    }

    /// Convert the entire document back to BPSV format
    pub fn to_bpsv_string(&self) -> String {
        let mut lines = Vec::new();

        // Header line
        lines.push(self.schema.to_header_line());

        // Sequence number line
        if let Some(seqn) = self.sequence_number {
            lines.push(format!("## seqn = {seqn}"));
        }

        // Data rows
        for row in &self.rows {
            lines.push(row.to_bpsv_line());
        }

        lines.join("\n")
    }

    /// Get all values for a specific field
    pub fn get_column(&self, field_name: &str) -> Result<Vec<&str>> {
        let field = self
            .schema
            .get_field(field_name)
            .ok_or_else(|| Error::FieldNotFound {
                field: field_name.to_string(),
            })?;

        let mut values = Vec::new();
        for row in &self.rows {
            if let Some(value) = row.get_raw(field.index) {
                values.push(value);
            }
        }

        Ok(values)
    }

    /// Convert all rows to maps for easier access
    pub fn to_maps(&self) -> Result<Vec<HashMap<String, String>>> {
        let mut maps = Vec::new();
        for row in &self.rows {
            maps.push(row.to_map(&self.schema)?);
        }
        Ok(maps)
    }

    /// Convert to owned rows for interning
    pub fn into_owned_rows(self) -> Vec<OwnedBpsvRow> {
        self.rows
            .into_iter()
            .map(|row| OwnedBpsvRow::from_borrowed(&row))
            .collect()
    }
}

/// An owned version of BpsvDocument for serialization
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OwnedBpsvDocument {
    /// The schema defining field structure
    schema: BpsvSchema,
    /// Sequence number (optional)
    sequence_number: Option<u32>,
    /// All data rows
    rows: Vec<OwnedBpsvRow>,
}

impl OwnedBpsvDocument {
    /// Create a new owned document
    pub fn new(schema: BpsvSchema) -> Self {
        Self {
            schema,
            sequence_number: None,
            rows: Vec::new(),
        }
    }

    /// Set the sequence number
    pub fn set_sequence_number(&mut self, seqn: Option<u32>) {
        self.sequence_number = seqn;
    }

    /// Add a row to the document
    pub fn add_row(&mut self, row: OwnedBpsvRow) {
        self.rows.push(row);
    }

    /// Get the schema
    pub fn schema(&self) -> &BpsvSchema {
        &self.schema
    }

    /// Get the sequence number
    pub fn sequence_number(&self) -> Option<u32> {
        self.sequence_number
    }

    /// Get the number of rows
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Get all rows
    pub fn rows(&self) -> &[OwnedBpsvRow] {
        &self.rows
    }

    /// Create from a borrowed document
    pub fn from_borrowed(doc: &BpsvDocument<'_>) -> Self {
        Self {
            schema: doc.schema.clone(),
            sequence_number: doc.sequence_number,
            rows: doc.rows.iter().map(OwnedBpsvRow::from_borrowed).collect(),
        }
    }

    /// Convert to BPSV string
    pub fn to_bpsv_string(&self) -> String {
        let mut lines = Vec::new();

        // Header line
        lines.push(self.schema.to_header_line());

        // Sequence number line
        if let Some(seqn) = self.sequence_number {
            lines.push(format!("## seqn = {seqn}"));
        }

        // Data rows
        for row in &self.rows {
            lines.push(row.as_borrowed().to_bpsv_line());
        }

        lines.join("\n")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{BpsvFieldType, BpsvSchema};

    fn create_test_schema() -> BpsvSchema {
        let mut schema = BpsvSchema::new();
        schema
            .add_field("Region".to_string(), BpsvFieldType::String(0))
            .unwrap();
        schema
            .add_field("BuildConfig".to_string(), BpsvFieldType::Hex(16))
            .unwrap();
        schema
            .add_field("BuildId".to_string(), BpsvFieldType::Decimal(4))
            .unwrap();
        schema
    }

    #[test]
    fn test_row_operations() {
        let schema = create_test_schema();
        let mut row = BpsvRow::new(vec!["us", "abcd1234abcd1234abcd1234abcd1234", "1234"]);

        assert_eq!(row.len(), 3);
        assert_eq!(row.get_raw(0), Some("us"));
        assert_eq!(row.get_raw_by_name("Region", &schema), Some("us"));

        let typed_values = row.get_typed_values(&schema).unwrap();
        assert_eq!(typed_values.len(), 3);
        assert_eq!(typed_values[0], BpsvValue::String("us".to_string()));
        assert_eq!(
            typed_values[1],
            BpsvValue::Hex("abcd1234abcd1234abcd1234abcd1234".to_string())
        );
        assert_eq!(typed_values[2], BpsvValue::Decimal(1234));
    }

    #[test]
    fn test_document_creation() {
        let content = "";
        let schema = create_test_schema();
        let mut doc = BpsvDocument::new(content, schema);

        doc.set_sequence_number(Some(12345));
        assert_eq!(doc.sequence_number(), Some(12345));

        doc.add_row(vec!["us", "abcd1234abcd1234abcd1234abcd1234", "1234"])
            .unwrap();
        doc.add_row(vec!["eu", "1234abcd1234abcd1234abcd1234abcd", "5678"])
            .unwrap();

        assert_eq!(doc.row_count(), 2);
        assert!(!doc.is_empty());
    }

    #[test]
    fn test_find_rows() {
        let content = "";
        let schema = create_test_schema();
        let mut doc = BpsvDocument::new(content, schema);

        doc.add_row(vec!["us", "abcd1234abcd1234abcd1234abcd1234", "1234"])
            .unwrap();
        doc.add_row(vec!["eu", "1234abcd1234abcd1234abcd1234abcd", "5678"])
            .unwrap();
        doc.add_row(vec!["us", "deadbeefdeadbeefdeadbeefdeadbeef", "9999"])
            .unwrap();

        let us_rows = doc.find_rows_by_field("Region", "us").unwrap();
        assert_eq!(us_rows, vec![0, 2]);

        let eu_rows = doc.find_rows_by_field("Region", "eu").unwrap();
        assert_eq!(eu_rows, vec![1]);
    }

    #[test]
    fn test_column_access() {
        let content = "";
        let schema = create_test_schema();
        let mut doc = BpsvDocument::new(content, schema);

        doc.add_row(vec!["us", "abcd1234abcd1234abcd1234abcd1234", "1234"])
            .unwrap();
        doc.add_row(vec!["eu", "1234abcd1234abcd1234abcd1234abcd", "5678"])
            .unwrap();

        let regions = doc.get_column("Region").unwrap();
        assert_eq!(regions, vec!["us", "eu"]);

        let build_ids = doc.get_column("BuildId").unwrap();
        assert_eq!(build_ids, vec!["1234", "5678"]);
    }

    #[test]
    fn test_to_bpsv_string() {
        let content = "";
        let schema = create_test_schema();
        let mut doc = BpsvDocument::new(content, schema);
        doc.set_sequence_number(Some(12345));
        doc.add_row(vec!["us", "abcd1234abcd1234abcd1234abcd1234", "1234"])
            .unwrap();

        let bpsv_string = doc.to_bpsv_string();
        let lines: Vec<&str> = bpsv_string.lines().collect();

        assert_eq!(lines[0], "Region!STRING:0|BuildConfig!HEX:16|BuildId!DEC:4");
        assert_eq!(lines[1], "## seqn = 12345");
        assert_eq!(lines[2], "us|abcd1234abcd1234abcd1234abcd1234|1234");
    }

    #[test]
    fn test_schema_mismatch() {
        let content = "";
        let schema = create_test_schema();
        let mut doc = BpsvDocument::new(content, schema);

        // Too few values
        let result = doc.add_row(vec!["us"]);
        assert!(matches!(result, Err(Error::SchemaMismatch { .. })));

        // Too many values
        let result = doc.add_row(vec!["us", "hex", "123", "extra"]);
        assert!(matches!(result, Err(Error::SchemaMismatch { .. })));
    }
}