Struct Codec

Source
pub struct Codec {
    pub resources: Vec<Resource>,
}
Expand description

Represents a collection of localized resources and provides methods to read, write, cache, and load these resources.

Fields§

§resources: Vec<Resource>

The collection of resources managed by this codec.

Implementations§

Source§

impl Codec

Source

pub fn new() -> Codec

Creates a new, empty Codec.

§Returns

A new Codec instance with no resources.

Source

pub fn builder() -> CodecBuilder

Creates a new CodecBuilder for fluent construction.

This method returns a builder that allows you to chain method calls to add resources from files and then build the final Codec instance.

§Example
use langcodec::Codec;

let codec = Codec::builder()
    .add_file("en.strings")?
    .add_file("fr.strings")?
    .build();
§Returns

Returns a new CodecBuilder instance.

Source

pub fn iter(&self) -> Iter<'_, Resource>

Returns an iterator over all resources.

Source

pub fn iter_mut(&mut self) -> IterMut<'_, Resource>

Returns a mutable iterator over all resources.

Source

pub fn get_by_language(&self, lang: &str) -> Option<&Resource>

Finds a resource by its language code, if present.

Source

pub fn get_mut_by_language(&mut self, lang: &str) -> Option<&mut Resource>

Finds a mutable resource by its language code, if present.

Source

pub fn add_resource(&mut self, resource: Resource)

Adds a new resource to the collection.

Source

pub fn find_entries(&self, key: &str) -> Vec<(&Resource, &Entry)>

Finds an entry by its key across all languages.

Returns an iterator over all resources and their matching entries.

§Arguments
  • key - The entry key to search for
§Returns

An iterator yielding (&Resource, &Entry) pairs for all matching entries.

§Example
use langcodec::Codec;

let mut codec = Codec::new();
// ... load resources ...

for (resource, entry) in codec.find_entries("welcome_message") {
    println!("{}: {}", resource.metadata.language, entry.value);
}
Source

pub fn find_entry(&self, key: &str, language: &str) -> Option<&Entry>

Finds an entry by its key in a specific language.

§Arguments
  • key - The entry key to search for
  • language - The language code (e.g., “en”, “fr”)
§Returns

Some(&Entry) if found, None otherwise.

§Example
use langcodec::Codec;

let mut codec = Codec::new();
// ... load resources ...

if let Some(entry) = codec.find_entry("welcome_message", "en") {
    println!("English welcome: {}", entry.value);
}
Source

pub fn find_entry_mut( &mut self, key: &str, language: &str, ) -> Option<&mut Entry>

Finds a mutable entry by its key in a specific language.

§Arguments
  • key - The entry key to search for
  • language - The language code (e.g., “en”, “fr”)
§Returns

Some(&mut Entry) if found, None otherwise.

§Example
use langcodec::Codec;
use langcodec::types::Translation;

let mut codec = Codec::new();
// ... load resources ...

if let Some(entry) = codec.find_entry_mut("welcome_message", "en") {
    entry.value = Translation::Singular("Hello, World!".to_string());
    entry.status = langcodec::types::EntryStatus::Translated;
}
Source

pub fn update_translation( &mut self, key: &str, language: &str, translation: Translation, status: Option<EntryStatus>, ) -> Result<(), Error>

Updates a translation for a specific key and language.

§Arguments
  • key - The entry key to update
  • language - The language code (e.g., “en”, “fr”)
  • translation - The new translation value
  • status - Optional new status (defaults to Translated)
§Returns

Ok(()) if the entry was found and updated, Err if not found.

§Example
use langcodec::{Codec, types::{Translation, EntryStatus}};

let mut codec = Codec::new();
// Add an entry first
codec.add_entry("welcome", "en", Translation::Singular("Hello".to_string()), None, None)?;

codec.update_translation(
    "welcome",
    "en",
    Translation::Singular("Hello, World!".to_string()),
    Some(EntryStatus::Translated)
)?;
Source

pub fn add_entry( &mut self, key: &str, language: &str, translation: Translation, comment: Option<String>, status: Option<EntryStatus>, ) -> Result<(), Error>

Adds a new entry to a specific language.

If the language doesn’t exist, it will be created automatically.

§Arguments
  • key - The entry key
  • language - The language code (e.g., “en”, “fr”)
  • translation - The translation value
  • comment - Optional comment for translators
  • status - Optional status (defaults to New)
§Returns

Ok(()) if the entry was added successfully.

§Example
use langcodec::{Codec, types::{Translation, EntryStatus}};

let mut codec = Codec::new();

codec.add_entry(
    "new_message",
    "en",
    Translation::Singular("This is a new message".to_string()),
    Some("This is a new message for users".to_string()),
    Some(EntryStatus::New)
)?;
Source

pub fn remove_entry(&mut self, key: &str, language: &str) -> Result<(), Error>

Removes an entry from a specific language.

§Arguments
  • key - The entry key to remove
  • language - The language code (e.g., “en”, “fr”)
§Returns

Ok(()) if the entry was found and removed, Err if not found.

§Example
use langcodec::{Codec, types::{Translation, EntryStatus}};

let mut codec = Codec::new();
// Add a resource first
codec.add_entry("test_key", "en", Translation::Singular("Test".to_string()), None, None)?;

// Now remove it
codec.remove_entry("test_key", "en")?;
Source

pub fn copy_entry( &mut self, key: &str, from_language: &str, to_language: &str, update_status: bool, ) -> Result<(), Error>

Copies an entry from one language to another.

This is useful for creating new translations based on existing ones.

§Arguments
  • key - The entry key to copy
  • from_language - The source language
  • to_language - The target language
  • update_status - Whether to update the status to New in the target language
§Returns

Ok(()) if the entry was copied successfully, Err if not found.

§Example
use langcodec::{Codec, types::{Translation, EntryStatus}};

let mut codec = Codec::new();
// Add source entry first
codec.add_entry("welcome", "en", Translation::Singular("Hello".to_string()), None, None)?;

// Copy English entry to French as a starting point
codec.copy_entry("welcome", "en", "fr", true)?;
Source

pub fn languages(&self) -> impl Iterator<Item = &str>

Gets all languages available in the codec.

§Returns

An iterator over all language codes.

§Example
use langcodec::Codec;

let codec = Codec::new();
// ... load resources ...

for language in codec.languages() {
    println!("Available language: {}", language);
}
Source

pub fn all_keys(&self) -> impl Iterator<Item = &str>

Gets all unique entry keys across all languages.

§Returns

An iterator over all unique entry keys.

§Example
use langcodec::Codec;

let codec = Codec::new();
// ... load resources ...

for key in codec.all_keys() {
    println!("Available key: {}", key);
}
Source

pub fn has_entry(&self, key: &str, language: &str) -> bool

Checks if an entry exists in a specific language.

§Arguments
  • key - The entry key to check
  • language - The language code (e.g., “en”, “fr”)
§Returns

true if the entry exists, false otherwise.

§Example
use langcodec::Codec;

let codec = Codec::new();
// ... load resources ...

if codec.has_entry("welcome_message", "en") {
    println!("English welcome message exists");
}
Source

pub fn entry_count(&self, language: &str) -> usize

Gets the count of entries in a specific language.

§Arguments
  • language - The language code (e.g., “en”, “fr”)
§Returns

The number of entries in the specified language, or 0 if the language doesn’t exist.

§Example
use langcodec::Codec;

let codec = Codec::new();
// ... load resources ...

let count = codec.entry_count("en");
println!("English has {} entries", count);
Source

pub fn validate(&self) -> Result<(), Error>

Validates the codec for common issues.

§Returns

Ok(()) if validation passes, Err(Error) with details if validation fails.

§Example
use langcodec::Codec;

let mut codec = Codec::new();
// ... add resources ...

if let Err(validation_error) = codec.validate() {
    eprintln!("Validation failed: {}", validation_error);
}
Source

pub fn merge_resources( resources: &[Resource], conflict_strategy: ConflictStrategy, ) -> Result<Resource, Error>

Merges multiple resources into a single resource with conflict resolution.

This function merges resources that all have the same language. Only entries with the same ID are treated as conflicts.

§Arguments
  • resources - The resources to merge (must all have the same language)
  • conflict_strategy - How to handle conflicting entries (same ID)
§Returns

A merged resource with all entries from the input resources.

§Errors

