Codec

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 extend_from(&mut self, other: Codec)

Appends all resources from another Codec into this one.

Source

pub fn from_codecs<I>(codecs: I) -> Codec
where I: IntoIterator<Item = Codec>,

Constructs a Codec from multiple Codec instances by concatenating their resources.

Source

pub fn merge_codecs<I>(codecs: I, strategy: &ConflictStrategy) -> Codec
where I: IntoIterator<Item = Codec>,

Merges multiple Codec instances into one and merges resources by language using the given strategy.

Returns the merged Codec containing resources merged per language group.

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 clean_up_resources(&mut self)

Cleans up resources by removing empty resources and entries.

Source

pub fn merge_resources(&mut self, strategy: &ConflictStrategy) -> usize

Merge resources with the same language by the given strategy.

This method groups resources by language and merges multiple resources that share the same language into a single resource. Resources with unique languages are left unchanged.

§Arguments
  • strategy - The conflict resolution strategy to use when merging entries with the same ID across multiple resources
§Returns

The number of merge operations performed. A merge operation occurs when there are 2 or more resources for the same language.

§Example
use langcodec::{Codec, types::ConflictStrategy};

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

let merges_performed = codec.merge_resources(&ConflictStrategy::Last);
println!("Merged {} language groups", merges_performed);
§Behavior
  • Resources are grouped by language
  • Only languages with multiple resources are merged
  • The merged resource replaces all original resources for that language
  • Resources with unique languages remain unchanged
  • Entries are merged according to the specified conflict strategy
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 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 Clone for Codec

Source§

fn clone(&self) -> Codec

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 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> 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

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

Initializes a with the given initializer. Read more
Source§

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

Dereferences the given pointer. Read more
Source§

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

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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.