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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use crate::types::binary::OwnedBinary;
use crate::wrapper::env::term_to_binary;
use crate::wrapper::NIF_TERM;
use crate::{Binary, Decoder, Env, NifResult};
use std::cmp::Ordering;
use std::fmt::{self, Debug};
#[derive(Clone, Copy)]
pub struct Term<'a> {
term: NIF_TERM,
env: Env<'a>,
}
impl<'a> Debug for Term<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
crate::wrapper::term::fmt(self.as_c_arg(), f)
}
}
impl<'a> Term<'a> {
pub unsafe fn new(env: Env<'a>, inner: NIF_TERM) -> Self {
Term { term: inner, env }
}
pub fn as_c_arg(&self) -> NIF_TERM {
self.term
}
pub fn get_env(&self) -> Env<'a> {
self.env
}
pub fn in_env<'b>(&self, env: Env<'b>) -> Term<'b> {
if self.get_env() == env {
unsafe { Term::new(env, self.as_c_arg()) }
} else {
unsafe {
Term::new(
env,
rustler_sys::enif_make_copy(env.as_c_arg(), self.as_c_arg()),
)
}
}
}
pub fn decode<T>(self) -> NifResult<T>
where
T: Decoder<'a>,
{
Decoder::decode(self)
}
pub fn decode_as_binary(self) -> NifResult<Binary<'a>> {
if self.is_binary() {
return Binary::from_term(self);
}
Binary::from_iolist(self)
}
pub fn to_binary(self) -> OwnedBinary {
let raw_binary = unsafe { term_to_binary(self.env.as_c_arg(), self.as_c_arg()) }.unwrap();
unsafe { OwnedBinary::from_raw(raw_binary) }
}
}
impl<'a> PartialEq for Term<'a> {
fn eq(&self, other: &Term) -> bool {
unsafe { rustler_sys::enif_is_identical(self.as_c_arg(), other.as_c_arg()) == 1 }
}
}
impl<'a> Eq for Term<'a> {}
fn cmp(lhs: &Term, rhs: &Term) -> Ordering {
let ord = unsafe { rustler_sys::enif_compare(lhs.as_c_arg(), rhs.as_c_arg()) };
match ord {
0 => Ordering::Equal,
n if n < 0 => Ordering::Less,
_ => Ordering::Greater,
}
}
impl<'a> Ord for Term<'a> {
fn cmp(&self, other: &Term) -> Ordering {
cmp(self, other)
}
}
impl<'a> PartialOrd for Term<'a> {
fn partial_cmp(&self, other: &Term<'a>) -> Option<Ordering> {
Some(cmp(self, other))
}
}
unsafe impl<'a> Sync for Term<'a> {}
unsafe impl<'a> Send for Term<'a> {}