all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Lukas Wagner <l.wagner@proxmox.com>
To: pve-devel@lists.proxmox.com, pbs-devel@lists.proxmox.com
Subject: [pve-devel] [PATCH proxmox v2 3/5] time: posix: add bindings for strftime_l
Date: Mon, 11 Dec 2023 14:29:06 +0100	[thread overview]
Message-ID: <20231211132908.267921-4-l.wagner@proxmox.com> (raw)
In-Reply-To: <20231211132908.267921-1-l.wagner@proxmox.com>

This variant of strftime can be provided with a locale_t, which
determines the locale used for time formatting.

A struct `Locale` was also introduced as a safe wrapper around
locale_t.

Signed-off-by: Lukas Wagner <l.wagner@proxmox.com>
---
 proxmox-time/src/posix.rs | 99 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 99 insertions(+)

diff --git a/proxmox-time/src/posix.rs b/proxmox-time/src/posix.rs
index 5913816..9c8002a 100644
--- a/proxmox-time/src/posix.rs
+++ b/proxmox-time/src/posix.rs
@@ -140,6 +140,93 @@ pub fn strftime(format: &str, t: &libc::tm) -> Result<String, Error> {
     Ok(str_slice.to_owned())
 }
 
+//  The `libc` crate does not yet contain bindings for `strftime_l`
+#[link(name = "c")]
+extern "C" {
+    #[link_name = "strftime_l"]
+    fn libc_strftime_l(
+        s: *mut libc::c_char,
+        max: libc::size_t,
+        format: *const libc::c_char,
+        time: *const libc::tm,
+        locale: libc::locale_t,
+    ) -> libc::size_t;
+}
+
+/// Safe bindings to libc's `strftime_l`
+///
+/// The compared to `strftime`, `strftime_l` allows the caller to provide a
+/// locale object.
+pub fn strftime_l(format: &str, t: &libc::tm, locale: &Locale) -> Result<String, Error> {
+    let format = CString::new(format).map_err(|err| format_err!("{err}"))?;
+    let mut buf = vec![0u8; 8192];
+
+    let res = unsafe {
+        libc_strftime_l(
+            buf.as_mut_ptr() as *mut libc::c_char,
+            buf.len() as libc::size_t,
+            format.as_ptr(),
+            t as *const libc::tm,
+            locale.locale,
+        )
+    };
+    if res == !0 {
+        // -1,, it's unsigned
+        // man strftime: POSIX.1-2001  does  not  specify  any  errno  settings   for strftime()
+        bail!("strftime failed");
+    }
+
+    // `res` is a `libc::size_t`, which on a different target architecture might not be directly
+    // assignable to a `usize`. Thus, we actually want a cast here.
+    #[allow(clippy::unnecessary_cast)]
+    let len = res as usize;
+
+    if len == 0 {
+        bail!("strftime: result len is 0 (string too large)");
+    };
+
+    let c_str = CStr::from_bytes_with_nul(&buf[..len + 1]).map_err(|err| format_err!("{err}"))?;
+    let str_slice: &str = c_str.to_str()?;
+    Ok(str_slice.to_owned())
+}
+
+/// A safe wrapper for `libc::locale_t`.
+///
+/// The enclosed locale object will be automatically freed by `Drop::drop`
+pub struct Locale {
+    locale: libc::locale_t,
+}
+
+impl Locale {
+    /// Portable, minimal locale environment
+    const C: &'static str = "C";
+
+    /// Create a new locale object.
+    /// `category_mask` is expected to be a bitmask based on the
+    /// LC_*_MASK constants from libc. The locale will be set to `locale`
+    /// for every entry in the bitmask which is set.
+    pub fn new(category_mask: i32, locale: &str) -> Result<Self, Error> {
+        let format = CString::new(locale).map_err(|err| format_err!("{err}"))?;
+
+        let locale =
+            unsafe { libc::newlocale(category_mask, format.as_ptr(), std::ptr::null_mut()) };
+
+        if locale.is_null() {
+            return Err(std::io::Error::last_os_error().into());
+        }
+
+        Ok(Self { locale })
+    }
+}
+
+impl Drop for Locale {
+    fn drop(&mut self) {
+        unsafe {
+            libc::freelocale(self.locale);
+        }
+    }
+}
+
 /// Format epoch as local time
 pub fn strftime_local(format: &str, epoch: i64) -> Result<String, Error> {
     let localtime = localtime(epoch)?;
@@ -391,3 +478,15 @@ fn test_timezones() {
     let res = epoch_to_rfc3339_utc(parsed).expect("converting to RFC failed");
     assert_eq!(expected_utc, res);
 }
+
+#[test]
+fn test_strftime_l() {
+    let epoch = 1609263000;
+
+    let locale = Locale::new(libc::LC_ALL, Locale::C).expect("could not create locale");
+    let time = gmtime(epoch).expect("gmtime failed");
+
+    let formatted = strftime_l("%a, %d %b %Y %T %z", &time, &locale).expect("strftime_l failed");
+
+    assert_eq!(formatted, "Tue, 29 Dec 2020 17:30:00 +0000");
+}
-- 
2.39.2





WARNING: multiple messages have this Message-ID
From: Lukas Wagner <l.wagner@proxmox.com>
To: pve-devel@lists.proxmox.com, pbs-devel@lists.proxmox.com
Subject: [pbs-devel] [PATCH proxmox v2 3/5] time: posix: add bindings for strftime_l
Date: Mon, 11 Dec 2023 14:29:06 +0100	[thread overview]
Message-ID: <20231211132908.267921-4-l.wagner@proxmox.com> (raw)
In-Reply-To: <20231211132908.267921-1-l.wagner@proxmox.com>

This variant of strftime can be provided with a locale_t, which
determines the locale used for time formatting.

A struct `Locale` was also introduced as a safe wrapper around
locale_t.

Signed-off-by: Lukas Wagner <l.wagner@proxmox.com>
---
 proxmox-time/src/posix.rs | 99 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 99 insertions(+)

diff --git a/proxmox-time/src/posix.rs b/proxmox-time/src/posix.rs
index 5913816..9c8002a 100644
--- a/proxmox-time/src/posix.rs
+++ b/proxmox-time/src/posix.rs
@@ -140,6 +140,93 @@ pub fn strftime(format: &str, t: &libc::tm) -> Result<String, Error> {
     Ok(str_slice.to_owned())
 }
 
+//  The `libc` crate does not yet contain bindings for `strftime_l`
+#[link(name = "c")]
+extern "C" {
+    #[link_name = "strftime_l"]
+    fn libc_strftime_l(
+        s: *mut libc::c_char,
+        max: libc::size_t,
+        format: *const libc::c_char,
+        time: *const libc::tm,
+        locale: libc::locale_t,
+    ) -> libc::size_t;
+}
+
+/// Safe bindings to libc's `strftime_l`
+///
+/// The compared to `strftime`, `strftime_l` allows the caller to provide a
+/// locale object.
+pub fn strftime_l(format: &str, t: &libc::tm, locale: &Locale) -> Result<String, Error> {
+    let format = CString::new(format).map_err(|err| format_err!("{err}"))?;
+    let mut buf = vec![0u8; 8192];
+
+    let res = unsafe {
+        libc_strftime_l(
+            buf.as_mut_ptr() as *mut libc::c_char,
+            buf.len() as libc::size_t,
+            format.as_ptr(),
+            t as *const libc::tm,
+            locale.locale,
+        )
+    };
+    if res == !0 {
+        // -1,, it's unsigned
+        // man strftime: POSIX.1-2001  does  not  specify  any  errno  settings   for strftime()
+        bail!("strftime failed");
+    }
+
+    // `res` is a `libc::size_t`, which on a different target architecture might not be directly
+    // assignable to a `usize`. Thus, we actually want a cast here.
+    #[allow(clippy::unnecessary_cast)]
+    let len = res as usize;
+
+    if len == 0 {
+        bail!("strftime: result len is 0 (string too large)");
+    };
+
+    let c_str = CStr::from_bytes_with_nul(&buf[..len + 1]).map_err(|err| format_err!("{err}"))?;
+    let str_slice: &str = c_str.to_str()?;
+    Ok(str_slice.to_owned())
+}
+
+/// A safe wrapper for `libc::locale_t`.
+///
+/// The enclosed locale object will be automatically freed by `Drop::drop`
+pub struct Locale {
+    locale: libc::locale_t,
+}
+
+impl Locale {
+    /// Portable, minimal locale environment
+    const C: &'static str = "C";
+
+    /// Create a new locale object.
+    /// `category_mask` is expected to be a bitmask based on the
+    /// LC_*_MASK constants from libc. The locale will be set to `locale`
+    /// for every entry in the bitmask which is set.
+    pub fn new(category_mask: i32, locale: &str) -> Result<Self, Error> {
+        let format = CString::new(locale).map_err(|err| format_err!("{err}"))?;
+
+        let locale =
+            unsafe { libc::newlocale(category_mask, format.as_ptr(), std::ptr::null_mut()) };
+
+        if locale.is_null() {
+            return Err(std::io::Error::last_os_error().into());
+        }
+
+        Ok(Self { locale })
+    }
+}
+
+impl Drop for Locale {
+    fn drop(&mut self) {
+        unsafe {
+            libc::freelocale(self.locale);
+        }
+    }
+}
+
 /// Format epoch as local time
 pub fn strftime_local(format: &str, epoch: i64) -> Result<String, Error> {
     let localtime = localtime(epoch)?;
@@ -391,3 +478,15 @@ fn test_timezones() {
     let res = epoch_to_rfc3339_utc(parsed).expect("converting to RFC failed");
     assert_eq!(expected_utc, res);
 }
+
+#[test]
+fn test_strftime_l() {
+    let epoch = 1609263000;
+
+    let locale = Locale::new(libc::LC_ALL, Locale::C).expect("could not create locale");
+    let time = gmtime(epoch).expect("gmtime failed");
+
+    let formatted = strftime_l("%a, %d %b %Y %T %z", &time, &locale).expect("strftime_l failed");
+
+    assert_eq!(formatted, "Tue, 29 Dec 2020 17:30:00 +0000");
+}
-- 
2.39.2





  parent reply	other threads:[~2023-12-11 13:29 UTC|newest]

Thread overview: 16+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2023-12-11 13:29 [pve-devel] [PATCH proxmox v2 0/5] sys: email: always format 'Date' header with C locale Lukas Wagner
2023-12-11 13:29 ` [pbs-devel] " Lukas Wagner
2023-12-11 13:29 ` [pve-devel] [PATCH proxmox v2 1/5] time: posix: use strftime from the `libc` crate Lukas Wagner
2023-12-11 13:29   ` [pbs-devel] " Lukas Wagner
2023-12-11 13:29 ` [pve-devel] [PATCH proxmox v2 2/5] time: posix: inline vars in string formatting Lukas Wagner
2023-12-11 13:29   ` [pbs-devel] " Lukas Wagner
2023-12-11 13:29 ` Lukas Wagner [this message]
2023-12-11 13:29   ` [pbs-devel] [PATCH proxmox v2 3/5] time: posix: add bindings for strftime_l Lukas Wagner
2023-12-11 13:29 ` [pve-devel] [PATCH proxmox v2 4/5] time: posix: add epoch_to_rfc2822 Lukas Wagner
2023-12-11 13:29   ` [pbs-devel] " Lukas Wagner
2023-12-11 13:29 ` [pve-devel] [PATCH proxmox v2 5/5] sys: email: use `epoch_to_rfc2822` from proxmox_time Lukas Wagner
2023-12-11 13:29   ` [pbs-devel] " Lukas Wagner
2024-01-08 10:42 ` [pve-devel] [PATCH proxmox v2 0/5] sys: email: always format 'Date' header with C locale Lukas Wagner
2024-01-08 10:42   ` [pbs-devel] " Lukas Wagner
2024-01-08 11:13 ` [pve-devel] applied-series: " Wolfgang Bumiller
2024-01-08 11:13   ` [pbs-devel] " Wolfgang Bumiller

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20231211132908.267921-4-l.wagner@proxmox.com \
    --to=l.wagner@proxmox.com \
    --cc=pbs-devel@lists.proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal