Skip to content

Commit

Permalink
Implement support for conversions of paths
Browse files Browse the repository at this point in the history
  • Loading branch information
filmor committed May 2, 2024
1 parent 6bd2a80 commit 7b2ba25
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions rustler/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::{Env, Error, NifResult, Term};
#[macro_use]
pub mod atom;
pub mod i128;
pub mod path;
pub use crate::types::atom::Atom;

pub mod binary;
Expand Down
29 changes: 29 additions & 0 deletions rustler/src/types/path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use crate::{Decoder, Encoder, Env, Error, NifResult, Term};
use std::path::{Path, PathBuf};

impl Encoder for Path {
fn encode<'a>(&self, env: Env<'a>) -> Term<'a> {
self.as_os_str().to_str().encode(env)
}
}

impl Encoder for PathBuf {
fn encode<'a>(&self, env: Env<'a>) -> Term<'a> {
self.as_path().encode(env)
}
}

impl<'a> Decoder<'a> for &'a Path {
fn decode(term: Term<'a>) -> NifResult<Self> {
let bin = term.decode_as_binary().or(Err(Error::BadArg))?;
let s = std::str::from_utf8(bin.as_slice()).or(Err(Error::BadArg))?;
Ok(Path::new(s))
}
}

impl<'a> Decoder<'a> for PathBuf {
fn decode(term: Term<'a>) -> NifResult<Self> {
let s: &str = term.decode()?;
Ok(PathBuf::from(s))
}
}
2 changes: 2 additions & 0 deletions rustler_tests/lib/rustler_test.ex
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,6 @@ defmodule RustlerTest do
def maybe_add_one_to_tuple(_tuple), do: err()
def add_i32_from_tuple(_tuple), do: err()
def greeting_person_from_tuple(_tuple), do: err()

def append_to_path(_path, _to_append), do: err()
end
2 changes: 2 additions & 0 deletions rustler_tests/native/rustler_test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod test_error;
mod test_list;
mod test_map;
mod test_nif_attrs;
mod test_path;
mod test_primitives;
mod test_range;
mod test_resource;
Expand Down Expand Up @@ -103,6 +104,7 @@ rustler::init!(
test_codegen::reserved_keywords::reserved_keywords_type_echo,
test_codegen::generic_types::generic_struct_echo,
test_codegen::generic_types::mk_generic_map,
test_path::append_to_path,
],
load = load
);
Expand Down
8 changes: 8 additions & 0 deletions rustler_tests/native/rustler_test/src/test_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use std::path::{Path, PathBuf};

#[rustler::nif]
pub fn append_to_path(p: &Path, comp: &str) -> PathBuf {
let mut p = p.to_path_buf();
p.push(comp);
p
}
Empty file.

0 comments on commit 7b2ba25

Please sign in to comment.