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
//! # Unstable encoding traits.
//!
//! The traits in this module are unstable, meaning that they are **outside
//! the usual SemVer guarantee**, and may freely change or be removed in patch
//! versions.
//!
//! They are provided here mostly for documentation purposes (e.g. you can
//! check [`EncodeReturn`] to see which types are possible as the return value
//! of a function pointer).
//!
//! If you would like to use some of these, please [open an issue], then we
//! can discuss making them stable.
//!
//! [open an issue]: https://github.com/madsmtm/objc2/issues/new
#![cfg_attr(
    feature = "unstable-docsrs",
    doc(cfg(feature = "unstable-encode-internals"))
)]

use crate::encode::{Encode, Encoding};
use crate::rc::Id;
use crate::runtime::Bool;
use crate::Message;

mod return_private {
    pub trait Sealed {}
}

/// Types that are safe as the return value from Objective-C.
///
/// We currently don't need a similar `EncodeArgument` trait, but we might in
/// the future.
//
// Note: While this is not public, it is still a breaking change to change,
// since `block2` relies on it.
pub trait EncodeReturn: return_private::Sealed {
    /// The Objective-C type-encoding for this type.
    const ENCODING_RETURN: Encoding;
}

impl return_private::Sealed for () {}
impl EncodeReturn for () {
    const ENCODING_RETURN: Encoding = Encoding::Void;
}

impl<T: Encode> return_private::Sealed for T {}
impl<T: Encode> EncodeReturn for T {
    const ENCODING_RETURN: Encoding = T::ENCODING;
}

mod convert_private {
    pub trait Sealed {}
}

impl<T: EncodeReturn> convert_private::Sealed for T {}
impl convert_private::Sealed for bool {}

// Implemented in rc/writeback.rs
impl<T: Message> convert_private::Sealed for &mut Id<T> {}
impl<T: Message> convert_private::Sealed for Option<&mut Id<T>> {}
impl<T: Message> convert_private::Sealed for &mut Option<Id<T>> {}
impl<T: Message> convert_private::Sealed for Option<&mut Option<Id<T>>> {}

/// Represents types that can be converted to/from an [`Encode`] type.
///
/// This is implemented specially for [`bool`] to allow using that as
/// Objective-C `BOOL`, where it would otherwise not be allowed (since they
/// are not ABI compatible).
///
/// This is also done specially for `&mut Id<_>`-like arguments, to allow
/// using those as "out" parameters.
pub trait EncodeConvertArgument: convert_private::Sealed {
    /// The inner type that this can be converted to and from.
    #[doc(hidden)]
    type __Inner: Encode;

    /// A helper type for out parameters.
    #[doc(hidden)]
    type __StoredBeforeMessage: Sized;

    #[doc(hidden)]
    fn __from_declared_param(inner: Self::__Inner) -> Self;

    #[doc(hidden)]
    fn __into_argument(self) -> (Self::__Inner, Self::__StoredBeforeMessage);

    #[doc(hidden)]
    unsafe fn __process_after_message_send(_stored: Self::__StoredBeforeMessage) {}
}

/// Same as [`EncodeConvertArgument`], but for return types.
pub trait EncodeConvertReturn: convert_private::Sealed {
    /// The inner type that this can be converted to and from.
    #[doc(hidden)]
    type __Inner: EncodeReturn;

    #[doc(hidden)]
    fn __into_declared_return(self) -> Self::__Inner;

    #[doc(hidden)]
    fn __from_return(inner: Self::__Inner) -> Self;
}

impl<T: Encode> EncodeConvertArgument for T {
    type __Inner = Self;

    type __StoredBeforeMessage = ();

    #[inline]
    fn __from_declared_param(inner: Self::__Inner) -> Self {
        inner
    }

    #[inline]
    fn __into_argument(self) -> (Self::__Inner, Self::__StoredBeforeMessage) {
        (self, ())
    }
}

impl<T: EncodeReturn> EncodeConvertReturn for T {
    type __Inner = Self;

    #[inline]
    fn __into_declared_return(self) -> Self::__Inner {
        self
    }

    #[inline]
    fn __from_return(inner: Self::__Inner) -> Self {
        inner
    }
}

impl EncodeConvertArgument for bool {
    type __Inner = Bool;

    type __StoredBeforeMessage = ();

    #[inline]
    fn __from_declared_param(inner: Self::__Inner) -> Self {
        inner.as_bool()
    }

    #[inline]
    fn __into_argument(self) -> (Self::__Inner, Self::__StoredBeforeMessage) {
        (Bool::new(self), ())
    }
}

impl EncodeConvertReturn for bool {
    type __Inner = Bool;

