matrix_sdk_ffi/
utils.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{mem::ManuallyDrop, ops::Deref};
16
17use async_compat::TOKIO1 as RUNTIME;
18use ruma::{MilliSecondsSinceUnixEpoch, UInt};
19use tracing::warn;
20
21#[derive(Debug, Clone)]
22pub struct Timestamp(u64);
23
24impl From<MilliSecondsSinceUnixEpoch> for Timestamp {
25    fn from(date: MilliSecondsSinceUnixEpoch) -> Self {
26        Self(date.0.into())
27    }
28}
29
30uniffi::custom_newtype!(Timestamp, u64);
31
32pub(crate) fn u64_to_uint(u: u64) -> UInt {
33    UInt::new(u).unwrap_or_else(|| {
34        warn!("u64 -> UInt conversion overflowed, falling back to UInt::MAX");
35        UInt::MAX
36    })
37}
38
39/// Tiny wrappers for data types that must be dropped in the context of an async
40/// runtime.
41///
42/// This is useful whenever such a data type may transitively call some
43/// runtime's `block_on` function in their `Drop` impl (since we lack async drop
44/// at the moment), like done in some `deadpool` drop impls.
45pub(crate) struct AsyncRuntimeDropped<T>(ManuallyDrop<T>);
46
47impl<T> AsyncRuntimeDropped<T> {
48    /// Create a new wrapper for this type that will be dropped under an async
49    /// runtime.
50    pub fn new(val: T) -> Self {
51        Self(ManuallyDrop::new(val))
52    }
53}
54
55impl<T> Drop for AsyncRuntimeDropped<T> {
56    fn drop(&mut self) {
57        let _guard = RUNTIME.enter();
58        // SAFETY: self.inner is never used again, which is the only requirement
59        //         for ManuallyDrop::drop to be used safely.
60        unsafe {
61            ManuallyDrop::drop(&mut self.0);
62        }
63    }
64}
65
66// What is an `AsyncRuntimeDropped<T>`, if not a `T` in disguise?
67impl<T> Deref for AsyncRuntimeDropped<T> {
68    type Target = T;
69
70    fn deref(&self) -> &Self::Target {
71        &self.0
72    }
73}
74
75impl<T: Clone> Clone for AsyncRuntimeDropped<T> {
76    fn clone(&self) -> Self {
77        Self(self.0.clone())
78    }
79}