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
//! BPSV document builder for creating BPSV content programmatically

use crate::document::OwnedBpsvDocument;
use crate::error::{Error, Result};
use crate::field_type::BpsvFieldType;
use crate::schema::BpsvSchema;
use crate::value::BpsvValue;

/// Builder for creating BPSV documents
///
/// # Examples
///
/// ```
/// use ngdp_bpsv::{BpsvBuilder, BpsvFieldType, BpsvValue};
///
/// let mut builder = BpsvBuilder::new();
///
/// // Define schema
/// builder.add_field("Region", BpsvFieldType::String(0))?;
/// builder.add_field("BuildConfig", BpsvFieldType::Hex(16))?;
/// builder.add_field("BuildId", BpsvFieldType::Decimal(4))?;
///
/// // Set sequence number
/// builder.set_sequence_number(12345);
///
/// // Add data rows
/// builder.add_row(vec![
///     BpsvValue::String("us".to_string()),
///     BpsvValue::Hex("abcd1234abcd1234abcd1234abcd1234".to_string()),
///     BpsvValue::Decimal(1234),
/// ])?;
///
/// builder.add_row(vec![
///     BpsvValue::String("eu".to_string()),
///     BpsvValue::Hex("1234abcd1234abcd1234abcd1234abcd".to_string()),
///     BpsvValue::Decimal(5678),
/// ])?;
///
/// let document = builder.build()?;
/// let bpsv_string = document.to_bpsv_string();
/// # Ok::<(), ngdp_bpsv::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct BpsvBuilder {
    /// Schema being built
    schema: BpsvSchema,
    /// Sequence number (optional)
    sequence_number: Option<u32>,
    /// Rows to add to the document
    rows: Vec<Vec<BpsvValue>>,
}

impl BpsvBuilder {
    /// Create a new BPSV builder
    #[must_use]
    pub fn new() -> Self {
        Self {
            schema: BpsvSchema::new(),
            sequence_number: None,
            rows: Vec::new(),
        }
    }

    /// Create a builder from an existing schema
    #[must_use]
    pub fn from_schema(schema: BpsvSchema) -> Self {
        Self {
            schema,
            sequence_number: None,
            rows: Vec::new(),
        }
    }

    /// Add a field to the schema
    ///
    /// # Errors
    ///
    /// Returns an error if the field name already exists in the schema.
    ///
    /// # Examples
    ///
    /// ```
    /// use ngdp_bpsv::{BpsvBuilder, BpsvFieldType};
    ///
    /// let mut builder = BpsvBuilder::new();
    /// builder.add_field("Region", BpsvFieldType::String(0))?;
    /// builder.add_field("BuildId", BpsvFieldType::Decimal(4))?;
    /// # Ok::<(), ngdp_bpsv::Error>(())
    /// ```
    pub fn add_field(&mut self, name: &str, field_type: BpsvFieldType) -> Result<&mut Self> {
        self.schema.add_field(name.to_string(), field_type)?;
        Ok(self)
    }

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

    /// Clear the sequence number
    pub fn clear_sequence_number(&mut self) -> &mut Self {
        self.sequence_number = None;
        self
    }

