1#![cfg_attr(docsrs, feature(doc_cfg))]
75#![allow(
76 unused_imports,
77 clippy::single_component_path_imports,
78 clippy::unnecessary_cast
79)]
80
81mod app_helpers;
82mod spline;
83mod system_monitors;
84#[cfg(feature = "v2_5")]
85pub use spline::BSplineType;
86pub use spline::{
87 ConstGradingBSplineCurve, GradingBSplineCurve, GradingRGBCurve, SharedGradingBSplineCurve,
88 SharedGradingRGBCurve,
89};
90#[cfg(feature = "v2_5")]
91pub use spline::{GradingHueCurve, SharedGradingHueCurve};
92pub use system_monitors::SystemMonitors;
93mod baker;
94pub use app_helpers::{
95 ColorSpaceMenuHelper, ColorSpaceMenuParameters, DisplayViewFromFile, LegacyViewingPipeline,
96 LegacyViewingStage, MixingColorSpaceManager, MixingSlider,
97};
98mod builtin_config_registry;
99mod builtin_transform_registry;
100mod color_space_set;
101mod colorspace;
102mod config;
103#[cfg(feature = "v2_5")]
104mod config_merging;
105#[cfg(feature = "v2_5")]
106pub use config_merging::{ConfigMerger, ConfigMergingParameters, ConstConfigMerger, MergeStrategy};
107mod config_io_proxy;
108mod const_config_item;
109mod const_rules;
110pub mod constants;
111mod context;
112mod enum_text;
113mod file_rules;
114mod format_metadata;
115pub mod grading;
116mod image_desc;
117mod look;
118mod named_transform;
119mod output_writer;
120mod processor;
121mod processor_metadata;
122pub mod transform;
123mod types;
124mod view_transform;
125mod viewing_rules;
126
127pub use baker::Baker;
128pub use builtin_config_registry::BuiltinConfigRegistry;
129pub use builtin_transform_registry::BuiltinTransformRegistry;
130pub use color_space_set::{ColorSpaceSet, ColorSpaceSetRef, ConstColorSpaceSet};
131pub use colorspace::{ColorSpace, ColorSpaceRef, ConstColorSpace};
132pub use config::{Config, ConfigProcessorTarget, ConfigRef, ConstConfig};
133pub use config_io_proxy::{ConfigIOProvider, ConfigIOProxy};
134pub use const_config_item::{ConstLook, ConstNamedTransform, ConstViewTransform};
135pub use const_rules::{ConstFileRules, ConstViewingRules};
136pub use context::{ConstContext, Context};
137pub use enum_text::OcioEnumText;
138pub use file_rules::FileRules;
139pub use format_metadata::{ConstFormatMetadata, FormatMetadata};
140pub use image_desc::{
141 CustomImageLayout, ImageDescChannel, ImageDescProvider, NativeImageDataPointers,
142 NativeImageDesc, NativeImageDescInfo, NativeImageLayout,
143};
144pub use look::Look;
145pub use named_transform::NamedTransform;
146pub use processor::{
147 CPUProcessor, DynamicProperty, GPUProcessor, GpuShaderCreator, GpuShaderDesc,
148 GpuShaderDescView, GpuTexture2D, GpuTexture3D, GpuTextureChannel, GpuTextureDimensions,
149 GpuUniform, GpuUniformCache, GpuUniformCopy, GpuUniformType, GpuUniformValue,
150 PackedConversionLayout, PackedImageLayout, PlanarByteLayout, PlanarBytes, PlanarBytesMut,
151 PlanarF32Layout, Processor, SignedPlanarByteLayout, SignedPlanarBytes, SignedPlanarBytesMut,
152 StaticCPUProcessor, TextureInfo,
153};
154pub use processor::{
155 PersistentPolicyCreator, ShaderCacheIdPolicy, ShaderClonePolicy, ShaderCodeSection,
156 ShaderCreatorOptions, ShaderExtractionHooks, ShaderFinalizeControl, ShaderLifecycle,
157 ShaderSections, ShaderTexture, ShaderTextureAction, ShaderTextureControl, ShaderTexturePolicy,
158 ShaderUniform, ShaderUniformAction, ShaderUniformControl, ShaderUniformGetter,
159 ShaderUniformRegistration,
160};
161pub use processor_metadata::{ConstProcessorMetadata, ProcessorMetadata};
162pub use types::*;
163#[cfg(feature = "v2_6")]
164mod v2_6;
165#[cfg(feature = "v2_6")]
166pub use v2_6::{metadata_id_element, ViewWithAliases};
167pub use view_transform::ViewTransform;
168pub use viewing_rules::ViewingRules;
169
170use std::cell::RefCell;
171use std::ffi::{c_void, CStr, CString};
172use std::ptr::NonNull;
173use std::sync::{Arc, Mutex, OnceLock};
174use thiserror::Error;
175
176pub use ocio_sys;
177
178#[derive(Debug, Error)]
179pub enum OcioError {
185 #[error("OpenColorIO error: {0}")]
186 Ocio(String),
187 #[error("OpenColorIO file not found: {0}")]
190 MissingFile(String),
191 #[error("Validation failed: {0}")]
192 ValidationFailed(String),
193 #[error("invalid input: {0}")]
194 InvalidInput(String),
195 #[error("path contains interior NUL byte")]
196 InteriorNul,
197 #[error("OpenColorIO handle allocation failed")]
198 AllocationFailed,
199}
200
201pub type Result<T> = std::result::Result<T, OcioError>;
203
204type LoggingCallback = dyn Fn(&str) + Send + Sync + 'static;
205type ComputeHashCallback = dyn Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static;
206
207thread_local! {
208 static COMPUTE_HASH_OUTPUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
209 static IN_LOGGING_CALLBACK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
210}
211
212fn check_logging_reentrancy() -> Result<()> {
213 if IN_LOGGING_CALLBACK.with(std::cell::Cell::get) {
214 return Err(OcioError::InvalidInput(
215 "OCIO logging APIs cannot be called from an OCIO logging callback".into(),
216 ));
217 }
218 Ok(())
219}
220
221fn logging_callback_slot() -> &'static Mutex<Option<Arc<LoggingCallback>>> {
222 static SLOT: OnceLock<Mutex<Option<Arc<LoggingCallback>>>> = OnceLock::new();
223 SLOT.get_or_init(|| Mutex::new(None))
224}
225
226fn logging_callback_update_lock() -> &'static Mutex<()> {
227 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
228 LOCK.get_or_init(|| Mutex::new(()))
229}
230
231fn compute_hash_callback_slot() -> &'static Mutex<Option<Arc<ComputeHashCallback>>> {
232 static SLOT: OnceLock<Mutex<Option<Arc<ComputeHashCallback>>>> = OnceLock::new();
233 SLOT.get_or_init(|| Mutex::new(None))
234}
235
236fn compute_hash_callback_update_lock() -> &'static Mutex<()> {
237 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
238 LOCK.get_or_init(|| Mutex::new(()))
239}
240
241unsafe extern "C" fn rust_logging_callback(message: *const i8) {
242 if message.is_null() {
243 return;
244 }
245
246 let callback = logging_callback_slot()
247 .lock()
248 .unwrap_or_else(|poisoned| poisoned.into_inner())
249 .clone();
250 if let Some(callback) = callback {
251 let message = unsafe { CStr::from_ptr(message).to_string_lossy() };
252 IN_LOGGING_CALLBACK.with(|active| {
253 struct Reset<'a>(&'a std::cell::Cell<bool>);
254 impl Drop for Reset<'_> {
255 fn drop(&mut self) {
256 self.0.set(false);
257 }
258 }
259 active.set(true);
260 let _reset = Reset(active);
261 let _ = catch_callback_unwind(std::panic::AssertUnwindSafe(|| callback(&message)));
262 });
263 }
264}
265
266unsafe extern "C" fn rust_compute_hash_callback(
267 input: *const u8,
268 input_len: usize,
269 output: *mut *const u8,
270 output_len: *mut usize,
271) -> bool {
272 if (input.is_null() && input_len != 0) || output.is_null() || output_len.is_null() {
273 return false;
274 }
275 let callback = compute_hash_callback_slot()
276 .lock()
277 .unwrap_or_else(|poisoned| poisoned.into_inner())
278 .clone();
279 let Some(callback) = callback else {
280 return false;
281 };
282 let input = if input_len == 0 {
283 &[]
284 } else {
285 unsafe { std::slice::from_raw_parts(input, input_len) }
286 };
287 let Ok(value) = catch_callback_unwind(std::panic::AssertUnwindSafe(|| callback(input))) else {
288 return false;
289 };
290 COMPUTE_HASH_OUTPUT.with(|slot| {
291 let mut slot = slot.borrow_mut();
292 *slot = value;
293 unsafe {
294 *output = slot.as_ptr();
295 *output_len = slot.len();
296 }
297 });
298 true
299}
300
301pub fn is_stub_build() -> bool {
307 unsafe { ocio_sys::ocio_runtime_is_stub() }
308}
309
310pub unsafe fn current_config() -> Option<Config> {
324 unsafe { try_current_config() }.ok().flatten()
325}
326
327pub unsafe fn try_current_config() -> Result<Option<Config>> {
350 clear_last_error();
351 let handle = unsafe { ocio_sys::ocio_get_isolated_current_config() };
352 ocio_call_status()?;
353 Ok(std::ptr::NonNull::new(handle).map(|handle| Config { handle }))
354}
355
356pub unsafe fn try_current_config_native_copy() -> Result<Option<Config>> {
377 clear_last_error();
378 let handle = unsafe { ocio_sys::ocio_get_current_config() };
379 ocio_call_status()?;
380 Ok(std::ptr::NonNull::new(handle).map(|handle| Config { handle }))
381}
382
383pub unsafe fn try_const_current_config() -> Result<Option<ConstConfig>> {
400 clear_last_error();
401 let handle = unsafe { ocio_sys::ocio_get_isolated_const_current_config() };
402 ocio_call_status()?;
403 Ok(std::ptr::NonNull::new(handle).map(|handle| ConstConfig { handle }))
404}
405
406pub unsafe fn try_const_current_config_shared() -> Result<Option<ConstConfig>> {
415 clear_last_error();
416 let handle = unsafe { ocio_sys::ocio_get_const_current_config() };
417 ocio_call_status()?;
418 Ok(std::ptr::NonNull::new(handle).map(|handle| ConstConfig { handle }))
419}
420
421#[deprecated(since = "0.2.0", note = "compat alias; prefer current_config()")]
422pub unsafe fn get_current_config() -> Option<Config> {
430 unsafe { current_config() }
431}
432
433#[deprecated(
438 since = "0.2.0",
439 note = "discarded OCIO errors; prefer try_set_current_config()"
440)]
441pub fn set_current_config(config: &Config) {
442 let _ = try_set_current_config(config);
443}
444
445pub fn try_set_current_config(config: &Config) -> Result<()> {
450 clear_last_error();
451 unsafe { ocio_sys::ocio_set_isolated_current_config(config.handle.as_ptr(), false) };
452 ocio_call_status()
453}
454
455pub fn try_set_const_current_config(config: &ConstConfig) -> Result<()> {
461 clear_last_error();
462 unsafe { ocio_sys::ocio_set_isolated_current_config(config.handle.as_ptr(), true) };
463 ocio_call_status()
464}
465
466#[deprecated(
472 since = "0.2.0",
473 note = "discarded OCIO errors; prefer try_clear_all_caches()"
474)]
475pub fn clear_all_caches() {
476 let _ = try_clear_all_caches();
477}
478
479pub fn try_clear_all_caches() -> Result<()> {
481 clear_last_error();
482 unsafe { ocio_sys::ocio_clear_all_caches() };
483 ocio_call_status()
484}
485
486pub fn version() -> Option<String> {
488 unsafe { cstr_to_opt_string(ocio_sys::ocio_get_version()) }
489}
490
491pub fn version_hex() -> i32 {
493 unsafe { ocio_sys::ocio_get_version_hex() }
494}
495
496pub fn logging_level() -> crate::LoggingLevel {
500 try_logging_level().unwrap_or(crate::LoggingLevel::Unknown)
501}
502
503pub fn try_logging_level() -> Result<crate::LoggingLevel> {
505 check_logging_reentrancy()?;
506 let l = unsafe { ocio_sys::ocio_get_logging_level() };
507 Ok(match l {
508 0 => crate::LoggingLevel::None,
509 1 => crate::LoggingLevel::Warning,
510 2 => crate::LoggingLevel::Info,
511 3 => crate::LoggingLevel::Debug,
512 _ => crate::LoggingLevel::Unknown,
513 })
514}
515
516#[deprecated(
521 since = "0.2.0",
522 note = "discarded OCIO errors; prefer try_set_logging_level()"
523)]
524pub fn set_logging_level(level: crate::LoggingLevel) {
525 let _ = try_set_logging_level(level);
526}
527
528pub fn try_set_logging_level(level: crate::LoggingLevel) -> Result<()> {
530 check_logging_reentrancy()?;
531 if level as i32 == 4 {
532 return Err(OcioError::InvalidInput(
533 "OpenColorIO does not support trace logging".into(),
534 ));
535 }
536 clear_last_error();
537 unsafe { ocio_sys::ocio_set_logging_level(level as i32) };
538 ocio_call_status()
539}
540
541pub fn try_log_message(level: crate::LoggingLevel, message: impl AsRef<str>) -> Result<()> {
546 check_logging_reentrancy()?;
547 if level as i32 == 4 {
548 return Err(OcioError::InvalidInput(
549 "OpenColorIO does not support trace logging".into(),
550 ));
551 }
552 let message = cstring(message)?;
553 clear_last_error();
554 unsafe { ocio_sys::ocio_log_message(level as i32, message.as_ptr()) };
555 ocio_call_status()
556}
557
558pub fn set_logging_callback(callback: impl Fn(&str) + Send + Sync + 'static) -> Result<()> {
579 check_logging_reentrancy()?;
580 if !is_stub_build() && version_hex() < 0x0205_0200 {
581 return Err(OcioError::InvalidInput(
582 "OCIO before 2.5.2 requires externally synchronized logging callback replacement"
583 .into(),
584 ));
585 }
586 unsafe { set_logging_callback_unchecked(callback) }
589}
590
591pub unsafe fn set_logging_callback_unchecked(
599 callback: impl Fn(&str) + Send + Sync + 'static,
600) -> Result<()> {
601 check_logging_reentrancy()?;
602 let update = logging_callback_update_lock()
603 .lock()
604 .unwrap_or_else(|poisoned| poisoned.into_inner());
605 let callback = Arc::new(callback) as Arc<LoggingCallback>;
606 let previous = {
607 let mut slot = logging_callback_slot()
608 .lock()
609 .unwrap_or_else(|poisoned| poisoned.into_inner());
610 (*slot).replace(callback)
611 };
612
613 clear_last_error();
614 unsafe { ocio_sys::ocio_set_logging_callback(Some(rust_logging_callback)) };
615 let result = ocio_call_status();
616 let discarded = if result.is_err() {
617 let mut slot = logging_callback_slot()
618 .lock()
619 .unwrap_or_else(|poisoned| poisoned.into_inner());
620 std::mem::replace(&mut *slot, previous)
621 } else {
622 previous
623 };
624 drop(update);
625 drop(discarded);
626 result
627}
628
629pub fn reset_logging_callback() -> Result<()> {
636 check_logging_reentrancy()?;
637 if !is_stub_build() && version_hex() < 0x0205_0200 {
638 return Err(OcioError::InvalidInput(
639 "OCIO before 2.5.2 requires externally synchronized logging callback replacement"
640 .into(),
641 ));
642 }
643 unsafe { reset_logging_callback_unchecked() }
646}
647
648pub unsafe fn reset_logging_callback_unchecked() -> Result<()> {
654 check_logging_reentrancy()?;
655 let update = logging_callback_update_lock()
656 .lock()
657 .unwrap_or_else(|poisoned| poisoned.into_inner());
658 clear_last_error();
659 unsafe { ocio_sys::ocio_reset_logging_callback() };
660 ocio_call_status()?;
661 let previous = logging_callback_slot()
662 .lock()
663 .unwrap_or_else(|poisoned| poisoned.into_inner())
664 .take();
665 drop(update);
666 drop(previous);
667 Ok(())
668}
669
670pub unsafe fn set_compute_hash_callback(
695 callback: impl Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,
696) -> Result<()> {
697 let update = compute_hash_callback_update_lock()
698 .lock()
699 .unwrap_or_else(|poisoned| poisoned.into_inner());
700 let callback = Arc::new(callback) as Arc<ComputeHashCallback>;
701 let previous = {
702 let mut slot = compute_hash_callback_slot()
703 .lock()
704 .unwrap_or_else(|poisoned| poisoned.into_inner());
705 (*slot).replace(callback)
706 };
707 clear_last_error();
708 unsafe { ocio_sys::ocio_set_compute_hash_callback(Some(rust_compute_hash_callback)) };
709 let result = ocio_call_status();
710 let discarded = if result.is_err() {
711 let mut slot = compute_hash_callback_slot()
712 .lock()
713 .unwrap_or_else(|poisoned| poisoned.into_inner());
714 std::mem::replace(&mut *slot, previous)
715 } else {
716 previous
717 };
718 drop(update);
719 drop(discarded);
720 result
721}
722
723pub unsafe fn reset_compute_hash_callback() -> Result<()> {
735 let update = compute_hash_callback_update_lock()
736 .lock()
737 .unwrap_or_else(|poisoned| poisoned.into_inner());
738 clear_last_error();
739 unsafe { ocio_sys::ocio_reset_compute_hash_callback() };
740 ocio_call_status()?;
741 let previous = compute_hash_callback_slot()
742 .lock()
743 .unwrap_or_else(|poisoned| poisoned.into_inner())
744 .take();
745 drop(update);
746 drop(previous);
747 Ok(())
748}
749
750pub fn resolve_config_path(original_path: impl AsRef<str>) -> Result<String> {
756 let original_path = cstring(original_path)?;
757 clear_last_error();
758 let resolved =
759 unsafe { cstr_to_opt_string(ocio_sys::ocio_resolve_config_path(original_path.as_ptr())) };
760 ocio_call_status()?;
761 resolved
762 .ok_or_else(|| OcioError::Ocio("OpenColorIO returned a null resolved config path".into()))
763}
764
765pub fn extract_ocioz_archive(
776 archive_path: impl AsRef<str>,
777 destination_dir: impl AsRef<str>,
778) -> Result<()> {
779 let archive_path = cstring(archive_path)?;
780 let destination_dir = cstring(destination_dir)?;
781 clear_last_error();
782 unsafe {
783 ocio_sys::ocio_extract_ocioz_archive(archive_path.as_ptr(), destination_dir.as_ptr());
784 }
785 ocio_call_status()
786}
787
788pub unsafe fn get_env_variable(name: impl AsRef<str>) -> Result<Option<String>> {
795 let name = cstring(name)?;
796 clear_last_error();
797 let value = unsafe { cstr_to_opt_string(ocio_sys::ocio_get_env_variable(name.as_ptr())) };
798 ocio_call_status()?;
799 Ok(value)
800}
801
802pub unsafe fn set_env_variable(name: impl AsRef<str>, value: impl AsRef<str>) -> Result<()> {
809 let name = cstring(name)?;
810 let value = cstring(value)?;
811 clear_last_error();
812 unsafe { ocio_sys::ocio_set_env_variable(name.as_ptr(), value.as_ptr()) };
813 ocio_call_status()
814}
815
816pub unsafe fn unset_env_variable(name: impl AsRef<str>) -> Result<()> {
823 let name = cstring(name)?;
824 clear_last_error();
825 unsafe { ocio_sys::ocio_unset_env_variable(name.as_ptr()) };
826 ocio_call_status()
827}
828
829pub unsafe fn is_env_variable_present(name: impl AsRef<str>) -> Result<bool> {
836 let name = cstring(name)?;
837 clear_last_error();
838 let present = unsafe { ocio_sys::ocio_is_env_variable_present(name.as_ptr()) };
839 ocio_call_status()?;
840 Ok(present)
841}
842
843#[deprecated(
845 since = "0.2.0",
846 note = "discarded OCIO errors; prefer try_set_logging_level()"
847)]
848pub fn set_logging_level_to_override(level: crate::LoggingLevel) {
849 let _ = try_set_logging_level(level);
850}
851
852pub unsafe fn processor_cache_flags() -> crate::ProcessorCacheFlags {
863 unsafe { try_const_current_config() }
864 .ok()
865 .flatten()
866 .and_then(|config| config.processor_cache_flags().ok())
867 .unwrap_or(crate::ProcessorCacheFlags(0))
868}
869
870#[deprecated(
872 since = "0.2.0",
873 note = "discarded OCIO errors; prefer try_set_processor_cache_flags()"
874)]
875pub unsafe fn set_processor_cache_flags(flags: crate::ProcessorCacheFlags) {
883 let _ = unsafe { try_set_processor_cache_flags(flags) };
884}
885
886pub unsafe fn try_set_processor_cache_flags(flags: crate::ProcessorCacheFlags) -> Result<()> {
901 if let Some(current) = unsafe { try_const_current_config()? } {
902 if current.processor_cache_flags()? != flags {
903 let config = current.create_editable_copy()?;
904 config.try_set_processor_cache_flags(flags.0 as i32)?;
905 try_set_current_config(&config)?;
906 }
907 }
908 Ok(())
909}
910
911pub(crate) fn cstring(value: impl AsRef<str>) -> Result<CString> {
912 CString::new(value.as_ref()).map_err(|_| OcioError::InteriorNul)
913}
914
915pub(crate) unsafe fn cstr_to_opt_string(ptr: *const i8) -> Option<String> {
916 if ptr.is_null() {
917 None
918 } else {
919 Some(std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned())
920 }
921}
922
923pub(crate) unsafe fn cstr_from_mut(ptr: *mut c_void) -> Option<String> {
925 cstr_to_opt_string(ptr as *const i8)
926}
927
928pub(crate) fn clear_last_error() {
929 unsafe { ocio_sys::ocio_error_clear_last() };
930}
931
932pub(crate) fn discard_callback_panic(payload: Box<dyn std::any::Any + Send>) {
935 if let Err(second) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(payload))) {
936 std::mem::forget(second);
937 }
938}
939
940pub(crate) fn catch_callback_unwind<F, T>(callback: F) -> std::result::Result<T, ()>
941where
942 F: FnOnce() -> T + std::panic::UnwindSafe,
943{
944 match std::panic::catch_unwind(callback) {
945 Ok(value) => Ok(value),
946 Err(payload) => {
947 discard_callback_panic(payload);
948 Err(())
949 }
950 }
951}
952
953pub(crate) fn last_error_message() -> Option<String> {
954 unsafe { cstr_to_opt_string(ocio_sys::ocio_error_get_last()) }
955}
956
957fn take_last_error() -> Option<(String, bool)> {
963 let message = last_error_message();
964 message.map(|message| {
965 let missing_file = unsafe { ocio_sys::ocio_error_get_last_kind() == 1 };
966 clear_last_error();
967 (message, missing_file)
968 })
969}
970
971fn bridge_error(message: String, missing_file: bool) -> OcioError {
972 if missing_file {
973 OcioError::MissingFile(message)
974 } else {
975 OcioError::Ocio(message)
976 }
977}
978
979pub(crate) fn validation_status() -> Result<()> {
980 match take_last_error() {
981 Some((message, _)) => Err(OcioError::ValidationFailed(message)),
982 None => Ok(()),
983 }
984}
985
986pub(crate) fn ocio_call_status() -> Result<()> {
987 match take_last_error() {
988 Some((message, missing_file)) => Err(bridge_error(message, missing_file)),
989 None => Ok(()),
990 }
991}
992
993pub(crate) fn handle_result(handle: *mut c_void) -> Result<NonNull<c_void>> {
994 match NonNull::new(handle) {
995 Some(handle) => Ok(handle),
996 None => match take_last_error() {
997 Some((message, missing_file)) => Err(bridge_error(message, missing_file)),
998 None => Err(OcioError::AllocationFailed),
999 },
1000 }
1001}
1002
1003#[cfg(test)]
1004mod tests {
1005 #[cfg(ocio_stub)]
1006 static CALLBACK_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1007
1008 #[test]
1009 fn hash_callback_accepts_null_empty_input() {
1010 #[cfg(ocio_stub)]
1011 let _test_guard = CALLBACK_TEST_LOCK.lock().unwrap();
1012 let _guard = super::compute_hash_callback_update_lock().lock().unwrap();
1013 let previous =
1014 super::compute_hash_callback_slot()
1015 .lock()
1016 .unwrap()
1017 .replace(std::sync::Arc::new(|input| {
1018 assert!(input.is_empty());
1019 b"hash".to_vec()
1020 }));
1021 let mut output = std::ptr::null();
1022 let mut output_len = 0;
1023 assert!(!unsafe {
1024 super::rust_compute_hash_callback(std::ptr::null(), 1, &mut output, &mut output_len)
1025 });
1026 let succeeded = unsafe {
1027 super::rust_compute_hash_callback(std::ptr::null(), 0, &mut output, &mut output_len)
1028 };
1029 assert!(succeeded);
1030 assert_eq!(
1031 unsafe { std::slice::from_raw_parts(output, output_len) },
1032 b"hash"
1033 );
1034 *super::compute_hash_callback_slot().lock().unwrap() = previous;
1035 }
1036
1037 #[test]
1038 #[cfg(ocio_stub)]
1039 fn callback_captures_are_dropped_without_internal_locks() {
1040 use std::sync::atomic::{AtomicBool, Ordering};
1041 use std::sync::Arc;
1042
1043 struct Probe {
1044 update: &'static std::sync::Mutex<()>,
1045 slot_unlocked: fn() -> bool,
1046 ok: Arc<AtomicBool>,
1047 }
1048 impl Drop for Probe {
1049 fn drop(&mut self) {
1050 self.ok.store(
1051 self.update.try_lock().is_ok() && (self.slot_unlocked)(),
1052 Ordering::SeqCst,
1053 );
1054 }
1055 }
1056 let _test_guard = CALLBACK_TEST_LOCK.lock().unwrap();
1057 for reset in [false, true] {
1058 let ok = Arc::new(AtomicBool::new(false));
1059 let probe = Probe {
1060 update: super::logging_callback_update_lock(),
1061 slot_unlocked: || super::logging_callback_slot().try_lock().is_ok(),
1062 ok: Arc::clone(&ok),
1063 };
1064 super::set_logging_callback(move |_| {
1065 let _ = &probe;
1066 })
1067 .unwrap();
1068 if reset {
1069 super::reset_logging_callback().unwrap();
1070 } else {
1071 super::set_logging_callback(|_| {}).unwrap();
1072 super::reset_logging_callback().unwrap();
1073 }
1074 assert!(ok.load(Ordering::SeqCst));
1075
1076 let ok = Arc::new(AtomicBool::new(false));
1077 let probe = Probe {
1078 update: super::compute_hash_callback_update_lock(),
1079 slot_unlocked: || super::compute_hash_callback_slot().try_lock().is_ok(),
1080 ok: Arc::clone(&ok),
1081 };
1082 unsafe {
1085 super::set_compute_hash_callback(move |_| {
1086 let _ = &probe;
1087 Vec::new()
1088 })
1089 }
1090 .unwrap();
1091 if reset {
1092 unsafe { super::reset_compute_hash_callback() }.unwrap();
1093 } else {
1094 unsafe { super::set_compute_hash_callback(|_| Vec::new()) }.unwrap();
1095 unsafe { super::reset_compute_hash_callback() }.unwrap();
1096 }
1097 assert!(ok.load(Ordering::SeqCst));
1098 }
1099 }
1100
1101 #[test]
1102 #[allow(deprecated)]
1103 fn unsupported_trace_logging_is_rejected_before_native_call() {
1104 assert!(matches!(
1105 super::try_set_logging_level(super::LoggingLevel::Trace),
1106 Err(super::OcioError::InvalidInput(_))
1107 ));
1108 assert!(matches!(
1109 super::try_log_message(super::LoggingLevel::Trace, "message"),
1110 Err(super::OcioError::InvalidInput(_))
1111 ));
1112 }
1113
1114 use super::*;
1115
1116 #[test]
1117 fn processor_cache_flags_no_crash() {
1118 let f = unsafe { processor_cache_flags() };
1120 assert!(unsafe { try_set_processor_cache_flags(f) }.is_ok());
1121 }
1122
1123 #[test]
1124 fn current_config_no_crash() {
1125 let _ = unsafe { current_config() };
1126 }
1127
1128 #[test]
1129 fn try_current_config_no_crash() {
1130 let _ = unsafe { try_current_config() };
1131 }
1132
1133 #[cfg(feature = "bundled")]
1134 #[test]
1135 fn bridge_errors_are_consumed_after_handle_conversion() {
1136 let path = cstring("this-file-does-not-exist.ocio").expect("valid test path");
1137 clear_last_error();
1138 let handle = unsafe { ocio_sys::ocio_config_create_from_file(path.as_ptr().cast()) };
1139
1140 let error = handle_result(handle).expect_err("missing config");
1141 if version_hex() >= 0x02060000 {
1142 assert!(matches!(error, OcioError::MissingFile(_)));
1143 } else {
1144 assert!(matches!(
1145 error,
1146 OcioError::Ocio(_) | OcioError::MissingFile(_)
1147 ));
1148 }
1149 assert!(last_error_message().is_none());
1150 assert_eq!(unsafe { ocio_sys::ocio_error_get_last_kind() }, 0);
1151 }
1152
1153 #[cfg(feature = "bundled")]
1154 #[test]
1155 fn bridge_errors_are_consumed_after_validation() {
1156 let transform = crate::transform::FileTransform::create().expect("file transform create");
1157
1158 assert!(matches!(
1159 transform.validate(),
1160 Err(OcioError::ValidationFailed(_))
1161 ));
1162 assert!(last_error_message().is_none());
1163 }
1164
1165 #[test]
1166 #[allow(deprecated)]
1167 fn current_config_compat_alias_no_crash() {
1168 let _ = unsafe { get_current_config() };
1169 }
1170}