Returns an error if:

  • No resources are provided
  • Resources have different languages (each Resource represents one language)
§Example
use langcodec::{Codec, types::{Resource, Metadata, Entry, Translation, EntryStatus}};

let mut codec = Codec::new();
// ... load resources ...

// Create some sample resources for merging
let resource1 = Resource {
    metadata: Metadata {
        language: "en".to_string(),
        domain: "domain".to_string(),
        custom: std::collections::HashMap::new(),
    },
    entries: vec![
        Entry {
            id: "hello".to_string(),
            value: Translation::Singular("Hello".to_string()),
            comment: None,
            status: EntryStatus::Translated,
            custom: std::collections::HashMap::new(),
        }
    ],
};

let merged = Codec::merge_resources(
    &[resource1],
    langcodec::types::ConflictStrategy::Last
)?;
Source

pub fn write_resource_to_file( resource: &Resource, output_path: &str, ) -> Result<(), Error>

Writes a resource to a file with automatic format detection.

§Arguments
  • resource - The resource to write
  • output_path - The output file path
§Returns

Ok(()) on success, Err(Error) on failure.

§Example
use langcodec::{Codec, types::{Resource, Metadata, Entry, Translation, EntryStatus}};

let resource = Resource {
    metadata: Metadata {
        language: "en".to_string(),
        domain: "domain".to_string(),
        custom: std::collections::HashMap::new(),
    },
    entries: vec![],
};
Codec::write_resource_to_file(&resource, "output.strings")?;
Source

pub fn convert_resources_to_format( resources: Vec<Resource>, output_path: &str, output_format: FormatType, ) -> Result<(), Error>

Converts a vector of resources to a specific output format.

§Arguments
  • resources - The resources to convert
  • output_path - The output file path
  • output_format - The target format
§Returns

Ok(()) on success, Err(Error) on failure.

§Example
use langcodec::{Codec, types::{Resource, Metadata, Entry, Translation, EntryStatus}, formats::FormatType};

let resources = vec![Resource {
    metadata: Metadata {
        language: "en".to_string(),
        domain: "domain".to_string(),
        custom: std::collections::HashMap::new(),
    },
    entries: vec![],
}];
Codec::convert_resources_to_format(
    resources,
    "output.strings",
    FormatType::Strings(None)
)?;
Source

pub fn read_file_by_type<P>( &mut self, path: P, format_type: FormatType, ) -> Result<(), Error>
where P: AsRef<Path>,

Reads a resource file given its path and explicit format type.

§Parameters
  • path: Path to the resource file.
  • format_type: The format type of the resource file.
§Returns

Ok(()) if the file was successfully read and resources loaded, or an Error otherwise.

Source

pub fn read_file_by_extension<P>( &mut self, path: P, lang: Option<String>, ) -> Result<(), Error>
where P: AsRef<Path>,

Reads a resource file by inferring its format from the file extension. Optionally infers language from the path if not provided.

§Parameters
  • path: Path to the resource file.
  • lang: Optional language code to use.
§Returns

Ok(()) if the file was successfully read, or an Error if the format is unsupported or reading fails.

Source

pub fn write_to_file(&self) -> Result<(), Error>

Writes all managed resources back to their respective files, grouped by domain.

§Returns

Ok(()) if all writes succeed, or an Error otherwise.

Source

pub fn cache_to_file<P>(&self, path: P) -> Result<(), Error>
where P: AsRef<Path>,

Caches the current resources to a JSON file.

§Parameters
  • path: Destination file path for the cache.
§Returns

Ok(()) if caching succeeds, or an Error if file I/O or serialization fails.

Source

pub fn load_from_file<P>(path: P) -> Result<Codec, Error>
where P: AsRef<Path>,

Loads resources from a JSON cache file.

§Parameters
  • path: Path to the JSON file containing cached resources.
§Returns

Ok(Codec) with loaded resources, or an Error if loading or deserialization fails.

Trait Implementations§

Source§

impl Debug for Codec

Source§

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

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

impl Default for Codec

Source§

fn default() -> Codec

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Codec

§

impl RefUnwindSafe for Codec

§

impl Send for Codec

§

impl Sync for Codec

§

impl Unpin for Codec

§

impl UnwindSafe for Codec

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> 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, 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.