BinFile

Struct BinFile 

Source
pub struct BinFile { /* private fields */ }
Expand description

Handle to an opened .bin file.

Implementations§

Source§

impl BinFile

Source

pub fn create( path: impl AsRef<Path>, secret: &str, config: BinConfig, ) -> Result<Self>

Create a new .bin file.

§Arguments
  • path - File path for the new .bin file
  • secret - Secret password for accessing the file
  • config - Configuration for the .bin file
§Example
use promocrypt_core::{BinFile, BinConfig, Alphabet, CheckPosition, CounterMode, AuditInfo, CodeFormat};

let config = BinConfig {
    name: "production".to_string(),
    alphabet: Alphabet::default_alphabet(),
    code_length: 9,
    check_position: CheckPosition::End,
    secret_key: String::new(), // Will be generated
    storage_key: String::new(), // Will be generated
    storage_encryption_enabled: false,
    damm_table: promocrypt_core::DammTable::new(26),
    counter_mode: CounterMode::External,
    format: CodeFormat::default(),
    audit: AuditInfo::default(),
};

let bin = BinFile::create("production.bin", "my-secret", config).unwrap();
Source

pub fn create_in_memory(secret: &str, config: BinConfig) -> Result<Vec<u8>>

Create .bin in memory (for database storage).

Source

pub fn open_readonly(path: impl AsRef<Path>) -> Result<Self>

Open with machineID (read-only access).

Source

pub fn open_with_secret(path: impl AsRef<Path>, secret: &str) -> Result<Self>

Open with secret (full access).

Source

pub fn from_bytes_readonly(data: &[u8]) -> Result<Self>

Open from bytes with machineID (read-only access).

Source

pub fn from_bytes_with_secret(data: &[u8], secret: &str) -> Result<Self>

Open from bytes with secret (full access).

Source

pub fn try_open_readonly(path: impl AsRef<Path>) -> Option<Self>

Try to open with machineID, returns None on any error.

Source

pub fn try_open_with_secret( path: impl AsRef<Path>, secret: &str, ) -> Option<Self>

Try to open with secret, returns None on any error.

Source

pub fn config(&self) -> &BinConfig

Get configuration (both access levels).

Source

pub fn name(&self) -> &str

Get name.

Source

pub fn alphabet(&self) -> &Alphabet

Get alphabet.

Source

pub fn code_length(&self) -> usize

Get code length (without check digit).

Source

pub fn total_length(&self) -> usize

Get total code length (with check digit).

Source

pub fn check_position(&self) -> CheckPosition

Get check position.

Source

pub fn counter_mode(&self) -> &CounterMode

Get counter mode.

Source

pub fn audit(&self) -> &AuditInfo

Get audit info (both access levels).

Source

pub fn access_level(&self) -> AccessLevel

Get access level.

Source

pub fn is_bound(&self) -> bool

Check if file is bound to a machine.

Source

pub fn format(&self) -> &CodeFormat

Get code format.

Source

pub fn is_storage_encryption_enabled(&self) -> bool

Check if storage encryption is enabled.

Source

pub fn get_history(&self) -> &History

Get history.

Source

pub fn get_generation_log(&self) -> &[GenerationLogEntry]

Get generation log.

Source

pub fn total_codes_generated(&self) -> u64

Get total codes generated.

Source

pub fn validate(&self, code: &str) -> ValidationResult

Validate a code (both access levels). Handles formatted codes by stripping prefix/suffix/separators.

Source

pub fn is_valid(&self, code: &str) -> bool

Quick validation check.

Source

pub fn validate_batch(&self, codes: &[&str]) -> Vec<ValidationResult>

Validate multiple codes at once.

Source

pub fn generate(&mut self) -> Result<String>

Generate a single code (requires FullAccess). Returns formatted code with prefix/suffix/separators if configured. If storage_encryption_enabled, returns encrypted code.

Source

pub fn generate_batch(&mut self, count: usize) -> Result<Vec<String>>

Generate batch of codes (requires FullAccess).

Source

pub fn generate_at(&self, counter: u64) -> Result<String>

Generate code at specific counter (doesn’t update counter).

Source

pub fn generate_batch_at( &self, start_counter: u64, count: usize, ) -> Result<Vec<String>>

Generate batch at specific counter (doesn’t update counter).

Source

pub fn get_counter(&self) -> Result<u64>

Get current counter value.

Source

pub fn set_counter(&mut self, value: u64) -> Result<()>

Set counter value (requires FullAccess).

This sets the counter to a specific value. Use with caution as it can cause duplicate codes if set to a previously used value.

§Arguments
  • value - The new counter value
§Errors

Returns an error if:

  • Access level is not FullAccess
  • Counter mode is Manual or External (counter not stored)
  • IO error during save
