Skip to content

Commit

Permalink
Enforce const evaluation in path! macro
Browse files Browse the repository at this point in the history
By using a temporary const value, we can enforce that the path! macro
always causes a compiler error for illegal values even if it is not used
in a const context.  This makes it easier to write correct code.
  • Loading branch information
robin-nitrokey committed May 24, 2024
1 parent 2ad7785 commit 498fee7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Fixed build error that would occur on Windows systems.
- Added path iteration utilities ([#47][])

## Changed

- Enforced const evaluation for `path!`.

[#47]: https://github.com/trussed-dev/littlefs2/pull/47
[#57]: https://github.com/trussed-dev/littlefs2/pull/57

Expand Down
19 changes: 15 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,14 +165,15 @@ pub struct Version {

/// Creates a path from a string without a trailing null.
///
/// Panics if the string contains null bytes or non-ascii characters.
/// Panics and causes a compiler error if the string contains null bytes or non-ascii characters.
///
/// # Examples
///
/// ```
/// use littlefs2::{path, path::Path};
///
/// const HOME: &Path = path!("/home");
/// let root = path!("/");
/// ```
///
/// Illegal values:
Expand All @@ -186,11 +187,21 @@ pub struct Version {
/// # use littlefs2::{path, path::Path};
/// const WITH_UTF8: &Path = path!("/höme"); // does not compile
/// ```
///
/// The macro enforces const evaluation so that compilation fails for illegal values even if the
/// macro is not used in a const context:
///
/// ```compile_fail
/// # use littlefs2::path;
/// let path = path!("te\0st"); // does not compile
/// ```
#[macro_export]
macro_rules! path {
($path:literal) => {
$crate::path::Path::from_str_with_nul(::core::concat!($path, "\0"))
};
($path:literal) => {{
const _PATH: &$crate::path::Path =
$crate::path::Path::from_str_with_nul(::core::concat!($path, "\0"));
_PATH
}};
}

#[cfg(test)]
Expand Down

0 comments on commit 498fee7

Please sign in to comment.