hcl/expr/variable.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
use crate::{Identifier, InternalString, Result};
use serde::Deserialize;
use std::ops::Deref;
/// A type representing a variable in an HCL expression.
///
/// It is a wrapper around the [`Identifier`] type and behaves the same in most cases via its
/// `Deref` implementation.
///
/// This is a separate type to differentiate between bare identifiers and variable identifiers
/// which have different semantics in different scopes.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct Variable(Identifier);
impl Variable {
/// Create a new `Variable` after validating that it only contains characters that are allowed
/// in HCL identifiers.
///
/// See the documentation of [`Identifier::new`] for more.
///
/// # Errors
///
/// If `ident` contains characters that are not allowed in HCL identifiers or if it is empty an
/// error will be returned.
pub fn new<T>(ident: T) -> Result<Self>
where
T: Into<InternalString>,
{
Identifier::new(ident).map(Variable)
}
/// Create a new `Variable` after sanitizing the input if necessary.
///
/// See the documentation of [`Identifier::sanitized`] for more.
pub fn sanitized<T>(ident: T) -> Self
where
T: AsRef<str>,
{
Variable(Identifier::sanitized(ident))
}
/// Create a new `Variable` from an identifier without checking if it is valid in HCL.
///
/// It is the caller's responsibility to ensure that the variable identifier is valid.
///
/// See the documentation of [`Identifier::unchecked`] for more.
///
/// # Safety
///
/// This function is not marked as unsafe because it does not cause undefined behaviour.
/// However, attempting to serialize an invalid variable identifier to HCL will produce invalid
/// output.
pub fn unchecked<T>(ident: T) -> Self
where
T: Into<InternalString>,
{
Variable(Identifier::unchecked(ident))
}
/// Consume `self` and return the wrapped `Identifier`.
pub fn into_inner(self) -> Identifier {
self.0
}
}
impl Deref for Variable {
type Target = Identifier;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<Identifier> for Variable {
fn from(ident: Identifier) -> Self {
Variable(ident)
}
}