├── AUTHORS ├── CHANGES ├── CMakeLists.txt ├── LICENSE ├── README.md ├── THIRD-PARTY-NOTICES ├── VERSION ├── bsc-m03.cpp ├── common ├── LICENSE ├── platform.h └── rangecoder.h ├── hutucker ├── LICENSE ├── README ├── example.c ├── hu-tucker.c └── hu-tucker.h ├── libsais ├── CHANGES ├── LICENSE ├── VERSION ├── libsais.c ├── libsais.h ├── libsais16.c └── libsais16.h ├── m03_model.h ├── m03_parser.h ├── m03_tables.h └── ska_sort └── ska_sort.hpp /AUTHORS: -------------------------------------------------------------------------------- 1 | -- Authors of bsc-m03 2 | 3 | Ilya Grebnov 4 | 5 | -- This program is based on (at least) the work of 6 | 7 | Michael Maniscalco, Atsushi Komiya, Pochang Chen, 8 | Surya Kandau, Malte Skarupke, Danny Dube, Vincent Beaudoin, 9 | Takahiro Ota, Hiroyoshi Morita and Akiko Manada. 10 | 11 | 12 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | * 2023-05-08 : Version 0.5.5 2 | * Fixed segmentation fault on Unix based systems. 3 | 4 | * 2022-11-27 : Version 0.5.0 5 | * Compression ratio improvements. 6 | 7 | * 2022-11-20 : Version 0.4.0 8 | * Compression ratio improvements. 9 | 10 | * 2022-11-10 : Version 0.3.0 11 | * Compression ratio improvements. 12 | 13 | * 2022-01-08 : Version 0.2.1 14 | * Performance improvements. 15 | 16 | * 2022-01-05 : Version 0.2 17 | * Memory usage improvements. 18 | * Compression ratio improvements. 19 | 20 | * 2021-12-07 : Version 0.1.1 - 0.1.2 21 | * Minor compression ratio improvements. 22 | 23 | * 2021-12-03 : Version 0.1.0 24 | * Initial public release of the bsc-m03. 25 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 3.9) 2 | 3 | project ("bsc-m03") 4 | 5 | add_executable (bsc-m03 bsc-m03.cpp hutucker/hu-tucker.c libsais/libsais.c libsais/libsais16.c) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bsc-m03 2 | 3 | The bsc-m03 is experimental block sorting compressor based on M03 context aware compression algorithm invented by Michael Maniscalco: 4 | * Michael Maniscalco *M03: A solution for context based blocksort (BWT) compression*, 2004 5 | * Jurgen Abel *Post BWT stages of the Burrows-Wheeler compression algorithm*, 2010 6 | 7 | Moreover, the bsc-m03 compressor is a practical implementation of *Compression via Substring Enumeration* for byte-oriented sources: 8 | * Danny Dube, Vincent Beaudoin *Lossless Data Compression via Substring Enumeration*, 2010 9 | * Takahiro Ota, Hiroyoshi Morita, Akiko Manada *Compression by Substring Enumeration with a Finite Alphabet Using Sorting*, 2018 10 | 11 | Copyright (c) 2021-2024 Ilya Grebnov 12 | 13 | ## License 14 | The bsc-m03 is released under the [GNU General Public License](LICENSE "GNU General Public License") 15 | 16 | ## Changes 17 | * 2023-05-08 : Version 0.5.5 18 | * Fixed segmentation fault on Unix based systems. 19 | * 2022-11-27 : Version 0.5.0 20 | * Compression ratio improvements. 21 | * 2022-11-20 : Version 0.4.0 22 | * Compression ratio improvements. 23 | * 2022-11-10 : Version 0.3.0 24 | * Compression ratio improvements. 25 | * 2022-01-08 : Version 0.2.1 26 | * Performance improvements. 27 | * 2022-01-05 : Version 0.2 28 | * Memory usage improvements. 29 | * Compression ratio improvements. 30 | * 2021-12-07 : Version 0.1.1 - 0.1.2 31 | * Minor compression ratio improvements. 32 | * 2021-12-03 : Version 0.1.0 33 | * Initial public release of the bsc-m03. 34 | 35 | # Benchmarks 36 | 37 | ### Calgary Corpus ### 38 | | File name | Input size (bytes) | Output size (bytes) | Bits per symbol | 39 | |:---------------:|:-----------:|:------------:|:-------:| 40 | | bib | 111261 | 24479 | 1.760 | 41 | | book1 | 768771 | 203745 | 2.120 | 42 | | book2 | 610856 | 138870 | 1.819 | 43 | | geo | 102400 | 52465 | 4.099 | 44 | | news | 377109 | 105621 | 2.241 | 45 | | obj1 | 21504 | 9775 | 3.637 | 46 | | obj2 | 246814 | 68003 | 2.204 | 47 | | paper1 | 53161 | 14957 | 2.251 | 48 | | paper2 | 82199 | 22594 | 2.199 | 49 | | pic | 513216 | 44424 | 0.692 | 50 | | progc | 39611 | 11257 | 2.274 | 51 | | progl | 71646 | 13512 | 1.509 | 52 | | progp | 49379 | 9248 | 1.498 | 53 | | trans | 93695 | 15310 | 1.307 | 54 | 55 | ### Canterbury Corpus ### 56 | | File name | Input size (bytes) | Output size (bytes) | Bits per symbol | 57 | |:---------------:|:-----------:|:------------:|:-------:| 58 | | alice29.txt | 152089 | 38562 | 2.028 | 59 | | asyoulik.txt | 125179 | 35889 | 2.294 | 60 | | cp.html | 24603 | 6872 | 2.235 | 61 | | fields.c | 11150 | 2685 | 1.926 | 62 | | grammar.lsp | 3721 | 1120 | 2.408 | 63 | | kennedy.xls | 1029744 | 57440 | 0.446 | 64 | | lcet10.txt | 426754 | 94823 | 1.778 | 65 | | plrabn12.txt | 481861 | 129770 | 2.154 | 66 | | ptt5 | 513216 | 44424 | 0.692 | 67 | | sum | 38240 | 11426 | 2.390 | 68 | | xargs.1 | 4227 | 1585 | 3.000 | 69 | 70 | ### Large Canterbury Corpus ### 71 | | File name | Input size (bytes) | Output size (bytes) | Bits per symbol | 72 | |:---------------:|:-----------:|:------------:|:-------:| 73 | | bible.txt | 4047392 | 698395 | 1.380 | 74 | | E.coli | 4638690 | 1126125 | 1.942 | 75 | | world192.txt | 2473400 | 376173 | 1.217 | 76 | 77 | ### Silesia Corpus ### 78 | | File name | Input size (bytes) | Output size (bytes) | Bits per symbol | 79 | |:---------------:|:-----------:|:------------:|:-------:| 80 | | dickens | 10192446 | 2199344 | 1.726 | 81 | | mozilla | 51220480 | 15589159 | 2.435 | 82 | | mr | 9970564 | 2156826 | 1.731 | 83 | | nci | 33553445 | 1126386 | 0.269 | 84 | | ooffice | 6152192 | 2503991 | 3.256 | 85 | | osdb | 10085684 | 2223002 | 1.763 | 86 | | reymont | 6627202 | 958772 | 1.157 | 87 | | samba | 21606400 | 3794300 | 1.405 | 88 | | sao | 7251944 | 4649723 | 5.129 | 89 | | webster | 41458703 | 6253627 | 1.207 | 90 | | xml | 5345280 | 357958 | 0.536 | 91 | | x-ray | 8474240 | 3681388 | 3.475 | 92 | 93 | ### Manzini Corpus ### 94 | | File name | Input size (bytes) | Output size (bytes) | Bits per symbol | 95 | |:---------------:|:-----------:|:------------:|:-------:| 96 | | chr22.dna | 34553758 | 7206269 | 1.668 | 97 | | etext99 | 105277340 | 21422251 | 1.628 | 98 | | gcc-3.0.tar | 86630400 | 10046880 | 0.928 | 99 | | howto | 39422105 | 7504315 | 1.523 | 100 | | jdk13c | 69728899 | 2612434 | 0.300 | 101 | | linux-2.4.5.tar | 116254720 | 16351863 | 1.125 | 102 | | rctail96 | 114711151 | 9707347 | 0.677 | 103 | | rfc | 116421901 | 14871775 | 1.022 | 104 | | sprot34.dat | 109617186 | 17157222 | 1.252 | 105 | | w3c2 | 104201579 | 5598687 | 0.430 | 106 | 107 | ### Maximum Compression Corpus ### 108 | | File name | Input size (bytes) | Output size (bytes) | Bits per symbol | 109 | |:---------------:|:-----------:|:------------:|:-------:| 110 | | A10.jpg | 842468 | 823533 | 7.820 | 111 | | AcroRd32.exe | 3870784 | 1555832 | 3.216 | 112 | | english.dic | 465211 | 145096 | 2.495 | 113 | | FlashMX.pdf | 4526946 | 3712716 | 6.561 | 114 | | FP.LOG | 20617071 | 502648 | 0.195 | 115 | | MSO97.DLL | 3782416 | 1878076 | 3.972 | 116 | | ohs.doc | 4168192 | 803171 | 1.542 | 117 | | rafale.bmp | 4149414 | 745470 | 1.437 | 118 | | vcfiu.hlp | 4121418 | 604165 | 1.173 | 119 | | world95.txt | 2988578 | 442271 | 1.184 | 120 | 121 | ### Large Text Compression Benchmark Corpus ### 122 | | File name | Input size (bytes) | Output size (bytes) | Bits per symbol | 123 | |:---------------:|:-----------:|:------------:|:-------:| 124 | | enwik8 | 100000000 | 20263925 | 1.621 | 125 | | enwik9 | 1000000000 | 160018905 | 1.280 | 126 | 127 | ### Pizza & Chilli Corpus ### 128 | | File name | Input size (bytes) | Output size (bytes) | Bits per symbol | 129 | |:---------------:|:-----------:|:------------:|:-------:| 130 | | dblp.xml | 296135874 | 21926695 | 0.592 | 131 | | dna | 403927746 | 86414423 | 1.711 | 132 | | english.1024MB | 1073741824 | 193810792 | 1.444 | 133 | | pitches | 55832855 | 16984071 | 2.434 | 134 | | proteins | 1184051855 | 304486803 | 2.057 | 135 | | sources | 210866607 | 29749020 | 1.129 | 136 | 137 | ### Pizza & Chilli Repetitive Corpus ### 138 | | File name | Input size (bytes) | Output size (bytes) | Bits per symbol | 139 | |:---------------:|:-----------:|:------------:|:-------:| 140 | | cere | 461286644 | 8576879 | 0.149 | 141 | | coreutils | 205281778 | 4293243 | 0.167 | 142 | | einstein.de.txt | 92758441 | 132286 | 0.011 | 143 | | einstein.en.txt | 467626544 | 336029 | 0.006 | 144 | | Escherichia_Coli | 112689515 | 7928044 | 0.563 | 145 | | influenza | 154808555 | 1760692 | 0.091 | 146 | | kernel | 257961616 | 2955825 | 0.092 | 147 | | para | 429265758 | 10730998 | 0.200 | 148 | | world_leaders | 46968181 | 518220 | 0.088 | 149 | | fib41 | 267914296 | 83 | 0.000 | 150 | | rs.13 | 216747218 | 86 | 0.000 | 151 | | tm29 | 268435456 | 158 | 0.000 | 152 | -------------------------------------------------------------------------------- /THIRD-PARTY-NOTICES: -------------------------------------------------------------------------------- 1 | The bsc-m03 uses third-party libraries or other resources that may 2 | be distributed under licenses different than the bsc-m03 software. 3 | 4 | The attached notices are provided for information only. 5 | 6 | License notice for 'libbsc' library 7 | ----------------------------------- 8 | 9 | Copyright (c) 2009-2021 Ilya Grebnov 10 | 11 | Licensed under the Apache License, Version 2.0 (the "License"); 12 | you may not use this file except in compliance with the License. 13 | You may obtain a copy of the License at 14 | 15 | http://www.apache.org/licenses/LICENSE-2.0 16 | 17 | Unless required by applicable law or agreed to in writing, software 18 | distributed under the License is distributed on an "AS IS" BASIS, 19 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | See the License for the specific language governing permissions and 21 | limitations under the License. 22 | 23 | License notice for 'hutucker' library 24 | ------------------------------------- 25 | 26 | /* 27 | * Linearithmic Hu-Tucker Coding. 28 | * Copyright (C) 2018 Pochang Chen 29 | * 30 | * This program is free software: you can redistribute it and/or modify 31 | * it under the terms of the GNU General Public License as published by 32 | * the Free Software Foundation, either version 3 of the License, or 33 | * (at your option) any later version. 34 | * 35 | * This program is distributed in the hope that it will be useful, 36 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 37 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 38 | * GNU General Public License for more details. 39 | * 40 | * You should have received a copy of the GNU General Public License 41 | * along with this program. If not, see . 42 | */ 43 | 44 | License notice for 'libsais' library 45 | ------------------------------------ 46 | 47 | Copyright (c) 2021-2022 Ilya Grebnov 48 | 49 | Licensed under the Apache License, Version 2.0 (the "License"); 50 | you may not use this file except in compliance with the License. 51 | You may obtain a copy of the License at 52 | 53 | http://www.apache.org/licenses/LICENSE-2.0 54 | 55 | Unless required by applicable law or agreed to in writing, software 56 | distributed under the License is distributed on an "AS IS" BASIS, 57 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 58 | See the License for the specific language governing permissions and 59 | limitations under the License. 60 | 61 | License notice for 'ska_sort' library 62 | ------------------------------------- 63 | 64 | // Copyright Malte Skarupke 2016. 65 | // Distributed under the Boost Software License, Version 1.0. 66 | // (See http://www.boost.org/LICENSE_1_0.txt) 67 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 0.5.5 -------------------------------------------------------------------------------- /bsc-m03.cpp: -------------------------------------------------------------------------------- 1 | /*-- 2 | 3 | This file is a part of bsc-m03 project. 4 | 5 | Copyright (c) 2021-2024 Ilya Grebnov 6 | 7 | bsc-m03 is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | bsc-m03 is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with bsc-m03. If not, see . 19 | 20 | --*/ 21 | 22 | #define _CRT_SECURE_NO_WARNINGS 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | #include 31 | 32 | #include "libsais/libsais.h" 33 | #include "libsais/libsais16.h" 34 | 35 | #include "common/platform.h" 36 | #include "common/rangecoder.h" 37 | 38 | #define MAX_ALPHABET_SIZE (256 * 256) 39 | 40 | #include "m03_parser.h" 41 | 42 | #pragma warning( push ) 43 | #pragma warning( disable : 6385 ) 44 | #pragma warning( disable : 6386 ) 45 | 46 | int32_t root_frequencies[MAX_ALPHABET_SIZE + 1]; 47 | 48 | #if !defined(BSC_DECOMPRESSION_ONLY) 49 | 50 | template static int32_t compress_memory_block(uint8_t * buffer, int32_t block_size) 51 | { 52 | int32_t indexes[32] = { -1 }; 53 | int32_t compressed_size = -1; 54 | int32_t symbol_size = (int32_t)sizeof(symbol_t); 55 | int32_t block_symbols = block_size / symbol_size; 56 | int32_t r = next_power_of_2(std::max(block_symbols / 16, 1048576)); 57 | 58 | if (block_size % symbol_size != 0) 59 | { 60 | fprintf(stderr, "\nError: Block size of %d bytes is not a multiple of symbol width!\n", block_size); 61 | return -2; 62 | } 63 | 64 | if (int32_t * libsais_temp = (int32_t *)malloc(block_symbols * sizeof(int32_t))) 65 | { 66 | int32_t result = symbol_size == 1 67 | ? libsais_bwt_aux(buffer, buffer, libsais_temp, block_symbols, 0, root_frequencies, r, indexes) 68 | : libsais16_bwt_aux((uint16_t *)buffer, (uint16_t *)buffer, libsais_temp, block_symbols, 0, root_frequencies, r, indexes); 69 | 70 | free(libsais_temp); 71 | 72 | if (result == 0) 73 | { 74 | if (symbol_t * L = (symbol_t *)malloc(((size_t)block_symbols + 1) * sizeof(symbol_t))) 75 | { 76 | if (m03_parser * parser = (m03_parser *)malloc(sizeof(m03_parser))) 77 | { 78 | { 79 | int32_t primary_index = indexes[0]; 80 | 81 | memcpy(&L[0] , &((symbol_t *)buffer)[0] , primary_index * sizeof(symbol_t)); 82 | memcpy(&L[primary_index + 1], &((symbol_t *)buffer)[primary_index], ((size_t)block_symbols - (size_t)primary_index) * sizeof(symbol_t)); 83 | 84 | L[primary_index] = 0; 85 | } 86 | 87 | RangeCoder coder; 88 | coder.InitEncoder(buffer, block_size); 89 | coder.EncodeValue(1, symbol_size, 2); 90 | 91 | for (int32_t t = 0; t <= (block_symbols - 1) / r; ++t) 92 | { 93 | coder.EncodeValue(1, indexes[t], block_symbols); 94 | } 95 | 96 | if (parser->initialize(L, block_symbols + 1, indexes[0], root_frequencies, 1 << (8 * symbol_size), &coder)) 97 | { 98 | parser->run(); 99 | parser->destroy(); 100 | 101 | compressed_size = coder.FinishEncoder(); 102 | } 103 | else 104 | { 105 | fprintf(stderr, "\nError: Not enough memory!\n"); 106 | } 107 | 108 | free(parser); 109 | } 110 | else 111 | { 112 | fprintf(stderr, "\nError: Not enough memory!\n"); 113 | } 114 | 115 | if (compressed_size >= block_size) 116 | { 117 | compressed_size = -1; 118 | 119 | if (int32_t * libsais_temp = (int32_t *)malloc(((size_t)block_symbols + 1) * sizeof(int32_t))) 120 | { 121 | { 122 | int32_t primary_index = indexes[0]; 123 | 124 | memcpy(&((symbol_t *)buffer)[0] , &L[0] , primary_index * sizeof(symbol_t)); 125 | memcpy(&((symbol_t *)buffer)[primary_index], &L[primary_index + 1], ((size_t)block_symbols - (size_t)primary_index) * sizeof(symbol_t)); 126 | } 127 | 128 | result = symbol_size == 1 129 | ? libsais_unbwt_aux((uint8_t *)buffer, (uint8_t *)buffer, libsais_temp, block_symbols, root_frequencies, r, indexes) 130 | : libsais16_unbwt_aux((uint16_t *)buffer, (uint16_t *)buffer, libsais_temp, block_symbols, root_frequencies, r, indexes); 131 | 132 | if (result == 0) 133 | { 134 | compressed_size = block_size; 135 | } 136 | else 137 | { 138 | fprintf(stderr, "\nError: libsais_unbwt failed, please contact the author!\n"); 139 | } 140 | 141 | free(libsais_temp); 142 | } 143 | else 144 | { 145 | fprintf(stderr, "\nError: Not enough memory!\n"); 146 | } 147 | } 148 | 149 | free(L); 150 | } 151 | else 152 | { 153 | fprintf(stderr, "\nError: Not enough memory!\n"); 154 | } 155 | } 156 | else 157 | { 158 | fprintf(stderr, "\nError: libsais_bwt failed, please contact the author!\n"); 159 | } 160 | } 161 | else 162 | { 163 | fprintf(stderr, "\nError: Not enough memory!\n"); 164 | } 165 | 166 | return compressed_size; 167 | } 168 | 169 | #endif 170 | 171 | template static int32_t decompress_burrows_wheeler_transform(RangeCoder * coder, int32_t primary_index, int32_t block_symbols, uint8_t * buffer) 172 | { 173 | int32_t result = -1; 174 | int32_t symbol_size = (int32_t)sizeof(symbol_t); 175 | 176 | if (symbol_t * L = (symbol_t *)malloc(((size_t)block_symbols + 1) * sizeof(symbol_t))) 177 | { 178 | if (m03_parser * parser = (m03_parser *)malloc(sizeof(m03_parser))) 179 | { 180 | if (parser->initialize(L, block_symbols + 1, primary_index, root_frequencies, 1 << (8 * symbol_size), coder)) 181 | { 182 | parser->run(); 183 | parser->destroy(); 184 | 185 | { 186 | memcpy(&((symbol_t *)buffer)[0] , &L[0] , primary_index * sizeof(symbol_t)); 187 | memcpy(&((symbol_t *)buffer)[primary_index], &L[primary_index + 1], ((size_t)block_symbols - (size_t)primary_index) * sizeof(symbol_t)); 188 | 189 | result = 0; 190 | } 191 | } 192 | else 193 | { 194 | fprintf(stderr, "\nError: Not enough memory!\n"); 195 | } 196 | 197 | free(parser); 198 | } 199 | else 200 | { 201 | fprintf(stderr, "\nError: Not enough memory!\n"); 202 | } 203 | 204 | free(L); 205 | } 206 | else 207 | { 208 | fprintf(stderr, "\nError: Not enough memory!\n"); 209 | } 210 | 211 | return result; 212 | } 213 | 214 | static int32_t decompress_memory_block(uint8_t * buffer, int32_t compressed_size, int32_t block_size) 215 | { 216 | RangeCoder coder; 217 | coder.InitDecoder(buffer); 218 | 219 | int32_t indexes[32] = { -1 }; 220 | int32_t decompressed_size = -1; 221 | int32_t symbol_size = coder.DecodeValue(1, 2); 222 | int32_t block_symbols = block_size / symbol_size; 223 | int32_t r = next_power_of_2(std::max(block_symbols / 16, 1048576)); 224 | 225 | for (int32_t t = 0; t <= (block_symbols - 1) / r; ++t) 226 | { 227 | indexes[t] = coder.DecodeValue(1, block_symbols); 228 | } 229 | 230 | int32_t result = symbol_size == 1 231 | ? decompress_burrows_wheeler_transform (&coder, indexes[0], block_symbols, buffer) 232 | : decompress_burrows_wheeler_transform(&coder, indexes[0], block_symbols, buffer); 233 | 234 | if (result == 0) 235 | { 236 | if (int32_t * libsais_temp = (int32_t *)malloc(((size_t)block_symbols + 1) * sizeof(int32_t))) 237 | { 238 | result = symbol_size == 1 239 | ? libsais_unbwt_aux(buffer, buffer, libsais_temp, block_symbols, root_frequencies, r, indexes) 240 | : libsais16_unbwt_aux((uint16_t *)buffer, (uint16_t *)buffer, libsais_temp, block_symbols, root_frequencies, r, indexes); 241 | 242 | if (result == 0) 243 | { 244 | decompressed_size = block_size; 245 | } 246 | else 247 | { 248 | fprintf(stderr, "\nError: libsais_unbwt failed, please contact the author!\n"); 249 | } 250 | 251 | free(libsais_temp); 252 | } 253 | else 254 | { 255 | fprintf(stderr, "\nError: Not enough memory!\n"); 256 | } 257 | } 258 | 259 | return decompressed_size; 260 | } 261 | 262 | #if !defined(BSC_DECOMPRESSION_ONLY) 263 | 264 | static int compress_file(const char * input_file_name, const char * output_file_name, int32_t max_block_size, int32_t symbol_size) 265 | { 266 | clock_t start_time = clock(); 267 | if (FILE * input_file = fopen(input_file_name, "rb")) 268 | { 269 | if (FILE * output_file = fopen(output_file_name, "wb")) 270 | { 271 | fseeko(input_file, 0, SEEK_END); int64_t remaining_size = ftello(input_file); rewind(input_file); 272 | 273 | int64_t buffer_size = std::min(remaining_size, (int64_t)max_block_size) + 16384; buffer_size += buffer_size / 16; 274 | 275 | if (uint8_t * buffer = (uint8_t *)malloc(buffer_size * sizeof(uint8_t))) 276 | { 277 | int64_t input_bytes = 0, output_bytes = 0; 278 | 279 | while (remaining_size > 0) 280 | { 281 | fprintf(stdout, "\rCompressing %.55s(%02d%%)", input_file_name, (int)((input_bytes * 100) / (input_bytes + remaining_size))); fflush(stdout); 282 | 283 | int32_t block_size = (int32_t)std::min(remaining_size, (int64_t)max_block_size); 284 | 285 | if (fread(buffer, sizeof(uint8_t), block_size, input_file) != block_size) 286 | { 287 | fprintf(stderr, "\nError: Unable to read input file!\n"); 288 | break; 289 | } 290 | 291 | int32_t compressed_size = symbol_size == 1 292 | ? compress_memory_block (buffer, block_size) 293 | : compress_memory_block(buffer, block_size); 294 | 295 | if (compressed_size <= 0 || compressed_size > block_size) 296 | { 297 | fprintf(stderr, "\nError: compression failed, please contact the author!\n"); 298 | break; 299 | } 300 | 301 | if (fwrite(&block_size, sizeof(uint8_t), sizeof(block_size), output_file) != sizeof(block_size)) 302 | { 303 | fprintf(stderr, "\nError: Unable to write output file!\n"); 304 | break; 305 | } 306 | 307 | if (fwrite(&compressed_size, sizeof(uint8_t), sizeof(compressed_size), output_file) != sizeof(compressed_size)) 308 | { 309 | fprintf(stderr, "\nError: Unable to write output file!\n"); 310 | break; 311 | } 312 | 313 | if (fwrite(buffer, sizeof(uint8_t), compressed_size, output_file) != compressed_size) 314 | { 315 | fprintf(stderr, "\nError: Unable to write output file\n"); 316 | break; 317 | } 318 | 319 | remaining_size -= block_size; 320 | input_bytes += block_size; 321 | output_bytes += sizeof(block_size) + sizeof(compressed_size) + compressed_size; 322 | } 323 | 324 | if (remaining_size == 0) 325 | { 326 | fprintf(stdout, "\r%.55s compressed from %lld into %lld in %.3f seconds (%.3f bps).\n", input_file_name, (long long int)input_bytes, (long long int)output_bytes, ((double)clock() - start_time) / CLOCKS_PER_SEC, (8.0 * symbol_size * output_bytes) / input_bytes); 327 | } 328 | 329 | free(buffer); 330 | } 331 | else 332 | { 333 | fprintf(stderr, "Error: Not enough memory!\n"); 334 | } 335 | 336 | fclose(output_file); 337 | } 338 | else 339 | { 340 | fprintf(stderr, "Error: Unable to open output file!\n"); 341 | } 342 | 343 | fclose(input_file); 344 | } 345 | else 346 | { 347 | fprintf(stderr, "Error: Unable to open input file!\n"); 348 | } 349 | 350 | return 0; 351 | } 352 | 353 | #endif 354 | 355 | static int decompress_file(const char * input_file_name, const char * output_file_name) 356 | { 357 | clock_t start_time = clock(); 358 | if (FILE * input_file = fopen(input_file_name, "rb")) 359 | { 360 | if (FILE * output_file = fopen(output_file_name, "wb")) 361 | { 362 | int32_t max_block_size; 363 | if (fread(&max_block_size, sizeof(uint8_t), sizeof(max_block_size), input_file) == sizeof(max_block_size)) 364 | { 365 | fseeko(input_file, 0, SEEK_END); int64_t remaining_size = ftello(input_file); rewind(input_file); 366 | 367 | if (uint8_t * buffer = (uint8_t *)malloc(max_block_size * sizeof(uint8_t))) 368 | { 369 | int64_t input_bytes = 0, output_bytes = 0; 370 | 371 | while (remaining_size > 0) 372 | { 373 | fprintf(stdout, "\rDecompressing %.55s(%02d%%)", input_file_name, (int)((input_bytes * 100) / (input_bytes + remaining_size))); fflush(stdout); 374 | 375 | int32_t block_size, compressed_size; 376 | if (fread(&block_size, sizeof(uint8_t), sizeof(block_size), input_file) != sizeof(block_size)) 377 | { 378 | fprintf(stderr, "\nError: Unable to read input file!\n"); 379 | break; 380 | } 381 | 382 | if (fread(&compressed_size, sizeof(uint8_t), sizeof(compressed_size), input_file) != sizeof(compressed_size)) 383 | { 384 | fprintf(stderr, "\nError: Unable to read input file!\n"); 385 | break; 386 | } 387 | 388 | if (block_size > max_block_size || compressed_size > block_size) 389 | { 390 | fprintf(stderr, "\nError: The compressed data is corrupted!\n"); 391 | break; 392 | } 393 | 394 | if (fread(buffer, sizeof(uint8_t), compressed_size, input_file) != compressed_size) 395 | { 396 | fprintf(stderr, "\nError: Unable to read input file!\n"); 397 | break; 398 | } 399 | 400 | int32_t decompressed_size = compressed_size < block_size 401 | ? decompress_memory_block(buffer, compressed_size, block_size) 402 | : block_size; 403 | 404 | if (decompressed_size != block_size) 405 | { 406 | fprintf(stderr, "\nError: The compressed data is corrupted!\n"); 407 | break; 408 | } 409 | 410 | if (fwrite(buffer, sizeof(uint8_t), decompressed_size, output_file) != decompressed_size) 411 | { 412 | fprintf(stderr, "\nError: Unable to write output file\n"); 413 | break; 414 | } 415 | 416 | remaining_size -= sizeof(block_size) + sizeof(compressed_size) + compressed_size; 417 | input_bytes += sizeof(block_size) + sizeof(compressed_size) + compressed_size; 418 | output_bytes += decompressed_size; 419 | } 420 | 421 | if (remaining_size == 0) 422 | { 423 | fprintf(stdout, "\r%.55s decompressed from %lld into %lld in %.3f seconds.\n", input_file_name, (long long int)input_bytes, (long long int)output_bytes, ((double)clock() - start_time) / CLOCKS_PER_SEC); 424 | } 425 | 426 | free(buffer); 427 | } 428 | else 429 | { 430 | fprintf(stderr, "Error: Not enough memory!\n"); 431 | } 432 | } 433 | else 434 | { 435 | fprintf(stderr, "Error: Unable to read input file!\n"); 436 | } 437 | 438 | fclose(output_file); 439 | } 440 | else 441 | { 442 | fprintf(stderr, "Error: Unable to open output file!\n"); 443 | } 444 | 445 | fclose(input_file); 446 | } 447 | else 448 | { 449 | fprintf(stderr, "Error: Unable to open input file!\n"); 450 | } 451 | 452 | return 0; 453 | } 454 | 455 | static int print_usage() 456 | { 457 | #if !defined(BSC_DECOMPRESSION_ONLY) 458 | fprintf(stdout, "Usage: bsc-m03 input-file output-file \n"); 459 | fprintf(stdout, " -b Block size in bytes, default 128MB (memory usage is ~13x).\n"); 460 | fprintf(stdout, " -w<8|16> Symbol width in bits.\n"); 461 | #else 462 | fprintf(stdout, "Usage: bsc-m03 d input-file output-file\n"); 463 | #endif 464 | 465 | return 0; 466 | } 467 | 468 | int main(int argc, const char * argv[]) 469 | { 470 | fprintf(stdout, "bsc-m03 is experimental block sorting compressor. Version 0.5.5 (8 May 2024).\n"); 471 | fprintf(stdout, "Copyright (c) 2021-2024 Ilya Grebnov . ABSOLUTELY NO WARRANTY.\n"); 472 | fprintf(stdout, "This program is based on (at least) the work of Michael Maniscalco (see AUTHORS).\n\n"); 473 | 474 | int32_t max_block_size = 128 * 1024 * 1024; 475 | int32_t symbol_width = 8; 476 | 477 | if (argc < 4 || strlen(argv[1]) != 1) 478 | { 479 | return print_usage(); 480 | } 481 | 482 | for (int32_t i = 4; i < argc; ++i) 483 | { 484 | if (argv[i][0] != '-') 485 | { 486 | return print_usage(); 487 | } 488 | 489 | switch (argv[i][1]) 490 | { 491 | case 'b': 492 | { 493 | max_block_size = atoi(argv[i] + 2); 494 | if (max_block_size <= 0 || max_block_size > 2047 * 1024 * 1024) { return print_usage(); } 495 | 496 | break; 497 | } 498 | 499 | case 'w': 500 | { 501 | symbol_width = atoi(argv[i] + 2); 502 | if (symbol_width != 8 && symbol_width != 16) { return print_usage(); } 503 | 504 | break; 505 | } 506 | 507 | default: 508 | { 509 | return print_usage(); 510 | } 511 | } 512 | } 513 | 514 | switch (argv[1][0]) 515 | { 516 | #if !defined(BSC_DECOMPRESSION_ONLY) 517 | case 'c': 518 | case 'C': 519 | case 'e': 520 | case 'E': 521 | { 522 | return compress_file(argv[2], argv[3], max_block_size, symbol_width / 8); 523 | } 524 | #endif 525 | 526 | case 'd': 527 | case 'D': 528 | { 529 | if (argc != 4) { return print_usage(); } 530 | 531 | return decompress_file(argv[2], argv[3]); 532 | } 533 | 534 | default: 535 | { 536 | return print_usage(); 537 | } 538 | } 539 | 540 | return 0; 541 | } 542 | 543 | #pragma warning( pop ) 544 | -------------------------------------------------------------------------------- /common/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /common/platform.h: -------------------------------------------------------------------------------- 1 | /*-----------------------------------------------------------*/ 2 | /* Block Sorting, Lossless Data Compression Library. */ 3 | /* Interface to platform specific functions and constants */ 4 | /*-----------------------------------------------------------*/ 5 | 6 | /*-- 7 | 8 | This file is a part of bsc and/or libbsc, a program and a library for 9 | lossless, block-sorting data compression. 10 | 11 | Copyright (c) 2009-2021 Ilya Grebnov 12 | 13 | Licensed under the Apache License, Version 2.0 (the "License"); 14 | you may not use this file except in compliance with the License. 15 | You may obtain a copy of the License at 16 | 17 | http://www.apache.org/licenses/LICENSE-2.0 18 | 19 | Unless required by applicable law or agreed to in writing, software 20 | distributed under the License is distributed on an "AS IS" BASIS, 21 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | See the License for the specific language governing permissions and 23 | limitations under the License. 24 | 25 | Please see the file LICENSE for full copyright information. 26 | 27 | See also the bsc and libbsc web site: 28 | http://libbsc.com/ for more information. 29 | 30 | --*/ 31 | 32 | /*-- 33 | 34 | NOTICE: This file has been modified for use in the bsc-m03 project. 35 | 36 | --*/ 37 | 38 | #ifndef _LIBBSC_PLATFORM_H 39 | #define _LIBBSC_PLATFORM_H 40 | 41 | #ifdef _MSC_VER 42 | #define fseeko(stream, offset, origin) _fseeki64(stream, offset, origin) 43 | #define ftello(stream) _ftelli64(stream) 44 | #endif 45 | 46 | #if defined(_MSC_VER) 47 | #include 48 | #elif defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) 49 | #include 50 | #endif 51 | 52 | #if defined(__GNUC__) 53 | #define INLINE __inline__ 54 | #elif defined(_MSC_VER) 55 | #define INLINE __forceinline 56 | #elif defined(__IBMC__) 57 | #define INLINE _Inline 58 | #elif defined(__cplusplus) 59 | #define INLINE inline 60 | #else 61 | #define INLINE /* */ 62 | #endif 63 | 64 | #if defined(_MSC_VER) 65 | #define NOINLINE __declspec(noinline) 66 | #elif defined(__GNUC__) 67 | #define NOINLINE __attribute__ ((noinline)) 68 | #else 69 | #define NOINLINE /* */ 70 | #endif 71 | 72 | #if defined(_MSC_VER) 73 | #define ALIGNED(x) __declspec(align(x)) 74 | #elif defined(__GNUC__) 75 | #define ALIGNED(x) __attribute__ ((aligned(x))) 76 | #endif 77 | 78 | #if defined(__GNUC__) || defined(__clang__) || defined(__CUDACC__) 79 | #define RESTRICT __restrict__ 80 | #elif defined(_MSC_VER) || defined(__INTEL_COMPILER) 81 | #define RESTRICT __restrict 82 | #else 83 | #define RESTRICT /* */ 84 | #endif 85 | 86 | #if defined(__GNUC__) || defined(__clang__) 87 | #define byteswap_uint64(x) (__builtin_bswap64(x)) 88 | #define bit_scan_reverse(x) (__builtin_clz(x) ^ 31) 89 | #define bit_scan_forward(x) (__builtin_ctz(x)) 90 | #define bit_scan_forward64(x) (__builtin_ctzll(x)) 91 | #elif defined(_MSC_VER) 92 | #define byteswap_uint64(x) (_byteswap_uint64(x)) 93 | 94 | #pragma intrinsic(_BitScanReverse) 95 | #pragma intrinsic(_BitScanForward) 96 | 97 | static inline __forceinline unsigned long bit_scan_reverse(unsigned long x) 98 | { 99 | unsigned long index; 100 | _BitScanReverse(&index, x); 101 | return index; 102 | } 103 | 104 | static inline __forceinline unsigned long bit_scan_forward(unsigned long x) 105 | { 106 | unsigned long index; 107 | _BitScanForward(&index, x); 108 | return index; 109 | } 110 | #endif 111 | 112 | static INLINE unsigned int next_power_of_2(unsigned int v) 113 | { 114 | v--; 115 | 116 | v |= v >> 1; 117 | v |= v >> 2; 118 | v |= v >> 4; 119 | v |= v >> 8; 120 | v |= v >> 16; 121 | v++; 122 | 123 | return v; 124 | } 125 | 126 | #endif 127 | 128 | /*-----------------------------------------------------------*/ 129 | /* End platform.h */ 130 | /*-----------------------------------------------------------*/ 131 | -------------------------------------------------------------------------------- /common/rangecoder.h: -------------------------------------------------------------------------------- 1 | /*-----------------------------------------------------------*/ 2 | /* Block Sorting, Lossless Data Compression Library. */ 3 | /* Range coder */ 4 | /*-----------------------------------------------------------*/ 5 | 6 | /*-- 7 | 8 | This file is a part of bsc and/or libbsc, a program and a library for 9 | lossless, block-sorting data compression. 10 | 11 | Copyright (c) 2009-2021 Ilya Grebnov 12 | 13 | Licensed under the Apache License, Version 2.0 (the "License"); 14 | you may not use this file except in compliance with the License. 15 | You may obtain a copy of the License at 16 | 17 | http://www.apache.org/licenses/LICENSE-2.0 18 | 19 | Unless required by applicable law or agreed to in writing, software 20 | distributed under the License is distributed on an "AS IS" BASIS, 21 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | See the License for the specific language governing permissions and 23 | limitations under the License. 24 | 25 | Please see the file LICENSE for full copyright information. 26 | 27 | See also the bsc and libbsc web site: 28 | http://libbsc.com/ for more information. 29 | 30 | --*/ 31 | 32 | /*-- 33 | 34 | NOTICE: This file has been modified for use in the bsc-m03 project. 35 | 36 | --*/ 37 | 38 | #ifndef _LIBBSC_CODER_RANGECODER_H 39 | #define _LIBBSC_CODER_RANGECODER_H 40 | 41 | #include "platform.h" 42 | 43 | class RangeCoder 44 | { 45 | 46 | private: 47 | 48 | union ari 49 | { 50 | struct u 51 | { 52 | unsigned int low32; 53 | unsigned int carry; 54 | } u; 55 | unsigned long long low; 56 | } ari; 57 | 58 | unsigned int ari_code; 59 | unsigned int ari_ffnum; 60 | unsigned int ari_cache; 61 | unsigned int ari_range; 62 | 63 | const unsigned char * RESTRICT ari_input; 64 | unsigned char * RESTRICT ari_output; 65 | unsigned char * RESTRICT ari_outputEOB; 66 | unsigned char * RESTRICT ari_outputStart; 67 | 68 | INLINE void OutputByte(unsigned char s) 69 | { 70 | *ari_output++ = s; 71 | }; 72 | 73 | INLINE unsigned char InputByte() 74 | { 75 | return *ari_input++; 76 | }; 77 | 78 | NOINLINE unsigned int ShiftLow() 79 | { 80 | if (ari.u.low32 < 0xff000000U || ari.u.carry) 81 | { 82 | OutputByte(ari_cache + ari.u.carry); 83 | if (ari_ffnum) 84 | { 85 | unsigned char s = ari.u.carry - 1; 86 | do { OutputByte(s); } while (--ari_ffnum); 87 | } 88 | ari_cache = ari.u.low32 >> 24; ari.u.carry = 0; 89 | } 90 | else 91 | { 92 | ari_ffnum++; 93 | } 94 | 95 | ari.u.low32 <<= 8; return ari_range << 8; 96 | } 97 | 98 | public: 99 | 100 | INLINE void InitEncoder(unsigned char * output, int outputSize) 101 | { 102 | ari_outputStart = output; 103 | ari_output = output; 104 | ari_outputEOB = output + outputSize - 16; 105 | ari.low = 0; 106 | ari_ffnum = 0; 107 | ari_cache = 0; 108 | ari_range = 0xffffffff; 109 | }; 110 | 111 | INLINE int FinishEncoder() 112 | { 113 | ShiftLow(); ShiftLow(); ShiftLow(); ShiftLow(); ShiftLow(); 114 | return (int)(ari_output - ari_outputStart); 115 | } 116 | 117 | INLINE void Encode(unsigned int cum_freq, unsigned int sym_freq, unsigned int total_freq) 118 | { 119 | unsigned int range = ari_range / total_freq; 120 | ari.low += (unsigned long long)cum_freq * range; ari_range = sym_freq * range; 121 | 122 | while (ari_range < 0x1000000) { ari_range = ShiftLow(); } 123 | } 124 | 125 | template INLINE unsigned int EncodeBit(unsigned int bit, int probability) 126 | { 127 | unsigned int range = (((unsigned long long)ari_range) * probability) >> P; 128 | ari.low = ari.low + ((~bit + 1u) & range); 129 | ari_range = range + ((~bit + 1u) & (ari_range - range - range)); 130 | 131 | while (ari_range < 0x1000000) { ari_range = ShiftLow(); } 132 | 133 | return bit; 134 | } 135 | 136 | INLINE unsigned int EncodeValue(unsigned int min, unsigned int value, unsigned int max) 137 | { 138 | assert(min <= value && value <= max); 139 | 140 | while (max - min >= 0x10000) 141 | { 142 | unsigned int median = min + ((max - min) >> 1); 143 | if (value > median) 144 | { 145 | EncodeBit<1>(1, 1); 146 | min = median + 1; 147 | } 148 | else 149 | { 150 | EncodeBit<1>(0, 1); 151 | max = median; 152 | } 153 | } 154 | 155 | if (min != max) 156 | { 157 | Encode(value - min, 1, max - min + 1); 158 | } 159 | 160 | return value; 161 | } 162 | 163 | INLINE void InitDecoder(const unsigned char * input) 164 | { 165 | ari_input = input; 166 | ari_code = 0; 167 | ari_range = 0xffffffff; 168 | ari_code = (ari_code << 8) | InputByte(); 169 | ari_code = (ari_code << 8) | InputByte(); 170 | ari_code = (ari_code << 8) | InputByte(); 171 | ari_code = (ari_code << 8) | InputByte(); 172 | ari_code = (ari_code << 8) | InputByte(); 173 | }; 174 | 175 | INLINE unsigned int GetCumFreq(unsigned int total_freq) 176 | { 177 | while (ari_range < 0x1000000) 178 | { 179 | ari_range <<= 8; ari_code = (ari_code << 8) | InputByte(); 180 | } 181 | 182 | return ari_code / (ari_range / total_freq); 183 | } 184 | 185 | INLINE void Decode(unsigned int cum_freq, unsigned int sym_freq, unsigned int total_freq) 186 | { 187 | unsigned int range = ari_range / total_freq; 188 | ari_code -= cum_freq * range; ari_range = sym_freq * range; 189 | } 190 | 191 | template INLINE int DecodeBit(int probability) 192 | { 193 | while (ari_range < 0x1000000) 194 | { 195 | ari_range <<= 8; ari_code = (ari_code << 8) | InputByte(); 196 | } 197 | 198 | unsigned int range = (((unsigned long long)ari_range) * probability) >> P; 199 | int bit = ari_code >= range; 200 | 201 | ari_range = bit ? ari_range - range : range; 202 | ari_code = bit ? ari_code - range : ari_code; 203 | 204 | return bit; 205 | } 206 | 207 | INLINE unsigned int DecodeValue(unsigned int min, unsigned int max) 208 | { 209 | assert(min <= max); 210 | 211 | while (max - min >= 0x10000) 212 | { 213 | unsigned int median = min + ((max - min) >> 1); 214 | if (DecodeBit<1>(1)) 215 | { 216 | min = median + 1; 217 | } 218 | else 219 | { 220 | max = median; 221 | } 222 | } 223 | 224 | if (min != max) 225 | { 226 | unsigned int cum_freq = GetCumFreq(max - min + 1); 227 | Decode(cum_freq, 1, max - min + 1); min += cum_freq; 228 | } 229 | 230 | return min; 231 | } 232 | }; 233 | 234 | #endif 235 | 236 | /*-----------------------------------------------------------*/ 237 | /* End rangecoder.h */ 238 | /*-----------------------------------------------------------*/ 239 | -------------------------------------------------------------------------------- /hutucker/README: -------------------------------------------------------------------------------- 1 | This is an O(n log n) implementation of Hu-Tucker coding.[1] 2 | 3 | This is the algorithm: 4 | 1. Label node 0, ..., n-1 'terminal' 5 | 2. Repeat (n - 1) times: 6 | (a) Find the pair (i, j) such that 7 | (i) i < j, 8 | (ii) neither node i nor j is labeled 'none', 9 | (iii) none of node i+1, ..., j-1 is labeled 'terminal', 10 | (iv) weight[i] + weight[j] are minimal, 11 | (v) i is minimal if the selection is not unique after (iv), and 12 | (vi) j is minimal if the selection is not unique after (v) 13 | (b) Merge node i with node j, and saves it as new node i 14 | (c) weight[i] += weight[j] 15 | (d) Label node i 'internal' 16 | (e) Label node j 'none' 17 | 3. A tree has been built with root being node 0. 18 | Traverse this tree for length of code. 19 | This tree is not alphabetical. 20 | Nevertheless, the length of code produced by the tree is correct. 21 | 22 | See example.c for computing the actual code from the length. 23 | 24 | We need a non-trivial data structure to implement 2(a) efficiently. 25 | This is the data structure: 26 | 1. It is a perfect binary tree. 27 | The nodes in this tree are called "segnodes" to distinguish them from 28 | nodes in the coding tree. 29 | This tree shall have at least n leaf segnodes. 30 | 2. Each segnode is implicitly associated with a range [a, b). 31 | The range of the leaf segnode i is [i, i+1). 32 | The range of each internal segnode is union of the ranges of its children. 33 | (Alternatively, the range of each internal nodes is the union of 34 | the ranges of all leaf nodes in its subtree.) 35 | 3. Each segnode also has 6 explicit fields (n, m, l, r, i, j). 36 | n: The number of nodes [a, b) labeled 'terminal' or 'internal' 37 | m: The number of nodes [a, b) labeled 'terminal' 38 | l: The index such that: 39 | (i) l in [a, b), 40 | (ii) node l is not labeled 'none', 41 | (iii) none of node l, ..., i-1 is labeled 'terminal', 42 | (iv) weight[l] is minimal, and 43 | (v) l is minimal if the selection is not unique after (iv) 44 | r: The index such that: 45 | (i) r in [a, b), 46 | (ii) node r is not labeled 'none', 47 | (iii) none of node r, ..., b-1 is labeled 'terminal', 48 | (iv) weight[r] is minimal, and 49 | (v) r is minimal if the selection is not unique after (iv) 50 | i, j: The pair of indices such that: 51 | (i) a <= i < j < b, 52 | (ii) neither node i nor j is labeled 'none', 53 | (iii) none of node i+1, ..., j-1 is labeled 'terminal', 54 | (iv) weight[i] + weight[j] are minimal, 55 | (v) i is minimal if the selection is not unique after (iv), and 56 | (vi) j is minimal if the selection is not unique after (v) 57 | 4. The explicit fields can be trivially computed for leaf segnodes: 58 | (a) Leaf segnode i labeled 'terminal': 59 | (n, m, l, r, i, j) = (1, 1, i, i, None, None) 60 | (b) Leaf segnode i labeled 'internal': 61 | (n, m, l, r, i, j) = (1, 0, i, i, None, None) 62 | (c) Leaf segnode i labeled 'none': 63 | (n, m, l, r, i, j) = (0, 0, None, None, None, None) 64 | 5. The explicit fields can be efficiently computed for internal segnodes, 65 | if we have access to correct labels of its children segnodes. 66 | Let its left children be L, and its right children be R. 67 | n: L.n + R.n 68 | m: L.n + R.m 69 | l: L.l if L.m > 0, otherwise the better of L.l and R.l 70 | r: R.r if R.m > 0, otherwise the better of L.r and R.r 71 | i, j: the best of (L.i, L.j), (L.r, R.l) and (R.i, R.j) 72 | 73 | Analysis: 74 | 1. This data structure can be built in O(n). 75 | 2. The (i, j) step 2(a) is the (i, j) of the root of the data structure, 76 | which can be looked up in O(1). 77 | 3. When the weight[i] and label of node i changed, 78 | leaf segnode i and its ancestors need to be updated. 79 | That's O(log n) updates and O(1) per update. 80 | Same for node j. 81 | 4. Step 2 is repeated O(n) times. 82 | Other parts are trivial. 83 | Therefore, the overall time is O(n log n). 84 | 85 | 86 | [1]: Hu, T. C.; Tucker, A. C. (1971) "Optimal Computer Search Trees 87 | and Variable-Length Alphabetical Codes", SIAM Journal on 88 | Applied Mathematics. 21 (4): 514. 89 | -------------------------------------------------------------------------------- /hutucker/example.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Linearithmic Hu-Tucker Coding. 3 | * Copyright (C) 2018 Pochang Chen 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include "hu-tucker.h" 23 | 24 | int main() { 25 | size_t n; 26 | if (scanf("%zu", &n) != 1) 27 | return 1; 28 | if (n < 1) { 29 | errno = EINVAL; 30 | perror(NULL); 31 | return 1; 32 | } 33 | 34 | unsigned long *weight = calloc(n, sizeof(unsigned long)); 35 | if (!weight) { 36 | perror("calloc"); 37 | return 1; 38 | } 39 | 40 | for (size_t i = 0; i < n; i++) 41 | scanf("%lu", weight + i); 42 | 43 | unsigned long sumweight = 0; 44 | for (size_t i = 0; i < n; i++) { 45 | sumweight += weight[i]; 46 | if (sumweight < weight[i]) { 47 | errno = EOVERFLOW; 48 | perror(NULL); 49 | return 1; 50 | } 51 | } 52 | 53 | unsigned long *tmp = malloc(hutucker_tmp_size(n)); 54 | if (!tmp) { 55 | perror("malloc"); 56 | return 1; 57 | } 58 | hutucker_get_lengths(n, weight, tmp); 59 | free(tmp); 60 | 61 | unsigned long maxlength = 0; 62 | for (size_t i = 0; i < n; i++) 63 | if (weight[i] > maxlength) 64 | maxlength = weight[i]; 65 | 66 | unsigned char *str = malloc(maxlength + 1); 67 | if (!str) { 68 | perror("malloc"); 69 | return 1; 70 | } 71 | for (size_t i = 0, l = 0; i < n; i++) { 72 | if (l < weight[i]) 73 | memset(str + l, '0', weight[i] - l); 74 | l = weight[i]; 75 | str[l] = '\0'; 76 | puts(str); 77 | for (size_t j = l - 1; j != (size_t) -1; j--) 78 | if ((str[j] ^= '0' ^ '1') == '1') 79 | break; 80 | } 81 | 82 | free(str); 83 | free(weight); 84 | } 85 | -------------------------------------------------------------------------------- /hutucker/hu-tucker.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Linearithmic Hu-Tucker Coding. 3 | * Copyright (C) 2018 Pochang Chen 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | /*-- 20 | 21 | NOTICE: This file has been modified for use in the bsc-m03 project. 22 | 23 | --*/ 24 | 25 | #include "hu-tucker.h" 26 | 27 | typedef struct { 28 | // number of (terminal or internal) nodes under this segnode 29 | size_t n; 30 | // number of terminal node under this segnode, if n >= 1 31 | size_t m; 32 | // index of minimum weight in the leftmost block, if n >= 1 33 | size_t l; 34 | // index of minimum weight in the rightmost block, if n >= 1 35 | size_t r; 36 | // indices of minimum weight pair in the same block, if n >= 2 37 | size_t i, j; 38 | } segnode; 39 | 40 | static void segupdate(segnode *pa, segnode *lc, segnode *rc, unsigned int *w) { 41 | if (!lc->n) { 42 | *pa = *rc; 43 | return; 44 | } 45 | if (!rc->n) { 46 | *pa = *lc; 47 | return; 48 | } 49 | pa->n = lc->n + rc->n; 50 | pa->m = lc->m + rc->m; 51 | pa->l = ( lc->m || w[lc->l] <= w[rc->l]) ? lc->l : rc->l; 52 | pa->r = (!rc->m && w[lc->r] <= w[rc->r]) ? lc->r : rc->r; 53 | pa->i = lc->r; 54 | pa->j = rc->l; 55 | if (lc->n >= 2 && w[lc->i] + w[lc->j] <= w[pa->i] + w[pa->j]) { 56 | pa->i = lc->i; 57 | pa->j = lc->j; 58 | } 59 | if (rc->n >= 2 && w[rc->i] + w[rc->j] < w[pa->i] + w[pa->j]) { 60 | pa->i = rc->i; 61 | pa->j = rc->j; 62 | } 63 | } 64 | static void segterminal(segnode *x, size_t id) { 65 | x->n = x->m = 1; 66 | x->l = x->r = id; 67 | } 68 | static void seginternal(segnode *x, size_t id) { 69 | x->n = 1; 70 | x->m = 0; 71 | x->l = x->r = id; 72 | } 73 | static void segnone(segnode *x) { 74 | x->n = 0; 75 | } 76 | static size_t raise_power_of_two(size_t n) { 77 | size_t ans = 1; 78 | while (ans < n) 79 | ans *= 2; 80 | return ans; 81 | } 82 | 83 | size_t hutucker_tmp_size(size_t n) { 84 | // TODO check overflow for very large n 85 | size_t m = raise_power_of_two(n); 86 | return sizeof(segnode) * (2 * m - 1) + 87 | sizeof(size_t) * (n + (2 * n - 1) + (2 * n - 1)); 88 | } 89 | 90 | void hutucker_get_lengths(size_t n, unsigned int *weight, void *tmp) { 91 | size_t m = raise_power_of_two(n); 92 | segnode *seg = (segnode *) tmp; 93 | size_t *cur = (size_t *) (seg + 2 * m - 1); 94 | size_t *pa = (size_t *) (cur + n); 95 | size_t *level = (size_t *) (pa + 2 * n - 1); 96 | 97 | for (size_t i = 0; i < n; i++) { 98 | segterminal(seg + m - 1 + i, i); 99 | cur[i] = i; 100 | } 101 | for (size_t i = n; i < m; i++) 102 | segnone(seg + m - 1 + i); 103 | 104 | for (size_t i = m - 2; i != (size_t) -1; i--) 105 | segupdate(seg + i, seg + 2 * i + 1, seg + 2 * i + 2, weight); 106 | 107 | for (size_t k = 0; k < n - 1; k++) { 108 | size_t i = seg->i, j = seg->j; 109 | 110 | weight[i] += weight[j]; 111 | pa[cur[i]] = pa[cur[j]] = n + k; 112 | cur[i] = n + k; 113 | 114 | seginternal(seg + m - 1 + i, i); 115 | for (size_t l = m + i; l /= 2; ) 116 | segupdate(seg + l - 1, seg + 2 * l - 1, seg + 2 * l, weight); 117 | 118 | segnone(seg + m - 1 + j); 119 | for (size_t l = m + j; l /= 2; ) 120 | segupdate(seg + l - 1, seg + 2 * l - 1, seg + 2 * l, weight); 121 | } 122 | 123 | level[2 * n - 2] = 0; 124 | for (size_t i = 2 * n - 3; i != (size_t) -1; i--) 125 | level[i] = level[pa[i]] + 1; 126 | for (size_t i = 0; i < n; i++) 127 | weight[i] = (unsigned int)level[i]; 128 | } 129 | -------------------------------------------------------------------------------- /hutucker/hu-tucker.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Linearithmic Hu-Tucker Coding. 3 | * Copyright (C) 2018 Pochang Chen 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | /*-- 20 | 21 | NOTICE: This file has been modified for use in the bsc-m03 project. 22 | 23 | --*/ 24 | 25 | #pragma once 26 | 27 | #ifdef __cplusplus 28 | extern "C" { 29 | #endif 30 | 31 | #include 32 | 33 | /** 34 | * This algorithm needs some temporary memories to work. 35 | * This function computes how much temporary memories are needed. 36 | */ 37 | size_t hutucker_tmp_size(size_t n); 38 | 39 | /** 40 | * Given the weight of n symbols, determine the length of hu-tucker code 41 | * of each symbols. 42 | * 43 | * Precondition: 44 | * n: number of symbols 45 | * weight[i] (0 <= i < n): the weight of symbol i 46 | * weight[0] + ... + weight[n - 1] must not exceed UINT_MAX 47 | * tmp: buffer with size >= hutucker_tmp_size(n) 48 | * 49 | * Postcondition: 50 | * weight[i] (0 <= i < n): the length of hu-tucker code of symbol i 51 | */ 52 | void hutucker_get_lengths(size_t n, unsigned int *weight, void *tmp); 53 | 54 | #ifdef __cplusplus 55 | } 56 | #endif 57 | -------------------------------------------------------------------------------- /libsais/CHANGES: -------------------------------------------------------------------------------- 1 | Changes in 2.10.0 (April 12, 2025) 2 | - Improved performance, with noticeable gains on ARM architecture. 3 | - Fixed compiler warnings and addressed undefined behavior. 4 | 5 | Changes in 2.9.1 (March 19, 2025) 6 | - No functional changes, resolved compiler warnings & undefined behavior. 7 | 8 | Changes in 2.9.0 (March 16, 2025) 9 | - Support for generalized suffix array (GSA) construction. 10 | - Support for longest common prefix array (LCP) construction for generalized suffix array (GSA). 11 | 12 | Changes in 2.8.7 (January 16, 2025) 13 | - Restore the input array after suffix array construction (libsais64 & libsais16x64). 14 | 15 | Changes in 2.8.6 (November 18, 2024) 16 | - Fixed out-of-bound memory access issue for large inputs. 17 | 18 | Changes in 2.8.5 (July 31, 2024) 19 | - Miscellaneous changes to reduce compiler warnings about implicit functions. 20 | 21 | Changes in 2.8.4 (June 13, 2024) 22 | - Additional OpenMP acceleration (libsais16 & libsais16x64). 23 | 24 | Changes in 2.8.3 (June 11, 2024) 25 | - Implemented suffix array construction of a long 16-bit array (libsais16x64). 26 | 27 | Changes in 2.8.2 (May 27, 2024) 28 | - Implemented suffix array construction of a long 64-bit array (libsais64). 29 | 30 | Changes in 2.8.1 (April 5, 2024) 31 | - Fixed out-of-bound memory access issue for large inputs (libsais64). 32 | 33 | Changes in 2.8.0 (March 3, 2024) 34 | - Implemented permuted longest common prefix array (PLCP) construction of an integer array. 35 | - Fixed compilation error when compiling the library with OpenMP enabled. 36 | 37 | Changes in 2.7.5 (February 26, 2024) 38 | - Improved performance of suffix array and burrows wheeler transform construction on degenerate inputs. 39 | 40 | Changes in 2.7.4 (February 23, 2024) 41 | - Resolved strict aliasing violation resulted in invalid code generation by Intel compiler. 42 | 43 | Changes in 2.7.3 (April 21, 2023) 44 | - CMake script for library build and integration with other projects. 45 | 46 | Changes in 2.7.2 (April 18, 2023) 47 | - Fixed out-of-bound memory access issue for large inputs (libsais64). 48 | 49 | Changes in 2.7.1 (June 19, 2022) 50 | - Improved cache coherence for ARMv8 architecture. 51 | 52 | Changes in 2.7.0 (April 12, 2022) 53 | - Support for longest common prefix array (LCP) construction. 54 | 55 | Changes in 2.6.5 (January 1, 2022) 56 | - Exposed functions to construct suffix array of a given integer array. 57 | - Improved detection of various compiler intrinsics. 58 | - Capped free space parameter to avoid crashing due to 32-bit integer overflow. 59 | 60 | Changes in 2.6.0 (October 21, 2021) 61 | - libsais16 for 16-bit inputs. 62 | 63 | Changes in 2.5.0 (October 15, 2021) 64 | - Support for optional symbol frequency tables. 65 | 66 | Changes in 2.4.0 (July 14, 2021) 67 | - Reverse Burrows-Wheeler transform. 68 | 69 | Changes in 2.3.0 (June 23, 2021) 70 | - Burrows-Wheeler transform with auxiliary indexes. 71 | 72 | Changes in 2.2.0 (April 27, 2021) 73 | - libsais64 for inputs larger than 2GB. 74 | 75 | Changes in 2.1.0 (April 19, 2021) 76 | - Additional OpenMP acceleration. 77 | 78 | Changes in 2.0.0 (April 4, 2021) 79 | - OpenMP acceleration. 80 | 81 | Changes in 1.0.0 (February 23, 2021) 82 | - Initial Release. 83 | -------------------------------------------------------------------------------- /libsais/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /libsais/VERSION: -------------------------------------------------------------------------------- 1 | 2.10.0 2 | -------------------------------------------------------------------------------- /libsais/libsais.h: -------------------------------------------------------------------------------- 1 | /*-- 2 | 3 | This file is a part of libsais, a library for linear time suffix array, 4 | longest common prefix array and burrows wheeler transform construction. 5 | 6 | Copyright (c) 2021-2025 Ilya Grebnov 7 | 8 | Licensed under the Apache License, Version 2.0 (the "License"); 9 | you may not use this file except in compliance with the License. 10 | You may obtain a copy of the License at 11 | 12 | http://www.apache.org/licenses/LICENSE-2.0 13 | 14 | Unless required by applicable law or agreed to in writing, software 15 | distributed under the License is distributed on an "AS IS" BASIS, 16 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | See the License for the specific language governing permissions and 18 | limitations under the License. 19 | 20 | Please see the file LICENSE for full copyright information. 21 | 22 | --*/ 23 | 24 | #ifndef LIBSAIS_H 25 | #define LIBSAIS_H 1 26 | 27 | #define LIBSAIS_VERSION_MAJOR 2 28 | #define LIBSAIS_VERSION_MINOR 10 29 | #define LIBSAIS_VERSION_PATCH 0 30 | #define LIBSAIS_VERSION_STRING "2.10.0" 31 | 32 | #ifdef _WIN32 33 | #ifdef LIBSAIS_SHARED 34 | #ifdef LIBSAIS_EXPORTS 35 | #define LIBSAIS_API __declspec(dllexport) 36 | #else 37 | #define LIBSAIS_API __declspec(dllimport) 38 | #endif 39 | #else 40 | #define LIBSAIS_API 41 | #endif 42 | #else 43 | #define LIBSAIS_API 44 | #endif 45 | 46 | #ifdef __cplusplus 47 | extern "C" { 48 | #endif 49 | 50 | #include 51 | 52 | /** 53 | * Creates the libsais context that allows reusing allocated memory with each libsais operation. 54 | * In multi-threaded environments, use one context per thread for parallel executions. 55 | * @return the libsais context, NULL otherwise. 56 | */ 57 | LIBSAIS_API void * libsais_create_ctx(void); 58 | 59 | #if defined(LIBSAIS_OPENMP) 60 | /** 61 | * Creates the libsais context that allows reusing allocated memory with each parallel libsais operation using OpenMP. 62 | * In multi-threaded environments, use one context per thread for parallel executions. 63 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 64 | * @return the libsais context, NULL otherwise. 65 | */ 66 | LIBSAIS_API void * libsais_create_ctx_omp(int32_t threads); 67 | #endif 68 | 69 | /** 70 | * Destroys the libsass context and free previusly allocated memory. 71 | * @param ctx The libsais context (can be NULL). 72 | */ 73 | LIBSAIS_API void libsais_free_ctx(void * ctx); 74 | 75 | /** 76 | * Constructs the suffix array of a given string. 77 | * @param T [0..n-1] The input string. 78 | * @param SA [0..n-1+fs] The output array of suffixes. 79 | * @param n The length of the given string. 80 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 81 | * @param freq [0..255] The output symbol frequency table (can be NULL). 82 | * @return 0 if no error occurred, -1 or -2 otherwise. 83 | */ 84 | LIBSAIS_API int32_t libsais(const uint8_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq); 85 | 86 | /** 87 | * Constructs the generalized suffix array (GSA) of given string set. 88 | * @param T [0..n-1] The input string set using 0 as separators (T[n-1] must be 0). 89 | * @param SA [0..n-1+fs] The output array of suffixes. 90 | * @param n The length of the given string set. 91 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 92 | * @param freq [0..255] The output symbol frequency table (can be NULL). 93 | * @return 0 if no error occurred, -1 or -2 otherwise. 94 | */ 95 | LIBSAIS_API int32_t libsais_gsa(const uint8_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq); 96 | 97 | /** 98 | * Constructs the suffix array of a given integer array. 99 | * Note, during construction input array will be modified, but restored at the end if no errors occurred. 100 | * @param T [0..n-1] The input integer array. 101 | * @param SA [0..n-1+fs] The output array of suffixes. 102 | * @param n The length of the integer array. 103 | * @param k The alphabet size of the input integer array. 104 | * @param fs Extra space available at the end of SA array (can be 0, but 4k or better 6k is recommended for optimal performance). 105 | * @return 0 if no error occurred, -1 or -2 otherwise. 106 | */ 107 | LIBSAIS_API int32_t libsais_int(int32_t * T, int32_t * SA, int32_t n, int32_t k, int32_t fs); 108 | 109 | /** 110 | * Constructs the suffix array of a given string using libsais context. 111 | * @param ctx The libsais context. 112 | * @param T [0..n-1] The input string. 113 | * @param SA [0..n-1+fs] The output array of suffixes. 114 | * @param n The length of the given string. 115 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 116 | * @param freq [0..255] The output symbol frequency table (can be NULL). 117 | * @return 0 if no error occurred, -1 or -2 otherwise. 118 | */ 119 | LIBSAIS_API int32_t libsais_ctx(const void * ctx, const uint8_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq); 120 | 121 | /** 122 | * Constructs the generalized suffix array (GSA) of given string set using libsais context. 123 | * @param ctx The libsais context. 124 | * @param T [0..n-1] The input string set using 0 as separators (T[n-1] must be 0). 125 | * @param SA [0..n-1+fs] The output array of suffixes. 126 | * @param n The length of the given string set. 127 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 128 | * @param freq [0..255] The output symbol frequency table (can be NULL). 129 | * @return 0 if no error occurred, -1 or -2 otherwise. 130 | */ 131 | LIBSAIS_API int32_t libsais_gsa_ctx(const void * ctx, const uint8_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq); 132 | 133 | #if defined(LIBSAIS_OPENMP) 134 | /** 135 | * Constructs the suffix array of a given string in parallel using OpenMP. 136 | * @param T [0..n-1] The input string. 137 | * @param SA [0..n-1+fs] The output array of suffixes. 138 | * @param n The length of the given string. 139 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 140 | * @param freq [0..255] The output symbol frequency table (can be NULL). 141 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 142 | * @return 0 if no error occurred, -1 or -2 otherwise. 143 | */ 144 | LIBSAIS_API int32_t libsais_omp(const uint8_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq, int32_t threads); 145 | 146 | /** 147 | * Constructs the generalized suffix array (GSA) of given string set in parallel using OpenMP. 148 | * @param T [0..n-1] The input string set using 0 as separators (T[n-1] must be 0). 149 | * @param SA [0..n-1+fs] The output array of suffixes. 150 | * @param n The length of the given string set. 151 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 152 | * @param freq [0..255] The output symbol frequency table (can be NULL). 153 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 154 | * @return 0 if no error occurred, -1 or -2 otherwise. 155 | */ 156 | LIBSAIS_API int32_t libsais_gsa_omp(const uint8_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq, int32_t threads); 157 | 158 | /** 159 | * Constructs the suffix array of a given integer array in parallel using OpenMP. 160 | * Note, during construction input array will be modified, but restored at the end if no errors occurred. 161 | * @param T [0..n-1] The input integer array. 162 | * @param SA [0..n-1+fs] The output array of suffixes. 163 | * @param n The length of the integer array. 164 | * @param k The alphabet size of the input integer array. 165 | * @param fs Extra space available at the end of SA array (can be 0, but 4k or better 6k is recommended for optimal performance). 166 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 167 | * @return 0 if no error occurred, -1 or -2 otherwise. 168 | */ 169 | LIBSAIS_API int32_t libsais_int_omp(int32_t * T, int32_t * SA, int32_t n, int32_t k, int32_t fs, int32_t threads); 170 | #endif 171 | 172 | /** 173 | * Constructs the burrows-wheeler transformed string (BWT) of a given string. 174 | * @param T [0..n-1] The input string. 175 | * @param U [0..n-1] The output string (can be T). 176 | * @param A [0..n-1+fs] The temporary array. 177 | * @param n The length of the given string. 178 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 179 | * @param freq [0..255] The output symbol frequency table (can be NULL). 180 | * @return The primary index if no error occurred, -1 or -2 otherwise. 181 | */ 182 | LIBSAIS_API int32_t libsais_bwt(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq); 183 | 184 | /** 185 | * Constructs the burrows-wheeler transformed string (BWT) of a given string with auxiliary indexes. 186 | * @param T [0..n-1] The input string. 187 | * @param U [0..n-1] The output string (can be T). 188 | * @param A [0..n-1+fs] The temporary array. 189 | * @param n The length of the given string. 190 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 191 | * @param freq [0..255] The output symbol frequency table (can be NULL). 192 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 193 | * @param I [0..(n-1)/r] The output auxiliary indexes. 194 | * @return 0 if no error occurred, -1 or -2 otherwise. 195 | */ 196 | LIBSAIS_API int32_t libsais_bwt_aux(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t r, int32_t * I); 197 | 198 | /** 199 | * Constructs the burrows-wheeler transformed string (BWT) of a given string using libsais context. 200 | * @param ctx The libsais context. 201 | * @param T [0..n-1] The input string. 202 | * @param U [0..n-1] The output string (can be T). 203 | * @param A [0..n-1+fs] The temporary array. 204 | * @param n The length of the given string. 205 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 206 | * @param freq [0..255] The output symbol frequency table (can be NULL). 207 | * @return The primary index if no error occurred, -1 or -2 otherwise. 208 | */ 209 | LIBSAIS_API int32_t libsais_bwt_ctx(const void * ctx, const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq); 210 | 211 | /** 212 | * Constructs the burrows-wheeler transformed string (BWT) of a given string with auxiliary indexes using libsais context. 213 | * @param ctx The libsais context. 214 | * @param T [0..n-1] The input string. 215 | * @param U [0..n-1] The output string (can be T). 216 | * @param A [0..n-1+fs] The temporary array. 217 | * @param n The length of the given string. 218 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 219 | * @param freq [0..255] The output symbol frequency table (can be NULL). 220 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 221 | * @param I [0..(n-1)/r] The output auxiliary indexes. 222 | * @return 0 if no error occurred, -1 or -2 otherwise. 223 | */ 224 | LIBSAIS_API int32_t libsais_bwt_aux_ctx(const void * ctx, const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t r, int32_t * I); 225 | 226 | #if defined(LIBSAIS_OPENMP) 227 | /** 228 | * Constructs the burrows-wheeler transformed string (BWT) of a given string in parallel using OpenMP. 229 | * @param T [0..n-1] The input string. 230 | * @param U [0..n-1] The output string (can be T). 231 | * @param A [0..n-1+fs] The temporary array. 232 | * @param n The length of the given string. 233 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 234 | * @param freq [0..255] The output symbol frequency table (can be NULL). 235 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 236 | * @return The primary index if no error occurred, -1 or -2 otherwise. 237 | */ 238 | LIBSAIS_API int32_t libsais_bwt_omp(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t threads); 239 | 240 | /** 241 | * Constructs the burrows-wheeler transformed string (BWT) of a given string with auxiliary indexes in parallel using OpenMP. 242 | * @param T [0..n-1] The input string. 243 | * @param U [0..n-1] The output string (can be T). 244 | * @param A [0..n-1+fs] The temporary array. 245 | * @param n The length of the given string. 246 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 247 | * @param freq [0..255] The output symbol frequency table (can be NULL). 248 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 249 | * @param I [0..(n-1)/r] The output auxiliary indexes. 250 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 251 | * @return 0 if no error occurred, -1 or -2 otherwise. 252 | */ 253 | LIBSAIS_API int32_t libsais_bwt_aux_omp(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t r, int32_t * I, int32_t threads); 254 | #endif 255 | 256 | /** 257 | * Creates the libsais reverse BWT context that allows reusing allocated memory with each libsais_unbwt_* operation. 258 | * In multi-threaded environments, use one context per thread for parallel executions. 259 | * @return the libsais context, NULL otherwise. 260 | */ 261 | LIBSAIS_API void * libsais_unbwt_create_ctx(void); 262 | 263 | #if defined(LIBSAIS_OPENMP) 264 | /** 265 | * Creates the libsais reverse BWT context that allows reusing allocated memory with each parallel libsais_unbwt_* operation using OpenMP. 266 | * In multi-threaded environments, use one context per thread for parallel executions. 267 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 268 | * @return the libsais context, NULL otherwise. 269 | */ 270 | LIBSAIS_API void * libsais_unbwt_create_ctx_omp(int32_t threads); 271 | #endif 272 | 273 | /** 274 | * Destroys the libsass reverse BWT context and free previusly allocated memory. 275 | * @param ctx The libsais context (can be NULL). 276 | */ 277 | LIBSAIS_API void libsais_unbwt_free_ctx(void * ctx); 278 | 279 | /** 280 | * Constructs the original string from a given burrows-wheeler transformed string (BWT) with primary index. 281 | * @param T [0..n-1] The input string. 282 | * @param U [0..n-1] The output string (can be T). 283 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 284 | * @param n The length of the given string. 285 | * @param freq [0..255] The input symbol frequency table (can be NULL). 286 | * @param i The primary index. 287 | * @return 0 if no error occurred, -1 or -2 otherwise. 288 | */ 289 | LIBSAIS_API int32_t libsais_unbwt(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t i); 290 | 291 | /** 292 | * Constructs the original string from a given burrows-wheeler transformed string (BWT) with primary index using libsais reverse BWT context. 293 | * @param ctx The libsais reverse BWT context. 294 | * @param T [0..n-1] The input string. 295 | * @param U [0..n-1] The output string (can be T). 296 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 297 | * @param n The length of the given string. 298 | * @param freq [0..255] The input symbol frequency table (can be NULL). 299 | * @param i The primary index. 300 | * @return 0 if no error occurred, -1 or -2 otherwise. 301 | */ 302 | LIBSAIS_API int32_t libsais_unbwt_ctx(const void * ctx, const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t i); 303 | 304 | /** 305 | * Constructs the original string from a given burrows-wheeler transformed string (BWT) with auxiliary indexes. 306 | * @param T [0..n-1] The input string. 307 | * @param U [0..n-1] The output string (can be T). 308 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 309 | * @param n The length of the given string. 310 | * @param freq [0..255] The input symbol frequency table (can be NULL). 311 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 312 | * @param I [0..(n-1)/r] The input auxiliary indexes. 313 | * @return 0 if no error occurred, -1 or -2 otherwise. 314 | */ 315 | LIBSAIS_API int32_t libsais_unbwt_aux(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t r, const int32_t * I); 316 | 317 | /** 318 | * Constructs the original string from a given burrows-wheeler transformed string (BWT) with auxiliary indexes using libsais reverse BWT context. 319 | * @param ctx The libsais reverse BWT context. 320 | * @param T [0..n-1] The input string. 321 | * @param U [0..n-1] The output string (can be T). 322 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 323 | * @param n The length of the given string. 324 | * @param freq [0..255] The input symbol frequency table (can be NULL). 325 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 326 | * @param I [0..(n-1)/r] The input auxiliary indexes. 327 | * @return 0 if no error occurred, -1 or -2 otherwise. 328 | */ 329 | LIBSAIS_API int32_t libsais_unbwt_aux_ctx(const void * ctx, const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t r, const int32_t * I); 330 | 331 | #if defined(LIBSAIS_OPENMP) 332 | /** 333 | * Constructs the original string from a given burrows-wheeler transformed string (BWT) with primary index in parallel using OpenMP. 334 | * @param T [0..n-1] The input string. 335 | * @param U [0..n-1] The output string (can be T). 336 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 337 | * @param n The length of the given string. 338 | * @param freq [0..255] The input symbol frequency table (can be NULL). 339 | * @param i The primary index. 340 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 341 | * @return 0 if no error occurred, -1 or -2 otherwise. 342 | */ 343 | LIBSAIS_API int32_t libsais_unbwt_omp(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t i, int32_t threads); 344 | 345 | /** 346 | * Constructs the original string from a given burrows-wheeler transformed string (BWT) with auxiliary indexes in parallel using OpenMP. 347 | * @param T [0..n-1] The input string. 348 | * @param U [0..n-1] The output string (can be T). 349 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 350 | * @param n The length of the given string. 351 | * @param freq [0..255] The input symbol frequency table (can be NULL). 352 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 353 | * @param I [0..(n-1)/r] The input auxiliary indexes. 354 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 355 | * @return 0 if no error occurred, -1 or -2 otherwise. 356 | */ 357 | LIBSAIS_API int32_t libsais_unbwt_aux_omp(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t r, const int32_t * I, int32_t threads); 358 | #endif 359 | 360 | /** 361 | * Constructs the permuted longest common prefix array (PLCP) of a given string and a suffix array. 362 | * @param T [0..n-1] The input string. 363 | * @param SA [0..n-1] The input suffix array. 364 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 365 | * @param n The length of the string and the suffix array. 366 | * @return 0 if no error occurred, -1 otherwise. 367 | */ 368 | LIBSAIS_API int32_t libsais_plcp(const uint8_t * T, const int32_t * SA, int32_t * PLCP, int32_t n); 369 | 370 | /** 371 | * Constructs the permuted longest common prefix array (PLCP) of a given string set and a generalized suffix array (GSA). 372 | * @param T [0..n-1] The input string set using 0 as separators (T[n-1] must be 0). 373 | * @param SA [0..n-1] The input generalized suffix array. 374 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 375 | * @param n The length of the string set and the generalized suffix array. 376 | * @return 0 if no error occurred, -1 otherwise. 377 | */ 378 | LIBSAIS_API int32_t libsais_plcp_gsa(const uint8_t * T, const int32_t * SA, int32_t * PLCP, int32_t n); 379 | 380 | /** 381 | * Constructs the permuted longest common prefix array (PLCP) of a integer array and a suffix array. 382 | * @param T [0..n-1] The input integer array. 383 | * @param SA [0..n-1] The input suffix array. 384 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 385 | * @param n The length of the integer array and the suffix array. 386 | * @return 0 if no error occurred, -1 otherwise. 387 | */ 388 | LIBSAIS_API int32_t libsais_plcp_int(const int32_t * T, const int32_t * SA, int32_t * PLCP, int32_t n); 389 | 390 | /** 391 | * Constructs the longest common prefix array (LCP) of a given permuted longest common prefix array (PLCP) and a suffix array. 392 | * @param PLCP [0..n-1] The input permuted longest common prefix array. 393 | * @param SA [0..n-1] The input suffix array or generalized suffix array (GSA). 394 | * @param LCP [0..n-1] The output longest common prefix array (can be SA). 395 | * @param n The length of the permuted longest common prefix array and the suffix array. 396 | * @return 0 if no error occurred, -1 otherwise. 397 | */ 398 | LIBSAIS_API int32_t libsais_lcp(const int32_t * PLCP, const int32_t * SA, int32_t * LCP, int32_t n); 399 | 400 | #if defined(LIBSAIS_OPENMP) 401 | /** 402 | * Constructs the permuted longest common prefix array (PLCP) of a given string and a suffix array in parallel using OpenMP. 403 | * @param T [0..n-1] The input string. 404 | * @param SA [0..n-1] The input suffix array. 405 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 406 | * @param n The length of the string and the suffix array. 407 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 408 | * @return 0 if no error occurred, -1 otherwise. 409 | */ 410 | LIBSAIS_API int32_t libsais_plcp_omp(const uint8_t * T, const int32_t * SA, int32_t * PLCP, int32_t n, int32_t threads); 411 | 412 | /** 413 | * Constructs the permuted longest common prefix array (PLCP) of a given string set and a generalized suffix array (GSA) in parallel using OpenMP. 414 | * @param T [0..n-1] The input string set using 0 as separators (T[n-1] must be 0). 415 | * @param SA [0..n-1] The input generalized suffix array. 416 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 417 | * @param n The length of the string set and the generalized suffix array. 418 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 419 | * @return 0 if no error occurred, -1 otherwise. 420 | */ 421 | LIBSAIS_API int32_t libsais_plcp_gsa_omp(const uint8_t * T, const int32_t * SA, int32_t * PLCP, int32_t n, int32_t threads); 422 | 423 | /** 424 | * Constructs the permuted longest common prefix array (PLCP) of a given integer array and a suffix array in parallel using OpenMP. 425 | * @param T [0..n-1] The input integer array. 426 | * @param SA [0..n-1] The input suffix array. 427 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 428 | * @param n The length of the integer array and the suffix array. 429 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 430 | * @return 0 if no error occurred, -1 otherwise. 431 | */ 432 | LIBSAIS_API int32_t libsais_plcp_int_omp(const int32_t * T, const int32_t * SA, int32_t * PLCP, int32_t n, int32_t threads); 433 | 434 | /** 435 | * Constructs the longest common prefix array (LCP) of a given permuted longest common prefix array (PLCP) and a suffix array in parallel using OpenMP. 436 | * @param PLCP [0..n-1] The input permuted longest common prefix array. 437 | * @param SA [0..n-1] The input suffix array or generalized suffix array (GSA). 438 | * @param LCP [0..n-1] The output longest common prefix array (can be SA). 439 | * @param n The length of the permuted longest common prefix array and the suffix array. 440 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 441 | * @return 0 if no error occurred, -1 otherwise. 442 | */ 443 | LIBSAIS_API int32_t libsais_lcp_omp(const int32_t * PLCP, const int32_t * SA, int32_t * LCP, int32_t n, int32_t threads); 444 | #endif 445 | 446 | #ifdef __cplusplus 447 | } 448 | #endif 449 | 450 | #endif 451 | -------------------------------------------------------------------------------- /libsais/libsais16.h: -------------------------------------------------------------------------------- 1 | /*-- 2 | 3 | This file is a part of libsais, a library for linear time suffix array, 4 | longest common prefix array and burrows wheeler transform construction. 5 | 6 | Copyright (c) 2021-2025 Ilya Grebnov 7 | 8 | Licensed under the Apache License, Version 2.0 (the "License"); 9 | you may not use this file except in compliance with the License. 10 | You may obtain a copy of the License at 11 | 12 | http://www.apache.org/licenses/LICENSE-2.0 13 | 14 | Unless required by applicable law or agreed to in writing, software 15 | distributed under the License is distributed on an "AS IS" BASIS, 16 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | See the License for the specific language governing permissions and 18 | limitations under the License. 19 | 20 | Please see the file LICENSE for full copyright information. 21 | 22 | --*/ 23 | 24 | #ifndef LIBSAIS16_H 25 | #define LIBSAIS16_H 1 26 | 27 | #define LIBSAIS16_VERSION_MAJOR 2 28 | #define LIBSAIS16_VERSION_MINOR 10 29 | #define LIBSAIS16_VERSION_PATCH 0 30 | #define LIBSAIS16_VERSION_STRING "2.10.0" 31 | 32 | #ifdef _WIN32 33 | #ifdef LIBSAIS_SHARED 34 | #ifdef LIBSAIS_EXPORTS 35 | #define LIBSAIS16_API __declspec(dllexport) 36 | #else 37 | #define LIBSAIS16_API __declspec(dllimport) 38 | #endif 39 | #else 40 | #define LIBSAIS16_API 41 | #endif 42 | #else 43 | #define LIBSAIS16_API 44 | #endif 45 | 46 | #ifdef __cplusplus 47 | extern "C" { 48 | #endif 49 | 50 | #include 51 | 52 | /** 53 | * Creates the libsais16 context that allows reusing allocated memory with each libsais16 operation. 54 | * In multi-threaded environments, use one context per thread for parallel executions. 55 | * @return the libsais16 context, NULL otherwise. 56 | */ 57 | LIBSAIS16_API void * libsais16_create_ctx(void); 58 | 59 | #if defined(LIBSAIS_OPENMP) 60 | /** 61 | * Creates the libsais16 context that allows reusing allocated memory with each parallel libsais16 operation using OpenMP. 62 | * In multi-threaded environments, use one context per thread for parallel executions. 63 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 64 | * @return the libsais16 context, NULL otherwise. 65 | */ 66 | LIBSAIS16_API void * libsais16_create_ctx_omp(int32_t threads); 67 | #endif 68 | 69 | /** 70 | * Destroys the libsass context and free previusly allocated memory. 71 | * @param ctx The libsais16 context (can be NULL). 72 | */ 73 | LIBSAIS16_API void libsais16_free_ctx(void * ctx); 74 | 75 | /** 76 | * Constructs the suffix array of a given 16-bit string. 77 | * @param T [0..n-1] The input 16-bit string. 78 | * @param SA [0..n-1+fs] The output array of suffixes. 79 | * @param n The length of the given 16-bit string. 80 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 81 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 82 | * @return 0 if no error occurred, -1 or -2 otherwise. 83 | */ 84 | LIBSAIS16_API int32_t libsais16(const uint16_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq); 85 | 86 | /** 87 | * Constructs the generalized suffix array (GSA) of given 16-bit string set. 88 | * @param T [0..n-1] The input 16-bit string set using 0 as separators (T[n-1] must be 0). 89 | * @param SA [0..n-1+fs] The output array of suffixes. 90 | * @param n The length of the given 16-bit string set. 91 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 92 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 93 | * @return 0 if no error occurred, -1 or -2 otherwise. 94 | */ 95 | LIBSAIS16_API int32_t libsais16_gsa(const uint16_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq); 96 | 97 | /** 98 | * Constructs the suffix array of a given integer array. 99 | * Note, during construction input array will be modified, but restored at the end if no errors occurred. 100 | * @param T [0..n-1] The input integer array. 101 | * @param SA [0..n-1+fs] The output array of suffixes. 102 | * @param n The length of the integer array. 103 | * @param k The alphabet size of the input integer array. 104 | * @param fs Extra space available at the end of SA array (can be 0, but 4k or better 6k is recommended for optimal performance). 105 | * @return 0 if no error occurred, -1 or -2 otherwise. 106 | */ 107 | LIBSAIS16_API int32_t libsais16_int(int32_t * T, int32_t * SA, int32_t n, int32_t k, int32_t fs); 108 | 109 | /** 110 | * Constructs the suffix array of a given 16-bit string using libsais16 context. 111 | * @param ctx The libsais16 context. 112 | * @param T [0..n-1] The input 16-bit string. 113 | * @param SA [0..n-1+fs] The output array of suffixes. 114 | * @param n The length of the given 16-bit string. 115 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 116 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 117 | * @return 0 if no error occurred, -1 or -2 otherwise. 118 | */ 119 | LIBSAIS16_API int32_t libsais16_ctx(const void * ctx, const uint16_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq); 120 | 121 | /** 122 | * Constructs the generalized suffix array (GSA) of given 16-bit string set using libsais16 context. 123 | * @param ctx The libsais16 context. 124 | * @param T [0..n-1] The input 16-bit string set using 0 as separators (T[n-1] must be 0). 125 | * @param SA [0..n-1+fs] The output array of suffixes. 126 | * @param n The length of the given 16-bit string set. 127 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 128 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 129 | * @return 0 if no error occurred, -1 or -2 otherwise. 130 | */ 131 | LIBSAIS16_API int32_t libsais16_gsa_ctx(const void * ctx, const uint16_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq); 132 | 133 | #if defined(LIBSAIS_OPENMP) 134 | /** 135 | * Constructs the suffix array of a given 16-bit string in parallel using OpenMP. 136 | * @param T [0..n-1] The input 16-bit string. 137 | * @param SA [0..n-1+fs] The output array of suffixes. 138 | * @param n The length of the given 16-bit string. 139 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 140 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 141 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 142 | * @return 0 if no error occurred, -1 or -2 otherwise. 143 | */ 144 | LIBSAIS16_API int32_t libsais16_omp(const uint16_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq, int32_t threads); 145 | 146 | /** 147 | * Constructs the generalized suffix array (GSA) of given 16-bit string set in parallel using OpenMP. 148 | * @param T [0..n-1] The input 16-bit string set using 0 as separators (T[n-1] must be 0). 149 | * @param SA [0..n-1+fs] The output array of suffixes. 150 | * @param n The length of the given 16-bit string set. 151 | * @param fs The extra space available at the end of SA array (0 should be enough for most cases). 152 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 153 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 154 | * @return 0 if no error occurred, -1 or -2 otherwise. 155 | */ 156 | LIBSAIS16_API int32_t libsais16_gsa_omp(const uint16_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq, int32_t threads); 157 | 158 | /** 159 | * Constructs the suffix array of a given integer array in parallel using OpenMP. 160 | * Note, during construction input array will be modified, but restored at the end if no errors occurred. 161 | * @param T [0..n-1] The input integer array. 162 | * @param SA [0..n-1+fs] The output array of suffixes. 163 | * @param n The length of the integer array. 164 | * @param k The alphabet size of the input integer array. 165 | * @param fs Extra space available at the end of SA array (can be 0, but 4k or better 6k is recommended for optimal performance). 166 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 167 | * @return 0 if no error occurred, -1 or -2 otherwise. 168 | */ 169 | LIBSAIS16_API int32_t libsais16_int_omp(int32_t * T, int32_t * SA, int32_t n, int32_t k, int32_t fs, int32_t threads); 170 | #endif 171 | 172 | /** 173 | * Constructs the burrows-wheeler transformed 16-bit string (BWT) of a given 16-bit string. 174 | * @param T [0..n-1] The input 16-bit string. 175 | * @param U [0..n-1] The output 16-bit string (can be T). 176 | * @param A [0..n-1+fs] The temporary array. 177 | * @param n The length of the given 16-bit string. 178 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 179 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 180 | * @return The primary index if no error occurred, -1 or -2 otherwise. 181 | */ 182 | LIBSAIS16_API int32_t libsais16_bwt(const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq); 183 | 184 | /** 185 | * Constructs the burrows-wheeler transformed 16-bit string (BWT) of a given 16-bit string with auxiliary indexes. 186 | * @param T [0..n-1] The input 16-bit string. 187 | * @param U [0..n-1] The output 16-bit string (can be T). 188 | * @param A [0..n-1+fs] The temporary array. 189 | * @param n The length of the given 16-bit string. 190 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 191 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 192 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 193 | * @param I [0..(n-1)/r] The output auxiliary indexes. 194 | * @return 0 if no error occurred, -1 or -2 otherwise. 195 | */ 196 | LIBSAIS16_API int32_t libsais16_bwt_aux(const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t r, int32_t * I); 197 | 198 | /** 199 | * Constructs the burrows-wheeler transformed 16-bit string (BWT) of a given 16-bit string using libsais16 context. 200 | * @param ctx The libsais16 context. 201 | * @param T [0..n-1] The input 16-bit string. 202 | * @param U [0..n-1] The output 16-bit string (can be T). 203 | * @param A [0..n-1+fs] The temporary array. 204 | * @param n The length of the given 16-bit string. 205 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 206 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 207 | * @return The primary index if no error occurred, -1 or -2 otherwise. 208 | */ 209 | LIBSAIS16_API int32_t libsais16_bwt_ctx(const void * ctx, const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq); 210 | 211 | /** 212 | * Constructs the burrows-wheeler transformed 16-bit string (BWT) of a given 16-bit string with auxiliary indexes using libsais16 context. 213 | * @param ctx The libsais16 context. 214 | * @param T [0..n-1] The input 16-bit string. 215 | * @param U [0..n-1] The output 16-bit string (can be T). 216 | * @param A [0..n-1+fs] The temporary array. 217 | * @param n The length of the given 16-bit string. 218 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 219 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 220 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 221 | * @param I [0..(n-1)/r] The output auxiliary indexes. 222 | * @return 0 if no error occurred, -1 or -2 otherwise. 223 | */ 224 | LIBSAIS16_API int32_t libsais16_bwt_aux_ctx(const void * ctx, const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t r, int32_t * I); 225 | 226 | #if defined(LIBSAIS_OPENMP) 227 | /** 228 | * Constructs the burrows-wheeler transformed 16-bit string (BWT) of a given 16-bit string in parallel using OpenMP. 229 | * @param T [0..n-1] The input 16-bit string. 230 | * @param U [0..n-1] The output 16-bit string (can be T). 231 | * @param A [0..n-1+fs] The temporary array. 232 | * @param n The length of the given 16-bit string. 233 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 234 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 235 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 236 | * @return The primary index if no error occurred, -1 or -2 otherwise. 237 | */ 238 | LIBSAIS16_API int32_t libsais16_bwt_omp(const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t threads); 239 | 240 | /** 241 | * Constructs the burrows-wheeler transformed 16-bit string (BWT) of a given 16-bit string with auxiliary indexes in parallel using OpenMP. 242 | * @param T [0..n-1] The input 16-bit string. 243 | * @param U [0..n-1] The output 16-bit string (can be T). 244 | * @param A [0..n-1+fs] The temporary array. 245 | * @param n The length of the given 16-bit string. 246 | * @param fs The extra space available at the end of A array (0 should be enough for most cases). 247 | * @param freq [0..65535] The output 16-bit symbol frequency table (can be NULL). 248 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 249 | * @param I [0..(n-1)/r] The output auxiliary indexes. 250 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 251 | * @return 0 if no error occurred, -1 or -2 otherwise. 252 | */ 253 | LIBSAIS16_API int32_t libsais16_bwt_aux_omp(const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t r, int32_t * I, int32_t threads); 254 | #endif 255 | 256 | /** 257 | * Creates the libsais16 reverse BWT context that allows reusing allocated memory with each libsais16_unbwt_* operation. 258 | * In multi-threaded environments, use one context per thread for parallel executions. 259 | * @return the libsais16 context, NULL otherwise. 260 | */ 261 | LIBSAIS16_API void * libsais16_unbwt_create_ctx(void); 262 | 263 | #if defined(LIBSAIS_OPENMP) 264 | /** 265 | * Creates the libsais16 reverse BWT context that allows reusing allocated memory with each parallel libsais16_unbwt_* operation using OpenMP. 266 | * In multi-threaded environments, use one context per thread for parallel executions. 267 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 268 | * @return the libsais16 context, NULL otherwise. 269 | */ 270 | LIBSAIS16_API void * libsais16_unbwt_create_ctx_omp(int32_t threads); 271 | #endif 272 | 273 | /** 274 | * Destroys the libsass reverse BWT context and free previusly allocated memory. 275 | * @param ctx The libsais16 context (can be NULL). 276 | */ 277 | LIBSAIS16_API void libsais16_unbwt_free_ctx(void * ctx); 278 | 279 | /** 280 | * Constructs the original 16-bit string from a given burrows-wheeler transformed 16-bit string (BWT) with primary index. 281 | * @param T [0..n-1] The input 16-bit string. 282 | * @param U [0..n-1] The output 16-bit string (can be T). 283 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 284 | * @param n The length of the given 16-bit string. 285 | * @param freq [0..65535] The input 16-bit symbol frequency table (can be NULL). 286 | * @param i The primary index. 287 | * @return 0 if no error occurred, -1 or -2 otherwise. 288 | */ 289 | LIBSAIS16_API int32_t libsais16_unbwt(const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t i); 290 | 291 | /** 292 | * Constructs the original 16-bit string from a given burrows-wheeler transformed 16-bit string (BWT) with primary index using libsais16 reverse BWT context. 293 | * @param ctx The libsais16 reverse BWT context. 294 | * @param T [0..n-1] The input 16-bit string. 295 | * @param U [0..n-1] The output 16-bit string (can be T). 296 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 297 | * @param n The length of the given 16-bit string. 298 | * @param freq [0..65535] The input 16-bit symbol frequency table (can be NULL). 299 | * @param i The primary index. 300 | * @return 0 if no error occurred, -1 or -2 otherwise. 301 | */ 302 | LIBSAIS16_API int32_t libsais16_unbwt_ctx(const void * ctx, const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t i); 303 | 304 | /** 305 | * Constructs the original 16-bit string from a given burrows-wheeler transformed 16-bit string (BWT) with auxiliary indexes. 306 | * @param T [0..n-1] The input 16-bit string. 307 | * @param U [0..n-1] The output 16-bit string (can be T). 308 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 309 | * @param n The length of the given 16-bit string. 310 | * @param freq [0..65535] The input 16-bit symbol frequency table (can be NULL). 311 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 312 | * @param I [0..(n-1)/r] The input auxiliary indexes. 313 | * @return 0 if no error occurred, -1 or -2 otherwise. 314 | */ 315 | LIBSAIS16_API int32_t libsais16_unbwt_aux(const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t r, const int32_t * I); 316 | 317 | /** 318 | * Constructs the original 16-bit string from a given burrows-wheeler transformed 16-bit string (BWT) with auxiliary indexes using libsais16 reverse BWT context. 319 | * @param ctx The libsais16 reverse BWT context. 320 | * @param T [0..n-1] The input 16-bit string. 321 | * @param U [0..n-1] The output 16-bit string (can be T). 322 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 323 | * @param n The length of the given 16-bit string. 324 | * @param freq [0..65535] The input 16-bit symbol frequency table (can be NULL). 325 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 326 | * @param I [0..(n-1)/r] The input auxiliary indexes. 327 | * @return 0 if no error occurred, -1 or -2 otherwise. 328 | */ 329 | LIBSAIS16_API int32_t libsais16_unbwt_aux_ctx(const void * ctx, const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t r, const int32_t * I); 330 | 331 | #if defined(LIBSAIS_OPENMP) 332 | /** 333 | * Constructs the original 16-bit string from a given burrows-wheeler transformed 16-bit string (BWT) with primary index in parallel using OpenMP. 334 | * @param T [0..n-1] The input 16-bit string. 335 | * @param U [0..n-1] The output 16-bit string (can be T). 336 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 337 | * @param n The length of the given 16-bit string. 338 | * @param freq [0..65535] The input 16-bit symbol frequency table (can be NULL). 339 | * @param i The primary index. 340 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 341 | * @return 0 if no error occurred, -1 or -2 otherwise. 342 | */ 343 | LIBSAIS16_API int32_t libsais16_unbwt_omp(const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t i, int32_t threads); 344 | 345 | /** 346 | * Constructs the original 16-bit string from a given burrows-wheeler transformed 16-bit string (BWT) with auxiliary indexes in parallel using OpenMP. 347 | * @param T [0..n-1] The input 16-bit string. 348 | * @param U [0..n-1] The output 16-bit string (can be T). 349 | * @param A [0..n] The temporary array (NOTE, temporary array must be n + 1 size). 350 | * @param n The length of the given 16-bit string. 351 | * @param freq [0..65535] The input 16-bit symbol frequency table (can be NULL). 352 | * @param r The sampling rate for auxiliary indexes (must be power of 2). 353 | * @param I [0..(n-1)/r] The input auxiliary indexes. 354 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 355 | * @return 0 if no error occurred, -1 or -2 otherwise. 356 | */ 357 | LIBSAIS16_API int32_t libsais16_unbwt_aux_omp(const uint16_t * T, uint16_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t r, const int32_t * I, int32_t threads); 358 | #endif 359 | 360 | /** 361 | * Constructs the permuted longest common prefix array (PLCP) of a given 16-bit string and a suffix array. 362 | * @param T [0..n-1] The input 16-bit string. 363 | * @param SA [0..n-1] The input suffix array. 364 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 365 | * @param n The length of the 16-bit string and the suffix array. 366 | * @return 0 if no error occurred, -1 otherwise. 367 | */ 368 | LIBSAIS16_API int32_t libsais16_plcp(const uint16_t * T, const int32_t * SA, int32_t * PLCP, int32_t n); 369 | 370 | /** 371 | * Constructs the permuted longest common prefix array (PLCP) of a given 16-bit string set and a generalized suffix array (GSA). 372 | * @param T [0..n-1] The input 16-bit string set using 0 as separators (T[n-1] must be 0). 373 | * @param SA [0..n-1] The input generalized suffix array. 374 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 375 | * @param n The length of the string set and the generalized suffix array. 376 | * @return 0 if no error occurred, -1 otherwise. 377 | */ 378 | LIBSAIS16_API int32_t libsais16_plcp_gsa(const uint16_t * T, const int32_t * SA, int32_t * PLCP, int32_t n); 379 | 380 | /** 381 | * Constructs the longest common prefix array (LCP) of a given permuted longest common prefix array (PLCP) and a suffix array. 382 | * @param PLCP [0..n-1] The input permuted longest common prefix array. 383 | * @param SA [0..n-1] The input suffix array or generalized suffix array (GSA). 384 | * @param LCP [0..n-1] The output longest common prefix array (can be SA). 385 | * @param n The length of the permuted longest common prefix array and the suffix array. 386 | * @return 0 if no error occurred, -1 otherwise. 387 | */ 388 | LIBSAIS16_API int32_t libsais16_lcp(const int32_t * PLCP, const int32_t * SA, int32_t * LCP, int32_t n); 389 | 390 | #if defined(LIBSAIS_OPENMP) 391 | /** 392 | * Constructs the permuted longest common prefix array (PLCP) of a given 16-bit string and a suffix array in parallel using OpenMP. 393 | * @param T [0..n-1] The input 16-bit string. 394 | * @param SA [0..n-1] The input suffix array. 395 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 396 | * @param n The length of the 16-bit string and the suffix array. 397 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 398 | * @return 0 if no error occurred, -1 otherwise. 399 | */ 400 | LIBSAIS16_API int32_t libsais16_plcp_omp(const uint16_t * T, const int32_t * SA, int32_t * PLCP, int32_t n, int32_t threads); 401 | 402 | /** 403 | * Constructs the permuted longest common prefix array (PLCP) of a given 16-bit string set and a generalized suffix array (GSA) in parallel using OpenMP. 404 | * @param T [0..n-1] The input 16-bit string set using 0 as separators (T[n-1] must be 0). 405 | * @param SA [0..n-1] The input generalized suffix array. 406 | * @param PLCP [0..n-1] The output permuted longest common prefix array. 407 | * @param n The length of the string set and the generalized suffix array. 408 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 409 | * @return 0 if no error occurred, -1 otherwise. 410 | */ 411 | LIBSAIS16_API int32_t libsais16_plcp_gsa_omp(const uint16_t * T, const int32_t * SA, int32_t * PLCP, int32_t n, int32_t threads); 412 | 413 | /** 414 | * Constructs the longest common prefix array (LCP) of a given permuted longest common prefix array (PLCP) and a suffix array in parallel using OpenMP. 415 | * @param PLCP [0..n-1] The input permuted longest common prefix array. 416 | * @param SA [0..n-1] The input suffix array or generalized suffix array (GSA). 417 | * @param LCP [0..n-1] The output longest common prefix array (can be SA). 418 | * @param n The length of the permuted longest common prefix array and the suffix array. 419 | * @param threads The number of OpenMP threads to use (can be 0 for OpenMP default). 420 | * @return 0 if no error occurred, -1 otherwise. 421 | */ 422 | LIBSAIS16_API int32_t libsais16_lcp_omp(const int32_t * PLCP, const int32_t * SA, int32_t * LCP, int32_t n, int32_t threads); 423 | #endif 424 | 425 | #ifdef __cplusplus 426 | } 427 | #endif 428 | 429 | #endif 430 | -------------------------------------------------------------------------------- /m03_model.h: -------------------------------------------------------------------------------- 1 | /*-- 2 | 3 | This file is a part of bsc-m03 project. 4 | 5 | Copyright (c) 2021-2024 Ilya Grebnov 6 | 7 | bsc-m03 is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | bsc-m03 is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with bsc-m03. If not, see . 19 | 20 | --*/ 21 | 22 | #pragma once 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | #include 29 | 30 | #include "common/platform.h" 31 | #include "common/rangecoder.h" 32 | 33 | #include "m03_tables.h" 34 | 35 | #pragma warning( push ) 36 | #pragma warning( disable : 6385 ) 37 | #pragma warning( disable : 6386 ) 38 | 39 | enum m03_mode { encoding, decoding }; 40 | 41 | template class m03_model 42 | { 43 | protected: 44 | void initialize_model(RangeCoder * coder) 45 | { 46 | this->coder = coder; 47 | 48 | this->memset_uint16(this->T1_model , 1, sizeof(this->T1_model)); 49 | 50 | this->memset_uint16(this->T2_model_m0 , 1, sizeof(this->T2_model_m0)); 51 | this->memset_uint16(this->T2_model_m1 , 1, sizeof(this->T2_model_m1)); 52 | 53 | this->memset_uint16(this->T3_model_m0 , 1, sizeof(this->T2_model_m0)); 54 | this->memset_uint16(this->T3_model_m1 , 1, sizeof(this->T3_model_m1)); 55 | this->memset_uint16(this->T3_model_m2 , 1, sizeof(this->T3_model_m2)); 56 | 57 | this->memset_uint16(this->Tx_model_m0 , 1, sizeof(this->Tx_model_m0)); 58 | this->memset_uint16(this->Tx_model_m1 , 1, sizeof(this->Tx_model_m1)); 59 | this->memset_uint16(this->Tx_model_m2 , 1, sizeof(this->Tx_model_m2)); 60 | } 61 | 62 | void encode_root_frequencies(const int32_t * root_frequencies, int32_t k, int32_t n) 63 | { 64 | int64_t bit_freq[33]; 65 | int64_t bit_freq_sum[33]; 66 | 67 | { 68 | int64_t remaining_min = n, remaining_max = n, remaining_count = k; 69 | 70 | memset(bit_freq, 0, sizeof(bit_freq)); 71 | 72 | for (ptrdiff_t p = 0; p < k; ++p) 73 | { 74 | bit_freq[bit_scan_reverse(root_frequencies[p] + 1)]++; 75 | } 76 | 77 | for (ptrdiff_t bit = 0; bit <= 32 && remaining_count > 0; ++bit) 78 | { 79 | int64_t min_value = (1ll << (bit + 0)) - 1; 80 | int64_t max_value = (1ll << (bit + 1)) - 2; 81 | int64_t min = std::max(remaining_count - (remaining_max / (max_value + 1)), (int64_t)0); 82 | int64_t max = remaining_count * max_value < remaining_min ? remaining_count - 1 : remaining_count; 83 | 84 | this->coder->EncodeValue((unsigned int)min, (unsigned int)bit_freq[bit], (unsigned int)max); 85 | 86 | remaining_min -= bit_freq[bit] * max_value; 87 | remaining_max -= bit_freq[bit] * min_value; 88 | remaining_count -= bit_freq[bit]; 89 | } 90 | } 91 | 92 | { 93 | int64_t bit_sum = 0, remaining_min = 0, remaining_max = 0, remaining_total = n; 94 | 95 | for (ptrdiff_t bit = 32; bit >= 0; --bit) 96 | { 97 | int64_t min_value = (1ll << (bit + 0)) - 1; 98 | int64_t max_value = (1ll << (bit + 1)) - 2; 99 | 100 | bit_freq_sum[bit] = bit_sum; bit_sum += bit_freq[bit]; 101 | 102 | remaining_min += min_value * bit_freq[bit]; 103 | remaining_max += max_value * bit_freq[bit]; 104 | } 105 | 106 | for (ptrdiff_t p = 0; p < k; ++p) 107 | { 108 | int32_t bit = bit_scan_reverse(root_frequencies[p] + 1); 109 | 110 | { 111 | for (ptrdiff_t b = 0; b < bit; ++b) 112 | { 113 | if (bit_freq[b] > 0) 114 | { 115 | this->coder->Encode((unsigned int)bit_freq[b], (unsigned int)bit_freq_sum[b], (unsigned int)(bit_freq[b] + bit_freq_sum[b])); 116 | } 117 | 118 | assert(bit_freq_sum[b] > 0); bit_freq_sum[b]--; 119 | } 120 | 121 | if (bit_freq_sum[bit] > 0) 122 | { 123 | this->coder->Encode(0, (unsigned int)bit_freq[bit], (unsigned int)(bit_freq[bit] + bit_freq_sum[bit])); 124 | } 125 | 126 | assert(bit_freq[bit] > 0); bit_freq[bit]--; 127 | } 128 | 129 | { 130 | int64_t min_value = (1ll << (bit + 0)) - 1; 131 | int64_t max_value = (1ll << (bit + 1)) - 2; 132 | remaining_min -= min_value; 133 | remaining_max -= max_value; 134 | int64_t min = std::max(min_value, remaining_total - remaining_max); 135 | int64_t max = std::min(max_value, remaining_total - remaining_min); 136 | 137 | this->coder->EncodeValue((unsigned int)min, (unsigned int)root_frequencies[p], (unsigned int)max); 138 | 139 | remaining_total -= root_frequencies[p]; 140 | } 141 | } 142 | } 143 | } 144 | 145 | void decode_root_frequencies(int32_t * root_frequencies, int32_t k, int32_t n) 146 | { 147 | int64_t bit_freq[33]; 148 | int64_t bit_freq_sum[33]; 149 | 150 | { 151 | int64_t remaining_min = n, remaining_max = n, remaining_count = k; 152 | 153 | memset(bit_freq, 0, sizeof(bit_freq)); 154 | 155 | for (ptrdiff_t bit = 0; bit <= 32 && remaining_count > 0; ++bit) 156 | { 157 | int64_t min_value = (1ll << (bit + 0)) - 1; 158 | int64_t max_value = (1ll << (bit + 1)) - 2; 159 | int64_t min = std::max(remaining_count - (remaining_max / (max_value + 1)), (int64_t)0); 160 | int64_t max = remaining_count * max_value < remaining_min ? remaining_count - 1 : remaining_count; 161 | 162 | bit_freq[bit] = this->coder->DecodeValue((unsigned int)min, (unsigned int)max); 163 | 164 | remaining_min -= bit_freq[bit] * max_value; 165 | remaining_max -= bit_freq[bit] * min_value; 166 | remaining_count -= bit_freq[bit]; 167 | } 168 | } 169 | 170 | { 171 | int64_t bit_sum = 0, remaining_min = 0, remaining_max = 0, remaining_total = n; 172 | 173 | for (ptrdiff_t bit = 32; bit >= 0; --bit) 174 | { 175 | int64_t min_value = (1ll << (bit + 0)) - 1; 176 | int64_t max_value = (1ll << (bit + 1)) - 2; 177 | 178 | bit_freq_sum[bit] = bit_sum; bit_sum += bit_freq[bit]; 179 | 180 | remaining_min += min_value * bit_freq[bit]; 181 | remaining_max += max_value * bit_freq[bit]; 182 | } 183 | 184 | for (ptrdiff_t p = 0; p < k; ++p) 185 | { 186 | int32_t bit = 0; 187 | 188 | while (bit_freq_sum[bit] > 0) 189 | { 190 | if (bit_freq[bit] > 0) 191 | { 192 | unsigned int cum_freq = this->coder->GetCumFreq((unsigned int)(bit_freq[bit] + bit_freq_sum[bit])); 193 | if (cum_freq < bit_freq[bit]) 194 | { 195 | this->coder->Decode(0, (unsigned int)bit_freq[bit], (unsigned int)(bit_freq[bit] + bit_freq_sum[bit])); 196 | break; 197 | } 198 | else 199 | { 200 | this->coder->Decode((unsigned int)bit_freq[bit], (unsigned int)bit_freq_sum[bit], (unsigned int)(bit_freq[bit] + bit_freq_sum[bit]));; 201 | } 202 | } 203 | 204 | bit_freq_sum[bit]--; bit++; 205 | } 206 | 207 | assert(bit_freq[bit] > 0); bit_freq[bit]--; 208 | 209 | { 210 | int64_t min_value = (1ll << (bit + 0)) - 1; 211 | int64_t max_value = (1ll << (bit + 1)) - 2; 212 | remaining_min -= min_value; 213 | remaining_max -= max_value; 214 | int64_t min = std::max(min_value, remaining_total - remaining_max); 215 | int64_t max = std::min(max_value, remaining_total - remaining_min); 216 | 217 | root_frequencies[p] = this->coder->DecodeValue((unsigned int)min, (unsigned int)max); 218 | 219 | remaining_total -= root_frequencies[p]; 220 | } 221 | } 222 | } 223 | } 224 | 225 | int32_t predict(int32_t count, int32_t total, int32_t left_remaining, int32_t right_remaining, int32_t symbols_remaining, int32_t context) 226 | { 227 | int32_t inferred_right = std::max(total - left_remaining, 0); total -= inferred_right; right_remaining -= inferred_right << 1; 228 | 229 | assert(left_remaining > 0); assert(right_remaining > 0); assert(total <= left_remaining); assert(left_remaining <= right_remaining); 230 | 231 | if (total <= 3) 232 | { 233 | int32_t state = 0; 234 | state += 1 * (context); 235 | state += 32 * (std::min((int32_t)symbols_remaining - 2, 7)); 236 | state += 256 * (std::min((int32_t)bit_scan_reverse(inferred_right + 1), 3)); 237 | state += 1024 * (left_remaining + right_remaining + inferred_right == symbols_remaining); 238 | state += 2048 * (left_remaining == total); 239 | state += 4096 * (((int64_t)left_remaining * 11) / ((int64_t)right_remaining)); 240 | 241 | if (total == 1) 242 | { 243 | ptrdiff_t bucket = m03_T1_model_m0_state_table[state]; 244 | 245 | uint16_t * RESTRICT predictor = &this->T1_model[bucket][0]; 246 | if (predictor[0] + predictor[1] > m03_T1_model_m0_scale_table[bucket]) 247 | { 248 | predictor[0] = (predictor[0] + 1) >> 1; 249 | predictor[1] = (predictor[1] + 1) >> 1; 250 | } 251 | 252 | if (mode == m03_mode::encoding) 253 | { 254 | this->coder->Encode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 255 | } 256 | else 257 | { 258 | count = this->coder->GetCumFreq(predictor[0] + predictor[1]) >= predictor[0]; 259 | this->coder->Decode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 260 | } 261 | 262 | predictor[count]++; 263 | } 264 | else if (total == 2) 265 | { 266 | int32_t pivot = (count == 0) | (count == 2); 267 | 268 | { 269 | ptrdiff_t bucket = m03_T2_model_m0_state_table[state]; 270 | 271 | uint16_t * RESTRICT predictor = &this->T2_model_m0[bucket][0]; 272 | if (predictor[0] + predictor[1] > m03_T2_model_m0_scale_table[bucket]) 273 | { 274 | predictor[0] = (predictor[0] + 1) >> 1; 275 | predictor[1] = (predictor[1] + 1) >> 1; 276 | } 277 | 278 | if (mode == m03_mode::encoding) 279 | { 280 | this->coder->Encode(pivot ? predictor[0] : 0, predictor[pivot], predictor[0] + predictor[1]); 281 | } 282 | else 283 | { 284 | pivot = this->coder->GetCumFreq(predictor[0] + predictor[1]) >= predictor[0]; 285 | this->coder->Decode(pivot ? predictor[0] : 0, predictor[pivot], predictor[0] + predictor[1]); 286 | } 287 | 288 | predictor[pivot]++; 289 | } 290 | 291 | if (pivot) 292 | { 293 | count = count > 0; 294 | 295 | { 296 | ptrdiff_t bucket = m03_T2_model_m1_state_table[state]; 297 | 298 | uint16_t * RESTRICT predictor = &this->T2_model_m1[bucket][0]; 299 | if (predictor[0] + predictor[1] > m03_T2_model_m1_scale_table[bucket]) 300 | { 301 | predictor[0] = (predictor[0] + 1) >> 1; 302 | predictor[1] = (predictor[1] + 1) >> 1; 303 | } 304 | 305 | if (mode == m03_mode::encoding) 306 | { 307 | this->coder->Encode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 308 | } 309 | else 310 | { 311 | count = this->coder->GetCumFreq(predictor[0] + predictor[1]) >= predictor[0]; 312 | this->coder->Decode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 313 | } 314 | 315 | predictor[count]++; 316 | } 317 | 318 | count = count ? total : count; 319 | } 320 | else 321 | { 322 | count = 1; 323 | } 324 | } 325 | else 326 | { 327 | int32_t pivot = (count == 0) | (count == 3); 328 | 329 | { 330 | ptrdiff_t bucket = m03_T3_model_m0_state_table[state]; 331 | 332 | uint16_t * RESTRICT predictor = &this->T3_model_m0[bucket][0]; 333 | if (predictor[0] + predictor[1] > m03_T3_model_m0_scale_table[bucket]) 334 | { 335 | predictor[0] = (predictor[0] + 1) >> 1; 336 | predictor[1] = (predictor[1] + 1) >> 1; 337 | } 338 | 339 | if (mode == m03_mode::encoding) 340 | { 341 | this->coder->Encode(pivot ? predictor[0] : 0, predictor[pivot], predictor[0] + predictor[1]); 342 | } 343 | else 344 | { 345 | pivot = this->coder->GetCumFreq(predictor[0] + predictor[1]) >= predictor[0]; 346 | this->coder->Decode(pivot ? predictor[0] : 0, predictor[pivot], predictor[0] + predictor[1]); 347 | } 348 | 349 | predictor[pivot]++; 350 | } 351 | 352 | if (pivot) 353 | { 354 | count = count > 0; 355 | 356 | { 357 | ptrdiff_t bucket = m03_T3_model_m1_state_table[state]; 358 | 359 | uint16_t * RESTRICT predictor = &this->T3_model_m1[bucket][0]; 360 | if (predictor[0] + predictor[1] > m03_T3_model_m1_scale_table[bucket]) 361 | { 362 | predictor[0] = (predictor[0] + 1) >> 1; 363 | predictor[1] = (predictor[1] + 1) >> 1; 364 | } 365 | 366 | if (mode == m03_mode::encoding) 367 | { 368 | this->coder->Encode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 369 | } 370 | else 371 | { 372 | count = this->coder->GetCumFreq(predictor[0] + predictor[1]) >= predictor[0]; 373 | this->coder->Decode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 374 | } 375 | 376 | predictor[count]++; 377 | } 378 | 379 | count = count ? total : count; 380 | } 381 | else 382 | { 383 | count = count - 1; 384 | 385 | { 386 | ptrdiff_t bucket = m03_T3_model_m2_state_table[state]; 387 | 388 | uint16_t * RESTRICT predictor = &this->T3_model_m2[bucket][0]; 389 | if (predictor[0] + predictor[1] > m03_T3_model_m2_scale_table[bucket]) 390 | { 391 | predictor[0] = (predictor[0] + 1) >> 1; 392 | predictor[1] = (predictor[1] + 1) >> 1; 393 | } 394 | 395 | if (mode == m03_mode::encoding) 396 | { 397 | this->coder->Encode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 398 | } 399 | else 400 | { 401 | count = this->coder->GetCumFreq(predictor[0] + predictor[1]) >= predictor[0]; 402 | this->coder->Decode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 403 | } 404 | 405 | predictor[count]++; 406 | } 407 | 408 | count = count + 1; 409 | } 410 | } 411 | } 412 | else 413 | { 414 | int32_t state = 0; 415 | state += 1 * (std::min((int32_t)bit_scan_reverse(total - 3), 7)); 416 | state += 8 * (context); 417 | state += 256 * (std::min((int32_t)bit_scan_reverse(symbols_remaining - 1), 3)); 418 | state += 1024 * (left_remaining == total); 419 | state += 2048 * (inferred_right > 0); 420 | state += 4096 * (((int64_t)left_remaining * 11) / ((int64_t)right_remaining)); 421 | 422 | int32_t pivot = (count == 0) | (count == total); 423 | 424 | { 425 | ptrdiff_t bucket = m03_Tx_model_m0_state_table[state]; 426 | 427 | uint16_t * RESTRICT predictor = &this->Tx_model_m0[bucket][0]; 428 | if (predictor[0] + predictor[1] > m03_Tx_model_m0_scale_table[bucket]) 429 | { 430 | predictor[0] = (predictor[0] + 1) >> 1; 431 | predictor[1] = (predictor[1] + 1) >> 1; 432 | } 433 | 434 | if (mode == m03_mode::encoding) 435 | { 436 | this->coder->Encode(pivot ? predictor[0] : 0, predictor[pivot], predictor[0] + predictor[1]); 437 | } 438 | else 439 | { 440 | pivot = this->coder->GetCumFreq(predictor[0] + predictor[1]) >= predictor[0]; 441 | this->coder->Decode(pivot ? predictor[0] : 0, predictor[pivot], predictor[0] + predictor[1]); 442 | } 443 | 444 | predictor[pivot]++; 445 | } 446 | 447 | if (pivot) 448 | { 449 | count = count > 0; 450 | 451 | { 452 | ptrdiff_t bucket = m03_Tx_model_m1_state_table[state]; 453 | 454 | uint16_t * RESTRICT predictor = &this->Tx_model_m1[bucket][0]; 455 | if (predictor[0] + predictor[1] > m03_Tx_model_m1_scale_table[bucket]) 456 | { 457 | predictor[0] = (predictor[0] + 1) >> 1; 458 | predictor[1] = (predictor[1] + 1) >> 1; 459 | } 460 | 461 | if (mode == m03_mode::encoding) 462 | { 463 | this->coder->Encode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 464 | } 465 | else 466 | { 467 | count = this->coder->GetCumFreq(predictor[0] + predictor[1]) >= predictor[0]; 468 | this->coder->Decode(count ? predictor[0] : 0, predictor[count], predictor[0] + predictor[1]); 469 | } 470 | 471 | predictor[count]++; 472 | } 473 | 474 | count = count ? total : count; 475 | } 476 | else 477 | { 478 | state = 0; 479 | state += 1 * (std::min(total - 4, 15)); 480 | state += 16 * (context & 3); 481 | state += 64 * (((int64_t)left_remaining * 7) / ((int64_t)right_remaining)); 482 | state += 512 * (std::min((int32_t)bit_scan_reverse(symbols_remaining - 1), 3)); 483 | state += 2048 * (inferred_right >= total); 484 | 485 | int32_t min = 1, max = total - 1; context = 1; 486 | while (min != max && context < 16) 487 | { 488 | ptrdiff_t bucket = m03_Tx_model_m2_state_table[state * 16 + context]; 489 | 490 | uint16_t * RESTRICT predictor = &this->Tx_model_m2[bucket][0]; 491 | if (predictor[0] + predictor[1] > m03_Tx_model_m2_scale_table[bucket]) 492 | { 493 | predictor[0] = (predictor[0] + 1) >> 1; 494 | predictor[1] = (predictor[1] + 1) >> 1; 495 | } 496 | 497 | int32_t median = min + ((max - min + 1) >> 1), bit = count >= median; 498 | 499 | if (mode == m03_mode::encoding) 500 | { 501 | this->coder->Encode(bit ? predictor[0] : 0, predictor[bit], predictor[0] + predictor[1]); 502 | } 503 | else 504 | { 505 | bit = this->coder->GetCumFreq(predictor[0] + predictor[1]) >= predictor[0]; 506 | this->coder->Decode(bit ? predictor[0] : 0, predictor[bit], predictor[0] + predictor[1]); 507 | } 508 | 509 | predictor[bit]++; context += context + bit; min = bit ? median : min; max = bit ? max : median - 1; 510 | } 511 | 512 | count = mode == m03_mode::encoding 513 | ? this->coder->EncodeValue(min, count, max) 514 | : this->coder->DecodeValue(min, max); 515 | } 516 | } 517 | 518 | return count; 519 | } 520 | 521 | private: 522 | RangeCoder * coder; 523 | 524 | uint16_t T1_model[128][2]; 525 | 526 | uint16_t T2_model_m0[48][2]; 527 | uint16_t T2_model_m1[80][2]; 528 | 529 | uint16_t T3_model_m0[48][2]; 530 | uint16_t T3_model_m1[64][2]; 531 | uint16_t T3_model_m2[32][2]; 532 | 533 | uint16_t Tx_model_m0[64][2]; 534 | uint16_t Tx_model_m1[80][2]; 535 | uint16_t Tx_model_m2[256][2]; 536 | 537 | void memset_uint16(void * RESTRICT dst, uint16_t v, size_t size) 538 | { 539 | for (size_t i = 0; i < size / 2; ++i) { ((uint16_t *)dst)[i] = v; } 540 | } 541 | }; 542 | 543 | #pragma warning( pop ) 544 | -------------------------------------------------------------------------------- /m03_parser.h: -------------------------------------------------------------------------------- 1 | /*-- 2 | 3 | This file is a part of bsc-m03 project. 4 | 5 | Copyright (c) 2021-2024 Ilya Grebnov 6 | 7 | bsc-m03 is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | bsc-m03 is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with bsc-m03. If not, see . 19 | 20 | --*/ 21 | 22 | #pragma once 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | #include 29 | 30 | #include "common/platform.h" 31 | #include "common/rangecoder.h" 32 | 33 | #include "hutucker/hu-tucker.h" 34 | #include "ska_sort/ska_sort.hpp" 35 | 36 | #include "m03_model.h" 37 | 38 | #define OPTIMAL_ABT_SMALL_THRESHOLD (7) 39 | #define OPTIMAL_ABT_LARGE_THRESHOLD (256) 40 | #define MAX_SYMBOL_PIVOTS (64) 41 | 42 | #pragma warning( push ) 43 | #pragma warning( disable : 6385 ) 44 | #pragma warning( disable : 6386 ) 45 | 46 | typedef struct offset_queue 47 | { 48 | int32_t * offsets; 49 | ptrdiff_t count; 50 | ptrdiff_t size; 51 | 52 | bool initialize(ptrdiff_t size) 53 | { 54 | this->count = 0; 55 | this->size = size; 56 | this->offsets = (int32_t *)malloc(this->size * sizeof(int32_t)); 57 | 58 | return this->offsets != NULL; 59 | } 60 | 61 | INLINE void push_offset(const int32_t offset) 62 | { 63 | if (this->count == this->size) 64 | { 65 | this->offsets = this->resize(); 66 | } 67 | 68 | this->offsets[this->count++] = offset; 69 | } 70 | 71 | INLINE void reset() { this->count = 0; } 72 | 73 | INLINE void sort() { ska_sort(this->offsets, this->offsets + this->count); } 74 | 75 | NOINLINE int32_t * resize() 76 | { 77 | return (int32_t *)realloc(this->offsets, (this->size += this->size) * sizeof(int32_t)); 78 | } 79 | 80 | void destroy() 81 | { 82 | if (this->offsets != NULL) { free(this->offsets); this->offsets = NULL; } 83 | } 84 | 85 | } offset_queue; 86 | 87 | template 88 | class m03_parser: m03_model 89 | { 90 | public: 91 | 92 | bool initialize(symbol_t * L, int32_t n, int32_t primary_index, int32_t * root_frequencies, int32_t k, RangeCoder * coder) 93 | { 94 | memset(this, 0, sizeof(m03_parser)); 95 | 96 | this->L = L; 97 | this->n = n; 98 | this->primary_index = primary_index; 99 | this->root_frequencies = root_frequencies; 100 | this->k = k; 101 | 102 | if ((this->contexts = (symbol_context *)malloc(n * sizeof(symbol_context))) == NULL) 103 | { 104 | this->destroy(); 105 | return false; 106 | } 107 | 108 | if ((this->hutucker_tmp = malloc(hutucker_tmp_size(MAX_ALPHABET_SIZE + 1))) == NULL) 109 | { 110 | this->destroy(); 111 | return false; 112 | } 113 | 114 | if (!current_segments.initialize(next_power_of_2(std::max(n / 4, 64)))) 115 | { 116 | this->destroy(); 117 | return false; 118 | } 119 | 120 | if (!next_segments.initialize(next_power_of_2(std::max(n / 4, 64)))) 121 | { 122 | this->destroy(); 123 | return false; 124 | } 125 | 126 | memset(this->contexts, 0, n * sizeof(symbol_context)); 127 | 128 | this->initialize_model(coder); 129 | this->initialize_alphabetic_tree_roots(); 130 | 131 | return true; 132 | } 133 | 134 | void run() 135 | { 136 | if (mode == m03_mode::encoding) 137 | { 138 | this->encode_root_frequencies(this->root_frequencies, this->k, this->n - 1); 139 | this->initialize_root_context(this->root_frequencies); 140 | this->parse_contexts(); 141 | 142 | for (ptrdiff_t p = 0; p < n; ++p) 143 | { 144 | assert(p == this->primary_index || this->contexts[p].count == 1 ); 145 | assert(p == this->primary_index || this->contexts[p].symbol == L[p]); 146 | } 147 | } 148 | else 149 | { 150 | this->decode_root_frequencies(this->root_frequencies, this->k, this->n - 1); 151 | this->initialize_root_context(this->root_frequencies); 152 | this->parse_contexts(); 153 | 154 | for (ptrdiff_t p = 0; p < n; ++p) 155 | { 156 | L[p] = this->contexts[p].symbol; 157 | } 158 | } 159 | } 160 | 161 | void destroy() 162 | { 163 | if (this->contexts != NULL) { free(this->contexts); this->contexts = NULL; } 164 | if (this->hutucker_tmp != NULL) { free(this->hutucker_tmp); this->hutucker_tmp = NULL; } 165 | 166 | this->current_segments.destroy(); 167 | this->next_segments.destroy(); 168 | } 169 | 170 | private: 171 | 172 | #pragma pack(push, 1) 173 | 174 | typedef struct symbol_context 175 | { 176 | int32_t count; 177 | int32_t offset; 178 | symbol_t symbol; 179 | } symbol_context; 180 | 181 | #pragma pack(pop) 182 | 183 | symbol_t * L; 184 | int32_t n; 185 | int32_t primary_index; 186 | int32_t * root_frequencies; 187 | int32_t k; 188 | 189 | symbol_context * contexts; 190 | offset_queue current_segments; 191 | offset_queue next_segments; 192 | void * hutucker_tmp; 193 | 194 | int32_t parent_frequencies [MAX_ALPHABET_SIZE]; 195 | int32_t left_frequencies [MAX_ALPHABET_SIZE]; 196 | symbol_context left_contexts [MAX_ALPHABET_SIZE]; 197 | uint8_t symbol_pivots [MAX_ALPHABET_SIZE][MAX_SYMBOL_PIVOTS]; 198 | 199 | int32_t alphabetic_tree_keys[OPTIMAL_ABT_LARGE_THRESHOLD]; 200 | int32_t alphabetic_tree_weight[OPTIMAL_ABT_LARGE_THRESHOLD]; 201 | int64_t alphabetic_tree_cost[OPTIMAL_ABT_LARGE_THRESHOLD][OPTIMAL_ABT_LARGE_THRESHOLD]; 202 | uint8_t alphabetic_tree_root[OPTIMAL_ABT_LARGE_THRESHOLD][OPTIMAL_ABT_LARGE_THRESHOLD]; 203 | 204 | void initialize_alphabetic_tree_roots() 205 | { 206 | for (int32_t l = 0; l < OPTIMAL_ABT_LARGE_THRESHOLD - 1; ++l) 207 | { 208 | this->alphabetic_tree_root[l][l] = this->alphabetic_tree_root[l][l + 1] = l; 209 | } 210 | } 211 | 212 | void initialize_root_context(const int32_t * root_frequencies) 213 | { 214 | int32_t unique_symbols = 0, total_symbols = 1; 215 | 216 | this->current_segments.push_offset(0); 217 | 218 | for (int32_t c = 0; c < this->k; ++c) 219 | { 220 | if (root_frequencies[c] > 0) 221 | { 222 | this->contexts[unique_symbols].count = root_frequencies[c]; 223 | this->contexts[unique_symbols].offset = total_symbols; 224 | this->contexts[unique_symbols].symbol = c; 225 | 226 | this->current_segments.push_offset(total_symbols); 227 | 228 | unique_symbols++; total_symbols += root_frequencies[c]; 229 | } 230 | } 231 | 232 | m03_parser::normalize_context(&this->contexts[0], unique_symbols, total_symbols); 233 | } 234 | 235 | void parse_contexts() 236 | { 237 | while (this->current_segments.count > 0) 238 | { 239 | for (int32_t segment_start = 0; segment_start < this->current_segments.count;) 240 | { 241 | int32_t context_start = this->current_segments.offsets[segment_start]; 242 | int32_t context_end = context_start + this->contexts[context_start].count; 243 | int32_t segment_end = segment_start + 1; 244 | 245 | while (segment_end < this->current_segments.count && this->current_segments.offsets[segment_end] < context_end) 246 | { 247 | segment_end++; 248 | } 249 | 250 | assert(context_end - context_start > 1); 251 | assert(segment_end - segment_start > 1); 252 | 253 | if (this->is_trivial_context(context_start)) 254 | { 255 | m03_parser::split_trivial_context(this->contexts, this->next_segments, &this->current_segments.offsets[segment_start], &this->current_segments.offsets[segment_end]); 256 | } 257 | else 258 | { 259 | m03_parser::populate_context_frequencies(&this->contexts[context_start], &this->contexts[this->primary_index], &this->parent_frequencies[0]); 260 | this->split_context_recursive(&this->current_segments.offsets[segment_start], &this->current_segments.offsets[segment_end], 2); 261 | } 262 | 263 | segment_start = segment_end; 264 | } 265 | 266 | this->next_segments.sort(); 267 | this->current_segments.reset(); 268 | 269 | std::swap(this->current_segments, this->next_segments); 270 | } 271 | } 272 | 273 | void split_context_recursive(const int32_t * offsets, const int32_t * offsets_end, int32_t level) 274 | { 275 | assert(offsets_end - offsets > 0); 276 | 277 | if (offsets_end - offsets == 1) 278 | { 279 | m03_parser::populate_next_segments(&this->contexts[offsets[0]], &this->contexts[this->primary_index], &this->parent_frequencies[0], this->next_segments); 280 | return; 281 | } 282 | 283 | if (this->is_trivial_context(offsets[0])) 284 | { 285 | m03_parser::split_trivial_context(this->contexts, this->next_segments, offsets, offsets_end); 286 | return; 287 | } 288 | 289 | if (offsets_end - offsets >= OPTIMAL_ABT_SMALL_THRESHOLD && offsets_end - offsets <= OPTIMAL_ABT_LARGE_THRESHOLD) 290 | { 291 | this->build_optimal_alphabetic_tree(offsets, offsets_end); 292 | this->traverse_alphabetic_tree(offsets, 0, (int32_t)(offsets_end - offsets), level); 293 | return; 294 | } 295 | 296 | const int32_t * offsets_pivot = (offsets_end - offsets) > 2 297 | ? this->choose_context_pivot_using_heuristic(offsets, offsets_end) 298 | : &offsets[1]; 299 | 300 | this->split_context_by_pivot(offsets[0], offsets_pivot[0], level, (int32_t)(offsets_pivot - offsets), (int32_t)(offsets_end - offsets_pivot)); 301 | this->split_context_recursive(offsets, offsets_pivot, level + 1); 302 | this->split_context_recursive(offsets_pivot, offsets_end, level + 1); 303 | } 304 | 305 | void traverse_alphabetic_tree(const int32_t * offsets, int32_t l, int32_t r, int32_t level) 306 | { 307 | assert(l < r); 308 | 309 | if ((r - l < OPTIMAL_ABT_SMALL_THRESHOLD) || this->is_trivial_context(offsets[l])) 310 | { 311 | this->split_context_recursive(&offsets[l], &offsets[r], level); 312 | return; 313 | } 314 | 315 | int32_t offsets_pivot = this->alphabetic_tree_root[l][r - 1] + 1; 316 | 317 | this->split_context_by_pivot(offsets[l], offsets[offsets_pivot], level, offsets_pivot - l, r - offsets_pivot); 318 | this->traverse_alphabetic_tree(offsets, l, offsets_pivot, level + 1); 319 | this->traverse_alphabetic_tree(offsets, offsets_pivot, r, level + 1); 320 | } 321 | 322 | const int32_t * choose_context_pivot_using_heuristic(const int32_t * offsets, const int32_t * offsets_end) 323 | { 324 | assert(offsets_end - offsets > 2); 325 | 326 | int32_t context_begin = offsets[0]; 327 | int32_t context_end = offsets[0] + this->contexts[offsets[0]].count; 328 | size_t offsets_count = offsets_end - offsets; 329 | 330 | if (offsets_count == 3) 331 | { 332 | int64_t A = 1 + (int64_t)(offsets[1] ) - (int64_t)(context_begin); 333 | int64_t C = 1 + (int64_t)(context_end) - (int64_t)(offsets[2]); 334 | 335 | return C <= A ? &offsets[1] : &offsets[2]; 336 | } 337 | else if (offsets_count == 4) 338 | { 339 | int64_t A = 1 + (int64_t)(offsets[1] ) - (int64_t)(context_begin); 340 | int64_t B = 1 + (int64_t)(offsets[2] ) - (int64_t)(offsets[1]); 341 | int64_t C = 1 + (int64_t)(offsets[3] ) - (int64_t)(offsets[2]); 342 | int64_t D = 1 + (int64_t)(context_end) - (int64_t)(offsets[3]); 343 | 344 | const int32_t * offset1 = &offsets[1]; int64_t cost1 = pivot_cost3(B, C, D); 345 | const int32_t * offset2 = &offsets[2]; int64_t cost2 = A + B + C + D; 346 | const int32_t * offset3 = &offsets[3]; int64_t cost3 = pivot_cost3(A, B, C); 347 | 348 | if (cost2 <= cost1) { offset1 = offset2; cost1 = cost2; } 349 | if (cost3 < cost1) { offset1 = offset3; } 350 | 351 | return offset1; 352 | } 353 | else if (offsets_count == 5) 354 | { 355 | int64_t A = 1 + (int64_t)(offsets[1] ) - (int64_t)(context_begin); 356 | int64_t B = 1 + (int64_t)(offsets[2] ) - (int64_t)(offsets[1]); 357 | int64_t C = 1 + (int64_t)(offsets[3] ) - (int64_t)(offsets[2]); 358 | int64_t D = 1 + (int64_t)(offsets[4] ) - (int64_t)(offsets[3]); 359 | int64_t E = 1 + (int64_t)(context_end) - (int64_t)(offsets[4]); 360 | 361 | const int32_t * offset1 = &offsets[1]; int64_t cost1 = pivot_cost4(B, C, D, E); 362 | const int32_t * offset2 = &offsets[2]; int64_t cost2 = A + B + pivot_cost3(C, D, E); 363 | const int32_t * offset3 = &offsets[3]; int64_t cost3 = pivot_cost3(A, B, C) + D + E; 364 | const int32_t * offset4 = &offsets[4]; int64_t cost4 = pivot_cost4(A, B, C, D); 365 | 366 | if (cost2 <= cost1) { offset1 = offset2; cost1 = cost2; } 367 | if (cost3 < cost1) { offset1 = offset3; cost1 = cost3; } 368 | if (cost4 < cost1) { offset1 = offset4; } 369 | 370 | return offset1; 371 | } 372 | else if (offsets_count == 6) 373 | { 374 | int64_t A = 1 + (int64_t)(offsets[1] ) - (int64_t)(context_begin); 375 | int64_t B = 1 + (int64_t)(offsets[2] ) - (int64_t)(offsets[1]); 376 | int64_t C = 1 + (int64_t)(offsets[3] ) - (int64_t)(offsets[2]); 377 | int64_t D = 1 + (int64_t)(offsets[4] ) - (int64_t)(offsets[3]); 378 | int64_t E = 1 + (int64_t)(offsets[5] ) - (int64_t)(offsets[4]); 379 | int64_t F = 1 + (int64_t)(context_end) - (int64_t)(offsets[5]); 380 | 381 | const int32_t * offset1 = &offsets[1]; int64_t cost1 = pivot_cost5(B, C, D, E, F); 382 | const int32_t * offset2 = &offsets[2]; int64_t cost2 = A + B + pivot_cost4(C, D, E, F); 383 | const int32_t * offset3 = &offsets[3]; int64_t cost3 = pivot_cost3(A, B, C) + pivot_cost3(D, E, F); 384 | const int32_t * offset4 = &offsets[4]; int64_t cost4 = pivot_cost4(A, B, C, D) + E + F; 385 | const int32_t * offset5 = &offsets[5]; int64_t cost5 = pivot_cost5(A, B, C, D, E); 386 | 387 | if (cost2 <= cost1) { offset1 = offset2; cost1 = cost2; } 388 | if (cost3 <= cost1) { offset1 = offset3; cost1 = cost3; } 389 | if (cost4 < cost1) { offset1 = offset4; cost1 = cost4; } 390 | if (cost5 < cost1) { offset1 = offset5; } 391 | 392 | return offset1; 393 | } 394 | else 395 | { 396 | assert(offsets_count > OPTIMAL_ABT_LARGE_THRESHOLD); 397 | 398 | { 399 | for (int32_t segment_end = context_end, offsets_index = (int32_t)offsets_count - 1; offsets_index >= 0; --offsets_index) 400 | { 401 | int32_t segment_start = offsets[offsets_index]; 402 | 403 | this->left_frequencies[offsets_index] = 1 + segment_end - segment_start; segment_end = segment_start; 404 | } 405 | 406 | hutucker_get_lengths(offsets_count, (unsigned int *)this->left_frequencies, this->hutucker_tmp); 407 | } 408 | 409 | { 410 | uint8_t path[64] = { 0 }; 411 | for (int32_t offsets_index = 0, length = 0; offsets_index < offsets_count; ++offsets_index) 412 | { 413 | for (; length < this->left_frequencies[offsets_index]; ++length) { path[length] = 0; } 414 | 415 | length = this->left_frequencies[offsets_index]; if (path[0] == 1) { return &offsets[offsets_index]; } 416 | 417 | for (int32_t k = length - 1; k >= 0; --k) { if (path[k] ^= 1) { break; } } 418 | } 419 | } 420 | 421 | return NULL; 422 | } 423 | } 424 | 425 | void build_optimal_alphabetic_tree(const int32_t * offsets, const int32_t * offsets_end) 426 | { 427 | ptrdiff_t offsets_count = (ptrdiff_t)(offsets_end - offsets); 428 | 429 | assert(offsets_count >= OPTIMAL_ABT_SMALL_THRESHOLD && offsets_count <= OPTIMAL_ABT_LARGE_THRESHOLD); 430 | 431 | this->alphabetic_tree_keys[offsets_count - 1] = 1 + offsets[0] + this->contexts[offsets[0]].count - offsets[offsets_count - 1]; 432 | 433 | for (ptrdiff_t offsets_index = offsets_count - 2; offsets_index >= 0; --offsets_index) 434 | { 435 | this->alphabetic_tree_keys[offsets_index] = 1 + offsets[offsets_index + 1] - offsets[offsets_index]; 436 | this->alphabetic_tree_cost[offsets_index][offsets_index + 1] = this->alphabetic_tree_weight[offsets_index] = this->alphabetic_tree_keys[offsets_index] + this->alphabetic_tree_keys[offsets_index + 1]; 437 | } 438 | 439 | for (ptrdiff_t length = 3; length <= offsets_count; ++length) 440 | { 441 | for (ptrdiff_t l = 0, r = length - 1; r < offsets_count; ++l, ++r) 442 | { 443 | uint8_t best_root = this->alphabetic_tree_root[l][r - 1]; 444 | int64_t best_cost = this->alphabetic_tree_cost[l][best_root] + this->alphabetic_tree_cost[best_root + 1][r]; 445 | 446 | for (ptrdiff_t root = (ptrdiff_t)best_root + 1; root <= (ptrdiff_t)this->alphabetic_tree_root[l + 1][r]; ++root) 447 | { 448 | int64_t cost = this->alphabetic_tree_cost[l][root] + this->alphabetic_tree_cost[root + 1][r]; 449 | if (cost < best_cost) { best_cost = cost; best_root = (uint8_t)root; } 450 | } 451 | 452 | this->alphabetic_tree_weight[l] += this->alphabetic_tree_keys[r]; 453 | this->alphabetic_tree_cost[l][r] = best_cost + this->alphabetic_tree_weight[l]; 454 | this->alphabetic_tree_root[l][r] = best_root; 455 | } 456 | } 457 | } 458 | 459 | void split_context_by_pivot(int32_t parent_context_offset, int32_t right_context_offset, int32_t level, int32_t left_subintervals, int32_t right_subintervals) 460 | { 461 | level = std::min(level, MAX_SYMBOL_PIVOTS - 1); 462 | 463 | symbol_context * parent_context = &this->contexts[parent_context_offset]; 464 | int32_t parent_interval_size = parent_context[0].count; 465 | int32_t parent_unique_symbols = 1; 466 | 467 | symbol_context * left_context = &this->left_contexts[0]; 468 | int32_t * left_frequencies = &this->left_frequencies[0]; 469 | int32_t left_interval_size = right_context_offset - parent_context_offset; 470 | int32_t left_unique_symbols = 0; 471 | 472 | int32_t right_interval_size = parent_interval_size - left_interval_size; 473 | int32_t right_unique_symbols = 0; 474 | 475 | if (mode == m03_mode::encoding) 476 | { 477 | if (left_interval_size <= right_interval_size) 478 | { 479 | int32_t parent_total_symbols = parent_interval_size; 480 | 481 | parent_total_symbols -= ((uint32_t)(this->primary_index - parent_context_offset) < (uint32_t)parent_total_symbols); 482 | 483 | while (parent_total_symbols > 1 && parent_context[parent_unique_symbols].count > 0) 484 | { 485 | parent_total_symbols -= parent_context[parent_unique_symbols].count; 486 | left_frequencies[parent_context[parent_unique_symbols].symbol] = 0; 487 | parent_unique_symbols++; 488 | } 489 | 490 | assert(parent_total_symbols > 0); parent_context[0].count = parent_total_symbols; 491 | left_frequencies[parent_context[0].symbol] = 0; 492 | 493 | left_frequencies[0] -= ((uint32_t)(this->primary_index - parent_context_offset) < (uint32_t)left_interval_size); 494 | 495 | for (int32_t p = parent_context_offset; p < parent_context_offset + left_interval_size; ++p) { left_frequencies[L[p]]++; } 496 | } 497 | else 498 | { 499 | int32_t parent_total_symbols = parent_interval_size; 500 | 501 | parent_total_symbols -= ((uint32_t)(this->primary_index - parent_context_offset) < (uint32_t)parent_total_symbols); 502 | 503 | while (parent_total_symbols > 1 && parent_context[parent_unique_symbols].count > 0) 504 | { 505 | parent_total_symbols -= parent_context[parent_unique_symbols].count; 506 | left_frequencies[parent_context[parent_unique_symbols].symbol] = parent_context[parent_unique_symbols].count; 507 | parent_unique_symbols++; 508 | } 509 | 510 | assert(parent_total_symbols > 0); parent_context[0].count = parent_total_symbols; 511 | left_frequencies[parent_context[0].symbol] = parent_total_symbols; 512 | 513 | left_frequencies[0] += ((uint32_t)(this->primary_index - right_context_offset) < (uint32_t)right_interval_size); 514 | 515 | for (int32_t p = right_context_offset; p < right_context_offset + right_interval_size; ++p) { left_frequencies[L[p]]--; } 516 | } 517 | } 518 | else 519 | { 520 | int32_t parent_total_symbols = parent_interval_size; 521 | 522 | parent_total_symbols -= ((uint32_t)(this->primary_index - parent_context_offset) < (uint32_t)parent_total_symbols); 523 | 524 | while (parent_total_symbols > 1 && parent_context[parent_unique_symbols].count > 0) 525 | { 526 | parent_total_symbols -= parent_context[parent_unique_symbols].count; 527 | parent_unique_symbols++; 528 | } 529 | 530 | assert(parent_total_symbols > 0); parent_context[0].count = parent_total_symbols; 531 | } 532 | 533 | int32_t left_leaf = left_subintervals == 1; 534 | int32_t right_leaf = right_subintervals == 1; 535 | 536 | int32_t left_remaining = left_interval_size; 537 | int32_t right_remaining = right_interval_size; 538 | 539 | left_remaining -= ((uint32_t)(this->primary_index - parent_context_offset) < (uint32_t)left_interval_size ); 540 | right_remaining -= ((uint32_t)(this->primary_index - right_context_offset ) < (uint32_t)right_interval_size); 541 | 542 | for (int32_t pivot_history = 0, parent_symbol_index = 0; parent_symbol_index < parent_unique_symbols; ++parent_symbol_index) 543 | { 544 | symbol_t symbol = parent_context[parent_symbol_index].symbol; 545 | int32_t offset = parent_context[parent_symbol_index].offset; 546 | int32_t total = parent_context[parent_symbol_index].count; 547 | int32_t count = mode == m03_mode::encoding ? left_frequencies[symbol] : 0; 548 | 549 | if ((left_remaining > 0) && (right_remaining > 0) && (left_remaining + right_remaining != total)) 550 | { 551 | int32_t context = this->symbol_pivots[symbol][level - 2] | this->symbol_pivots[symbol][level - 1]; 552 | int32_t simple = (total > 1) && (this->contexts[offset].count == total) && (this->contexts[offset + 1].count == 0); 553 | 554 | if (parent_symbol_index == parent_unique_symbols - 2) 555 | { 556 | symbol_t symbol1 = parent_context[parent_symbol_index + 1].symbol; 557 | int32_t offset1 = parent_context[parent_symbol_index + 1].offset; 558 | int32_t total1 = parent_context[parent_symbol_index + 1].count; 559 | 560 | context |= this->symbol_pivots[symbol1][level - 2] | this->symbol_pivots[symbol1][level - 1]; 561 | simple |= (total1 > 1) && (this->contexts[offset1].count == total1) && (this->contexts[offset1 + 1].count == 0); 562 | } 563 | 564 | context += 8 * simple + 16 * pivot_history; 565 | 566 | left_leaf &= (left_remaining == left_interval_size ); 567 | right_leaf &= (right_remaining == right_interval_size); 568 | 569 | if (total <= left_remaining + right_remaining - total) 570 | { 571 | count = left_remaining <= right_remaining 572 | ? this->predict( count, total, left_remaining , right_remaining, parent_unique_symbols - parent_symbol_index, context + 2 * left_leaf + 4 * right_leaf) 573 | : total - this->predict(total - count, total, right_remaining, left_remaining , parent_unique_symbols - parent_symbol_index, context + 2 * right_leaf + 4 * left_leaf); 574 | } 575 | else 576 | { 577 | total = left_remaining + right_remaining - total; 578 | count = left_remaining - count; 579 | 580 | count = left_remaining <= right_remaining 581 | ? this->predict( count, total, left_remaining , right_remaining, parent_unique_symbols - parent_symbol_index, context + 2 * right_leaf + 4 * left_leaf) 582 | : total - this->predict(total - count, total, right_remaining, left_remaining , parent_unique_symbols - parent_symbol_index, context + 2 * left_leaf + 4 * right_leaf); 583 | 584 | count = left_remaining - count; 585 | total = left_remaining + right_remaining - total; 586 | } 587 | } 588 | else 589 | { 590 | count = std::min(left_remaining, total); 591 | } 592 | 593 | pivot_history |= (this->symbol_pivots[symbol][level] = (count == 0) | (count == total)); 594 | 595 | left_remaining = left_remaining - count; 596 | right_remaining = right_remaining + count - total; 597 | 598 | if (count > 0) 599 | { 600 | left_context[left_unique_symbols].count = count; 601 | left_context[left_unique_symbols].offset = parent_context[parent_symbol_index].offset; 602 | left_context[left_unique_symbols].symbol = symbol; 603 | 604 | parent_context[parent_symbol_index].count -= count; 605 | parent_context[parent_symbol_index].offset += count; 606 | 607 | left_unique_symbols++; 608 | } 609 | 610 | if (parent_context[parent_symbol_index].count > 0) 611 | { 612 | parent_context[right_unique_symbols] = parent_context[parent_symbol_index]; 613 | right_unique_symbols++; 614 | } 615 | } 616 | 617 | { 618 | memmove(&this->contexts[right_context_offset], &parent_context[0], right_unique_symbols * sizeof(symbol_context)); 619 | m03_parser::normalize_context(&this->contexts[right_context_offset], right_unique_symbols, right_interval_size); 620 | 621 | memcpy(&parent_context[0], &left_context[0], left_unique_symbols * sizeof(symbol_context)); 622 | m03_parser::normalize_context(&parent_context[0], left_unique_symbols, left_interval_size); 623 | } 624 | } 625 | 626 | INLINE bool is_trivial_context(int32_t context_start) 627 | { 628 | return this->contexts[context_start + 1].count == 0 && ((uint32_t)(this->primary_index - context_start) >= (uint32_t)this->contexts[context_start].count); 629 | } 630 | 631 | static void split_trivial_context(symbol_context * contexts, offset_queue & queue, const int32_t * offsets, const int32_t * offsets_end) 632 | { 633 | int32_t context_start = *offsets++; 634 | symbol_context parent_context = contexts[context_start]; 635 | 636 | for (; offsets < offsets_end;) 637 | { 638 | symbol_context * context = &contexts[context_start]; 639 | int32_t context_end = *offsets++; 640 | int32_t context_size = context_end - context_start; 641 | 642 | queue.push_offset(parent_context.offset); 643 | 644 | context[0].count = context_size; parent_context.count -= context_size; 645 | context[0].offset = parent_context.offset; parent_context.offset += context_size; 646 | context[0].symbol = parent_context.symbol; if (context_size > 1) { context[1].count = 0; } 647 | 648 | context_start = context_end; 649 | } 650 | 651 | queue.push_offset(parent_context.offset); 652 | 653 | contexts[context_start] = parent_context; if (contexts[context_start].count > 1) { contexts[context_start + 1].count = 0; } 654 | } 655 | 656 | static void populate_context_frequencies(symbol_context * context, symbol_context * primary_index_context, int32_t * frequencies) 657 | { 658 | int32_t total_symbols = context[0].count; 659 | int32_t unique_symbols = 1; 660 | 661 | total_symbols -= ((uint32_t)(primary_index_context - context) < (uint32_t)total_symbols); 662 | 663 | while (total_symbols > 1 && context[unique_symbols].count > 0) 664 | { 665 | frequencies[context[unique_symbols].symbol] = context[unique_symbols].count; 666 | total_symbols -= context[unique_symbols].count; unique_symbols++; 667 | } 668 | 669 | assert(total_symbols > 0); frequencies[context[0].symbol] = total_symbols; 670 | } 671 | 672 | static void populate_next_segments(symbol_context * context, symbol_context * primary_index_context, int32_t * frequencies, offset_queue & queue) 673 | { 674 | int32_t total_symbols = context[0].count; 675 | int32_t unique_symbols = 1; 676 | 677 | total_symbols -= ((uint32_t)(primary_index_context - context) < (uint32_t)total_symbols); 678 | 679 | while (total_symbols > 1 && context[unique_symbols].count > 0) 680 | { 681 | if (frequencies[context[unique_symbols].symbol] != context[unique_symbols].count) 682 | { 683 | queue.push_offset(context[unique_symbols].offset); 684 | } 685 | 686 | total_symbols -= context[unique_symbols].count; unique_symbols++; 687 | } 688 | 689 | if (total_symbols > 0 && frequencies[context[0].symbol] != total_symbols) 690 | { 691 | queue.push_offset(context[0].offset); 692 | } 693 | } 694 | 695 | static void normalize_context(symbol_context * context, int32_t unique_symbols, int32_t total_symbols) 696 | { 697 | if (unique_symbols > 1) 698 | { 699 | for (int32_t i = 1; i < unique_symbols; ++i) 700 | { 701 | symbol_context temp = context[i]; 702 | 703 | int32_t j = i; 704 | while (j > 0 && (context[j - 1].count < temp.count || (context[j - 1].count == temp.count && context[j - 1].symbol > temp.symbol))) 705 | { 706 | context[j] = context[j - 1]; j--; 707 | } 708 | 709 | context[j] = temp; 710 | } 711 | 712 | { 713 | symbol_context * contexts_start = &context[std::max(0, unique_symbols - 6)]; 714 | symbol_context * contexts_end = &context[unique_symbols - 1]; 715 | 716 | while (contexts_start < contexts_end) { std::swap(*contexts_start++, *contexts_end--); } 717 | } 718 | } 719 | 720 | assert(total_symbols > 0); context[0].count = total_symbols; if (unique_symbols < total_symbols) { context[unique_symbols].count = 0; } 721 | } 722 | 723 | INLINE static int64_t pivot_cost3(int64_t A, int64_t B, int64_t C) 724 | { 725 | return A + B + C + B + std::min(A, C); 726 | } 727 | 728 | INLINE static int64_t pivot_cost4(int64_t A, int64_t B, int64_t C, int64_t D) 729 | { 730 | return A + B + C + D + std::min(A + B + C + D, std::min(pivot_cost3(A, B, C), pivot_cost3(B, C, D))); 731 | } 732 | 733 | INLINE static int64_t pivot_cost5(int64_t A, int64_t B, int64_t C, int64_t D, int64_t E) 734 | { 735 | return A + B + C + D + E + std::min(std::min(pivot_cost4(B, C, D, E), A + B + pivot_cost3(C, D, E)), std::min(pivot_cost3(A, B, C) + D + E, pivot_cost4(A, B, C, D))); 736 | } 737 | }; 738 | 739 | #pragma warning( pop ) 740 | --------------------------------------------------------------------------------