//! Small helpers for building and reading Erlang terms. use erl_dist::term::{Atom, FixInteger, List, Pid, Reference, Term}; /// Atom from a string. pub fn atom(name: impl AsRef) -> Atom { Atom::from(name.as_ref()) } /// Empty list `[]`. pub fn nil() -> List { List::nil() } /// Proper list from a sequence of terms. pub fn list(items: impl IntoIterator) -> List { List::from(items.into_iter().collect::>()) } /// Small integer. pub fn int(n: i32) -> FixInteger { FixInteger::from(n) } /// 2-tuple `{a, b}`. pub fn tuple2(a: impl Into, b: impl Into) -> Term { Term::from(eetf::Tuple::from(vec![a.into(), b.into()])) } /// 3-tuple `{a, b, c}`. pub fn tuple3(a: impl Into, b: impl Into, c: impl Into) -> Term { Term::from(eetf::Tuple::from(vec![a.into(), b.into(), c.into()])) } /// 4-tuple. pub fn tuple4( a: impl Into, b: impl Into, c: impl Into, d: impl Into, ) -> Term { Term::from(eetf::Tuple::from(vec![a.into(), b.into(), c.into(), d.into()])) } /// N-tuple from a vec of terms. pub fn tuple(elements: Vec) -> Term { Term::from(eetf::Tuple::from(elements)) } /// Binary from bytes. pub fn binary(data: impl AsRef<[u8]>) -> Term { Term::from(eetf::Binary::from(data.as_ref().to_vec())) } /// String as a char list (Erlang string). pub fn string(s: impl AsRef) -> Term { Term::from(eetf::List::from( s.as_ref() .chars() .map(|c| Term::from(FixInteger::from(c as i32))) .collect::>(), )) } /// Local pid for this node (serial 0 — the "bot process"). pub fn local_pid(node: &str, creation: u32) -> Pid { Pid::new(node.to_string(), 0, 0, creation) } /// Fresh distribution reference. pub fn make_ref(node: &str, creation: u32) -> Reference { Reference { node: Atom::from(node), id: vec![rand::random(), rand::random(), rand::random()], creation, } } /// Try to extract an atom name. pub fn as_atom(term: &Term) -> Option<&str> { match term { Term::Atom(a) => Some(a.name.as_str()), _ => None, } } /// Pretty-print a term (debug-ish, good enough for logs). pub fn format_term(term: &Term) -> String { format!("{term}") }