Debian Codegraph @

libgrust/libproc_macro/bridge/ffistring.rs

raw
1 // Copyright (C) 2023-2024 Free Software Foundation, Inc.
2 //
3 // This file is part of the GNU Proc Macro Library. This library is free
4 // software; you can redistribute it and/or modify it under the
5 // terms of the GNU General Public License as published by the
6 // Free Software Foundation; either version 3, or (at your option)
7 // any later version.
8
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13
14 // Under Section 7 of GPL version 3, you are granted additional
15 // permissions described in the GCC Runtime Library Exception, version
16 // 3.1, as published by the Free Software Foundation.
17
18 // You should have received a copy of the GNU General Public License and
19 // a copy of the GCC Runtime Library Exception along with this program;
20 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
21 // <http://www.gnu.org/licenses/>.
22
23 use std::convert::TryInto;
24 use std::ffi::c_uchar;
25 use std::fmt;
26 use std::slice::from_raw_parts;
27 use std::str::from_utf8;
28
29 extern "C" {
30 fn FFIString__new(data: *const c_uchar, len: u64) -> FFIString;
31 fn FFIString__drop(string: *mut FFIString);
32 }
33
34 #[repr(C)]
35 #[derive(Debug)]
36 pub struct FFIString {
37 data: *const c_uchar,
38 len: u64,
39 }
40
41 impl<S> From<S> for FFIString
42 where
43 S: AsRef<str>,
44 {
45 fn from(s: S) -> Self {
46 unsafe { FFIString__new(s.as_ref().as_ptr(), s.as_ref().len() as u64) }
47 }
48 }
49
50 impl Clone for FFIString {
51 fn clone(&self) -> Self {
52 FFIString::from(&self.to_string())
53 }
54 }
55
56 impl Drop for FFIString {
57 fn drop(&mut self) {
58 unsafe {
59 FFIString__drop(self as *mut FFIString);
60 }
61 }
62 }
63
64 impl fmt::Display for FFIString {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.write_str(
67 from_utf8(unsafe {
68 from_raw_parts(self.data, self.len.try_into().map_err(|_| fmt::Error)?)
69 })
70 .map_err(|_| fmt::Error)?,
71 )
72 }
73 }