opencv_binding_generator/writer/rust_native/
constant.rs

1use std::borrow::Cow;
2use std::collections::HashMap;
3
4use clang::EntityKind;
5use once_cell::sync::Lazy;
6
7use super::element::{DefaultRustNativeElement, RustElement};
8use super::RustNativeGeneratedElement;
9use crate::constant::ValueKind;
10use crate::debug::NameDebug;
11use crate::type_ref::{FishStyle, NameStyle};
12use crate::{settings, CompiledInterpolation, Const, EntityElement, StrExt};
13
14impl RustElement for Const<'_> {
15	fn rust_module(&self) -> Cow<str> {
16		DefaultRustNativeElement::rust_module(self.entity())
17	}
18
19	fn rust_name(&self, style: NameStyle) -> Cow<str> {
20		let mut out = DefaultRustNativeElement::rust_name(self, self.entity(), style);
21		if let Some(without_suffix) = out.strip_suffix("_OCVRS_OVERRIDE") {
22			let new_len = without_suffix.len();
23			out.truncate(new_len);
24		}
25		out.into()
26	}
27
28	fn rendered_doc_comment(&self, comment_marker: &str, opencv_version: &str) -> String {
29		DefaultRustNativeElement::rendered_doc_comment(self.entity(), comment_marker, opencv_version)
30	}
31}
32
33impl RustNativeGeneratedElement for Const<'_> {
34	fn element_safe_id(&self) -> String {
35		format!("{}-{}", self.rust_module(), self.rust_name(NameStyle::decl()))
36	}
37
38	fn gen_rust(&self, opencv_version: &str) -> String {
39		static RUST_TPL: Lazy<CompiledInterpolation> = Lazy::new(|| include_str!("tpl/const/rust.tpl.rs").compile_interpolation());
40
41		let parent_is_class = self
42			.entity()
43			.get_lexical_parent()
44			.is_some_and(|p| matches!(p.get_kind(), EntityKind::ClassDecl | EntityKind::StructDecl));
45		let name = if parent_is_class {
46			self.rust_leafname(FishStyle::No)
47		} else {
48			self.rust_name(NameStyle::decl())
49		};
50
51		if let Some(value) = self.value() {
52			let typ = match settings::CONST_TYPE_OVERRIDE.get(name.as_ref()).unwrap_or(&value.kind) {
53				ValueKind::Integer => "i32",
54				ValueKind::UnsignedInteger => "u32",
55				ValueKind::Usize => "usize",
56				ValueKind::Float => "f32",
57				ValueKind::Double => "f64",
58				ValueKind::String => "&str",
59			};
60			RUST_TPL.interpolate(&HashMap::from([
61				("doc_comment", Cow::Owned(self.rendered_doc_comment("///", opencv_version))),
62				("debug", self.get_debug().into()),
63				("name", name),
64				("type", typ.into()),
65				("value", value.to_string().into()),
66			]))
67		} else {
68			"".to_string()
69		}
70	}
71}