1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
mod surface;
pub use surface::Surface;

mod word;
pub use word::Word;

mod words;
pub use words::Words;

use crate::PoS;

use std::iter::FlatMap;
use std::str::Lines;

type WordsFrom<'a> = fn(&'a str) -> Words<'a>;
type FlattenWords<'a> = FlatMap<Lines<'a>, Words<'a>, WordsFrom<'a>>;

pub struct WordIterator<'a> {
    word_it: FlattenWords<'a>,
}

impl<'a> WordIterator<'a> {
    pub fn from_lines(lines: &'a str) -> Self {
        Self {
            word_it: lines.lines().flat_map(Words::from),
        }
    }
}

impl<'a> Iterator for WordIterator<'a> {
    type Item = (Surface<'a>, PoS);

    fn next(&mut self) -> Option<Self::Item> {
        self.word_it.next().map(Word::surface_and_pos)
    }
}

impl<'a> DoubleEndedIterator for WordIterator<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.word_it.next_back().map(Word::surface_and_pos)
    }
}

#[cfg(feature = "tantivy")]
pub use tantivy_tokenizer::KyTea;

#[cfg(feature = "tantivy")]
mod tantivy_tokenizer {
    use tantivy::tokenizer::Token;
    use tantivy::tokenizer::Tokenizer;
    use tantivy::tokenizer::{BoxTokenStream, TokenStream};

    use super::{PoS, Surface, WordIterator};

    use std::iter::Enumerate;

    #[derive(Debug, Clone)]
    pub struct KyTea;

    impl Tokenizer for KyTea {
        fn token_stream<'a>(&self, text: &'a str) -> BoxTokenStream<'a> {
            KyTeaStream::from(text).into()
        }
    }

    struct KyTeaStream<'a> {
        original: &'a str,
        word_it: Enumerate<WordIterator<'a>>,
        token: Token,
    }

    impl<'a> KyTeaStream<'a> {
        fn from(text: &'a str) -> Self {
            KyTeaStream {
                original: text,
                word_it: WordIterator::from_lines(text).enumerate(),
                token: Token::default(),
            }
        }
    }

    impl<'a> TokenStream for KyTeaStream<'a> {
        fn advance(&mut self) -> bool {
            if let Some((i, (surface, pos))) = self.word_it.next() {
                self.token = to_token(self.original, surface, pos, i);
                true
            } else {
                false
            }
        }

        fn token(&self) -> &Token {
            &self.token
        }

        fn token_mut(&mut self) -> &mut Token {
            &mut self.token
        }
    }

    fn to_token<'a>(
        original: &'a str,
        Surface(surface): Surface<'a>,
        pos: PoS,
        position: usize,
    ) -> Token {
        // SAFETY: `original` and `surface` are both parts of the same text, i.e. the `original`.
        let offset_from = unsafe { surface.as_ptr().offset_from(original.as_ptr()) } as usize;
        let offset_to = offset_from + surface.len();
        let text = if pos != PoS::None {
            let mut word = format!("{}/", surface);
            word.push_str(pos.into());
            word
        } else {
            String::from(surface)
        };
        Token {
            offset_from,
            offset_to,
            position,
            text,
            position_length: 1,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    fn assert_surface_and_pos(
        res: Option<(Surface<'_>, PoS)>,
        expected_surface: &str,
        expected_pos: PoS,
    ) {
        assert_eq!(res, Some((Surface(expected_surface), expected_pos)));
    }

    #[test]
    fn word_iterator() {
        let words = "\na/名詞\tb/形容詞\nc/d\n\ne/UNK\n";
        let mut it = WordIterator::from_lines(words);
        assert_surface_and_pos(it.next(), "a", PoS::名詞);
        assert_surface_and_pos(it.next(), "b", PoS::形容詞);
        assert_surface_and_pos(it.next(), "c", PoS::None);
        assert_surface_and_pos(it.next(), "e", PoS::UNK);
        assert!(it.next().is_none());
    }
}