Skip to content

Commit b882d51

Browse files
authored
Implement support for conversions of paths (#608)
1 parent 3690679 commit b882d51

File tree

6 files changed

+42
-0
lines changed

6 files changed

+42
-0
lines changed

rustler/src/types/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use crate::{Env, Error, NifResult, Term};
33
#[macro_use]
44
pub mod atom;
55
pub mod i128;
6+
pub mod path;
67
pub use crate::types::atom::Atom;
78

89
pub mod binary;

rustler/src/types/path.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
use crate::{Decoder, Encoder, Env, Error, NifResult, Term};
2+
use std::path::{Path, PathBuf};
3+
4+
impl Encoder for Path {
5+
fn encode<'a>(&self, env: Env<'a>) -> Term<'a> {
6+
self.as_os_str().to_str().encode(env)
7+
}
8+
}
9+
10+
impl Encoder for PathBuf {
11+
fn encode<'a>(&self, env: Env<'a>) -> Term<'a> {
12+
self.as_path().encode(env)
13+
}
14+
}
15+
16+
impl<'a> Decoder<'a> for &'a Path {
17+
fn decode(term: Term<'a>) -> NifResult<Self> {
18+
let bin = term.decode_as_binary().or(Err(Error::BadArg))?;
19+
let s = std::str::from_utf8(bin.as_slice()).or(Err(Error::BadArg))?;
20+
Ok(Path::new(s))
21+
}
22+
}
23+
24+
impl<'a> Decoder<'a> for PathBuf {
25+
fn decode(term: Term<'a>) -> NifResult<Self> {
26+
let s: &str = term.decode()?;
27+
Ok(PathBuf::from(s))
28+
}
29+
}

rustler_tests/lib/rustler_test.ex

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,6 @@ defmodule RustlerTest do
133133
def maybe_add_one_to_tuple(_tuple), do: err()
134134
def add_i32_from_tuple(_tuple), do: err()
135135
def greeting_person_from_tuple(_tuple), do: err()
136+
137+
def append_to_path(_path, _to_append), do: err()
136138
end

rustler_tests/native/rustler_test/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ mod test_error;
77
mod test_list;
88
mod test_map;
99
mod test_nif_attrs;
10+
mod test_path;
1011
mod test_primitives;
1112
mod test_range;
1213
mod test_resource;
@@ -103,6 +104,7 @@ rustler::init!(
103104
test_codegen::reserved_keywords::reserved_keywords_type_echo,
104105
test_codegen::generic_types::generic_struct_echo,
105106
test_codegen::generic_types::mk_generic_map,
107+
test_path::append_to_path,
106108
],
107109
load = load
108110
);
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
use std::path::{Path, PathBuf};
2+
3+
#[rustler::nif]
4+
pub fn append_to_path(p: &Path, comp: &str) -> PathBuf {
5+
let mut p = p.to_path_buf();
6+
p.push(comp);
7+
p
8+
}

rustler_tests/test/path_test.exs

Whitespace-only changes.

0 commit comments

Comments
 (0)