mirror of
https://github.com/denoland/rusty_v8.git
synced 2025-01-11 08:34:01 -05:00
feat: Add v8::icu::get_language_tag()
(#953)
Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com> Co-authored-by: Bert Belder <bertbelder@gmail.com>
This commit is contained in:
parent
40cb4f8ec9
commit
760c48a089
3 changed files with 49 additions and 0 deletions
|
@ -4,6 +4,7 @@
|
|||
#include <iostream>
|
||||
|
||||
#include "support.h"
|
||||
#include "unicode/locid.h"
|
||||
#include "v8-callbacks.h"
|
||||
#include "v8/include/libplatform/libplatform.h"
|
||||
#include "v8/include/v8-fast-api-calls.h"
|
||||
|
@ -3148,3 +3149,24 @@ void v8__CompiledWasmModule__DELETE(v8::CompiledWasmModule* self) {
|
|||
delete self;
|
||||
}
|
||||
} // extern "C"
|
||||
|
||||
// icu
|
||||
|
||||
extern "C" {
|
||||
|
||||
size_t icu_get_default_locale(char* output, size_t output_len) {
|
||||
const icu_71::Locale& default_locale = icu::Locale::getDefault();
|
||||
icu_71::CheckedArrayByteSink sink(output, static_cast<uint32_t>(output_len));
|
||||
UErrorCode status = U_ZERO_ERROR;
|
||||
default_locale.toLanguageTag(sink, status);
|
||||
assert(status == U_ZERO_ERROR);
|
||||
assert(!sink.Overflowed());
|
||||
return sink.NumberOfBytesAppended();
|
||||
}
|
||||
|
||||
void icu_set_default_locale(const char* locale) {
|
||||
UErrorCode status = U_ZERO_ERROR;
|
||||
icu::Locale::setDefault(icu::Locale(locale), status);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
|
20
src/icu.rs
20
src/icu.rs
|
@ -1,4 +1,8 @@
|
|||
use std::{ffi::CString, os::raw::c_char};
|
||||
|
||||
extern "C" {
|
||||
fn icu_get_default_locale(output: *mut c_char, output_len: usize) -> usize;
|
||||
fn icu_set_default_locale(locale: *const c_char);
|
||||
fn udata_setCommonData_71(this: *const u8, error_code: *mut i32);
|
||||
}
|
||||
|
||||
|
@ -47,3 +51,19 @@ pub fn set_common_data_71(data: &'static [u8]) -> Result<(), i32> {
|
|||
Err(error_code)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns BCP47 language tag.
|
||||
pub fn get_language_tag() -> String {
|
||||
let mut output = [0u8; 1024];
|
||||
let len = unsafe {
|
||||
icu_get_default_locale(output.as_mut_ptr() as *mut c_char, output.len())
|
||||
};
|
||||
std::str::from_utf8(&output[..len]).unwrap().to_owned()
|
||||
}
|
||||
|
||||
pub fn set_default_locale(locale: &str) {
|
||||
unsafe {
|
||||
let c_str = CString::new(locale).expect("Invalid locale");
|
||||
icu_set_default_locale(c_str.as_ptr());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6764,6 +6764,13 @@ fn instance_of() {
|
|||
assert!(array.instance_of(&mut scope, array_constructor).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_default_locale() {
|
||||
v8::icu::set_default_locale("nb_NO");
|
||||
let default_locale = v8::icu::get_language_tag();
|
||||
assert_eq!(default_locale, "nb-NO");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weak_handle() {
|
||||
let _setup_guard = setup();
|
||||
|
|
Loading…
Reference in a new issue