    #[inline]
    fn __into_declared_return(self) -> Self::__Inner {
        Bool::new(self)
    }

    #[inline]
    fn __from_return(inner: Self::__Inner) -> Self {
        inner.as_bool()
    }
}

mod args_private {
    pub trait Sealed {}
}

/// Types that represent an ordered group of function arguments, where each
/// argument has an Objective-C type-encoding, or can be converted from one.
///
/// This is implemented for tuples of up to 16 arguments, where each argument
/// implements [`EncodeConvertArgument`]. It is primarily used to make generic
/// code a bit easier.
///
/// Note that tuples themselves don't implement [`Encode`] directly, because
/// they're not FFI-safe!
pub trait EncodeArguments: args_private::Sealed {
    /// The encodings for the arguments.
    const ENCODINGS: &'static [Encoding];
}

macro_rules! encode_args_impl {
    ($($Arg: ident),*) => {
        impl<$($Arg: EncodeConvertArgument),*> args_private::Sealed for ($($Arg,)*) {}

        impl<$($Arg: EncodeConvertArgument),*> EncodeArguments for ($($Arg,)*) {
            const ENCODINGS: &'static [Encoding] = &[
                // T::__Inner::ENCODING => T::ENCODING
                // bool::__Inner::ENCODING => Bool::ENCODING
                $($Arg::__Inner::ENCODING),*
            ];
        }
    };
}

encode_args_impl!();
encode_args_impl!(A);
encode_args_impl!(A, B);
encode_args_impl!(A, B, C);
encode_args_impl!(A, B, C, D);
encode_args_impl!(A, B, C, D, E);
encode_args_impl!(A, B, C, D, E, F);
encode_args_impl!(A, B, C, D, E, F, G);
encode_args_impl!(A, B, C, D, E, F, G, H);
encode_args_impl!(A, B, C, D, E, F, G, H, I);
encode_args_impl!(A, B, C, D, E, F, G, H, I, J);
encode_args_impl!(A, B, C, D, E, F, G, H, I, J, K);
encode_args_impl!(A, B, C, D, E, F, G, H, I, J, K, L);
encode_args_impl!(A, B, C, D, E, F, G, H, I, J, K, L, M);
encode_args_impl!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
encode_args_impl!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
encode_args_impl!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);

#[cfg(test)]
mod tests {
    use super::*;

    use core::any::TypeId;

    #[test]
    fn test_return() {
        assert_eq!(<i32>::ENCODING_RETURN, <i32>::ENCODING);
        assert_eq!(<()>::ENCODING_RETURN, Encoding::Void);
    }

    #[test]
    fn convert_normally_noop() {
        assert_eq!(
            TypeId::of::<<i32 as EncodeConvertArgument>::__Inner>(),
            TypeId::of::<i32>()
        );
        assert_eq!(
            <i32 as EncodeConvertArgument>::__from_declared_param(42),
            42
        );
        assert_eq!(EncodeConvertArgument::__into_argument(42i32).0, 42);
    }

    #[test]
    fn convert_i8() {
        assert_eq!(
            TypeId::of::<<i8 as EncodeConvertArgument>::__Inner>(),
            TypeId::of::<i8>()
        );
        assert_eq!(<i8 as EncodeConvertArgument>::__from_declared_param(-3), -3);
        assert_eq!(EncodeConvertArgument::__into_argument(-3i32).0, -3);
    }

    #[test]
    fn convert_bool() {
        assert!(!<bool as EncodeConvertArgument>::__from_declared_param(
            Bool::NO
        ));
        assert!(<bool as EncodeConvertArgument>::__from_declared_param(
            Bool::YES
        ));
        assert!(!<bool as EncodeConvertReturn>::__from_return(Bool::NO));
        assert!(<bool as EncodeConvertReturn>::__from_return(Bool::YES));

        assert!(!EncodeConvertArgument::__into_argument(false).0.as_bool());
        assert!(EncodeConvertArgument::__into_argument(true).0.as_bool());
        assert!(!EncodeConvertReturn::__into_declared_return(false).as_bool());
        assert!(EncodeConvertReturn::__into_declared_return(true).as_bool());

        #[cfg(all(feature = "apple", target_os = "macos", target_arch = "x86_64"))]
        assert_eq!(
            <bool as EncodeConvertArgument>::__Inner::ENCODING,
            Encoding::Char
        );
    }

    #[test]
    fn test_encode_arguments() {
        assert!(<()>::ENCODINGS.is_empty());
        assert_eq!(<(i8,)>::ENCODINGS, &[i8::ENCODING]);
        assert_eq!(<(i8, u32)>::ENCODINGS, &[i8::ENCODING, u32::ENCODING]);
    }
}