Skip to main content

read_file

Function read_file 

Source
pub fn read_file(path: &str) -> Result<String, CliError>
Expand description

Read a file from disk with size validation.

Reads the entire contents of a file into a string, with built-in protection against out-of-memory (OOM) attacks. Files larger than the configured maximum size will be rejected before reading.

§Arguments

  • path - Path to the file to read

§Returns

Returns the file contents as a String on success.

§Errors

Returns Err if:

  • The file metadata cannot be accessed
  • The file size exceeds the maximum allowed size (configurable via HEDL_MAX_FILE_SIZE)
  • The file cannot be read
  • The file contains invalid UTF-8

§Examples

use hedl_cli::commands::read_file;

// Read a small HEDL file
let content = read_file("example.hedl")?;
assert!(!content.is_empty());

// Files larger than the limit will fail
std::env::set_var("HEDL_MAX_FILE_SIZE", "1000"); // 1 KB limit
let result = read_file("large_file.hedl");
assert!(result.is_err());

§Security

This function includes protection against OOM attacks by checking the file size before reading. The maximum file size defaults to 1 GB but can be customized via the HEDL_MAX_FILE_SIZE environment variable.

§Performance

Uses fs::metadata() to check file size before allocating memory, preventing unnecessary memory allocation for oversized files.