iana_time_zone_haiku/lib.rs
1#![warn(clippy::all)]
2#![warn(clippy::cargo)]
3#![warn(clippy::undocumented_unsafe_blocks)]
4#![allow(unknown_lints)]
5#![warn(missing_copy_implementations)]
6#![warn(missing_debug_implementations)]
7#![warn(missing_docs)]
8#![warn(rust_2018_idioms)]
9#![warn(trivial_casts, trivial_numeric_casts)]
10#![warn(unsafe_op_in_unsafe_fn)]
11#![warn(unused_qualifications)]
12#![warn(variant_size_differences)]
13
14//! # iana-time-zone-haiku
15//!
16//! [](https://crates.io/crates/iana-time-zone-haiku)
17//! [](https://docs.rs/iana-time-zone/)
18//! [](https://crates.io/crates/iana-time-zone-haiku)
19//! [](https://github.com/strawlab/iana-time-zone/actions?query=branch%3Amain)
20//!
21//! [iana-time-zone](https://github.com/strawlab/iana-time-zone) support crate for Haiku OS.
22
23use std::os::raw::c_char;
24
25extern "C" {
26 fn iana_time_zone_haiku_get_tz(buf: *mut c_char, buf_size: usize) -> usize;
27}
28
29/// Get the current IANA time zone as a string.
30///
31/// On Haiku platforms this function will return [`Some`] with the timezone string
32/// or [`None`] if an error occurs. On all other platforms, [`None`] is returned.
33///
34/// # Examples
35///
36/// ```
37/// let timezone = iana_time_zone_haiku::get_timezone();
38/// ```
39#[must_use]
40pub fn get_timezone() -> Option<String> {
41 // The longest name in the IANA time zone database is 25 ASCII characters long.
42 let mut buf = [0u8; 32];
43 // SAFETY: a valid, aligned, non-NULL pointer and length are given which
44 // point to a single allocation.
45 let len = unsafe {
46 let buf_size = buf.len();
47 let buf_ptr = buf.as_mut_ptr().cast::<c_char>();
48 iana_time_zone_haiku_get_tz(buf_ptr, buf_size)
49 };
50 // The name should not be empty, or excessively long.
51 match buf.get(..len)? {
52 b"" => None,
53 s => Some(std::str::from_utf8(s).ok()?.to_owned()),
54 }
55}
56
57#[cfg(test)]
58mod tests {
59 #[test]
60 #[cfg(not(target_os = "haiku"))]
61 fn test_fallback_on_non_haiku_platforms() {
62 assert!(super::get_timezone().is_none());
63 }
64
65 #[test]
66 #[cfg(target_os = "haiku")]
67 fn test_retrieve_time_zone_on_haiku_platforms() {
68 let timezone = super::get_timezone().unwrap();
69 assert!(!timezone.is_empty());
70 }
71}