Skip to main content

Env

Struct Env 

Source
pub struct Env {
    pub data: Vec<Pair>,
    pub global: Vec<Pair>,
    pub path: String,
}
Expand description

The main environment container used by rust-env.

Env manages both:

  • Local environment variables loaded from a .env file
  • Global environment variables from the operating system

It provides functionality to:

  • Parse environment files into structured data
  • Retrieve values (local, global, or merged)
  • Modify environment entries
  • Persist changes back to a file

§Internal Representation

Environment data is stored as a vector of Pair:

  • Pair::Str(key, value) → single value
  • Pair::Vec(key, values) → list of values (semicolon-separated in file)
  • Pair::Comment(text) → comments in the file

§Fields

  • data: Local environment variables loaded from file
  • global: OS environment variables captured at runtime
  • path: Path to the associated .env file

§Behavior Notes

  • Local data comes from the file at path
  • Global data is loaded via std::env::vars()
  • set() writes changes immediately to disk
  • Lookup functions may fall back between global/local depending on method

§Example

use rust_env::{Env, Str};

let mut env = Env::new("./.env");

// Get a value
let port = env.get_pair("PORT");

// Set a value
env.set(Str("PORT", "8080"));

// Load OS environment variables
env.global_env();

// Debug print local env
env.debug_local();

§Notes

  • This struct is not thread-safe by default
  • All values are stored internally as strings
  • Vector values use ; as delimiter in files

Fields§

§data: Vec<Pair>§global: Vec<Pair>§path: String

Implementations§

Source§

impl Env

Source

pub fn parse(content: &str) -> Vec<Pair>

Parses a raw environment string into a list of Pair values.

This function converts .env-style text into structured data.

§Format Rules

Each line is expected to follow:

KEY=VALUE

Supported formats:

  • Single value:

    PORT=8080
  • Vector value (semicolon-separated):

    IP=127;0;0;1
§Behavior
  • Lines without = are ignored
  • Empty keys are ignored
  • Values containing ; are treated as vectors
  • Whitespace around values is trimmed
§Returns

A Vec<Pair> representing parsed environment entries.

§Example
use rust_env::Env;

let data = Env::parse("PORT=8080\nIP=127;0;0;1");
§Notes
  • This function does not read from files directly
  • It only parses in-memory strings
  • Comments are not fully supported unless explicitly handled
Source

pub fn marshal(val: Vec<Pair>) -> String

Converts a vector of Pair values into a valid .env formatted string.

This is the inverse of parse().

It serializes structured environment data back into text form.

§Output Format
  • Pair::Str(key, value)

    KEY=VALUE
  • Pair::Vec(key, values)

    KEY=a;b;c
  • Pair::Comment(text)

    #text
§Behavior
  • Values in vectors are joined using ;
  • Keys and values are written exactly as stored
  • No escaping is applied for special characters
§Returns

A formatted .env string.

§Example
use rust_env::{Env, Str};

let data = vec![
    Str("PORT", "8080"),
];

let out = Env::marshal(data);
§Notes
  • This function does not write to files
  • Formatting is minimal and not lossless (comments/order may be simplified)
Source

pub fn new(name: &str) -> Env

Creates a new Env instance from a .env file.

This function reads the file at the given path and parses its contents into structured environment data.

§Behavior
  • Loads local environment variables from the file
  • Parses content using .env rules (KEY=VALUE)
  • Stores results in self.data
  • Initializes an empty global environment store
§Arguments
  • name: Path to the .env file
§Returns

A fully initialized Env instance containing:

  • data: parsed local environment variables
  • global: empty until global_env() is called
  • path: stored file path
§Example
use rust_env::Env;

let env = Env::new("./.env");
§Notes
  • Panics if the file path is invalid or unreadable
  • This does NOT load OS environment variables automatically
  • Use global_env() to populate global environment data
Source

pub fn get_debug(self) -> Vec<Pair>

It will return the entire env local and global

§Example
use rust_env::{Env, Pair};

let env = Env::new("./.env");
let e: Vec<Pair> = env.get_debug();
Source

pub fn set(&mut self, h: Pair)

Creates a new Env instance from a .env file.

This function reads the file at the given path and parses its contents into structured environment data.

§Behavior
  • Loads local environment variables from the file
  • Parses content using .env rules (KEY=VALUE)
  • Stores results in self.data
  • Initializes an empty global environment store
§Arguments
  • name: Path to the .env file
§Returns

A fully initialized Env instance containing:

  • data: parsed local environment variables
  • global: empty until global_env() is called
  • path: stored file path
§Example
use rust_env::Env;

let env = Env::new("./.env");
§Notes
  • Panics if the file path is invalid or unreadable
  • This does NOT load OS environment variables automatically
  • Use global_env() to populate global environment data
