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
129
use displaydoc::Display;
use proc_macro2::TokenStream;
use quote::quote;
use std::str::FromStr;
use thiserror::Error;
pub enum HsType {
CString,
Empty,
IO(Box<HsType>),
}
impl std::fmt::Display for HsType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
HsType::CString => "CString".to_string(),
HsType::Empty => "()".to_string(),
HsType::IO(x) => format!("IO {}", x),
}
)
}
}
#[derive(Display, Error, Debug)]
pub enum Error {
UnsupportedHsType(String),
}
impl FromStr for HsType {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.trim();
if s.len() >= 2 && &s[..2] == "IO" {
Ok(HsType::IO(Box::new(s[2..].parse()?)))
} else {
match s.trim() {
"CString" => Ok(HsType::CString),
"()" => Ok(HsType::Empty),
ty => Err(Error::UnsupportedHsType(ty.to_string())),
}
}
}
}
impl HsType {
pub fn quote(&self) -> TokenStream {
match self {
HsType::CString => quote! { *const std::os::raw::c_char },
HsType::Empty => quote! { () },
HsType::IO(x) => x.quote(),
}
}
}
pub trait ReprHs {
fn into() -> HsType;
}
impl ReprHs for String {
fn into() -> HsType {
HsType::CString
}
}
impl ReprHs for &str {
fn into() -> HsType {
HsType::CString
}
}
impl ReprHs for () {
fn into() -> HsType {
HsType::Empty
}
}
pub trait ReprC<T> {
fn from(_: T) -> Self;
}
impl ReprC<*const std::os::raw::c_char> for &str {
#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn from(x: *const std::os::raw::c_char) -> Self {
unsafe { std::ffi::CStr::from_ptr(x) }.to_str().unwrap()
}
}
impl ReprC<*const std::os::raw::c_char> for String {
fn from(x: *const std::os::raw::c_char) -> Self {
let r: &str = ReprC::from(x);
r.to_string()
}
}
pub trait ReprRust<T> {
fn from(_: T) -> Self;
}
impl ReprRust<()> for () {
fn from(_: ()) -> Self {
()
}
}