use magnus::prelude::*;
use magnus::{Error, Ruby, method};
use lindera::token::Token;
#[magnus::wrap(class = "Lindera::Token", free_immediately, size)]
pub struct RbToken {
surface: String,
byte_start: usize,
byte_end: usize,
position: usize,
word_id: u32,
is_unknown: bool,
details: Option<Vec<String>>,
}
impl RbToken {
pub fn from_token(mut token: Token) -> Self {
let details = token.details().iter().map(|s| s.to_string()).collect();
Self {
surface: token.surface.to_string(),
byte_start: token.byte_start,
byte_end: token.byte_end,
position: token.position,
word_id: token.word_id.id,
is_unknown: token.word_id.is_unknown(),
details: Some(details),
}
}
fn surface(&self) -> String {
self.surface.clone()
}
fn byte_start(&self) -> usize {
self.byte_start
}
fn byte_end(&self) -> usize {
self.byte_end
}
fn position(&self) -> usize {
self.position
}
fn word_id(&self) -> u32 {
self.word_id
}
fn is_unknown(&self) -> bool {
self.is_unknown
}
fn details(&self) -> Option<Vec<String>> {
self.details.clone()
}
fn get_detail(&self, index: usize) -> Option<String> {
self.details.as_ref().and_then(|d| d.get(index).cloned())
}
fn to_s(&self) -> String {
self.surface.clone()
}
fn inspect(&self) -> String {
format!(
"#<Lindera::Token surface='{}', start={}, end={}, position={}, word_id={}, unknown={}>",
self.surface,
self.byte_start,
self.byte_end,
self.position,
self.word_id,
self.is_unknown
)
}
}
pub fn define(ruby: &Ruby, module: &magnus::RModule) -> Result<(), Error> {
let token_class = module.define_class("Token", ruby.class_object())?;
token_class.define_method("surface", method!(RbToken::surface, 0))?;
token_class.define_method("byte_start", method!(RbToken::byte_start, 0))?;
token_class.define_method("byte_end", method!(RbToken::byte_end, 0))?;
token_class.define_method("position", method!(RbToken::position, 0))?;
token_class.define_method("word_id", method!(RbToken::word_id, 0))?;
token_class.define_method("unknown?", method!(RbToken::is_unknown, 0))?;
token_class.define_method("details", method!(RbToken::details, 0))?;
token_class.define_method("get_detail", method!(RbToken::get_detail, 1))?;
token_class.define_method("to_s", method!(RbToken::to_s, 0))?;
token_class.define_method("inspect", method!(RbToken::inspect, 0))?;
Ok(())
}