§Example
use promocrypt_core::BinFile;

let mut bin = BinFile::open_with_secret("campaign.bin", "secret")?;
bin.set_counter(1000)?;
Source

pub fn capacity(&self) -> u128

Calculate the maximum capacity based on alphabet size and code length.

Capacity = alphabet_size ^ code_length

Source

pub fn reserve_counter_range(&mut self, count: u64) -> Result<u64>

Reserve a range of counter values atomically (requires FullAccess).

Returns the starting counter value and increments the stored counter by count. This is useful for parallel code generation where multiple workers need exclusive counter ranges.

§Arguments
  • count - Number of counter values to reserve
§Returns

The starting counter value of the reserved range.

§Errors

Returns an error if:

  • Access level is not FullAccess
  • Counter mode is External (counter not stored)
  • Counter overflow would occur
  • Reservation would exceed capacity
  • IO error during save
§Example
use promocrypt_core::BinFile;

let mut bin = BinFile::open_with_secret("campaign.bin", "secret")?;

// Reserve 10,000 counter values for this worker
let start = bin.reserve_counter_range(10000)?;

// Generate codes at the reserved counters (without updating counter)
let codes = bin.generate_batch_at(start, 10000)?;
Source

pub fn master_for_machine( &self, output_path: impl AsRef<Path>, target_machine_id: &[u8; 32], ) -> Result<()>

Master for a new machine (requires FullAccess).

Source

pub fn export_unbound(&self, output_path: impl AsRef<Path>) -> Result<()>

Export unbound copy (requires FullAccess).

Source

pub fn encrypt_code(&self, code: &str) -> Result<String>

Encrypt a code for database storage (requires FullAccess).

Source

pub fn decrypt_code(&self, encrypted: &str) -> Result<String>

Decrypt a code from database storage (requires FullAccess).

Source

pub fn encrypt_codes(&self, codes: &[&str]) -> Result<Vec<String>>

Encrypt multiple codes for storage (requires FullAccess).

Source

pub fn decrypt_codes(&self, encrypted: &[&str]) -> Result<Vec<String>>

Decrypt multiple codes from storage (requires FullAccess).

Source

pub fn set_storage_encryption(&mut self, enabled: bool) -> Result<()>

Enable or disable storage encryption (requires FullAccess).

Source

pub fn set_counter_mode(&mut self, mode: CounterMode) -> Result<()>

Update counter mode (requires FullAccess).

Source

pub fn set_format(&mut self, format: CodeFormat) -> Result<()>

Update code format (requires FullAccess).

Source

pub fn set_check_position(&mut self, position: CheckPosition) -> Result<()>

Update check position (requires FullAccess).

Source

pub fn set_prefix(&mut self, prefix: Option<String>) -> Result<()>

Set code prefix (requires FullAccess).

§Arguments
  • prefix - Optional prefix to prepend to generated codes
Source

pub fn set_suffix(&mut self, suffix: Option<String>) -> Result<()>

Set code suffix (requires FullAccess).

§Arguments
  • suffix - Optional suffix to append to generated codes
Source

pub fn set_separator(&mut self, separator: Option<char>) -> Result<()>

Set separator character (requires FullAccess).

§Arguments
  • separator - Optional separator character to insert at specified positions
Source

pub fn set_separator_positions(&mut self, positions: Vec<usize>) -> Result<()>

Set separator positions (requires FullAccess).

§Arguments
  • positions - Positions where separator should be inserted (0-based, before the character)
Source

pub fn save(&mut self) -> Result<()>

Save all configuration changes to the .bin file (requires FullAccess).

This persists all in-memory configuration changes to disk, including:

  • Format changes (prefix, suffix, separator, separator_positions)
  • Check position changes
  • Storage encryption changes
  • Counter mode changes
  • History and generation log updates
§Errors

Returns an error if:

  • Access level is not FullAccess
  • No file path is associated (in-memory file)
  • IO error during write
Source

pub fn rotate_secret( &mut self, old_secret: &str, new_secret: &str, ) -> Result<()>

Rotate the secret password (requires FullAccess). Re-encrypts the data_key with the new secret.

Source

pub fn export_history(&self) -> String

Export history as JSON.

Source

pub fn export_generation_log(&self) -> String

Export generation log as JSON.

Source

pub fn clear_history(&mut self, keep_last: Option<usize>) -> Result<()>

Clear history (requires FullAccess).

Source

pub fn clear_generation_log(&mut self, keep_last: Option<usize>) -> Result<()>

Clear generation log (requires FullAccess).

Source

pub fn get_stats(&self) -> BinStats

Get statistics about this .bin file.

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> 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> Same for T

Source§

type Output = T

Should always be Self
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V