Skip to main content

DecodedData

Enum DecodedData 

Source
pub enum DecodedData {
Show 16 variants Boolean(bool), F32(f32), F64(f64), I16(i16), I32(i32), I64(i64), ColourRGB(String), StringU8(String), StringU16(String), OptionalI16(i16), OptionalI32(i32), OptionalI64(i64), OptionalStringU8(String), OptionalStringU16(String), SequenceU16(Vec<u8>), SequenceU32(Vec<u8>),
}
Expand description

Runtime representation of table cell data supporting 16 different data types.

This enum provides a type-safe wrapper around the various data types that can appear in Total War game data tables. Each variant corresponds to a FieldType from the schema definition.

§Data Type Categories

§Numeric Types

  • Boolean: True/false values
  • F32/F64: Floating-point numbers (32-bit and 64-bit precision)
  • I16/I32/I64: Signed integers (16-bit, 32-bit, 64-bit)

§String Types

  • StringU8/StringU16: UTF-8 strings with length prefix (u8 or u16)
  • ColourRGB: Hexadecimal color strings (e.g., “FF0000” for red)

§Optional Types

  • OptionalI16/I32/I64: Integer types that can represent “null” via special values
  • OptionalStringU8/U16: String types that can be empty to represent “null”

§Sequence Types

  • SequenceU16/U32: Binary-encoded nested table data

Sequences represent recursive table structures - tables embedded within a single cell. The raw bytes encode a complete nested table with its own rows and columns. Used in complex tables like unit models where each row can contain sub-tables of equipment variants or LOD levels.

§Type Conversion

The enum provides automatic conversion between compatible types via convert_between_types:

  • Numeric types convert with casting (may lose precision)
  • Booleans convert to 0/1 for numbers, “true”/“false” for strings
  • Strings parse to numbers (returns error if invalid)
  • Sequences only convert between U16 and U32 variants

§String Representation

All variants can be converted to strings via data_to_string:

  • Numbers format with appropriate precision (floats: 4 decimals)
  • Sequences encode as base64 for display/export

§Usage Example

// Create from type and default value
let health = DecodedData::new_from_type_and_value(
    &FieldType::I32,
    &Some("100".to_string())
);

// Parse from user input
let name = DecodedData::new_from_type_and_string(
    &FieldType::StringU8,
    "Empire Swordsmen"
).unwrap();

// Convert between types
let health_float = health.convert_between_types(&FieldType::F32).unwrap();

// Display value
println!("Health: {}", health.data_to_string());

Variants§

§

Boolean(bool)

Boolean true/false value.

§

F32(f32)

32-bit floating-point number.

§

F64(f64)

64-bit floating-point number.

§

I16(i16)

16-bit signed integer.

§

I32(i32)

32-bit signed integer.

§

I64(i64)

64-bit signed integer.

§

ColourRGB(String)

RGB color as hex string (e.g., “FF0000” for red).

§

StringU8(String)

UTF-8 string with u16 length prefix.

§

StringU16(String)

UTF-16 string with u16 length prefix.

§

OptionalI16(i16)

Optional 16-bit signed integer.

§

OptionalI32(i32)

Optional 32-bit signed integer.

§

OptionalI64(i64)

Optional 64-bit signed integer.

§

OptionalStringU8(String)

Optional UTF-8 string with u16 length prefix.

§

OptionalStringU16(String)

Optional UTF-16 string with u16 length prefix.

§

SequenceU16(Vec<u8>)

Binary-encoded nested table with u16 entry count.

§

SequenceU32(Vec<u8>)

Binary-encoded nested table with u32 entry count.

Implementations§

Source§

impl DecodedData

Implementation of DecodedData.

Source

pub fn new_from_type_and_value( field_type: &FieldType, default_value: &Option<String>, ) -> Self

Creates a new DecodedData of the specified type with an optional default value.

This function is the primary constructor for creating table cell data. It handles type-specific initialization and default value parsing.

§Behavior
  • If default_value is Some, attempts to parse it according to field_type
  • If parsing fails or default_value is None, uses type-specific defaults:
    • Numeric types: 0 or 0.0
    • Booleans: false
    • Strings: empty string
    • Colors: “000000” (black) or “” depending on default_value presence
    • Sequences: minimal valid data ([0, 0] or [0, 0, 0, 0])
§Examples
// With default value
let health = DecodedData::new_from_type_and_value(
    &FieldType::I32,
    &Some("100".to_string())
);

// Without default (uses type default)
let name = DecodedData::new_from_type_and_value(
    &FieldType::StringU8,
    &None
);
Source

pub fn new_from_type_and_string( field_type: &FieldType, value: &str, ) -> Result<Self>

Parses a string value into a DecodedData of the specified type.

This function is used when importing data from text formats (TSV, user input, etc.) and requires strict validation - parsing failures return an error.

§Parsing Rules
  • Boolean: Accepts “true”/“false”, “1”/“0”, “yes”/“no” (case-insensitive)
  • Numeric: Standard Rust parsing (scientific notation supported for floats)
  • String/Color: Direct assignment (no validation for colors)
  • Sequence: Converts string bytes to Vec<u8>
