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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use std::cmp::Ordering;

use idx_sized::{
    IdxSized
    ,IdSet
    ,RemoveResult
};
use various_data_file::VariousDataFile;

pub mod entity;
use entity::FieldEntity;

#[derive(Clone)]
pub enum SearchCondition<'a>{
    Match(&'a [u8])
    ,Range(&'a [u8],&'a [u8])
    //,Partial(&'a str)
    //,Forward(&'a str)
    //,Backword(&'a str)
    //,Min(&'a [u8])
    //,Max(&'a [u8])
}

pub struct Field{
    index: IdxSized<FieldEntity>
    ,strings:VariousDataFile
}
impl Field{
    pub fn new(path_prefix:&str) -> Result<Field,std::io::Error>{
        match IdxSized::new(&(path_prefix.to_string()+".i")){
            Err(e)=>Err(e)
            ,Ok(index)=>{
                match VariousDataFile::new(&(path_prefix.to_string()+".d")){
                    Ok(strings)=>Ok(Field{
                        index
                        ,strings
                    })
                    ,Err(e)=>Err(e)
                }
            }
        }
    }
    pub fn entity<'a>(&self,id:u32)->Option<&'a FieldEntity>{
        if let Some(v)=self.index.triee().entity_value(id){
            Some(&v)
        }else{
            None
        }
    }
    pub fn str<'a>(&self,id:u32)->Option<&'a str>{
        if let Some(e)=self.entity(id){
            std::str::from_utf8(unsafe{
                std::slice::from_raw_parts(self.strings.offset(e.addr()) as *const u8,e.len())
            }).ok()
        }else{
            None
        }
    }
    pub fn num(&self,id:u32)->Option<f64>{
        if let Some(e)=self.entity(id){
            Some(e.num())
        }else{
            None
        }
    }
    fn search_cb(&self,cont:&[u8])->(Ordering,u32){
        self.index.triee().search_cb(|data|->Ordering{
            let str2=unsafe{
                std::slice::from_raw_parts(self.strings.offset(data.addr()) as *const u8,data.len())
            };
            if cont==str2{
                Ordering::Equal
            }else{
                natord::compare(
                    std::str::from_utf8(cont).unwrap()
                    ,std::str::from_utf8(str2).unwrap()
                )
            }
        })
    }
    pub fn search(&self,condition:SearchCondition)->IdSet{
        match condition{
            SearchCondition::Match(v)=>{
                self.search_match(v)
            }
            ,SearchCondition::Range(min,max)=>{
                self.search_range(min,max)
            }
            //,_=>IdSet::default()
        }
    }
    fn search_match(&self,cont:&[u8])->IdSet{
        let mut r:IdSet=IdSet::default();
        let (ord,found_id)=self.search_cb(cont);
        if ord==Ordering::Equal{
            r.insert(found_id);
            self.index.triee().sames(&mut r, found_id);
        }
        r
    }
    
    fn search_range(&self,min:&[u8],max:&[u8])->IdSet{
        let mut r:IdSet=IdSet::default();
        let (_,min_found_id)=self.search_cb(min);
        let (_,max_found_id)=self.search_cb(max);
        for (_,id,_) in self.index.triee().iter_by_id_from_to(min_found_id,max_found_id){
            r.insert(id);
            self.index.triee().sames(&mut r, max_found_id);
        }
        r
    }
    
    pub fn update(&mut self,id:u32,content:&[u8]) -> Option<u32>{
        //まずは消す(指定したidのデータが無い場合はスルーされる)
        if let RemoveResult::Unique(data)=self.index.delete(id){
            self.strings.remove(&data.word());    //削除対象がユニークの場合は対象文字列を完全削除
        }
        let cont=std::str::from_utf8(content).unwrap();
        let tree=self.index.triee();
        let (ord,found_id)=tree.search_cb(|data|->Ordering{
            let str2=std::str::from_utf8(self.strings.slice(data.word())).unwrap();

            if cont==str2{
                Ordering::Equal
            }else{
                natord::compare(cont,str2)
            }
        });
        if ord==Ordering::Equal && found_id!=0{
            if let Some(_node)=self.index.triee().node(id){
                //すでにデータがある場合
                self.index.triee_mut().update_same(found_id,id);
                Some(id)
            }else{
                self.index.insert_same(found_id)
            }
        }else{
            //新しく作る
            if let Some(word)=self.strings.insert(content){
                let e=FieldEntity::new(
                    word.address()
                    ,cont.parse().unwrap_or(0.0)
                );
                if let Some(_entity)=self.index.triee().node(id){
                    //既存データの更新処理
                    self.index.triee_mut().update_node(
                        found_id
                        ,id
                        ,e
                        ,ord
                    );
                    Some(id)
                }else{
                    //追加
                    self.index.insert_unique(e,found_id,ord)
                }
            }else{
                None
            }
        }
    }
    pub fn delete(&mut self,id:u32){
        self.index.delete(id);
    }
}