libgir/analysis/
try_from_glib.rs1use std::{borrow::Cow, sync::Arc};
2
3use crate::{Env, analysis::conversion_type::ConversionType, config, library};
4
5#[derive(Default, Clone, Debug)]
6pub enum TryFromGlib {
7 #[default]
8 Default,
9 NotImplemented,
10 Option,
11 OptionMandatory,
12 Result {
13 ok_type: Arc<str>,
14 err_type: Arc<str>,
15 },
16 ResultInfallible {
17 ok_type: Arc<str>,
18 },
19}
20
21impl TryFromGlib {
22 fn _new(
23 env: &Env,
24 type_id: library::TypeId,
25 mut config_mandatory: impl Iterator<Item = bool>,
26 mut config_infallible: impl Iterator<Item = bool>,
27 ) -> Self {
28 let conversion_type = ConversionType::of(env, type_id);
29 match conversion_type {
30 ConversionType::Option => {
31 if config_mandatory.next().unwrap_or(false) {
32 TryFromGlib::OptionMandatory
33 } else {
34 TryFromGlib::Option
35 }
36 }
37 ConversionType::Result { ok_type, err_type } => {
38 if config_infallible.next().unwrap_or(false) {
39 TryFromGlib::ResultInfallible {
40 ok_type: Arc::clone(&ok_type),
41 }
42 } else {
43 TryFromGlib::Result {
44 ok_type: Arc::clone(&ok_type),
45 err_type: Arc::clone(&err_type),
46 }
47 }
48 }
49 _ => TryFromGlib::NotImplemented,
50 }
51 }
52
53 pub fn from_type_defaults(env: &Env, type_id: library::TypeId) -> Self {
54 Self::_new(env, type_id, None.into_iter(), None.into_iter())
55 }
56
57 pub fn or_type_defaults(&self, env: &Env, type_id: library::TypeId) -> Cow<'_, Self> {
58 match self {
59 TryFromGlib::Default => Cow::Owned(Self::from_type_defaults(env, type_id)),
60 other => Cow::Borrowed(other),
61 }
62 }
63
64 pub fn from_parameter(
65 env: &Env,
66 type_id: library::TypeId,
67 configured_parameters: &[&config::functions::Parameter],
68 ) -> Self {
69 Self::_new(
70 env,
71 type_id,
72 configured_parameters.iter().filter_map(|par| par.mandatory),
73 configured_parameters
74 .iter()
75 .filter_map(|par| par.infallible),
76 )
77 }
78
79 pub fn from_return_value(
80 env: &Env,
81 type_id: library::TypeId,
82 configured_functions: &[&config::functions::Function],
83 ) -> Self {
84 Self::_new(
85 env,
86 type_id,
87 configured_functions.iter().filter_map(|f| f.ret.mandatory),
88 configured_functions.iter().filter_map(|f| f.ret.infallible),
89 )
90 }
91}