kabosu 0.7.0.1 → 0.7.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,204 @@
1
+ use magnus::typed_data::Obj;
2
+ use magnus::value::ReprValue;
3
+ use magnus::{gc, DataTypeFunctions, Error, RArray, Ruby, TypedData};
4
+ use std::mem::size_of;
5
+ use sudachi::analysis::mlist::MorphemeList;
6
+ use sudachi::analysis::node::ResultNode;
7
+
8
+ use crate::dictionary::{Dict, PosTable};
9
+ use crate::grouping::group_ranges;
10
+ use crate::morpheme::RbMorpheme;
11
+ use crate::nogvl::report_native_memory;
12
+
13
+ /// sudachi.rs's own result type: the analyzed text plus one node per morpheme.
14
+ pub(crate) type Analysis = MorphemeList<Dict>;
15
+
16
+ /// One analysis result (a tokenized text, a lookup, a split), kept exactly as
17
+ /// sudachi.rs produced it. Morphemes are `(list, index)` handles into it, so
18
+ /// nothing is copied per morpheme and a field costs nothing until it is asked
19
+ /// for. SudachiPy has the same shape.
20
+ #[derive(TypedData)]
21
+ #[magnus(class = "Kabosu::NativeMorphemeList", mark, size, free_immediately)]
22
+ pub(crate) struct RbMorphemeList {
23
+ list: Analysis,
24
+ pos_table: PosTable,
25
+ /// The lattice path cost, for lists that are a tokenization result.
26
+ path_cost: Option<i32>,
27
+ /// False for a list split from another one: the input buffer belongs to,
28
+ /// and is counted by, the list it was split from.
29
+ owns_input: bool,
30
+ reported_bytes: isize,
31
+ }
32
+
33
+ // SAFETY: `MorphemeList` shares its input buffer through an `Rc`, which is not
34
+ // thread-safe on its own. Every access to this struct, including its drop
35
+ // during GC sweeping, happens while holding the GVL, so the `Rc` is never
36
+ // touched by two threads at once. It must never be handed to code that runs
37
+ // with the GVL released.
38
+ unsafe impl Send for RbMorphemeList {}
39
+
40
+ impl DataTypeFunctions for RbMorphemeList {
41
+ fn mark(&self, marker: &gc::Marker) {
42
+ self.pos_table.mark(marker);
43
+ }
44
+
45
+ fn size(&self) -> usize {
46
+ size_of::<Self>() + self.native_bytes()
47
+ }
48
+ }
49
+
50
+ impl Drop for RbMorphemeList {
51
+ fn drop(&mut self) {
52
+ report_native_memory(-self.reported_bytes);
53
+ }
54
+ }
55
+
56
+ #[derive(Clone, Copy)]
57
+ enum Form {
58
+ Reading,
59
+ Dictionary,
60
+ Normalized,
61
+ }
62
+
63
+ /// Bytes an `InputBuffer` holds per byte of text: the original and normalized
64
+ /// copies plus their byte and character index tables.
65
+ const INPUT_BYTES_PER_TEXT_BYTE: usize = 40;
66
+
67
+ impl RbMorphemeList {
68
+ /// Wraps an analysis that owns its input (a tokenization or a lookup).
69
+ pub(crate) fn new(list: Analysis, pos_table: PosTable, path_cost: Option<i32>) -> Self {
70
+ Self::reported(list, pos_table, path_cost, true)
71
+ }
72
+
73
+ /// Wraps a list that shares its input with the list it was split from.
74
+ pub(crate) fn sharing_input(list: Analysis, pos_table: PosTable) -> Self {
75
+ Self::reported(list, pos_table, None, false)
76
+ }
77
+
78
+ fn reported(
79
+ list: Analysis,
80
+ pos_table: PosTable,
81
+ path_cost: Option<i32>,
82
+ owns_input: bool,
83
+ ) -> Self {
84
+ let mut this = Self {
85
+ list,
86
+ pos_table,
87
+ path_cost,
88
+ owns_input,
89
+ reported_bytes: 0,
90
+ };
91
+ this.reported_bytes = this.native_bytes() as isize;
92
+ report_native_memory(this.reported_bytes);
93
+ this
94
+ }
95
+
96
+ fn native_bytes(&self) -> usize {
97
+ let nodes = self.list.len() * size_of::<ResultNode>();
98
+ if self.owns_input {
99
+ nodes + self.list.surface().len() * INPUT_BYTES_PER_TEXT_BYTE
100
+ } else {
101
+ nodes
102
+ }
103
+ }
104
+
105
+ pub(crate) fn analysis(&self) -> &Analysis {
106
+ &self.list
107
+ }
108
+
109
+ pub(crate) fn pos_table(&self) -> PosTable {
110
+ self.pos_table
111
+ }
112
+
113
+ pub(crate) fn size(&self) -> usize {
114
+ self.list.len()
115
+ }
116
+
117
+ pub(crate) fn internal_cost(&self) -> Option<i32> {
118
+ self.path_cost
119
+ }
120
+
121
+ pub(crate) fn morpheme_at(rb_self: Obj<Self>, index: usize) -> Option<RbMorpheme> {
122
+ (index < rb_self.list.len()).then(|| RbMorpheme::listed(rb_self, index))
123
+ }
124
+
125
+ /// Every morpheme at once: one call instead of one per index when a list
126
+ /// is iterated.
127
+ pub(crate) fn morphemes(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RArray, Error> {
128
+ let morphemes = ruby.ary_new_capa(rb_self.list.len());
129
+ for index in 0..rb_self.list.len() {
130
+ morphemes.push(RbMorpheme::listed(rb_self, index))?;
131
+ }
132
+ Ok(morphemes)
133
+ }
134
+
135
+ // The bulk readers: one value per morpheme, straight from the analysis,
136
+ // without making a Morpheme object for any of them. Strings are frozen,
137
+ // like the ones a Morpheme returns.
138
+
139
+ fn forms(&self, ruby: &Ruby, form: Form) -> Result<RArray, Error> {
140
+ let forms = ruby.ary_new_capa(self.list.len());
141
+ for morpheme in self.list.iter() {
142
+ let string = ruby.str_new(match form {
143
+ Form::Reading => morpheme.reading_form(),
144
+ Form::Dictionary => morpheme.dictionary_form(),
145
+ Form::Normalized => morpheme.normalized_form(),
146
+ });
147
+ string.freeze();
148
+ forms.push(string)?;
149
+ }
150
+ Ok(forms)
151
+ }
152
+
153
+ pub(crate) fn surfaces(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
154
+ let surfaces = ruby.ary_new_capa(rb_self.list.len());
155
+ for morpheme in rb_self.list.iter() {
156
+ let surface = ruby.str_new(&morpheme.surface());
157
+ surface.freeze();
158
+ surfaces.push(surface)?;
159
+ }
160
+ Ok(surfaces)
161
+ }
162
+
163
+ pub(crate) fn reading_forms(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
164
+ rb_self.forms(ruby, Form::Reading)
165
+ }
166
+
167
+ pub(crate) fn dictionary_forms(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
168
+ rb_self.forms(ruby, Form::Dictionary)
169
+ }
170
+
171
+ pub(crate) fn normalized_forms(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
172
+ rb_self.forms(ruby, Form::Normalized)
173
+ }
174
+
175
+ pub(crate) fn parts_of_speech(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
176
+ let parts = ruby.ary_new_capa(rb_self.list.len());
177
+ for morpheme in rb_self.list.iter() {
178
+ parts.push(rb_self.pos_table.get(ruby, morpheme.part_of_speech_id())?)?;
179
+ }
180
+ Ok(parts)
181
+ }
182
+
183
+ pub(crate) fn total_costs(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
184
+ let costs = ruby.ary_new_capa(rb_self.list.len());
185
+ for morpheme in rb_self.list.iter() {
186
+ costs.push(morpheme.total_cost())?;
187
+ }
188
+ Ok(costs)
189
+ }
190
+
191
+ /// jpdb-style grouping: an Array of Arrays of `Kabosu::Morpheme`.
192
+ pub(crate) fn group_morphemes(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RArray, Error> {
193
+ let ranges = group_ranges(&rb_self.list);
194
+ let groups = ruby.ary_new_capa(ranges.len());
195
+ for range in ranges {
196
+ let group = ruby.ary_new_capa(range.len());
197
+ for index in range {
198
+ group.push(RbMorpheme::listed(rb_self, index))?;
199
+ }
200
+ groups.push(group)?;
201
+ }
202
+ Ok(groups)
203
+ }
204
+ }
@@ -1,27 +1,121 @@
1
+ use std::any::Any;
1
2
  use std::ffi::c_void;
3
+ use std::panic::{catch_unwind, AssertUnwindSafe};
2
4
 
3
- type RbNoGvlFn = unsafe extern "C" fn(*mut c_void) -> *mut c_void;
4
- type RbUnblockFn = unsafe extern "C" fn(*mut c_void);
5
+ use magnus::rb_sys::{protect, AsRawValue};
6
+ use magnus::{Error, Ruby};
7
+
8
+ use crate::errors::panic_message;
5
9
 
6
10
  unsafe extern "C" {
7
11
  fn rb_thread_call_without_gvl(
8
- func: Option<RbNoGvlFn>,
12
+ func: Option<unsafe extern "C" fn(*mut c_void) -> *mut c_void>,
9
13
  data1: *mut c_void,
10
- ubf: Option<RbUnblockFn>,
14
+ ubf: Option<unsafe extern "C" fn(*mut c_void)>,
11
15
  data2: *mut c_void,
12
16
  ) -> *mut c_void;
17
+ fn rb_gc_adjust_memory_usage(diff: isize);
18
+ fn ruby_xmalloc(size: usize) -> *mut c_void;
19
+ fn ruby_xfree(ptr: *mut c_void);
20
+ }
21
+
22
+ struct Call<F, R> {
23
+ func: Option<F>,
24
+ result: Option<std::thread::Result<R>>,
25
+ }
26
+
27
+ unsafe extern "C" fn trampoline<F: FnOnce() -> R, R>(data: *mut c_void) -> *mut c_void {
28
+ // SAFETY: `data` is the `Call` that `without_gvl` keeps alive on its stack
29
+ // for the duration of this call.
30
+ let call = unsafe { &mut *data.cast::<Call<F, R>>() };
31
+ if let Some(func) = call.func.take() {
32
+ // A panic must not unwind into Ruby's C frames.
33
+ call.result = Some(catch_unwind(AssertUnwindSafe(func)));
34
+ }
35
+ std::ptr::null_mut()
36
+ }
37
+
38
+ /// Why `without_gvl` has no result to give.
39
+ pub(crate) enum Stopped {
40
+ /// The function panicked.
41
+ Panic(Box<dyn Any + Send>),
42
+ /// Ruby delivered an exception, `Thread#kill` or a signal to this thread
43
+ /// around the call. Returning it from the method re-raises it.
44
+ Raised(Error),
45
+ }
46
+
47
+ impl Stopped {
48
+ /// The error to return to Ruby: the pending exception itself, or the one
49
+ /// `on_panic` makes of the panic message.
50
+ pub(crate) fn into_error(self, on_panic: impl FnOnce(&str) -> Error) -> Error {
51
+ match self {
52
+ Self::Panic(panic) => on_panic(panic_message(&*panic)),
53
+ Self::Raised(error) => error,
54
+ }
55
+ }
56
+ }
57
+
58
+ /// Runs `func` with the GVL released, so other Ruby threads run meanwhile.
59
+ ///
60
+ /// `func` must not touch Ruby: no Ruby objects, no Ruby API. The `Send` bound
61
+ /// enforces the first half, since magnus values are not `Send` and so cannot
62
+ /// be captured. There is no unblock function: `func` always runs to the end,
63
+ /// so keep it short.
64
+ ///
65
+ /// Ruby checks for interrupts when it takes the GVL back, and raises from
66
+ /// there: `Thread#raise`, `Timeout`, `Thread#kill`, a signal handler that
67
+ /// raises. That jump would skip every Rust destructor between here and the
68
+ /// method boundary, so it is caught and handed back as `Stopped::Raised`
69
+ /// instead. The caller cleans up and returns it, and only then is it raised.
70
+ /// Whatever `func` had produced by then is dropped here.
71
+ pub(crate) fn without_gvl<F, R>(func: F) -> Result<R, Stopped>
72
+ where
73
+ F: FnOnce() -> R + Send,
74
+ {
75
+ let mut call = Call {
76
+ func: Some(func),
77
+ result: None,
78
+ };
79
+ let nil = Ruby::get()
80
+ .expect("the GVL is only released by a thread that holds it")
81
+ .qnil()
82
+ .as_raw();
83
+ let data = (&raw mut call).cast::<c_void>();
84
+ // The closure holds nothing that needs dropping, so the jump `protect`
85
+ // catches skips no destructor.
86
+ let returned = protect(|| {
87
+ // SAFETY: `call` outlives the call, and `trampoline` is instantiated
88
+ // for exactly its type.
89
+ unsafe {
90
+ rb_thread_call_without_gvl(Some(trampoline::<F, R>), data, None, std::ptr::null_mut());
91
+ }
92
+ nil
93
+ });
94
+ match (returned, call.result) {
95
+ (Err(raised), _) => Err(Stopped::Raised(raised)),
96
+ (Ok(_), Some(Ok(result))) => Ok(result),
97
+ (Ok(_), Some(Err(panic))) => Err(Stopped::Panic(panic)),
98
+ (Ok(_), None) => {
99
+ unreachable!("rb_thread_call_without_gvl returned without running the function")
100
+ }
101
+ }
13
102
  }
14
103
 
15
- pub(crate) fn run_without_gvl<T>(task: &mut T, func: RbNoGvlFn) {
16
- // SAFETY:
17
- // - `task` remains alive during this call.
18
- // - `func` only works with Rust data and does not call Ruby APIs.
104
+ /// Tells Ruby's GC about native memory it cannot see, so that churning through
105
+ /// objects that are small on the Ruby heap but large off it still triggers
106
+ /// collections. Every positive report must be matched by a negative one when
107
+ /// the memory is freed. Must be called with the GVL held.
108
+ ///
109
+ /// `rb_gc_adjust_memory_usage` only records the number: the limit is checked
110
+ /// when Ruby itself next allocates through `xmalloc`. A caller that does
111
+ /// nothing but create tokenizers may never do that, so a growing report is
112
+ /// followed by a one-byte allocation to run the check now.
113
+ pub(crate) fn report_native_memory(bytes: isize) {
114
+ // SAFETY: these only touch the GC's malloc accounting; the GVL is held.
19
115
  unsafe {
20
- rb_thread_call_without_gvl(
21
- Some(func),
22
- (task as *mut T).cast::<c_void>(),
23
- None,
24
- std::ptr::null_mut(),
25
- );
116
+ rb_gc_adjust_memory_usage(bytes);
117
+ if bytes > 0 {
118
+ ruby_xfree(ruby_xmalloc(1));
119
+ }
26
120
  }
27
121
  }
@@ -1,142 +1,128 @@
1
- use magnus::{prelude::*, Error, RArray, Ruby, Symbol, Value};
1
+ use magnus::{prelude::*, Error, RArray, RString, Ruby, Symbol, Value};
2
2
  use sudachi::analysis::Mode;
3
3
  use sudachi::dic::subset::InfoSubset;
4
4
 
5
5
  use crate::errors::arg_error;
6
6
 
7
- pub(crate) fn parse_mode(mode: Option<&str>) -> Result<Mode, Error> {
8
- match mode {
9
- None | Some("C") | Some("c") => Ok(Mode::C),
10
- Some("A") | Some("a") => Ok(Mode::A),
11
- Some("B") | Some("b") => Ok(Mode::B),
12
- Some(other) => Err(arg_error(format!(
13
- "invalid mode {other:?}; expected \"A\", \"B\", or \"C\""
7
+ /// The name a Symbol or String argument spells, lower-cased.
8
+ fn option_name(value: Value) -> Option<String> {
9
+ let name = match Symbol::from_value(value) {
10
+ Some(symbol) => symbol.name().ok()?.into_owned(),
11
+ None => RString::from_value(value)?.to_string().ok()?,
12
+ };
13
+ Some(name.to_ascii_lowercase())
14
+ }
15
+
16
+ /// A split mode from `:a`/`:b`/`:c`, in either case, as a Symbol or a String.
17
+ /// `nil` is the default, mode C.
18
+ pub(crate) fn parse_mode(value: Option<Value>) -> Result<Mode, Error> {
19
+ let Some(value) = value.filter(|value| !value.is_nil()) else {
20
+ return Ok(Mode::C);
21
+ };
22
+ match option_name(value).as_deref() {
23
+ Some("a") => Ok(Mode::A),
24
+ Some("b") => Ok(Mode::B),
25
+ Some("c") => Ok(Mode::C),
26
+ _ => Err(arg_error(format_args!(
27
+ "invalid mode {}; expected :a, :b or :c",
28
+ value.inspect()
14
29
  ))),
15
30
  }
16
31
  }
17
32
 
33
+ pub(crate) fn mode_symbol(ruby: &Ruby, mode: Mode) -> Symbol {
34
+ ruby.to_symbol(match mode {
35
+ Mode::A => "a",
36
+ Mode::B => "b",
37
+ Mode::C => "c",
38
+ })
39
+ }
40
+
41
+ /// The word-info fields a tokenizer can be limited to: the name `fields`
42
+ /// reports each one as, the other spellings accepted for it (SudachiPy's
43
+ /// among them), and the sudachi.rs flag.
44
+ const FIELDS: &[(&str, &[&str], InfoSubset)] = &[
45
+ ("surface", &["headword"], InfoSubset::HEADWORD),
46
+ ("pos_id", &["pos", "part_of_speech"], InfoSubset::POS_ID),
47
+ (
48
+ "normalized_form",
49
+ &["normalized"],
50
+ InfoSubset::NORMALIZED_FORM,
51
+ ),
52
+ (
53
+ "dictionary_form",
54
+ &["dictionary", "dictionary_form_word_id"],
55
+ InfoSubset::DICTIONARY_FORM,
56
+ ),
57
+ ("reading_form", &["reading"], InfoSubset::READING_FORM),
58
+ (
59
+ "head_word_length",
60
+ &["index_form_length"],
61
+ InfoSubset::INDEX_FORM_LENGTH,
62
+ ),
63
+ ("split_a", &[], InfoSubset::SPLIT_A),
64
+ ("split_b", &[], InfoSubset::SPLIT_B),
65
+ ("split_c", &[], InfoSubset::SPLIT_C),
66
+ ("word_structure", &[], InfoSubset::WORD_STRUCTURE),
67
+ (
68
+ "synonym_group_ids",
69
+ &["synonym_group_id"],
70
+ InfoSubset::SYNONYM_GROUP_IDS,
71
+ ),
72
+ ("user_data", &[], InfoSubset::USER_DATA),
73
+ ];
74
+
75
+ fn field_flag(name: &str) -> Option<InfoSubset> {
76
+ FIELDS
77
+ .iter()
78
+ .find(|(canonical, aliases, _)| *canonical == name || aliases.contains(&name))
79
+ .map(|(_, _, flag)| *flag)
80
+ }
81
+
82
+ /// The fields to load, from an Array of Symbols or Strings in either case.
83
+ /// `nil` loads everything.
18
84
  pub(crate) fn parse_subset(value: Option<Value>) -> Result<InfoSubset, Error> {
19
- let Some(value) = value else {
85
+ let Some(value) = value.filter(|value| !value.is_nil()) else {
20
86
  return Ok(InfoSubset::all());
21
87
  };
22
-
23
- if value.is_nil() {
24
- return Ok(InfoSubset::all());
25
- }
26
-
27
- let ary = RArray::try_convert(value)
28
- .map_err(|_| arg_error("fields must be an Array (of String/Symbol) or nil"))?;
88
+ let fields = RArray::from_value(value)
89
+ .ok_or_else(|| arg_error("fields must be an Array of Symbols or Strings, or nil"))?;
29
90
 
30
91
  let mut subset = InfoSubset::empty();
31
- // SAFETY: we only read the array values while it is live on this stack frame.
32
- for &raw in unsafe { ary.as_slice() } {
33
- let name = if let Ok(sym) = Symbol::try_convert(raw) {
34
- sym.name()?.into_owned()
35
- } else if let Ok(s) = String::try_convert(raw) {
36
- s
37
- } else {
38
- return Err(arg_error(
39
- "fields must contain only String or Symbol values",
40
- ));
41
- };
42
-
43
- let normalized = name.to_ascii_lowercase();
44
- match subset_flag(&normalized) {
45
- Some(flag) => subset |= flag,
46
- None => {
47
- return Err(arg_error(format!(
48
- "unknown field {name:?}; expected one of: surface, headword, head_word_length, index_form_length, pos_id, normalized_form, dictionary_form, dictionary_form_word_id, reading_form, split_a, split_b, split_c, word_structure, synonym_group_ids, user_data"
49
- )))
50
- }
51
- }
92
+ for field in fields {
93
+ let flag = option_name(field).as_deref().and_then(field_flag);
94
+ subset |= flag.ok_or_else(|| {
95
+ let known: Vec<&str> = FIELDS.iter().map(|(name, _, _)| *name).collect();
96
+ arg_error(format_args!(
97
+ "unknown field {}; expected one of: {}",
98
+ field.inspect(),
99
+ known.join(", ")
100
+ ))
101
+ })?;
52
102
  }
53
-
54
103
  Ok(subset.normalize())
55
104
  }
56
105
 
57
- fn subset_flag(name: &str) -> Option<InfoSubset> {
58
- match name {
59
- "surface" | "headword" => Some(InfoSubset::HEADWORD),
60
- "head_word_length" | "index_form_length" => Some(InfoSubset::INDEX_FORM_LENGTH),
61
- "pos_id" => Some(InfoSubset::POS_ID),
62
- "normalized_form" | "normalized" => Some(InfoSubset::NORMALIZED_FORM),
63
- "dictionary_form" | "dictionary" | "dictionary_form_word_id" => {
64
- Some(InfoSubset::DICTIONARY_FORM)
65
- }
66
- "reading_form" | "reading" => Some(InfoSubset::READING_FORM),
67
- "split_a" => Some(InfoSubset::SPLIT_A),
68
- "split_b" => Some(InfoSubset::SPLIT_B),
69
- "split_c" => Some(InfoSubset::SPLIT_C),
70
- "user_data" => Some(InfoSubset::USER_DATA),
71
- "word_structure" => Some(InfoSubset::WORD_STRUCTURE),
72
- "synonym_group_id" | "synonym_group_ids" => Some(InfoSubset::SYNONYM_GROUP_IDS),
73
- _ => None,
74
- }
75
- }
76
-
106
+ /// The names of the fields in `subset`, as Symbols that `parse_subset` reads
107
+ /// back to the same subset.
77
108
  pub(crate) fn subset_to_array(ruby: &Ruby, subset: InfoSubset) -> Result<RArray, Error> {
78
- let ary = ruby.ary_new();
79
-
80
- if subset.contains(InfoSubset::HEADWORD) {
81
- ary.push(ruby.str_new("surface"))?;
82
- }
83
- if subset.contains(InfoSubset::INDEX_FORM_LENGTH) {
84
- ary.push(ruby.str_new("head_word_length"))?;
85
- }
86
- if subset.contains(InfoSubset::POS_ID) {
87
- ary.push(ruby.str_new("pos_id"))?;
88
- }
89
- if subset.contains(InfoSubset::NORMALIZED_FORM) {
90
- ary.push(ruby.str_new("normalized_form"))?;
91
- }
92
- if subset.contains(InfoSubset::DICTIONARY_FORM) {
93
- ary.push(ruby.str_new("dictionary_form"))?;
94
- ary.push(ruby.str_new("dictionary_form_word_id"))?;
95
- }
96
- if subset.contains(InfoSubset::READING_FORM) {
97
- ary.push(ruby.str_new("reading_form"))?;
98
- }
99
- if subset.contains(InfoSubset::SPLIT_A) {
100
- ary.push(ruby.str_new("split_a"))?;
101
- }
102
- if subset.contains(InfoSubset::SPLIT_B) {
103
- ary.push(ruby.str_new("split_b"))?;
104
- }
105
- if subset.contains(InfoSubset::SPLIT_C) {
106
- ary.push(ruby.str_new("split_c"))?;
107
- }
108
- if subset.contains(InfoSubset::USER_DATA) {
109
- ary.push(ruby.str_new("user_data"))?;
110
- }
111
- if subset.contains(InfoSubset::WORD_STRUCTURE) {
112
- ary.push(ruby.str_new("word_structure"))?;
113
- }
114
- if subset.contains(InfoSubset::SYNONYM_GROUP_IDS) {
115
- ary.push(ruby.str_new("synonym_group_id"))?;
109
+ let names = ruby.ary_new();
110
+ for (name, _, flag) in FIELDS {
111
+ if subset.contains(*flag) {
112
+ names.push(ruby.to_symbol(name))?;
113
+ }
116
114
  }
117
-
118
- Ok(ary)
115
+ Ok(names)
119
116
  }
120
117
 
121
- pub(crate) fn parse_user_dicts(value: Option<Value>) -> Result<Vec<String>, Error> {
122
- let Some(value) = value else {
123
- return Ok(Vec::new());
124
- };
125
-
126
- if value.is_nil() {
127
- return Ok(Vec::new());
118
+ /// Appends a Ruby String to `out` as UTF-8: copied as is when it already is
119
+ /// valid UTF-8, transcoded when it is in another encoding. Invalid bytes and
120
+ /// binary Strings raise `EncodingError`.
121
+ pub(crate) fn push_utf8(text: RString, out: &mut String) -> Result<(), Error> {
122
+ // SAFETY: the borrowed &str is copied before any Ruby code can run.
123
+ match unsafe { text.test_as_str() } {
124
+ Some(utf8) => out.push_str(utf8),
125
+ None => out.push_str(&text.to_string()?),
128
126
  }
129
-
130
- let ary = RArray::try_convert(value)
131
- .map_err(|_| arg_error("user_dicts must be an Array (of String) or nil"))?;
132
-
133
- let mut user_dicts = Vec::with_capacity(ary.len());
134
- // SAFETY: we only read the array values while it is live on this stack frame.
135
- for &raw in unsafe { ary.as_slice() } {
136
- let path = String::try_convert(raw)
137
- .map_err(|_| arg_error("user_dicts must contain only String values"))?;
138
- user_dicts.push(path);
139
- }
140
-
141
- Ok(user_dicts)
127
+ Ok(())
142
128
  }