libdd_library_config/config_read.rs
1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::io;
5use alloc::vec::Vec;
6
7/// Maximum allowed config file size (100 MB).
8pub const MAX_CONFIG_FILE_SIZE: usize = 100 * 1024 * 1024;
9
10/// Trait for reading configuration files from a filesystem or virtual filesystem.
11///
12/// Implement this to provide custom file access for environments where `std::fs`
13/// is not available (e.g. no_std, sandboxed, or in-memory configurations).
14pub trait ConfigRead {
15 /// Read the entire contents of the configuration file at `path`, like `std::fs::read`.
16 ///
17 /// A missing file must be reported as [`io::ErrorKind::NotFound`]; the configuration layer is
18 /// then treated as empty. Implementations **should** return [`io::ErrorKind::FileTooLarge`] for
19 /// files exceeding [`MAX_CONFIG_FILE_SIZE`] to avoid unnecessary allocations; the
20 /// configurator also checks the returned bytes as a safety net. Both are skipped with a
21 /// debug log, while any other error aborts config loading.
22 fn read(&self, path: &str) -> io::Result<Vec<u8>>;
23}
24
25/// Standard filesystem implementation of [`ConfigRead`].
26#[cfg(feature = "std")]
27pub struct StdConfigRead;
28
29#[cfg(feature = "std")]
30impl ConfigRead for StdConfigRead {
31 fn read(&self, path: &str) -> io::Result<Vec<u8>> {
32 let file = std::fs::File::open(path)?;
33 let len = file.metadata()?.len();
34 // Compare as u64 so 32-bit targets can't truncate an oversized length.
35 if len > MAX_CONFIG_FILE_SIZE as u64 {
36 return Err(io::ErrorKind::FileTooLarge.into());
37 }
38 // `len` is bounded by MAX_CONFIG_FILE_SIZE, so it fits in usize.
39 let mut buf = Vec::with_capacity(len as usize);
40 std::io::Read::read_to_end(&mut &file, &mut buf)?;
41 Ok(buf)
42 }
43}