protobuf_native/
internal.rs

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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright Materialize, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file at the
// root of this repository, or online at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[cfg(unix)]
use std::ffi::OsStr;
use std::fmt;
use std::io::{Read, Write};
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::os::raw::{c_char, c_int, c_void};
#[cfg(unix)]
use std::os::unix::prelude::OsStrExt;
use std::path::Path;

use cxx::kind::Trivial;
use cxx::{type_id, ExternType};

use crate::OperationFailedError;

// Pollyfill C++ APIs that aren't yet in cxx.
// See: https://github.com/dtolnay/cxx/pull/984
// See: https://github.com/dtolnay/cxx/pull/990

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        unsafe fn vec_u8_set_len(v: &mut Vec<u8>, new_len: usize);
    }

    unsafe extern "C++" {
        include!("protobuf-native/src/internal.h");

        #[namespace = "absl"]
        #[cxx_name = "string_view"]
        type StringView<'a> = crate::internal::StringView<'a>;

        #[namespace = "protobuf_native::internal"]
        fn string_view_from_bytes(bytes: &[u8]) -> StringView;
    }
}

unsafe fn vec_u8_set_len(v: &mut Vec<u8>, new_len: usize) {
    v.set_len(new_len)
}

#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct StringView<'a> {
    repr: MaybeUninit<[*const c_void; 2]>,
    borrow: PhantomData<&'a [c_char]>,
}

impl<'a> From<&'a str> for StringView<'a> {
    fn from(s: &'a str) -> StringView<'a> {
        ffi::string_view_from_bytes(s.as_bytes())
    }
}

impl<'a> From<ProtobufPath<'a>> for StringView<'a> {
    fn from(path: ProtobufPath<'a>) -> StringView<'a> {
        ffi::string_view_from_bytes(path.as_bytes())
    }
}

unsafe impl<'a> ExternType for StringView<'a> {
    type Id = type_id!("absl::string_view");
    type Kind = Trivial;
}

// Variable-width integer types.
// See: https://github.com/google/autocxx/issues/422#issuecomment-826987408

#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct CInt(pub c_int);

impl CInt {
    pub fn to_usize(self) -> Result<usize, OperationFailedError> {
        usize::try_from(self.0).map_err(|_| OperationFailedError)
    }

    pub fn expect_usize(self) -> usize {
        match self.to_usize() {
            Ok(n) => n,
            Err(_) => panic!("C int is not representible as a Rust usize: {}", self.0),
        }
    }

    pub fn try_from<T>(value: T) -> Result<CInt, T::Error>
    where
        T: TryInto<c_int>,
    {
        value.try_into().map(CInt)
    }

    pub fn expect_from<T>(value: T) -> CInt
    where
        T: TryInto<c_int> + Copy + fmt::Display,
    {
        match CInt::try_from(value) {
            Ok(n) => n,
            Err(_) => panic!("value is not representable as a C int: {}", value),
        }
    }
}

unsafe impl ExternType for CInt {
    type Id = type_id!("protobuf_native::internal::CInt");
    type Kind = Trivial;
}

#[derive(Debug)]
pub struct CVoid(pub c_void);

unsafe impl ExternType for CVoid {
    type Id = type_id!("protobuf_native::internal::CVoid");
    type Kind = Trivial;
}

// `Read` and `Write` adaptors for C++.

pub struct ReadAdaptor<'a>(pub &'a mut dyn Read);

impl ReadAdaptor<'_> {
    pub fn read(&mut self, buf: &mut [u8]) -> isize {
        match self.0.read(buf) {
            Ok(n) => n.try_into().expect("read bytes do not fit into isize"),
            Err(_) => -1,
        }
    }
}

pub struct WriteAdaptor<'a>(pub &'a mut dyn Write);

impl WriteAdaptor<'_> {
    pub fn write(&mut self, buf: &[u8]) -> bool {
        self.0.write_all(buf).as_status()
    }
}

/// Extensions to [`Result`].
pub trait ResultExt {
    /// Converts this result into a status boolean.
    ///
    /// If the result is `Ok`, returns true. If the result is `Err`, returns
    /// false.
    fn as_status(&self) -> bool;
}

impl<T, E> ResultExt for Result<T, E> {
    fn as_status(&self) -> bool {
        match self {
            Ok(_) => true,
            Err(_) => false,
        }
    }
}

/// Extensions to [`bool`].
pub trait BoolExt {
    /// Converts this status boolean into a result.
    ///
    /// If the status boolean is true, returns `Ok`. If the status boolean is
    /// false, returns `Err`.
    fn as_result(self) -> Result<(), OperationFailedError>;
}

