Platform agnostic way of getting the user's language tag

For the Tp-Note application I am searching a way to get the user's BCP47 language tag.
Under Unix one could evaluate the LANG environment variable or the result of the locale command.
How about MacOS and Windows? There are crates like language-tags or oxilangtag allowing to validate and normalize language tags. But how to get the user's language tag in a platform agnostic way?

I think macOS should use the same environment variables as Unix.

On Windows, you need to call the GetUserDefaultLocaleName API. With windows-sys:

let mut buf = [0u16; 85];
let len = unsafe { GetUserDefaultLocaleName(buf.as_mut_ptr(), buf.len() as i32) };
assert_ne!(len, 0);
println!("locale: {}", String::from_utf16_lossy(&buf[..((len-1) as usize)]));

which prints locale: en-NZ on my Windows laptop.

Thank you. I will try this.

For other readers of this thread:

Windows recommends replacing

let mut buf = [0u16; 85];

with the constant.

let mut buf = [0u16; LOCALE_NAME_MAX_LENGTH as usize];
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.