Source

pub fn load(&mut self, e: &str)

Loads environment data into the current Env instance.

This function parses a raw .env-style string and merges it into the existing local environment data.

It is similar to set, but operates on multiple entries at once and does not directly write to disk.

§Behavior
  • Parses the input string using .env rules (KEY=VALUE)
  • Supports vector values using ; separators
  • Ignores duplicate keys already present in self.data
  • Only updates in-memory state (does NOT persist to file)
§Arguments
  • e: A raw environment string (e.g. "PORT=8080\nIP=127;0;0;1")
§Example
use rust_env::Env;

let mut env = Env::new("./.env");

env.load("PORT=8080\nHOST=127.0.0.1");
env.debug();
§Notes
  • This does NOT modify the file on disk
  • Use set or upload for persistent changes
  • Duplicate keys are ignored based on existing local data
Source

pub fn debug(&self)

It’s a function to debug the entire env

§Example
use rust_env::Env;
let env: Env = Env::new("./.env");

env.debug();
Source

pub fn upload(path: &str, Pairs: Vec<Pair>) -> Env

This function allows one to marshal env pairs and write them to a certain file It’s similar to the new function But you can write external data to the env file

§Example
use rust_env::{Env, Str, Vct};

let env = Env::upload("./env", vec![
      Str("PORT", "6778"),
      Vct("IP", vec![
         "127",
          "0",
          "0"
      ])
]);
Source

pub fn global_env(&mut self)

You can upload the global env data on the environment

§Example
 use rust_env::Env;

 let mut env: Env = Env::upload("./.env", vec![
     //put your local config
 ]);

 env.debug();
 env.global_env();
 env.debug();
Source

pub fn get_local(&self, k: &str) -> Wrapper

get_local is similar to get_Pair But, You can just gt the local config Not the global

§Example
use rust_env::Wrapper;

let port = match get_local("PORT") {
    Wrapper::Str(v) => v,
    e => e
};
Source

pub fn get_global(&self, k: &str) -> Wrapper

Retrieves a value from the global (OS-level) environment variables.

This function searches only in the runtime environment provided by std::env::vars(), which is captured when global_env() is called.

§Behavior
  • Searches only global environment variables
  • Does NOT fall back to local .env data
  • Returns the first matching key if found
§Returns

A Wrapper enum:

  • Wrapper::Str(String) for single values
  • Wrapper::Vec(Vec<String>) (rare, depending on parsing rules)
  • Wrapper::Empty if the key does not exist
§Arguments
  • k: The environment variable key to search for
§Example
use rust_env::{Env, Wrapper};

let mut env = Env::new("./.env");
env.global_env(); // load OS environment variables

match env.get_global("PATH") {
    Wrapper::Str(v) => println!("PATH = {}", v),
    Wrapper::Empty => println!("Not found"),
    _ => println!("Unexpected format"),
}
§Notes
  • This only works after calling global_env()
  • Values come from the OS environment at runtime
  • This does not read from .env files
  • Lookup is linear (O(n))
Source

pub fn debug_global(&self)

It will print the global env

Source

pub fn debug_local(&self)

It will print the local env

§Example
use rust_env::Env;

let mut env = Env::new("./.env");
env.global_env();

//printing just global env
env.debug_global();

//printing just local env
env.debug_local()
Source

pub fn get_pair(&mut self, k: &str) -> Wrapper

Retrieves a value from the environment, checking both global and local scopes.

This function performs a merged lookup:

  1. Checks global environment variables (OS-level)
  2. Falls back to local .env data if not found
§Lookup Order
global → local
§Behavior
  • Returns the first matching key found
  • If the value is a string, returns Wrapper::Str
  • If the value is a list, returns Wrapper::Vec
  • If the key does not exist, returns Wrapper::Empty
§Arguments
  • k: The key to search for
§Returns

A Wrapper enum containing:

  • Wrapper::Str(String) for single values
  • Wrapper::Vec(Vec<String>) for list values
  • Wrapper::Empty if not found
§Example
use rust_env::{Env, Wrapper};

let mut env = Env::new("./.env");
env.global_env();

match env.get_pair("PORT") {
    Wrapper::Str(v) => println!("PORT = {}", v),
    Wrapper::Vec(v) => println!("List = {:?}", v),
    Wrapper::Empty => println!("Not found"),
}
§Notes
  • Global variables override local ones
  • This function does not modify state
  • Lookup is linear (O(n)) in both environments

Auto Trait Implementations§

§

impl Freeze for Env

§

impl RefUnwindSafe for Env

§

impl Send for Env

§

impl Sync for Env

§

impl Unpin for Env

§

impl UnsafeUnpin for Env

§

impl UnwindSafe for Env

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.