impl BoolExt for bool {
    fn as_result(self) -> Result<(), OperationFailedError> {
        match self {
            true => Ok(()),
            false => Err(OperationFailedError),
        }
    }
}

/// An adapter for passing paths to `libprotobuf`.
///
/// On Unix, the bytes in a path can be passed directly.
///
/// On Windows, the situation is complicated. Protobuf assumes paths are UTF-8
/// and converts them to wide-character strings before passing them to the
/// underlying Windows wide-char APIs. But paths in Rust might not valid UTF-8.
/// There's not much we can do to handle invalid UTF-8 correctly; we just throw
/// `to_string_lossy` at the problem and hope `libprotobuf` sorts it out.
///
/// The point is to make this correct and performant on Unix in all cases, and
/// correct in Windows as long as the path is valid UTF-8.
#[cfg(unix)]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct ProtobufPath<'a>(&'a Path);

#[cfg(windows)]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct ProtobufPath<'a> {
    inner: Vec<u8>,
    _phantom: PhantomData<'a>,
}

#[cfg(unix)]
impl<'a> ProtobufPath<'a> {
    pub fn as_path(&self) -> impl AsRef<Path> + 'a {
        self.0
    }
}

#[cfg(unix)]
impl<'a> From<&'a [u8]> for ProtobufPath<'a> {
    fn from(p: &'a [u8]) -> ProtobufPath<'a> {
        ProtobufPath(Path::new(OsStr::from_bytes(p)))
    }
}

#[cfg(unix)]
impl<'a> From<&'a Path> for ProtobufPath<'a> {
    fn from(p: &'a Path) -> ProtobufPath<'a> {
        ProtobufPath(p)
    }
}

#[cfg(unix)]
impl<'a> ProtobufPath<'a> {
    pub fn as_bytes(&self) -> &'a [u8] {
        self.0.as_os_str().as_bytes()
    }
}

#[cfg(windows)]
impl<'a> ProtobufPath<'a> {
    pub fn as_path(&self) -> impl AsRef<Path> {
        PathBuf::from(String::from_utf8_lossy(self.inner))
    }
}

#[cfg(windows)]
impl<'a> From<&'a [u8]> for ProtobufPath<'static> {
    fn from(p: &'a [u8]) -> ProtobufPath<'static> {
        ProtobufPath {
            inner: p.to_vec(),
            _phantom: PhantomData,
        }
    }
}

#[cfg(windows)]
impl<'a> From<Path> for ProtobufPath<'a> {
    fn from(p: Path) -> ProtobufPath<'a> {
        ProtobufPath {
            inner: p.to_string_lossy().into_owned().into_bytes(),
            _phantom: PhantomData,
        }
    }
}

#[cfg(windows)]
impl<'a> ProtobufPath<'a> {
    pub fn as_bytes(&self) -> &'a [u8] {
        &self.inner
    }
}

macro_rules! unsafe_ffi_conversions {
    ($ty:ty) => {
        #[allow(dead_code)]
        pub(crate) unsafe fn from_ffi_owned(from: *mut $ty) -> Pin<Box<Self>> {
            std::mem::transmute(from)
        }

        #[allow(dead_code)]
        pub(crate) unsafe fn from_ffi_ptr<'_a>(from: *const $ty) -> &'_a Self {
            std::mem::transmute(from)
        }

        #[allow(dead_code)]
        pub(crate) fn from_ffi_ref(from: &$ty) -> &Self {
            unsafe { std::mem::transmute(from) }
        }

        #[allow(dead_code)]
        pub(crate) unsafe fn from_ffi_mut<'_a>(from: *mut $ty) -> Pin<&'_a mut Self> {
            std::mem::transmute(from)
        }

        #[allow(dead_code)]
        pub(crate) fn as_ffi(&self) -> &$ty {
            unsafe { std::mem::transmute(self) }
        }

        #[allow(dead_code)]
        pub(crate) fn as_ffi_mut(self: Pin<&mut Self>) -> Pin<&mut $ty> {
            unsafe { std::mem::transmute(self) }
        }

        #[allow(dead_code)]
        pub(crate) fn as_ffi_mut_ptr(self: Pin<&mut Self>) -> *mut $ty {
            unsafe { std::mem::transmute(self) }
        }

        #[allow(dead_code)]
        pub(crate) unsafe fn as_ffi_mut_ptr_unpinned(&mut self) -> *mut $ty {
            std::mem::transmute(self)
        }
    };
}

pub(crate) use unsafe_ffi_conversions;