├── LICENSE.md ├── README.md ├── api.go ├── cedar.go ├── cedar_test.go ├── dict_test.go ├── doc.go ├── errors.go ├── example_test.go ├── io.go └── testdata ├── README.md └── dict.txt /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cedar-go [![GoDoc](https://godoc.org/github.com/adamzy/cedar-go?status.svg)](https://godoc.org/github.com/adamzy/cedar-go) 2 | 3 | Package `cedar-go` implementes double-array trie. 4 | 5 | It is a [Golang](https://golang.org/) port of [cedar](http://www.tkl.iis.u-tokyo.ac.jp/~ynaga/cedar) which is written in C++ by Naoki Yoshinaga. `cedar-go` currently implements the `reduced` verion of cedar. 6 | This package is not thread safe if there is one goroutine doing insertions or deletions. 7 | 8 | ## Install 9 | ``` 10 | go get github.com/adamzy/cedar-go 11 | ``` 12 | 13 | ## Usage 14 | ```go 15 | package main 16 | 17 | import ( 18 | "fmt" 19 | 20 | "github.com/adamzy/cedar-go" 21 | ) 22 | 23 | func main() { 24 | // create a new cedar trie. 25 | trie := cedar.New() 26 | 27 | // a helper function to print the id-key-value triple given trie node id 28 | printIdKeyValue := func(id int) { 29 | // the key of node `id`. 30 | key, _ := trie.Key(id) 31 | // the value of node `id`. 32 | value, _ := trie.Value(id) 33 | fmt.Printf("%d\t%s:%v\n", id, key, value) 34 | } 35 | 36 | // Insert key-value pairs. 37 | // The order of insertion is not important. 38 | trie.Insert([]byte("How many"), 0) 39 | trie.Insert([]byte("How many loved"), 1) 40 | trie.Insert([]byte("How many loved your moments"), 2) 41 | trie.Insert([]byte("How many loved your moments of glad grace"), 3) 42 | trie.Insert([]byte("姑苏"), 4) 43 | trie.Insert([]byte("姑苏城外"), 5) 44 | trie.Insert([]byte("姑苏城外寒山寺"), 6) 45 | 46 | // Get the associated value of a key directly. 47 | value, _ := trie.Get([]byte("How many loved your moments of glad grace")) 48 | fmt.Println(value) 49 | 50 | // Or, jump to the node first, 51 | id, _ := trie.Jump([]byte("How many loved your moments"), 0) 52 | // then get the key and the value 53 | printIdKeyValue(id) 54 | 55 | fmt.Println("\nPrefixMatch\nid\tkey:value") 56 | for _, id := range trie.PrefixMatch([]byte("How many loved your moments of glad grace"), 0) { 57 | printIdKeyValue(id) 58 | } 59 | 60 | fmt.Println("\nPrefixPredict\nid\tkey:value") 61 | for _, id := range trie.PrefixPredict([]byte("姑苏"), 0) { 62 | printIdKeyValue(id) 63 | } 64 | } 65 | ``` 66 | will produce 67 | ``` 68 | 3 69 | 281 How many loved your moments:2 70 | 71 | PrefixMatch 72 | id key:value 73 | 262 How many:0 74 | 268 How many loved:1 75 | 281 How many loved your moments:2 76 | 296 How many loved your moments of glad grace:3 77 | 78 | PrefixPredict 79 | id key:value 80 | 303 姑苏:4 81 | 309 姑苏城外:5 82 | 318 姑苏城外寒山寺:6 83 | ``` 84 | -------------------------------------------------------------------------------- /api.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | // Status reports the following statistics of the cedar: 4 | // keys: number of keys that are in the cedar, 5 | // nodes: number of trie nodes (slots in the base array) has been taken, 6 | // size: the size of the base array used by the cedar, 7 | // capacity: the capicity of the base array used by the cedar. 8 | func (da *Cedar) Status() (keys, nodes, size, capacity int) { 9 | for i := 0; i < da.Size; i++ { 10 | n := da.Array[i] 11 | if n.Check >= 0 { 12 | nodes++ 13 | if n.Value >= 0 { 14 | keys++ 15 | } 16 | } 17 | } 18 | return keys, nodes, da.Size, da.Capacity 19 | } 20 | 21 | // Jump travels from a node `from` to another node `to` by following the path `path`. 22 | // For example, if the following keys were inserted: 23 | // id key 24 | // 19 abc 25 | // 23 ab 26 | // 37 abcd 27 | // then 28 | // Jump([]byte("ab"), 0) = 23, nil // reach "ab" from root 29 | // Jump([]byte("c"), 23) = 19, nil // reach "abc" from "ab" 30 | // Jump([]byte("cd"), 23) = 37, nil // reach "abcd" from "ab" 31 | func (da *Cedar) Jump(path []byte, from int) (to int, err error) { 32 | for _, b := range path { 33 | if da.Array[from].Value >= 0 { 34 | return from, ErrNoPath 35 | } 36 | to = da.Array[from].base() ^ int(b) 37 | if da.Array[to].Check != from { 38 | return from, ErrNoPath 39 | } 40 | from = to 41 | } 42 | return to, nil 43 | } 44 | 45 | // Key returns the key of the node with the given `id`. 46 | // It will return ErrNoPath, if the node does not exist. 47 | func (da *Cedar) Key(id int) (key []byte, err error) { 48 | for id > 0 { 49 | from := da.Array[id].Check 50 | if from < 0 { 51 | return nil, ErrNoPath 52 | } 53 | if char := byte(da.Array[from].base() ^ id); char != 0 { 54 | key = append(key, char) 55 | } 56 | id = from 57 | } 58 | if id != 0 || len(key) == 0 { 59 | return nil, ErrInvalidKey 60 | } 61 | for i := 0; i < len(key)/2; i++ { 62 | key[i], key[len(key)-i-1] = key[len(key)-i-1], key[i] 63 | } 64 | return key, nil 65 | } 66 | 67 | // Value returns the value of the node with the given `id`. 68 | // It will return ErrNoValue, if the node does not have a value. 69 | func (da *Cedar) Value(id int) (value int, err error) { 70 | value = da.Array[id].Value 71 | if value >= 0 { 72 | return value, nil 73 | } 74 | to := da.Array[id].base() 75 | if da.Array[to].Check == id && da.Array[to].Value >= 0 { 76 | return da.Array[to].Value, nil 77 | } 78 | return 0, ErrNoValue 79 | } 80 | 81 | // Insert adds a key-value pair into the cedar. 82 | // It will return ErrInvalidValue, if value < 0 or >= ValueLimit. 83 | func (da *Cedar) Insert(key []byte, value int) error { 84 | if value < 0 || value >= ValueLimit { 85 | return ErrInvalidValue 86 | } 87 | p := da.get(key, 0, 0) 88 | *p = value 89 | return nil 90 | } 91 | 92 | // Update increases the value associated with the `key`. 93 | // The `key` will be inserted if it is not in the cedar. 94 | // It will return ErrInvalidValue, if the updated value < 0 or >= ValueLimit. 95 | func (da *Cedar) Update(key []byte, value int) error { 96 | p := da.get(key, 0, 0) 97 | 98 | // key was not inserted 99 | if *p == ValueLimit { 100 | *p = value 101 | return nil 102 | } 103 | 104 | // key was inserted before 105 | if *p+value < 0 || *p+value >= ValueLimit { 106 | return ErrInvalidValue 107 | } 108 | *p += value 109 | return nil 110 | } 111 | 112 | // Delete removes a key-value pair from the cedar. 113 | // It will return ErrNoPath, if the key has not been added. 114 | func (da *Cedar) Delete(key []byte) error { 115 | // if the path does not exist, or the end is not a leaf, nothing to delete 116 | to, err := da.Jump(key, 0) 117 | if err != nil { 118 | return ErrNoPath 119 | } 120 | 121 | if da.Array[to].Value < 0 { 122 | base := da.Array[to].base() 123 | if da.Array[base].Check == to { 124 | to = base 125 | } 126 | } 127 | 128 | for to > 0 { 129 | from := da.Array[to].Check 130 | base := da.Array[from].base() 131 | label := byte(to ^ base) 132 | 133 | // if `to` has sibling, remove `to` from the sibling list, then stop 134 | if da.Ninfos[to].Sibling != 0 || da.Ninfos[from].Child != label { 135 | // delete the label from the child ring first 136 | da.popSibling(from, base, label) 137 | // then release the current node `to` to the empty node ring 138 | da.pushEnode(to) 139 | break 140 | } 141 | // otherwise, just release the current node `to` to the empty node ring 142 | da.pushEnode(to) 143 | // then check its parent node 144 | to = from 145 | } 146 | return nil 147 | } 148 | 149 | // Get returns the value associated with the given `key`. 150 | // It is equivalent to 151 | // id, err1 = Jump(key) 152 | // value, err2 = Value(id) 153 | // Thus, it may return ErrNoPath or ErrNoValue, 154 | func (da *Cedar) Get(key []byte) (value int, err error) { 155 | to, err := da.Jump(key, 0) 156 | if err != nil { 157 | return 0, err 158 | } 159 | return da.Value(to) 160 | } 161 | 162 | // PrefixMatch returns a list of at most `num` nodes which match the prefix of the key. 163 | // If `num` is 0, it returns all matches. 164 | // For example, if the following keys were inserted: 165 | // id key 166 | // 19 abc 167 | // 23 ab 168 | // 37 abcd 169 | // then 170 | // PrefixMatch([]byte("abc"), 1) = [ 23 ] // match ["ab"] 171 | // PrefixMatch([]byte("abcd"), 0) = [ 23, 19, 37] // match ["ab", "abc", "abcd"] 172 | func (da *Cedar) PrefixMatch(key []byte, num int) (ids []int) { 173 | for from, i := 0, 0; i < len(key); i++ { 174 | to, err := da.Jump(key[i:i+1], from) 175 | if err != nil { 176 | break 177 | } 178 | if _, err := da.Value(to); err == nil { 179 | ids = append(ids, to) 180 | num-- 181 | if num == 0 { 182 | return 183 | } 184 | } 185 | from = to 186 | } 187 | return 188 | } 189 | 190 | // PrefixPredict returns a list of at most `num` nodes which has the key as their prefix. 191 | // These nodes are ordered by their keys. 192 | // If `num` is 0, it returns all matches. 193 | // For example, if the following keys were inserted: 194 | // id key 195 | // 19 abc 196 | // 23 ab 197 | // 37 abcd 198 | // then 199 | // PrefixPredict([]byte("ab"), 2) = [ 23, 19 ] // predict ["ab", "abc"] 200 | // PrefixPredict([]byte("ab"), 0) = [ 23, 19, 37 ] // predict ["ab", "abc", "abcd"] 201 | func (da *Cedar) PrefixPredict(key []byte, num int) (ids []int) { 202 | root, err := da.Jump(key, 0) 203 | if err != nil { 204 | return 205 | } 206 | for from, err := da.begin(root); err == nil; from, err = da.next(from, root) { 207 | ids = append(ids, from) 208 | num-- 209 | if num == 0 { 210 | return 211 | } 212 | } 213 | return 214 | } 215 | 216 | func (da *Cedar) begin(from int) (to int, err error) { 217 | for c := da.Ninfos[from].Child; c != 0; { 218 | to = da.Array[from].base() ^ int(c) 219 | c = da.Ninfos[to].Child 220 | from = to 221 | } 222 | if da.Array[from].base() > 0 { 223 | return da.Array[from].base(), nil 224 | } 225 | return from, nil 226 | } 227 | 228 | func (da *Cedar) next(from int, root int) (to int, err error) { 229 | c := da.Ninfos[from].Sibling 230 | for c == 0 && from != root && da.Array[from].Check >= 0 { 231 | from = da.Array[from].Check 232 | c = da.Ninfos[from].Sibling 233 | } 234 | if from == root { 235 | return 0, ErrNoPath 236 | } 237 | from = da.Array[da.Array[from].Check].base() ^ int(c) 238 | return da.begin(from) 239 | } 240 | -------------------------------------------------------------------------------- /cedar.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | const ValueLimit = int(^uint(0) >> 1) 4 | 5 | type node struct { 6 | Value int 7 | Check int 8 | } 9 | 10 | func (n *node) base() int { return -(n.Value + 1) } 11 | 12 | type ninfo struct { 13 | Sibling, Child byte 14 | } 15 | 16 | type block struct { 17 | Prev, Next, Num, Reject, Trial, Ehead int 18 | } 19 | 20 | func (b *block) init() { 21 | b.Num = 256 22 | b.Reject = 257 23 | } 24 | 25 | type Cedar struct { 26 | *cedar 27 | } 28 | 29 | type cedar struct { 30 | Array []node 31 | Ninfos []ninfo 32 | Blocks []block 33 | Reject [257]int 34 | BheadF int 35 | BheadC int 36 | BheadO int 37 | Capacity int 38 | Size int 39 | Ordered bool 40 | MaxTrial int 41 | } 42 | 43 | func New() *Cedar { 44 | da := cedar{ 45 | Array: make([]node, 256), 46 | Ninfos: make([]ninfo, 256), 47 | Blocks: make([]block, 1), 48 | Capacity: 256, 49 | Size: 256, 50 | Ordered: true, 51 | MaxTrial: 1, 52 | } 53 | 54 | da.Array[0] = node{-2, 0} 55 | for i := 1; i < 256; i++ { 56 | da.Array[i] = node{-(i - 1), -(i + 1)} 57 | } 58 | da.Array[1].Value = -255 59 | da.Array[255].Check = -1 60 | 61 | da.Blocks[0].Ehead = 1 62 | da.Blocks[0].init() 63 | 64 | for i := 0; i <= 256; i++ { 65 | da.Reject[i] = i + 1 66 | } 67 | 68 | return &Cedar{&da} 69 | } 70 | 71 | // Get value by key, insert the key if not exist 72 | func (da *cedar) get(key []byte, from, pos int) *int { 73 | for ; pos < len(key); pos++ { 74 | if value := da.Array[from].Value; value >= 0 && value != ValueLimit { 75 | to := da.follow(from, 0) 76 | da.Array[to].Value = value 77 | } 78 | from = da.follow(from, key[pos]) 79 | } 80 | to := from 81 | if da.Array[from].Value < 0 { 82 | to = da.follow(from, 0) 83 | } 84 | return &da.Array[to].Value 85 | } 86 | 87 | func (da *cedar) follow(from int, label byte) int { 88 | base := da.Array[from].base() 89 | to := base ^ int(label) 90 | if base < 0 || da.Array[to].Check < 0 { 91 | hasChild := false 92 | if base >= 0 { 93 | hasChild = (da.Array[base^int(da.Ninfos[from].Child)].Check == from) 94 | } 95 | to = da.popEnode(base, label, from) 96 | da.pushSibling(from, to^int(label), label, hasChild) 97 | } else if da.Array[to].Check != from { 98 | to = da.resolve(from, base, label) 99 | } else if da.Array[to].Check == from { 100 | } else { 101 | panic("cedar: internal error, should not be here") 102 | } 103 | return to 104 | } 105 | 106 | func (da *cedar) popBlock(bi int, head_in *int, last bool) { 107 | if last { 108 | *head_in = 0 109 | } else { 110 | b := &da.Blocks[bi] 111 | da.Blocks[b.Prev].Next = b.Next 112 | da.Blocks[b.Next].Prev = b.Prev 113 | if bi == *head_in { 114 | *head_in = b.Next 115 | } 116 | } 117 | } 118 | 119 | func (da *cedar) pushBlock(bi int, head_out *int, empty bool) { 120 | b := &da.Blocks[bi] 121 | if empty { 122 | *head_out, b.Prev, b.Next = bi, bi, bi 123 | } else { 124 | tail_out := &da.Blocks[*head_out].Prev 125 | b.Prev = *tail_out 126 | b.Next = *head_out 127 | *head_out, *tail_out, da.Blocks[*tail_out].Next = bi, bi, bi 128 | } 129 | } 130 | 131 | func (da *cedar) addBlock() int { 132 | if da.Size == da.Capacity { 133 | da.Capacity *= 2 134 | 135 | oldArray := da.Array 136 | da.Array = make([]node, da.Capacity) 137 | copy(da.Array, oldArray) 138 | 139 | oldNinfo := da.Ninfos 140 | da.Ninfos = make([]ninfo, da.Capacity) 141 | copy(da.Ninfos, oldNinfo) 142 | 143 | oldBlock := da.Blocks 144 | da.Blocks = make([]block, da.Capacity>>8) 145 | copy(da.Blocks, oldBlock) 146 | } 147 | 148 | da.Blocks[da.Size>>8].init() 149 | da.Blocks[da.Size>>8].Ehead = da.Size 150 | 151 | da.Array[da.Size] = node{-(da.Size + 255), -(da.Size + 1)} 152 | for i := da.Size + 1; i < da.Size+255; i++ { 153 | da.Array[i] = node{-(i - 1), -(i + 1)} 154 | } 155 | da.Array[da.Size+255] = node{-(da.Size + 254), -da.Size} 156 | 157 | da.pushBlock(da.Size>>8, &da.BheadO, da.BheadO == 0) 158 | da.Size += 256 159 | return da.Size>>8 - 1 160 | } 161 | 162 | func (da *cedar) transferBlock(bi int, head_in, head_out *int) { 163 | da.popBlock(bi, head_in, bi == da.Blocks[bi].Next) 164 | da.pushBlock(bi, head_out, *head_out == 0 && da.Blocks[bi].Num != 0) 165 | } 166 | 167 | func (da *cedar) popEnode(base int, label byte, from int) int { 168 | e := base ^ int(label) 169 | if base < 0 { 170 | e = da.findPlace() 171 | } 172 | bi := e >> 8 173 | n := &da.Array[e] 174 | b := &da.Blocks[bi] 175 | b.Num-- 176 | if b.Num == 0 { 177 | if bi != 0 { 178 | da.transferBlock(bi, &da.BheadC, &da.BheadF) 179 | } 180 | } else { 181 | da.Array[-n.Value].Check = n.Check 182 | da.Array[-n.Check].Value = n.Value 183 | if e == b.Ehead { 184 | b.Ehead = -n.Check 185 | } 186 | if bi != 0 && b.Num == 1 && b.Trial != da.MaxTrial { 187 | da.transferBlock(bi, &da.BheadO, &da.BheadC) 188 | } 189 | } 190 | n.Value = ValueLimit 191 | n.Check = from 192 | if base < 0 { 193 | da.Array[from].Value = -(e ^ int(label)) - 1 194 | } 195 | return e 196 | } 197 | 198 | func (da *cedar) pushEnode(e int) { 199 | bi := e >> 8 200 | b := &da.Blocks[bi] 201 | b.Num++ 202 | if b.Num == 1 { 203 | b.Ehead = e 204 | da.Array[e] = node{-e, -e} 205 | if bi != 0 { 206 | da.transferBlock(bi, &da.BheadF, &da.BheadC) 207 | } 208 | } else { 209 | prev := b.Ehead 210 | next := -da.Array[prev].Check 211 | da.Array[e] = node{-prev, -next} 212 | da.Array[prev].Check = -e 213 | da.Array[next].Value = -e 214 | if b.Num == 2 || b.Trial == da.MaxTrial { 215 | if bi != 0 { 216 | da.transferBlock(bi, &da.BheadC, &da.BheadO) 217 | } 218 | } 219 | b.Trial = 0 220 | } 221 | if b.Reject < da.Reject[b.Num] { 222 | b.Reject = da.Reject[b.Num] 223 | } 224 | da.Ninfos[e] = ninfo{} 225 | } 226 | 227 | // hasChild: wherether the `from` node has children 228 | func (da *cedar) pushSibling(from, base int, label byte, hasChild bool) { 229 | c := &da.Ninfos[from].Child 230 | keepOrder := *c == 0 231 | if da.Ordered { 232 | keepOrder = label > *c 233 | } 234 | if hasChild && keepOrder { 235 | c = &da.Ninfos[base^int(*c)].Sibling 236 | for da.Ordered && *c != 0 && *c < label { 237 | c = &da.Ninfos[base^int(*c)].Sibling 238 | } 239 | } 240 | da.Ninfos[base^int(label)].Sibling = *c 241 | *c = label 242 | } 243 | 244 | func (da *cedar) popSibling(from, base int, label byte) { 245 | c := &da.Ninfos[from].Child 246 | for *c != label { 247 | c = &da.Ninfos[base^int(*c)].Sibling 248 | } 249 | *c = da.Ninfos[base^int(*c)].Sibling 250 | } 251 | 252 | func (da *cedar) consult(base_n, base_p int, c_n, c_p byte) bool { 253 | c_n = da.Ninfos[base_n^int(c_n)].Sibling 254 | c_p = da.Ninfos[base_p^int(c_p)].Sibling 255 | for c_n != 0 && c_p != 0 { 256 | c_n = da.Ninfos[base_n^int(c_n)].Sibling 257 | c_p = da.Ninfos[base_p^int(c_p)].Sibling 258 | } 259 | return c_p != 0 260 | } 261 | 262 | func (da *cedar) setChild(base int, c byte, label byte, flag bool) []byte { 263 | child := make([]byte, 0, 257) 264 | if c == 0 { 265 | child = append(child, c) 266 | c = da.Ninfos[base^int(c)].Sibling 267 | } 268 | if da.Ordered { 269 | for c != 0 && c <= label { 270 | child = append(child, c) 271 | c = da.Ninfos[base^int(c)].Sibling 272 | } 273 | } 274 | if flag { 275 | child = append(child, label) 276 | } 277 | for c != 0 { 278 | child = append(child, c) 279 | c = da.Ninfos[base^int(c)].Sibling 280 | } 281 | return child 282 | } 283 | 284 | func (da *cedar) findPlace() int { 285 | if da.BheadC != 0 { 286 | return da.Blocks[da.BheadC].Ehead 287 | } 288 | if da.BheadO != 0 { 289 | return da.Blocks[da.BheadO].Ehead 290 | } 291 | return da.addBlock() << 8 292 | } 293 | 294 | func (da *cedar) findPlaces(child []byte) int { 295 | bi := da.BheadO 296 | if bi != 0 { 297 | bz := da.Blocks[da.BheadO].Prev 298 | nc := len(child) 299 | for { 300 | b := &da.Blocks[bi] 301 | if b.Num >= nc && nc < b.Reject { 302 | for e := b.Ehead; ; { 303 | base := e ^ int(child[0]) 304 | for i := 0; da.Array[base^int(child[i])].Check < 0; i++ { 305 | if i == len(child)-1 { 306 | b.Ehead = e 307 | return e 308 | } 309 | } 310 | e = -da.Array[e].Check 311 | if e == b.Ehead { 312 | break 313 | } 314 | } 315 | } 316 | b.Reject = nc 317 | if b.Reject < da.Reject[b.Num] { 318 | da.Reject[b.Num] = b.Reject 319 | } 320 | bi_ := b.Next 321 | b.Trial++ 322 | if b.Trial == da.MaxTrial { 323 | da.transferBlock(bi, &da.BheadO, &da.BheadC) 324 | } 325 | if bi == bz { 326 | break 327 | } 328 | bi = bi_ 329 | } 330 | } 331 | return da.addBlock() << 8 332 | } 333 | 334 | func (da *cedar) resolve(from_n, base_n int, label_n byte) int { 335 | to_pn := base_n ^ int(label_n) 336 | from_p := da.Array[to_pn].Check 337 | base_p := da.Array[from_p].base() 338 | 339 | flag := da.consult(base_n, base_p, da.Ninfos[from_n].Child, da.Ninfos[from_p].Child) 340 | var children []byte 341 | if flag { 342 | children = da.setChild(base_n, da.Ninfos[from_n].Child, label_n, true) 343 | } else { 344 | children = da.setChild(base_p, da.Ninfos[from_p].Child, 255, false) 345 | } 346 | var base int 347 | if len(children) == 1 { 348 | base = da.findPlace() 349 | } else { 350 | base = da.findPlaces(children) 351 | } 352 | base ^= int(children[0]) 353 | var from int 354 | var base_ int 355 | if flag { 356 | from = from_n 357 | base_ = base_n 358 | } else { 359 | from = from_p 360 | base_ = base_p 361 | } 362 | if flag && children[0] == label_n { 363 | da.Ninfos[from].Child = label_n 364 | } 365 | da.Array[from].Value = -base - 1 366 | for i := 0; i < len(children); i++ { 367 | to := da.popEnode(base, children[i], from) 368 | to_ := base_ ^ int(children[i]) 369 | if i == len(children)-1 { 370 | da.Ninfos[to].Sibling = 0 371 | } else { 372 | da.Ninfos[to].Sibling = children[i+1] 373 | } 374 | if flag && to_ == to_pn { // new node has no child 375 | continue 376 | } 377 | n := &da.Array[to] 378 | n_ := &da.Array[to_] 379 | n.Value = n_.Value 380 | if n.Value < 0 && children[i] != 0 { 381 | // this node has children, fix their check 382 | c := da.Ninfos[to_].Child 383 | da.Ninfos[to].Child = c 384 | da.Array[n.base()^int(c)].Check = to 385 | c = da.Ninfos[n.base()^int(c)].Sibling 386 | for c != 0 { 387 | da.Array[n.base()^int(c)].Check = to 388 | c = da.Ninfos[n.base()^int(c)].Sibling 389 | } 390 | } 391 | if !flag && to_ == from_n { // parent node moved 392 | from_n = to 393 | } 394 | if !flag && to_ == to_pn { 395 | da.pushSibling(from_n, to_pn^int(label_n), label_n, true) 396 | da.Ninfos[to_].Child = 0 397 | n_.Value = ValueLimit 398 | n_.Check = from_n 399 | } else { 400 | da.pushEnode(to_) 401 | } 402 | } 403 | if flag { 404 | return base ^ int(label_n) 405 | } 406 | return to_pn 407 | } 408 | -------------------------------------------------------------------------------- /cedar_test.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "testing" 7 | ) 8 | 9 | var ( 10 | cd *Cedar 11 | words = []string{ 12 | "a", "aa", "ab", "ac", "abc", "abd", 13 | "abcd", "abde", "abdf", "abcdef", "abcde", 14 | "abcdefghijklmn", "bcd", "b", "xyz", 15 | "中国", "中国北京", "中国上海", "中国广州", 16 | "中华", "中华文明", "中华民族", "中华人民共和国", 17 | "this", "this is", "this is a sentence.", 18 | } 19 | ) 20 | 21 | func loadTestData() { 22 | if cd != nil { 23 | return 24 | } 25 | cd = New() 26 | // cd.Ordered = false 27 | 28 | // add the keys 29 | for i, word := range words { 30 | if err := cd.Insert([]byte(word), i); err != nil { 31 | panic(err) 32 | } 33 | } 34 | 35 | for _, word := range words { 36 | if err := cd.Delete([]byte(word)); err != nil { 37 | panic(err) 38 | } 39 | } 40 | 41 | for i, word := range words { 42 | if err := cd.Update([]byte(word), i); err != nil { 43 | panic(err) 44 | } 45 | } 46 | 47 | // delete some keys 48 | for i := 0; i < len(words); i += 4 { 49 | if err := cd.Delete([]byte(words[i])); err != nil { 50 | panic(err) 51 | } 52 | } 53 | return 54 | } 55 | 56 | func TestBasic(t *testing.T) { 57 | loadTestData() 58 | // check the consistency 59 | checkConsistency(cd) 60 | } 61 | 62 | func TestSaveAndLoad(t *testing.T) { 63 | loadTestData() 64 | 65 | cd.SaveToFile("cedar.gob", "gob") 66 | defer os.Remove("cedar.gob") 67 | daGob := New() 68 | if err := daGob.LoadFromFile("cedar.gob", "gob"); err != nil { 69 | panic(err) 70 | } 71 | checkConsistency(daGob) 72 | 73 | cd.SaveToFile("cedar.json", "json") 74 | defer os.Remove("cedar.json") 75 | daJson := New() 76 | if err := daJson.LoadFromFile("cedar.json", "json"); err != nil { 77 | panic(err) 78 | } 79 | checkConsistency(daJson) 80 | } 81 | 82 | func TestPrefixMatch(t *testing.T) { 83 | var ids []int 84 | var keys []string 85 | var values []int 86 | 87 | ids = cd.PrefixMatch([]byte("abcdefg"), 0) 88 | keys = []string{"ab", "abcd", "abcde", "abcdef"} 89 | values = []int{2, 6, 10, 9} 90 | check(cd, ids, keys, values) 91 | 92 | ids = cd.PrefixMatch([]byte("中华人民共和国"), 0) 93 | keys = []string{"中华", "中华人民共和国"} 94 | values = []int{19, 22} 95 | check(cd, ids, keys, values) 96 | 97 | ids = cd.PrefixMatch([]byte("this is a sentence."), 0) 98 | keys = []string{"this", "this is a sentence."} 99 | values = []int{23, 25} 100 | check(cd, ids, keys, values) 101 | } 102 | 103 | func check(cd *Cedar, ids []int, keys []string, values []int) { 104 | if len(ids) != len(keys) { 105 | panic("wrong prefix match") 106 | } 107 | for i, n := range ids { 108 | key, _ := cd.Key(n) 109 | val, _ := cd.Value(n) 110 | if string(key) != keys[i] || val != values[i] { 111 | panic("wrong prefix match") 112 | } 113 | } 114 | } 115 | 116 | func TestOrder(t *testing.T) { 117 | c := New() 118 | c.Insert([]byte("a"), 1) 119 | c.Insert([]byte("b"), 3) 120 | c.Insert([]byte("d"), 6) 121 | c.Insert([]byte("ab"), 2) 122 | c.Insert([]byte("c"), 5) 123 | c.Insert([]byte(""), 0) 124 | c.Insert([]byte("bb"), 4) 125 | ids := c.PrefixPredict([]byte(""), 0) 126 | if len(ids) != 7 { 127 | panic("wrong order") 128 | } 129 | for i, n := range ids { 130 | val, _ := c.Value(n) 131 | if i != val { 132 | panic("wrong order") 133 | } 134 | } 135 | } 136 | 137 | func TestPrefixPredict(t *testing.T) { 138 | var ids []int 139 | var keys []string 140 | var values []int 141 | ids = cd.PrefixPredict([]byte("中华"), 0) 142 | keys = []string{"中华", "中华人民共和国", "中华民族"} 143 | values = []int{19, 22, 21} 144 | check(cd, ids, keys, values) 145 | 146 | ids = cd.PrefixPredict([]byte("中国"), 0) 147 | keys = []string{"中国", "中国上海", "中国广州"} 148 | values = []int{15, 17, 18} 149 | check(cd, ids, keys, values) 150 | } 151 | 152 | func checkConsistency(cd *Cedar) { 153 | for i, word := range words { 154 | id, err := cd.Jump([]byte(word), 0) 155 | if i%4 == 0 { 156 | if err == ErrNoPath { 157 | continue 158 | } 159 | _, err := cd.Value(id) 160 | if err == ErrNoValue { 161 | continue 162 | } 163 | panic("not deleted") 164 | } 165 | key, err := cd.Key(id) 166 | if err != nil { 167 | panic(err) 168 | } 169 | if string(key) != word { 170 | panic("key error") 171 | } 172 | value, err := cd.Value(id) 173 | if err != nil || value != i { 174 | fmt.Println(word, i, value, err) 175 | panic("value error") 176 | } 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /dict_test.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "log" 8 | "os" 9 | "testing" 10 | ) 11 | 12 | type item struct { 13 | key []byte 14 | value int 15 | } 16 | 17 | var dict []item 18 | 19 | var trie = New() 20 | 21 | func loadDict() { 22 | f, err := os.Open("testdata/dict.txt") 23 | if err != nil { 24 | panic("failed to open testdata/dict.txt") 25 | } 26 | 27 | defer f.Close() 28 | in := bufio.NewReader(f) 29 | 30 | added := make(map[string]struct{}) 31 | var key string 32 | var freq int 33 | var pos string 34 | for { 35 | _, err := fmt.Fscanln(in, &key, &freq, &pos) 36 | if err == io.EOF { 37 | break 38 | } 39 | if _, ok := added[string(key)]; !ok { 40 | dict = append(dict, item{[]byte(key), freq}) 41 | added[string(key)] = struct{}{} 42 | } 43 | } 44 | } 45 | 46 | func TestLargeDict(t *testing.T) { 47 | loadDict() 48 | size := len(dict) 49 | log.Println("dict size:", size) 50 | 51 | exist := func(i int) { 52 | item := dict[i] 53 | // fmt.Println(i, string(item.key)) 54 | id, err := trie.Jump(item.key, 0) 55 | failIfError(err) 56 | key, err := trie.Key(id) 57 | failIfError(err) 58 | value, err := trie.Value(id) 59 | failIfError(err) 60 | if string(key) != string(item.key) || value != item.value { 61 | v, _ := trie.Get(item.key) 62 | fmt.Println(i, string(key), string(item.key), value, item.value, v) 63 | panic("large dict test fail: no equal") 64 | } 65 | } 66 | notExist := func(i int) { 67 | _, err := trie.Get(dict[i].key) 68 | // fmt.Println(i, err) 69 | if err != ErrNoPath && err != ErrNoValue { 70 | panic("large dict test fail: should not exist") 71 | } 72 | } 73 | checkSize := func(exp int) { 74 | if keys, _, _, _ := trie.Status(); keys != exp { 75 | panic("not correct status") 76 | } 77 | } 78 | 79 | // Insert the first half of the dict. 80 | for i := 0; i < size/2; i++ { 81 | item := dict[i] 82 | if i%2 == 0 { 83 | if err := trie.Insert(item.key, item.value); err != nil { 84 | panic(err) 85 | } 86 | } else { 87 | if err := trie.Update(item.key, item.value); err != nil { 88 | panic(err) 89 | } 90 | } 91 | } 92 | checkSize(size / 2) 93 | 94 | // Check the first half of the dict. 95 | for i := 0; i < size/2; i++ { 96 | exist(i) 97 | } 98 | log.Println("first half OK") 99 | 100 | // Delete even items in the first half. 101 | for i := 0; i < size/2; i += 2 { 102 | err := trie.Delete(dict[i].key) 103 | failIfError(err) 104 | } 105 | checkSize(size / 2 / 2) 106 | 107 | // Make sure even items were deleted, and the rest are fine. 108 | for i := 0; i < size/2; i++ { 109 | if i%2 == 0 { 110 | notExist(i) 111 | } else { 112 | exist(i) 113 | } 114 | } 115 | log.Println("first half odd OK") 116 | 117 | // Insert the second half of the dict. 118 | for i := size / 2; i < size; i++ { 119 | item := dict[i] 120 | trie.Insert(item.key, item.value) 121 | } 122 | checkSize(size/2/2 + (size - size/2)) 123 | 124 | for i := 0; i < size/2; i++ { 125 | if i%2 == 0 { 126 | notExist(i) 127 | } else { 128 | exist(i) 129 | } 130 | } 131 | log.Println("first half odd still OK") 132 | 133 | // Delete even items in the second half. 134 | half := size / 2 135 | if half%2 == 1 { 136 | half++ 137 | } 138 | for i := half; i < size; i += 2 { 139 | err := trie.Delete(dict[i].key) 140 | failIfError(err) 141 | } 142 | // Make sure even items were deleted, and the rest are fine. 143 | for i := 0; i < size; i++ { 144 | if i%2 == 0 { 145 | notExist(i) 146 | } else { 147 | exist(i) 148 | } 149 | } 150 | log.Println("odd OK") 151 | 152 | // Insert all even terms. 153 | for i := 0; i < size; i += 2 { 154 | item := dict[i] 155 | notExist(i) 156 | trie.Update([]byte(item.key), item.value) 157 | } 158 | for i := 0; i < size; i += 1 { 159 | exist(i) 160 | } 161 | log.Println("all OK") 162 | 163 | // Insert every item again, should be fine. 164 | for i := 1; i < size; i++ { 165 | item := dict[i] 166 | trie.Insert([]byte(item.key), item.value) 167 | } 168 | for i := 1; i < size; i += 2 { 169 | exist(i) 170 | } 171 | log.Println("still OK") 172 | } 173 | 174 | func failIfError(err error) { 175 | if err != nil { 176 | panic(err) 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package cedar-go implements double-array trie. 2 | // 3 | // It is a golang port of cedar (http://www.tkl.iis.u-tokyo.ac.jp/~ynaga/cedar) which is written in C++ by Naoki Yoshinaga. 4 | // Currently cedar-go implements the `reduced` verion of cedar. 5 | // This package is not thread safe if there is one goroutine doing 6 | // insertions or deletions. 7 | // 8 | // Note 9 | // 10 | // key must be `[]byte` without zero items, 11 | // while value must be integer in the range [0, 2<<63-2] or [0, 2<<31-2] depends on the platform. 12 | package cedar 13 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrInvalidDataType = errors.New("cedar: invalid datatype") 7 | ErrInvalidValue = errors.New("cedar: invalid value") 8 | ErrInvalidKey = errors.New("cedar: invalid key") 9 | ErrNoPath = errors.New("cedar: no path") 10 | ErrNoValue = errors.New("cedar: no value") 11 | ) 12 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package cedar_test 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/adamzy/cedar-go" 7 | ) 8 | 9 | var trie *cedar.Cedar 10 | 11 | func Example() { 12 | trie = cedar.New() 13 | 14 | // Insert key-value pairs. 15 | // The order of insertion is not important. 16 | trie.Insert([]byte("How many"), 0) 17 | trie.Insert([]byte("How many loved"), 1) 18 | trie.Insert([]byte("How many loved your moments"), 2) 19 | trie.Insert([]byte("How many loved your moments of glad grace"), 3) 20 | trie.Insert([]byte("姑苏"), 4) 21 | trie.Insert([]byte("姑苏城外"), 5) 22 | trie.Insert([]byte("姑苏城外寒山寺"), 6) 23 | 24 | // Get the associated value of a key directly. 25 | value, _ := trie.Get([]byte("How many loved your moments of glad grace")) 26 | fmt.Println(value) 27 | 28 | // Or, use `jump` to get the id of the trie node fist, 29 | id, _ := trie.Jump([]byte("How many loved your moments"), 0) 30 | // then get the key and the value. 31 | key, _ := trie.Key(id) 32 | value, _ = trie.Value(id) 33 | fmt.Printf("%d\t%s:%v\n", id, key, value) 34 | 35 | // Output: 36 | // 3 37 | // 281 How many loved your moments:2 38 | } 39 | 40 | func Example_prefixMatch() { 41 | fmt.Println("id\tkey:value") 42 | for _, id := range trie.PrefixMatch([]byte("How many loved your moments of glad grace"), 0) { 43 | key, _ := trie.Key(id) 44 | value, _ := trie.Value(id) 45 | fmt.Printf("%d\t%s:%v\n", id, key, value) 46 | } 47 | // Output: 48 | // id key:value 49 | // 262 How many:0 50 | // 268 How many loved:1 51 | // 281 How many loved your moments:2 52 | // 296 How many loved your moments of glad grace:3 53 | } 54 | 55 | func Example_prefixPredict() { 56 | fmt.Println("id\tkey:value") 57 | for _, id := range trie.PrefixPredict([]byte("姑苏"), 0) { 58 | key, _ := trie.Key(id) 59 | value, _ := trie.Value(id) 60 | fmt.Printf("%d\t%s:%v\n", id, key, value) 61 | } 62 | // Output: 63 | // id key:value 64 | // 303 姑苏:4 65 | // 309 姑苏城外:5 66 | // 318 姑苏城外寒山寺:6 67 | } 68 | 69 | func Example_saveAndLoad() { 70 | trie.SaveToFile("cedar.gob", "gob") 71 | trie.SaveToFile("cedar.json", "json") 72 | 73 | trie.LoadFromFile("cedar.gob", "gob") 74 | trie.LoadFromFile("cedar.json", "json") 75 | } 76 | -------------------------------------------------------------------------------- /io.go: -------------------------------------------------------------------------------- 1 | package cedar 2 | 3 | import ( 4 | "bufio" 5 | "encoding/gob" 6 | "encoding/json" 7 | "io" 8 | "os" 9 | ) 10 | 11 | // Save saves the cedar to an io.Writer, 12 | // where dataType is either "json" or "gob". 13 | func (da *Cedar) Save(out io.Writer, dataType string) error { 14 | switch dataType { 15 | case "gob", "GOB": 16 | dataEecoder := gob.NewEncoder(out) 17 | return dataEecoder.Encode(da.cedar) 18 | case "json", "JSON": 19 | dataEecoder := json.NewEncoder(out) 20 | return dataEecoder.Encode(da.cedar) 21 | } 22 | return ErrInvalidDataType 23 | } 24 | 25 | // SaveToFile saves the cedar to a file, 26 | // where dataType is either "json" or "gob". 27 | func (da *Cedar) SaveToFile(fileName string, dataType string) error { 28 | file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0666) 29 | if err != nil { 30 | return err 31 | } 32 | defer file.Close() 33 | out := bufio.NewWriter(file) 34 | defer out.Flush() 35 | da.Save(out, dataType) 36 | return nil 37 | } 38 | 39 | // Load loads the cedar from an io.Writer, 40 | // where dataType is either "json" or "gob". 41 | func (da *Cedar) Load(in io.Reader, dataType string) error { 42 | switch dataType { 43 | case "gob", "GOB": 44 | dataDecoder := gob.NewDecoder(in) 45 | return dataDecoder.Decode(da.cedar) 46 | case "json", "JSON": 47 | dataDecoder := json.NewDecoder(in) 48 | return dataDecoder.Decode(da.cedar) 49 | } 50 | return ErrInvalidDataType 51 | } 52 | 53 | // LoadFromFile loads the cedar from a file, 54 | // where dataType is either "json" or "gob". 55 | func (da *Cedar) LoadFromFile(fileName string, dataType string) error { 56 | file, err := os.OpenFile(fileName, os.O_RDONLY, 0600) 57 | defer file.Close() 58 | if err != nil { 59 | return err 60 | } 61 | in := bufio.NewReader(file) 62 | return da.Load(in, dataType) 63 | } 64 | -------------------------------------------------------------------------------- /testdata/README.md: -------------------------------------------------------------------------------- 1 | This test dictionry is taken from [jieba](https://github.com/fxsjy/jieba). 2 | --------------------------------------------------------------------------------