§Errors

Returns an error if:

  • Numeric value cannot be parsed (invalid format or out of range)
  • Boolean value is not recognized
§Examples
// Parse valid values
let damage = DecodedData::new_from_type_and_string(&FieldType::I32, "42")?;
let enabled = DecodedData::new_from_type_and_string(&FieldType::Boolean, "true")?;

// This returns an error - invalid integer
let invalid = DecodedData::new_from_type_and_string(&FieldType::I32, "not a number");
assert!(invalid.is_err());
Source

pub fn is_field_type_correct(&self, field_type: &FieldType) -> bool

Validates that this DecodedData matches the expected FieldType.

This is used during table validation to ensure type safety - verifying that runtime data matches the schema definition.

§Returns
  • true if the variant matches the field type
  • false if there’s a type mismatch
§Examples
let data = DecodedData::I32(42);

assert!(data.is_field_type_correct(&FieldType::I32));
assert!(!data.is_field_type_correct(&FieldType::StringU8));
Source

pub fn convert_between_types(&self, new_field_type: &FieldType) -> Result<Self>

Converts this data to a different FieldType, performing automatic type coercion.

This function enables schema migration and type changes by converting data between compatible types. Conversion rules vary by type - some are lossless, others may truncate or fail.

§Conversion Rules
§Numeric Conversions
  • Between numeric types: Cast with potential precision/range loss
  • To Boolean: true if value >= 1, otherwise false
  • To String: Format with to_string()
§Boolean Conversions
  • To numeric: true → 1, false → 0
  • To string: “true” or “false”
  • To color: “FFFFFF” (white) or “000000” (black)
§String Conversions
  • To numeric: Parse string (returns error if invalid)
  • To Boolean: Parse “true”/“false”/“1”/“0” (returns error if invalid)
  • Between string types: Direct copy
§Sequence Conversions
  • U16 ↔ U32: Adjust padding bytes to match new entry count size
  • To other types: Returns default value for target type (data is lost)
§Errors

Returns an error if:

  • String cannot be parsed to target numeric/boolean type
  • Conversion is fundamentally incompatible
§Performance Note

Converting to the same type performs a clone operation. Use clone() directly if you need to copy data without type checking overhead.

§Examples
// Numeric conversions
let int_value = DecodedData::I32(42);
let float_value = int_value.convert_between_types(&FieldType::F32)?;

// String to number (can fail)
let text = DecodedData::StringU8("123".to_string());
let number = text.convert_between_types(&FieldType::I32)?;

// Invalid conversion returns error
let invalid = DecodedData::StringU8("not a number".to_string());
assert!(invalid.convert_between_types(&FieldType::I32).is_err());
Source

pub fn data_to_string(&self) -> Cow<'_, str>

Converts the data to a human-readable string representation.

This function formats data for display in UI, export to text formats (TSV), or logging. The formatting is optimized for readability rather than round-trip serialization.

§Formatting Rules
  • Boolean: “true” or “false”
  • Floats (F32/F64): Fixed 4 decimal places (e.g., “3.1416”)
  • Integers: Decimal format (e.g., “42”)
  • Strings/Colors: Direct output
  • Sequences: Base64-encoded binary data
§Performance

Returns Cow<str> to avoid allocation for string types (zero-copy), while formatting numeric types into owned strings only when needed.

§Examples
assert_eq!(DecodedData::Boolean(true).data_to_string(), "true");
assert_eq!(DecodedData::I32(42).data_to_string(), "42");
assert_eq!(DecodedData::F32(3.14159).data_to_string(), "3.1416");
Source

pub fn set_data(&mut self, new_data: &str) -> Result<()>

Updates the value while preserving the current type.

This method parses the provided string and updates the internal value, maintaining the same DecodedData variant. Used for in-place editing in table cells.

§Parsing
  • Numeric types: Parse from string (scientific notation supported for floats)
  • Boolean: Parse “true”/“false”/“1”/“0”/“yes”/“no” (case-insensitive)
  • String/Color: Direct assignment (no validation)
  • Sequence: Converts string bytes to Vec<u8>
§Errors

Returns an error if:

  • Numeric value cannot be parsed (invalid format or out of range)
  • Boolean value is not recognized
§Examples
let mut health = DecodedData::I32(100);
health.set_data("150")?;
assert_eq!(health.data_to_string(), "150");

// Type is preserved - this fails because "abc" isn't a valid integer
let result = health.set_data("abc");
assert!(result.is_err());

Trait Implementations§

Source§

impl Clone for DecodedData

Source§

fn clone(&self) -> DecodedData

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DecodedData

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for DecodedData

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<&DecodedData> for FieldType

Implementation of From<&RawDefinition> for `Definition.

Source§

fn from(data: &DecodedData) -> Self

Converts to this type from the input type.
Source§

impl Hash for DecodedData

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for DecodedData

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for DecodedData

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for DecodedData

Eq and PartialEq implementation of DecodedData. We need this implementation due to the float comparison being… special.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> Scalar for T
where T: 'static + Clone + PartialEq + Debug,