    /// Add a row of typed values
    ///
    /// The number of values must match the number of fields in the schema.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The number of values doesn't match the schema field count
    /// - Any value is incompatible with its corresponding field type
    /// - Any value fails validation
    pub fn add_row(&mut self, values: Vec<BpsvValue>) -> Result<&mut Self> {
        if values.len() != self.schema.field_count() {
            return Err(Error::SchemaMismatch {
                expected: self.schema.field_count(),
                actual: values.len(),
            });
        }

        // Validate that values are compatible with field types
        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(),
                });
            }

            // Also validate the actual value content
            let value_str = value.to_bpsv_string();
            field
                .field_type
                .validate_value(&value_str)
                .map_err(|mut err| {
                    if let Error::InvalidValue {
                        field: err_field, ..
                    } = &mut err
                    {
                        err_field.clone_from(&field.name);
                    }
                    err
                })?;
        }

        self.rows.push(values);
        Ok(self)
    }

    /// Add a row from raw string values
    ///
    /// Values will be parsed according to the field types in the schema.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The number of values doesn't match the schema field count
    /// - Any value fails to parse according to its field type
    pub fn add_raw_row(&mut self, values: &[String]) -> Result<&mut Self> {
        if values.len() != self.schema.field_count() {
            return Err(Error::SchemaMismatch {
                expected: self.schema.field_count(),
                actual: values.len(),
            });
        }

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

        self.rows.push(typed_values);
        Ok(self)
    }

    /// Add a row from a vector of values that can be converted to `BpsvValue`
    ///
    /// # Errors
    ///
    /// Returns an error if the converted values fail validation.
    ///
    /// # Examples
    ///
    /// ```
    /// use ngdp_bpsv::{BpsvBuilder, BpsvFieldType, BpsvValue};
    ///
    /// let mut builder = BpsvBuilder::new();
    /// builder.add_field("Region", BpsvFieldType::String(0))?;
    /// builder.add_field("BuildId", BpsvFieldType::Decimal(4))?;
    ///
    /// // Use homogeneous types or convert manually
    /// builder.add_row(vec![
    ///     BpsvValue::String("us".to_string()),
    ///     BpsvValue::Decimal(1234),
    /// ])?;
    /// # Ok::<(), ngdp_bpsv::Error>(())
    /// ```
    pub fn add_values_row<T>(&mut self, values: Vec<T>) -> Result<&mut Self>
    where
        T: Into<BpsvValue>,
    {
        let typed_values: Vec<BpsvValue> =
            values.into_iter().map(std::convert::Into::into).collect();
        self.add_row(typed_values)
    }

    /// Get the current number of fields
    #[must_use]
    pub fn field_count(&self) -> usize {
        self.schema.field_count()
    }

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

    /// Check if any fields have been defined
    #[must_use]
    pub fn has_fields(&self) -> bool {
        self.schema.field_count() > 0
    }

    /// Check if any rows have been added
    #[must_use]
    pub fn has_rows(&self) -> bool {
        !self.rows.is_empty()
    }

    /// Get the current schema
    #[must_use]
    pub fn schema(&self) -> &BpsvSchema {
        &self.schema
    }

    /// Clear all rows but keep the schema
    pub fn clear_rows(&mut self) -> &mut Self {
        self.rows.clear();
        self
    }

    /// Reset the builder to empty state
    pub fn reset(&mut self) -> &mut Self {
        self.schema = BpsvSchema::new();
        self.sequence_number = None;
        self.rows.clear();
        self
    }

    /// Build the final BPSV document
    ///
    /// This consumes the builder and returns an `OwnedBpsvDocument`.
    ///
    /// # Errors
    ///
    /// Returns an error if no fields have been defined in the schema.
    pub fn build(self) -> Result<OwnedBpsvDocument> {
        if self.schema.field_count() == 0 {
            return Err(Error::InvalidHeader {
                reason: "No fields defined in schema".to_string(),
            });
        }

        let mut document = OwnedBpsvDocument::new(self.schema);
        document.set_sequence_number(self.sequence_number);

        for row in self.rows {
            // Convert BpsvValue vec to OwnedBpsvRow
            let raw_values: Vec<String> = row.iter().map(|v| v.to_bpsv_string()).collect();
            document.add_row(crate::document::OwnedBpsvRow::new(raw_values));
        }

        Ok(document)
    }

    /// Build and return the BPSV string representation
    ///
    /// This is a convenience method that builds the document and converts it to a string.
    ///
    /// # Errors
    ///
    /// Returns an error if building the document fails.
    pub fn build_string(self) -> Result<String> {
        let document = self.build()?;
        Ok(document.to_bpsv_string())
    }

    /// Validate the current builder state
    ///
    /// Returns `Ok(())` if the builder is in a valid state, `Err` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No fields are defined
    /// - Any row has incorrect number of fields
    /// - Any value is incompatible with its field type
    pub fn validate(&self) -> Result<()> {
        if self.schema.field_count() == 0 {
            return Err(Error::InvalidHeader {
                reason: "No fields defined".to_string(),
            });
        }

        // Validate all rows
        for (row_index, row) in self.rows.iter().enumerate() {
            if row.len() != self.schema.field_count() {
                return Err(Error::RowValidation {
                    row_index,
                    reason: format!(
                        "Expected {} fields, got {}",
                        self.schema.field_count(),
                        row.len()
                    ),
                });
            }

            for (value, field) in row.iter().zip(self.schema.fields()) {
                if !value.is_compatible_with(&field.field_type) {
                    return Err(Error::RowValidation {
                        row_index,
                        reason: format!(
                            "Value '{}' is not compatible with field '{}' of type {}",
                            value.to_bpsv_string(),
                            field.name,
                            field.field_type
                        ),
                    });
                }
            }
        }

        Ok(())
    }

    /// Create a builder from existing BPSV content
    ///
    /// This parses the BPSV content and creates a builder with the same schema and data.
    ///
    /// # Errors
    ///
    /// Returns an error if the BPSV content cannot be parsed.
    ///
    /// # Examples
    ///
    /// ```
    /// use ngdp_bpsv::BpsvBuilder;
    ///
    /// let content = "Region!STRING:0|BuildId!DEC:4\n## seqn = 12345\nus|1234\neu|5678";
    ///
    /// let builder = BpsvBuilder::from_bpsv(content)?;
    /// assert_eq!(builder.field_count(), 2);
    /// assert_eq!(builder.row_count(), 2);
    /// # Ok::<(), ngdp_bpsv::Error>(())
    /// ```
    pub fn from_bpsv(content: &str) -> Result<Self> {
        let document = crate::parser::BpsvParser::parse(content)?;

        let mut builder = Self::from_schema(document.schema().clone());
        builder.sequence_number = document.sequence_number();

        // Convert all rows to typed values
        for row in document.rows() {
            let typed_values: Vec<BpsvValue> = row
                .raw_values()
                .iter()
                .zip(document.schema().fields())
                .map(|(value, field)| BpsvValue::parse(value, &field.field_type))
                .collect::<Result<Vec<_>>>()?;

            builder.rows.push(typed_values);
        }

        Ok(builder)
    }
}

