80f04c523f421d9fd2cd64fcbb9ae0c767781999
[ldk-c-bindings] / lightning-c-bindings / src / c_types / mod.rs
1 //! This module contains standard C-mapped types for types not in the original crate.
2
3 /// Auto-generated C-mapped types for templated containers
4 pub mod derived;
5
6 use bitcoin::Transaction as BitcoinTransaction;
7 use bitcoin::hashes::Hash;
8 use bitcoin::secp256k1::key::PublicKey as SecpPublicKey;
9 use bitcoin::secp256k1::key::SecretKey as SecpSecretKey;
10 use bitcoin::secp256k1::Signature as SecpSignature;
11 use bitcoin::secp256k1::Error as SecpError;
12 use bitcoin::secp256k1::recovery::RecoveryId;
13 use bitcoin::secp256k1::recovery::RecoverableSignature as SecpRecoverableSignature;
14 use bitcoin::bech32;
15
16 use core::convert::TryInto; // Bindings need at least rustc 1.34
17 use core::ffi::c_void;
18
19 #[cfg(feature = "std")]
20 pub(crate) use std::io::{self, Cursor, Read};
21 #[cfg(feature = "no-std")]
22 pub(crate) use core2::io::{self, Cursor, Read};
23 #[cfg(feature = "no-std")]
24 use alloc::{boxed::Box, vec::Vec, string::String};
25
26 #[repr(C)]
27 /// A dummy struct of which an instance must never exist.
28 /// This corresponds to the Rust type `Infallible`, or, in unstable rust, `!`
29 pub struct NotConstructable {
30         _priv_thing: core::convert::Infallible,
31 }
32 impl From<core::convert::Infallible> for NotConstructable {
33         fn from(_: core::convert::Infallible) -> Self { unreachable!(); }
34 }
35
36 /// Integer in the range `0..32`
37 #[derive(PartialEq, Eq, Copy, Clone)]
38 #[allow(non_camel_case_types)]
39 #[repr(C)]
40 pub struct u5(u8);
41
42 impl From<bech32::u5> for u5 {
43         fn from(o: bech32::u5) -> Self { Self(o.to_u8()) }
44 }
45 impl Into<bech32::u5> for u5 {
46         fn into(self) -> bech32::u5 { bech32::u5::try_from_u8(self.0).expect("u5 objects must be in the range 0..32") }
47 }
48
49 #[derive(Clone)]
50 #[repr(C)]
51 /// Represents a valid secp256k1 public key serialized in "compressed form" as a 33 byte array.
52 pub struct PublicKey {
53         /// The bytes of the public key
54         pub compressed_form: [u8; 33],
55 }
56 impl PublicKey {
57         pub(crate) fn from_rust(pk: &SecpPublicKey) -> Self {
58                 Self {
59                         compressed_form: pk.serialize(),
60                 }
61         }
62         pub(crate) fn into_rust(&self) -> SecpPublicKey {
63                 SecpPublicKey::from_slice(&self.compressed_form).unwrap()
64         }
65         pub(crate) fn is_null(&self) -> bool { self.compressed_form[..] == [0; 33][..] }
66         pub(crate) fn null() -> Self { Self { compressed_form: [0; 33] } }
67 }
68
69 #[repr(C)]
70 #[derive(Clone)]
71 /// Represents a valid secp256k1 secret key serialized as a 32 byte array.
72 pub struct SecretKey {
73         /// The bytes of the secret key
74         pub bytes: [u8; 32],
75 }
76 impl SecretKey {
77         // from_rust isn't implemented for a ref since we just return byte array refs directly
78         pub(crate) fn from_rust(sk: SecpSecretKey) -> Self {
79                 let mut bytes = [0; 32];
80                 bytes.copy_from_slice(&sk[..]);
81                 Self { bytes }
82         }
83         pub(crate) fn into_rust(&self) -> SecpSecretKey {
84                 SecpSecretKey::from_slice(&self.bytes).unwrap()
85         }
86 }
87
88 #[repr(C)]
89 #[derive(Clone)]
90 /// Represents a secp256k1 signature serialized as two 32-byte numbers
91 pub struct Signature {
92         /// The bytes of the signature in "compact" form
93         pub compact_form: [u8; 64],
94 }
95 impl Signature {
96         pub(crate) fn from_rust(pk: &SecpSignature) -> Self {
97                 Self {
98                         compact_form: pk.serialize_compact(),
99                 }
100         }
101         pub(crate) fn into_rust(&self) -> SecpSignature {
102                 SecpSignature::from_compact(&self.compact_form).unwrap()
103         }
104         // The following are used for Option<Signature> which we support, but don't use anymore
105         #[allow(unused)] pub(crate) fn is_null(&self) -> bool { self.compact_form[..] == [0; 64][..] }
106         #[allow(unused)] pub(crate) fn null() -> Self { Self { compact_form: [0; 64] } }
107 }
108
109 #[repr(C)]
110 #[derive(Clone)]
111 /// Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which
112 /// allows recovering the exact public key which created the signature given the message.
113 pub struct RecoverableSignature {
114         /// The bytes of the signature in "compact" form plus a "Recovery ID" which allows for
115         /// recovery.
116         pub serialized_form: [u8; 68],
117 }
118 impl RecoverableSignature {
119         pub(crate) fn from_rust(pk: &SecpRecoverableSignature) -> Self {
120                 let (id, compact_form) = pk.serialize_compact();
121                 let mut serialized_form = [0; 68];
122                 serialized_form[0..64].copy_from_slice(&compact_form[..]);
123                 serialized_form[64..].copy_from_slice(&id.to_i32().to_le_bytes());
124                 Self { serialized_form }
125         }
126         pub(crate) fn into_rust(&self) -> SecpRecoverableSignature {
127                 let mut id = [0; 4];
128                 id.copy_from_slice(&self.serialized_form[64..]);
129                 SecpRecoverableSignature::from_compact(&self.serialized_form[0..64],
130                                 RecoveryId::from_i32(i32::from_le_bytes(id)).expect("Invalid Recovery ID"))
131                         .unwrap()
132         }
133 }
134
135 #[repr(C)]
136 #[derive(Copy, Clone)]
137 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
138 pub enum Secp256k1Error {
139         /// Signature failed verification
140         IncorrectSignature,
141         /// Badly sized message ("messages" are actually fixed-sized digests; see the MESSAGE_SIZE constant)
142         InvalidMessage,
143         /// Bad public key
144         InvalidPublicKey,
145         /// Bad signature
146         InvalidSignature,
147         /// Bad secret key
148         InvalidSecretKey,
149         /// Bad recovery id
150         InvalidRecoveryId,
151         /// Invalid tweak for add_assign or mul_assign
152         InvalidTweak,
153         /// tweak_add_check failed on an xonly public key
154         TweakCheckFailed,
155         /// Didn't pass enough memory to context creation with preallocated memory
156         NotEnoughMemory,
157 }
158 impl Secp256k1Error {
159         pub(crate) fn from_rust(err: SecpError) -> Self {
160                 match err {
161                         SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
162                         SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
163                         SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
164                         SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
165                         SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
166                         SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
167                         SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
168                         SecpError::TweakCheckFailed => Secp256k1Error::TweakCheckFailed,
169                         SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
170                 }
171         }
172         pub(crate) fn into_rust(self) -> SecpError {
173                 match self {
174                         Secp256k1Error::IncorrectSignature => SecpError::IncorrectSignature,
175                         Secp256k1Error::InvalidMessage => SecpError::InvalidMessage,
176                         Secp256k1Error::InvalidPublicKey => SecpError::InvalidPublicKey,
177                         Secp256k1Error::InvalidSignature => SecpError::InvalidSignature,
178                         Secp256k1Error::InvalidSecretKey => SecpError::InvalidSecretKey,
179                         Secp256k1Error::InvalidRecoveryId => SecpError::InvalidRecoveryId,
180                         Secp256k1Error::InvalidTweak => SecpError::InvalidTweak,
181                         Secp256k1Error::TweakCheckFailed => SecpError::TweakCheckFailed,
182                         Secp256k1Error::NotEnoughMemory => SecpError::NotEnoughMemory,
183                 }
184         }
185 }
186
187 #[repr(C)]
188 #[derive(Copy, Clone)]
189 /// Represents an error returned from the bech32 library during validation of some bech32 data
190 pub enum Bech32Error {
191         /// String does not contain the separator character
192         MissingSeparator,
193         /// The checksum does not match the rest of the data
194         InvalidChecksum,
195         /// The data or human-readable part is too long or too short
196         InvalidLength,
197         /// Some part of the string contains an invalid character
198         InvalidChar(u32),
199         /// Some part of the data has an invalid value
200         InvalidData(u8),
201         /// The bit conversion failed due to a padding issue
202         InvalidPadding,
203         /// The whole string must be of one case
204         MixedCase,
205 }
206 impl Bech32Error {
207         pub(crate) fn from_rust(err: bech32::Error) -> Self {
208                 match err {
209                         bech32::Error::MissingSeparator => Self::MissingSeparator,
210                         bech32::Error::InvalidChecksum => Self::InvalidChecksum,
211                         bech32::Error::InvalidLength => Self::InvalidLength,
212                         bech32::Error::InvalidChar(c) => Self::InvalidChar(c as u32),
213                         bech32::Error::InvalidData(d) => Self::InvalidData(d),
214                         bech32::Error::InvalidPadding => Self::InvalidPadding,
215                         bech32::Error::MixedCase => Self::MixedCase,
216                 }
217         }
218         pub(crate) fn into_rust(self) -> bech32::Error {
219                 match self {
220                         Self::MissingSeparator => bech32::Error::MissingSeparator,
221                         Self::InvalidChecksum => bech32::Error::InvalidChecksum,
222                         Self::InvalidLength => bech32::Error::InvalidLength,
223                         Self::InvalidChar(c) => bech32::Error::InvalidChar(core::char::from_u32(c).expect("Invalid UTF-8 character in Bech32Error::InvalidChar")),
224                         Self::InvalidData(d) => bech32::Error::InvalidData(d),
225                         Self::InvalidPadding => bech32::Error::InvalidPadding,
226                         Self::MixedCase => bech32::Error::MixedCase,
227                 }
228         }
229 }
230
231 #[repr(C)]
232 #[derive(Clone, Copy, PartialEq)]
233 /// Sub-errors which don't have specific information in them use this type.
234 pub struct Error {
235         /// Zero-Sized_types aren't consistent across Rust/C/C++, so we add some size here
236         pub _dummy: u8,
237 }
238
239 #[repr(C)]
240 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
241 #[derive(Clone, Copy, PartialEq)]
242 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
243 pub enum IOError {
244         NotFound,
245         PermissionDenied,
246         ConnectionRefused,
247         ConnectionReset,
248         ConnectionAborted,
249         NotConnected,
250         AddrInUse,
251         AddrNotAvailable,
252         BrokenPipe,
253         AlreadyExists,
254         WouldBlock,
255         InvalidInput,
256         InvalidData,
257         TimedOut,
258         WriteZero,
259         Interrupted,
260         Other,
261         UnexpectedEof,
262 }
263 #[cfg(feature = "std")]
264 impl IOError {
265         pub(crate) fn from_rust(err: std::io::Error) -> Self {
266                 match err.kind() {
267                         std::io::ErrorKind::NotFound => IOError::NotFound,
268                         std::io::ErrorKind::PermissionDenied => IOError::PermissionDenied,
269                         std::io::ErrorKind::ConnectionRefused => IOError::ConnectionRefused,
270                         std::io::ErrorKind::ConnectionReset => IOError::ConnectionReset,
271                         std::io::ErrorKind::ConnectionAborted => IOError::ConnectionAborted,
272                         std::io::ErrorKind::NotConnected => IOError::NotConnected,
273                         std::io::ErrorKind::AddrInUse => IOError::AddrInUse,
274                         std::io::ErrorKind::AddrNotAvailable => IOError::AddrNotAvailable,
275                         std::io::ErrorKind::BrokenPipe => IOError::BrokenPipe,
276                         std::io::ErrorKind::AlreadyExists => IOError::AlreadyExists,
277                         std::io::ErrorKind::WouldBlock => IOError::WouldBlock,
278                         std::io::ErrorKind::InvalidInput => IOError::InvalidInput,
279                         std::io::ErrorKind::InvalidData => IOError::InvalidData,
280                         std::io::ErrorKind::TimedOut => IOError::TimedOut,
281                         std::io::ErrorKind::WriteZero => IOError::WriteZero,
282                         std::io::ErrorKind::Interrupted => IOError::Interrupted,
283                         std::io::ErrorKind::Other => IOError::Other,
284                         std::io::ErrorKind::UnexpectedEof => IOError::UnexpectedEof,
285                         _ => IOError::Other,
286                 }
287         }
288         pub(crate) fn to_rust(&self) -> std::io::Error {
289                 std::io::Error::new(match self {
290                         IOError::NotFound => std::io::ErrorKind::NotFound,
291                         IOError::PermissionDenied => std::io::ErrorKind::PermissionDenied,
292                         IOError::ConnectionRefused => std::io::ErrorKind::ConnectionRefused,
293                         IOError::ConnectionReset => std::io::ErrorKind::ConnectionReset,
294                         IOError::ConnectionAborted => std::io::ErrorKind::ConnectionAborted,
295                         IOError::NotConnected => std::io::ErrorKind::NotConnected,
296                         IOError::AddrInUse => std::io::ErrorKind::AddrInUse,
297                         IOError::AddrNotAvailable => std::io::ErrorKind::AddrNotAvailable,
298                         IOError::BrokenPipe => std::io::ErrorKind::BrokenPipe,
299                         IOError::AlreadyExists => std::io::ErrorKind::AlreadyExists,
300                         IOError::WouldBlock => std::io::ErrorKind::WouldBlock,
301                         IOError::InvalidInput => std::io::ErrorKind::InvalidInput,
302                         IOError::InvalidData => std::io::ErrorKind::InvalidData,
303                         IOError::TimedOut => std::io::ErrorKind::TimedOut,
304                         IOError::WriteZero => std::io::ErrorKind::WriteZero,
305                         IOError::Interrupted => std::io::ErrorKind::Interrupted,
306                         IOError::Other => std::io::ErrorKind::Other,
307                         IOError::UnexpectedEof => std::io::ErrorKind::UnexpectedEof,
308                 }, "")
309         }
310 }
311
312 #[repr(C)]
313 /// A serialized transaction, in (pointer, length) form.
314 ///
315 /// This type optionally owns its own memory, and thus the semantics around access change based on
316 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
317 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
318 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
319 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
320 /// you would be invalid.
321 ///
322 /// Note that, while it may change in the future, because transactions on the Rust side are stored
323 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
324 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
325 /// `data_is_owned` either set or unset at your discretion.
326 pub struct Transaction {
327         /// The serialized transaction data.
328         ///
329         /// This is non-const for your convenience, an object passed to Rust is never written to.
330         pub data: *mut u8,
331         /// The length of the serialized transaction
332         pub datalen: usize,
333         /// Whether the data pointed to by `data` should be freed or not.
334         pub data_is_owned: bool,
335 }
336 impl Transaction {
337         fn from_vec(vec: Vec<u8>) -> Self {
338                 let datalen = vec.len();
339                 let data = Box::into_raw(vec.into_boxed_slice());
340                 Self {
341                         data: unsafe { (*data).as_mut_ptr() },
342                         datalen,
343                         data_is_owned: true,
344                 }
345         }
346         pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
347                 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
348                 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
349         }
350         pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
351                 let vec = ::bitcoin::consensus::encode::serialize(btc);
352                 Self::from_vec(vec)
353         }
354 }
355 impl Drop for Transaction {
356         fn drop(&mut self) {
357                 if self.data_is_owned && self.datalen != 0 {
358                         let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
359                 }
360         }
361 }
362 impl Clone for Transaction {
363         fn clone(&self) -> Self {
364                 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
365                 let mut v = Vec::new();
366                 v.extend_from_slice(&sl);
367                 Self::from_vec(v)
368         }
369 }
370 #[no_mangle]
371 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
372 pub extern "C" fn Transaction_free(_res: Transaction) { }
373
374 pub(crate) fn bitcoin_to_C_outpoint(outpoint: ::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
375         crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: outpoint.txid.into_inner() }, outpoint.vout.try_into().unwrap())
376 }
377 pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
378         unsafe {
379                 ::bitcoin::blockdata::transaction::OutPoint {
380                         txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
381                 }
382         }
383 }
384
385 #[repr(C)]
386 #[derive(Clone)]
387 /// A transaction output including a scriptPubKey and value.
388 /// This type *does* own its own memory, so must be free'd appropriately.
389 pub struct TxOut {
390         /// The script_pubkey in this output
391         pub script_pubkey: derived::CVec_u8Z,
392         /// The value, in satoshis, of this output
393         pub value: u64,
394 }
395
396 impl TxOut {
397         pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
398                 ::bitcoin::blockdata::transaction::TxOut {
399                         script_pubkey: self.script_pubkey.into_rust().into(),
400                         value: self.value,
401                 }
402         }
403         pub(crate) fn from_rust(txout: ::bitcoin::blockdata::transaction::TxOut) -> Self {
404                 Self {
405                         script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.into_bytes()),
406                         value: txout.value
407                 }
408         }
409 }
410
411 #[no_mangle]
412 /// Convenience function for constructing a new TxOut
413 pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
414         TxOut { script_pubkey, value }
415 }
416 #[no_mangle]
417 /// Frees the data pointed to by script_pubkey.
418 pub extern "C" fn TxOut_free(_res: TxOut) { }
419 #[no_mangle]
420 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
421 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
422
423 #[repr(C)]
424 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
425 /// own the memory pointed to by data.
426 pub struct u8slice {
427         /// A pointer to the byte buffer
428         pub data: *const u8,
429         /// The number of bytes pointed to by `data`.
430         pub datalen: usize
431 }
432 impl u8slice {
433         pub(crate) fn from_slice(s: &[u8]) -> Self {
434                 Self {
435                         data: s.as_ptr(),
436                         datalen: s.len(),
437                 }
438         }
439         pub(crate) fn to_slice(&self) -> &[u8] {
440                 if self.datalen == 0 { return &[]; }
441                 unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
442         }
443         pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
444                 let sl = self.to_slice();
445                 Cursor::new(sl)
446         }
447         pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
448                 Self::from_slice(v.as_slice())
449         }
450 }
451 pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
452         let mut res = Vec::new();
453         r.read_to_end(&mut res).unwrap();
454         derived::CVec_u8Z::from(res)
455 }
456
457 #[repr(C)]
458 #[derive(Copy, Clone)]
459 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
460 /// look up the corresponding function in rust-lightning's docs.
461 pub struct ThirtyTwoBytes {
462         /// The thirty-two bytes
463         pub data: [u8; 32],
464 }
465 impl ThirtyTwoBytes {
466         pub(crate) fn null() -> Self {
467                 Self { data: [0; 32] }
468         }
469 }
470
471 #[repr(C)]
472 /// A 3-byte byte array.
473 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
474 #[derive(Clone)]
475 #[repr(C)]
476 /// A 4-byte byte array.
477 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
478 #[derive(Clone)]
479 #[repr(C)]
480 /// A 12-byte byte array.
481 pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
482 #[derive(Clone)]
483 #[repr(C)]
484 /// A 16-byte byte array.
485 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
486 #[derive(Clone)]
487 #[repr(C)]
488 /// A 20-byte byte array.
489 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
490
491 pub(crate) struct VecWriter(pub Vec<u8>);
492 impl lightning::util::ser::Writer for VecWriter {
493         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
494                 self.0.extend_from_slice(buf);
495                 Ok(())
496         }
497 }
498 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
499         let mut out = VecWriter(Vec::new());
500         i.write(&mut out).unwrap();
501         derived::CVec_u8Z::from(out.0)
502 }
503 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
504         I::read(&mut s.to_slice())
505 }
506 pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
507         I::read(&mut s.to_slice())
508 }
509 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
510         I::read(&mut s.to_slice(), args)
511 }
512
513 #[repr(C)]
514 /// A Rust str object, ie a reference to a UTF8-valid string.
515 /// This is *not* null-terminated so cannot be used directly as a C string!
516 pub struct Str {
517         /// A pointer to the string's bytes, in UTF8 encoding
518         pub chars: *const u8,
519         /// The number of bytes (not characters!) pointed to by `chars`
520         pub len: usize,
521         /// Whether the data pointed to by `chars` should be freed or not.
522         pub chars_is_owned: bool,
523 }
524 impl Into<Str> for &'static str {
525         fn into(self) -> Str {
526                 Str { chars: self.as_ptr(), len: self.len(), chars_is_owned: false }
527         }
528 }
529 impl Into<Str> for &mut &'static str {
530         fn into(self) -> Str {
531                 let us: &'static str = *self;
532                 us.into()
533         }
534 }
535
536 impl Str {
537         pub(crate) fn into_str(&self) -> &'static str {
538                 if self.len == 0 { return ""; }
539                 core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
540         }
541         pub(crate) fn into_string(mut self) -> String {
542                 let bytes = if self.len == 0 {
543                         Vec::new()
544                 } else if self.chars_is_owned {
545                         let ret = unsafe {
546                                 Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
547                         }.into();
548                         self.chars_is_owned = false;
549                         ret
550                 } else {
551                         let mut ret = Vec::with_capacity(self.len);
552                         ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
553                         ret
554                 };
555                 String::from_utf8(bytes).unwrap()
556         }
557 }
558 impl Into<Str> for String {
559         fn into(self) -> Str {
560                 let s = Box::leak(self.into_boxed_str());
561                 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
562         }
563 }
564 impl Clone for Str {
565         fn clone(&self) -> Self {
566                 self.into_str().clone().into()
567         }
568 }
569
570 impl Drop for Str {
571         fn drop(&mut self) {
572                 if self.chars_is_owned && self.len != 0 {
573                         let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
574                 }
575         }
576 }
577 #[no_mangle]
578 /// Frees the data buffer, if chars_is_owned is set and len > 0.
579 pub extern "C" fn Str_free(_res: Str) { }
580
581 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
582 // Thus, they must gracefully handle being completely null in _free.
583
584 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
585 // everywhere in the containers.
586
587 #[repr(C)]
588 pub(crate) union CResultPtr<O, E> {
589         pub(crate) result: *mut O,
590         pub(crate) err: *mut E,
591 }
592 #[repr(C)]
593 pub(crate) struct CResultTempl<O, E> {
594         pub(crate) contents: CResultPtr<O, E>,
595         pub(crate) result_ok: bool,
596 }
597 impl<O, E> CResultTempl<O, E> {
598         pub(crate) extern "C" fn ok(o: O) -> Self {
599                 CResultTempl {
600                         contents: CResultPtr {
601                                 result: Box::into_raw(Box::new(o)),
602                         },
603                         result_ok: true,
604                 }
605         }
606         pub(crate) extern "C" fn err(e: E) -> Self {
607                 CResultTempl {
608                         contents: CResultPtr {
609                                 err: Box::into_raw(Box::new(e)),
610                         },
611                         result_ok: false,
612                 }
613         }
614 }
615 impl<O, E> Drop for CResultTempl<O, E> {
616         fn drop(&mut self) {
617                 if self.result_ok {
618                         if unsafe { !self.contents.result.is_null() } {
619                                 unsafe { Box::from_raw(self.contents.result) };
620                         }
621                 } else if unsafe { !self.contents.err.is_null() } {
622                         unsafe { Box::from_raw(self.contents.err) };
623                 }
624         }
625 }
626
627 /// Utility to make it easy to set a pointer to null and get its original value in line.
628 pub(crate) trait TakePointer<T> {
629         fn take_ptr(&mut self) -> T;
630 }
631 impl<T> TakePointer<*const T> for *const T {
632         fn take_ptr(&mut self) -> *const T {
633                 let ret = *self;
634                 *self = core::ptr::null();
635                 ret
636         }
637 }
638 impl<T> TakePointer<*mut T> for *mut T {
639         fn take_ptr(&mut self) -> *mut T {
640                 let ret = *self;
641                 *self = core::ptr::null_mut();
642                 ret
643         }
644 }
645
646
647 pub(crate) mod ObjOps {
648         #[cfg(feature = "no-std")]
649         use alloc::boxed::Box;
650
651         #[inline]
652         #[must_use = "returns new dangling pointer"]
653         pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
654                 let ptr = Box::into_raw(Box::new(obj));
655                 nonnull_ptr_to_inner(ptr)
656         }
657         #[inline]
658         pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
659                 if core::mem::size_of::<T>() == 0 {
660                         // We map `None::<T>` as `T { inner: null, .. }` which works great for all
661                         // non-Zero-Sized-Types `T`.
662                         // For ZSTs, we need to differentiate between null implying `None` and null implying
663                         // `Some` with no allocation.
664                         // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
665                         // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
666                         // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
667                         // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
668                         // fine.
669                         // Note that we add 4095 here as at least the Java client assumes that the low bit on
670                         // any heap pointer is 0, which is generally provided by malloc, but which is not true
671                         // for ZSTs "allocated" by `Box::new`.
672                         debug_assert_eq!(ptr as usize, 1);
673                         unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
674                 } else {
675                         // In order to get better test coverage, also increment non-ZST pointers with
676                         // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
677                         #[cfg(test_mod_pointers)]
678                         unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
679                         #[cfg(not(test_mod_pointers))]
680                         unsafe { ptr as *mut T }
681                 }
682         }
683         #[inline]
684         /// Invert nonnull_ptr_to_inner
685         pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
686                 if core::mem::size_of::<T>() == 0 {
687                         unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
688                 } else {
689                         #[cfg(test_mod_pointers)]
690                         unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
691                         #[cfg(not(test_mod_pointers))]
692                         ptr
693                 }
694         }
695 }
696
697 #[cfg(test_mod_pointers)]
698 #[no_mangle]
699 /// This function exists for memory safety testing purposes. It should never be used in production
700 /// code
701 pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
702         if ptr as usize == 1 {
703                 core::ptr::null()
704         } else {
705                 unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
706         }
707 }
708
709 pub(crate) struct SmartPtr<T> {
710         ptr: *mut T,
711 }
712 impl<T> SmartPtr<T> {
713         pub(crate) fn from_obj(o: T) -> Self {
714                 Self { ptr: Box::into_raw(Box::new(o)) }
715         }
716         pub(crate) fn null() -> Self {
717                 Self { ptr: core::ptr::null_mut() }
718         }
719 }
720 impl<T> Drop for SmartPtr<T> {
721         fn drop(&mut self) {
722                 if self.ptr != core::ptr::null_mut() {
723                         unsafe { Box::from_raw(self.ptr); }
724                 }
725         }
726 }
727 impl<T> core::ops::Deref for SmartPtr<T> {
728         type Target = *mut T;
729         fn deref(&self) -> &*mut T {
730                 &self.ptr
731         }
732 }