Skip to content

Commit

Permalink
Add non-UTF-8 example; closes #66
Browse files Browse the repository at this point in the history
  • Loading branch information
allan2 committed Oct 5, 2024
1 parent db89b9d commit df9668e
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
9 changes: 9 additions & 0 deletions examples/non-utf8/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "non-utf8-example"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
dotenvy = { path = "../../dotenvy" }
encoding_rs_io = "0.1"
Binary file added examples/non-utf8/env-example-utf16
Binary file not shown.
35 changes: 35 additions & 0 deletions examples/non-utf8/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//! dotenvy only handles UTF-8.
//!
//! If a source file is non-UTF-8, it can still be loaded with help from the `encoding_rs_io` crate.

use dotenvy::EnvLoader;
use encoding_rs_io::DecodeReaderBytes;
use std::{
error::{self, Error},
fs,
io::{self, Read},
};

fn main() -> Result<(), Box<dyn error::Error>> {
let path = "env-example-utf16";

// this will fail
let e = EnvLoader::with_path(path).load().unwrap_err();
let io_err = e.source().unwrap().downcast_ref::<io::Error>().unwrap();
assert_eq!(io_err.kind(), io::ErrorKind::InvalidData);

// with `encoding_rs_io`, this will work
let bytes = fs::read(path)?;
let mut decoder = DecodeReaderBytes::new(&bytes[..]);
let mut dest = Vec::new();

// read to end to ensure the stream is fully decoded
decoder.read_to_end(&mut dest)?;

// `path` setter provides the path to error messages
let env_map = EnvLoader::with_reader(&dest[..]).path(path).load()?;

println!("HOST={}", env_map.var("HOST")?);

Ok(())
}

0 comments on commit df9668e

Please sign in to comment.