impl Default for BpsvBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_building() {
        let mut builder = BpsvBuilder::new();

        builder
            .add_field("Region", BpsvFieldType::String(0))
            .unwrap();
        builder
            .add_field("BuildId", BpsvFieldType::Decimal(4))
            .unwrap();
        builder.set_sequence_number(12345);

        builder
            .add_row(vec![
                BpsvValue::String("us".to_string()),
                BpsvValue::Decimal(1234),
            ])
            .unwrap();

        builder
            .add_row(vec![
                BpsvValue::String("eu".to_string()),
                BpsvValue::Decimal(5678),
            ])
            .unwrap();

        let document = builder.build().unwrap();

        assert_eq!(document.sequence_number(), Some(12345));
        assert_eq!(document.row_count(), 2);
        assert_eq!(document.schema().field_count(), 2);
    }

    #[test]
    fn test_raw_row_addition() {
        let mut builder = BpsvBuilder::new();

        builder
            .add_field("Region", BpsvFieldType::String(0))
            .unwrap();
        builder
            .add_field("BuildId", BpsvFieldType::Decimal(4))
            .unwrap();

        builder
            .add_raw_row(&["us".to_string(), "1234".to_string()])
            .unwrap();
        builder
            .add_raw_row(&["eu".to_string(), "5678".to_string()])
            .unwrap();

        let document = builder.build().unwrap();
        assert_eq!(document.row_count(), 2);
    }

    #[test]
    fn test_values_row_addition() {
        let mut builder = BpsvBuilder::new();

        builder
            .add_field("Region", BpsvFieldType::String(0))
            .unwrap();
        builder
            .add_field("BuildId", BpsvFieldType::Decimal(4))
            .unwrap();

        builder
            .add_raw_row(&["us".to_string(), "1234".to_string()])
            .unwrap();
        builder
            .add_raw_row(&["eu".to_string(), "5678".to_string()])
            .unwrap();

        let document = builder.build().unwrap();
        assert_eq!(document.row_count(), 2);
    }

    #[test]
    fn test_build_string() {
        let mut builder = BpsvBuilder::new();

        builder
            .add_field("Region", BpsvFieldType::String(0))
            .unwrap();
        builder
            .add_field("BuildId", BpsvFieldType::Decimal(4))
            .unwrap();
        builder.set_sequence_number(12345);

        builder
            .add_raw_row(&["us".to_string(), "1234".to_string()])
            .unwrap();

        let bpsv_string = builder.build_string().unwrap();
        let lines: Vec<&str> = bpsv_string.lines().collect();

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

    #[test]
    fn test_from_bpsv() {
        let content = r"Region!STRING:0|BuildId!DEC:4
## seqn = 12345
us|1234
eu|5678";

        let builder = BpsvBuilder::from_bpsv(content).unwrap();

        assert_eq!(builder.field_count(), 2);
        assert_eq!(builder.row_count(), 2);

        let rebuilt = builder.build_string().unwrap();

        // Parse both and compare structure (order might differ)
        let original_doc = crate::parser::BpsvParser::parse(content).unwrap();
        let rebuilt_doc = crate::parser::BpsvParser::parse(&rebuilt).unwrap();

        assert_eq!(
            original_doc.sequence_number(),
            rebuilt_doc.sequence_number()
        );
        assert_eq!(original_doc.row_count(), rebuilt_doc.row_count());
        assert_eq!(
            original_doc.schema().field_count(),
            rebuilt_doc.schema().field_count()
        );
    }

    #[test]
    fn test_validation() {
        let mut builder = BpsvBuilder::new();

        // No fields defined
        assert!(builder.validate().is_err());

        builder
            .add_field("Region", BpsvFieldType::String(0))
            .unwrap();
        builder
            .add_field("BuildId", BpsvFieldType::Decimal(4))
            .unwrap();

        // Valid now
        assert!(builder.validate().is_ok());

        // Add compatible row
        builder
            .add_row(vec![
                BpsvValue::String("us".to_string()),
                BpsvValue::Decimal(1234),
            ])
            .unwrap();

        assert!(builder.validate().is_ok());
    }

    #[test]
    fn test_schema_mismatch_errors() {
        let mut builder = BpsvBuilder::new();
        builder
            .add_field("Region", BpsvFieldType::String(0))
            .unwrap();

        // Too many values
        let result = builder.add_row(vec![
            BpsvValue::String("us".to_string()),
            BpsvValue::Decimal(1234),
        ]);
        assert!(matches!(result, Err(Error::SchemaMismatch { .. })));

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

    #[test]
    fn test_incompatible_value_types() {
        let mut builder = BpsvBuilder::new();
        builder
            .add_field("Region", BpsvFieldType::String(0))
            .unwrap();

        // Try to add decimal value to string field
        let result = builder.add_row(vec![BpsvValue::Decimal(1234)]);
        assert!(matches!(result, Err(Error::InvalidValue { .. })));
    }

    #[test]
    fn test_builder_state_methods() {
        let mut builder = BpsvBuilder::new();

        assert_eq!(builder.field_count(), 0);
        assert_eq!(builder.row_count(), 0);
        assert!(!builder.has_fields());
        assert!(!builder.has_rows());

        builder
            .add_field("Region", BpsvFieldType::String(0))
            .unwrap();

        assert_eq!(builder.field_count(), 1);
        assert!(builder.has_fields());
        assert!(!builder.has_rows());

        builder.add_values_row(vec!["us"]).unwrap();

        assert_eq!(builder.row_count(), 1);
        assert!(builder.has_rows());

        builder.clear_rows();

        assert_eq!(builder.row_count(), 0);
        assert!(!builder.has_rows());
        assert!(builder.has_fields());

        builder.reset();

        assert_eq!(builder.field_count(), 0);
        assert_eq!(builder.row_count(), 0);
        assert!(!builder.has_fields());
        assert!(!builder.has_rows());
    }
}