├── .gitignore ├── .travis.yml ├── COPYING ├── MANIFEST.in ├── README.md ├── SPEC.md ├── build.py ├── dev-requirements.txt ├── pyproject.toml ├── rencode ├── __init__.py ├── _rencode.pyx └── rencode_orig.py └── tests ├── test_rencode.py └── timetest.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | *.c 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | db.sqlite3 60 | 61 | # Flask stuff: 62 | instance/ 63 | .webassets-cache 64 | 65 | # Scrapy stuff: 66 | .scrapy 67 | 68 | # Sphinx documentation 69 | docs/_build/ 70 | 71 | # PyBuilder 72 | target/ 73 | 74 | # Jupyter Notebook 75 | .ipynb_checkpoints 76 | 77 | # IPython 78 | profile_default/ 79 | ipython_config.py 80 | 81 | # pyenv 82 | .python-version 83 | 84 | # celery beat schedule file 85 | celerybeat-schedule 86 | 87 | # SageMath parsed files 88 | *.sage.py 89 | 90 | # Environments 91 | .env 92 | .venv 93 | env/ 94 | venv/ 95 | ENV/ 96 | env.bak/ 97 | venv.bak/ 98 | 99 | # Spyder project settings 100 | .spyderproject 101 | .spyproject 102 | 103 | # Rope project settings 104 | .ropeproject 105 | 106 | # mkdocs documentation 107 | /site 108 | 109 | # mypy 110 | .mypy_cache/ 111 | .dmypy.json 112 | dmypy.json 113 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | env: 4 | global: 5 | - TWINE_USERNAME=andrew.resch 6 | 7 | matrix: 8 | include: 9 | - sudo: required 10 | services: 11 | - docker 12 | env: PIP=pip 13 | - os: osx 14 | language: generic 15 | env: PIP=pip2 16 | 17 | install: 18 | - $PIP install -r dev-requirements.txt 19 | 20 | script: 21 | - $PIP install cibuildwheel==0.10.0 22 | - cibuildwheel --output-dir wheelhouse 23 | - | 24 | if [[ $TRAVIS_TAG ]]; then 25 | $PIP install twine 26 | python -m twine upload wheelhouse/*.whl 27 | fi 28 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include COPYING 2 | include README.md 3 | include tests/*.py 4 | include rencode/rencode.c 5 | include rencode/_rencode.pyx -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rencode 2 | 3 | The rencode module is similar to bencode from the BitTorrent project. For complex, heterogeneous data structures with many small elements, r-encodings take up significantly less space than b-encodings: 4 | 5 | ``` 6 | >>> len(rencode.dumps({'a':0, 'b':[1,2], 'c':99})) 7 | 13 8 | 9 | >>> len(bencode.bencode({'a':0, 'b':[1,2], 'c':99})) 10 | 26 11 | ``` 12 | 13 | This version of rencode is a complete rewrite in Cython to attempt to increase the performance over the pure Python module written by Petru Paler, Connelly Barnes et al. 14 | 15 | ## Data Format 16 | See [SPEC](SPEC.md) 17 | 18 | ## Performance Comparison 19 | The test program used for these results is included in the repository: 20 | https://github.com/aresch/rencode/blob/master/tests/timetest.py 21 | 22 | ### Encode functions 23 | ``` 24 | test_encode_fixed_pos_int: 25 | rencode.pyx: 0.003s (+0.013s) 589.17% 26 | rencode.py: 0.016s 27 | 28 | test_encode_int_int_size: 29 | rencode.pyx: 0.006s (+0.032s) 625.99% 30 | rencode.py: 0.038s 31 | 32 | test_encode_int_long_long_size: 33 | rencode.pyx: 0.014s (+0.026s) 279.96% 34 | rencode.py: 0.040s 35 | 36 | test_encode_int_short_size: 37 | rencode.pyx: 0.006s (+0.030s) 629.80% 38 | rencode.py: 0.036s 39 | 40 | test_encode_str: 41 | rencode.pyx: 0.006s (+0.010s) 263.96% 42 | rencode.py: 0.017s 43 | 44 | test_encode_dict: 45 | rencode.pyx: 0.135s (+0.302s) 324.68% 46 | rencode.py: 0.437s 47 | 48 | test_encode_fixed_list: 49 | rencode.pyx: 0.012s (+0.025s) 307.78% 50 | rencode.py: 0.037s 51 | 52 | test_encode_fixed_neg_int: 53 | rencode.pyx: 0.003s (+0.012s) 536.97% 54 | rencode.py: 0.015s 55 | 56 | test_encode_fixed_dict: 57 | rencode.pyx: 0.046s (+0.105s) 331.07% 58 | rencode.py: 0.151s 59 | 60 | test_encode_int_char_size: 61 | rencode.pyx: 0.005s (+0.029s) 687.64% 62 | rencode.py: 0.034s 63 | 64 | test_encode_fixed_str: 65 | rencode.pyx: 0.003s (+0.011s) 438.07% 66 | rencode.py: 0.015s 67 | 68 | test_encode_list: 69 | rencode.pyx: 0.148s (+0.228s) 253.68% 70 | rencode.py: 0.376s 71 | 72 | test_encode_none: 73 | rencode.pyx: 0.004s (+0.011s) 386.06% 74 | rencode.py: 0.014s 75 | 76 | test_encode_int_big_number: 77 | rencode.pyx: 0.011s (+0.019s) 264.32% 78 | rencode.py: 0.030s 79 | 80 | test_encode_float_64bit: 81 | rencode.pyx: 0.003s (+0.011s) 416.19% 82 | rencode.py: 0.014s 83 | 84 | test_encode_bool: 85 | rencode.pyx: 0.004s (+0.014s) 447.57% 86 | rencode.py: 0.018s 87 | 88 | test_encode_float_32bit: 89 | rencode.pyx: 0.003s (+0.010s) 417.86% 90 | rencode.py: 0.014s 91 | 92 | Encode functions totals: 93 | rencode.pyx: 0.412s (+0.888s) 315.49% 94 | rencode.py: 1.301s 95 | ``` 96 | ### Decode functions 97 | 98 | ``` 99 | test_decode_fixed_list: 100 | rencode.pyx: 0.003s (+0.020s) 848.67% 101 | rencode.py: 0.022s 102 | 103 | test_decode_int_long_long_size: 104 | rencode.pyx: 0.003s (+0.013s) 484.80% 105 | rencode.py: 0.016s 106 | 107 | test_decode_dict: 108 | rencode.pyx: 0.267s (+0.406s) 251.81% 109 | rencode.py: 0.673s 110 | 111 | test_decode_fixed_dict: 112 | rencode.pyx: 0.087s (+0.123s) 241.32% 113 | rencode.py: 0.211s 114 | 115 | test_decode_float_32bit: 116 | rencode.pyx: 0.002s (+0.007s) 536.88% 117 | rencode.py: 0.009s 118 | 119 | test_decode_int_big_number: 120 | rencode.pyx: 0.007s (+0.010s) 256.05% 121 | rencode.py: 0.017s 122 | 123 | test_decode_int_char_size: 124 | rencode.pyx: 0.002s (+0.014s) 754.12% 125 | rencode.py: 0.016s 126 | 127 | test_decode_fixed_neg_int: 128 | rencode.pyx: 0.001s (+0.004s) 389.03% 129 | rencode.py: 0.006s 130 | 131 | test_decode_fixed_str: 132 | rencode.pyx: 0.009s (+0.009s) 199.78% 133 | rencode.py: 0.019s 134 | 135 | test_decode_float_64bit: 136 | rencode.pyx: 0.002s (+0.007s) 540.17% 137 | rencode.py: 0.009s 138 | 139 | test_decode_bool: 140 | rencode.pyx: 0.002s (+0.004s) 369.49% 141 | rencode.py: 0.006s 142 | 143 | test_decode_fixed_pos_int: 144 | rencode.pyx: 0.002s (+0.004s) 368.96% 145 | rencode.py: 0.006s 146 | 147 | test_decode_list: 148 | rencode.pyx: 0.019s (+0.247s) 1403.77% 149 | rencode.py: 0.266s 150 | 151 | test_decode_none: 152 | rencode.pyx: 0.002s (+0.004s) 367.05% 153 | rencode.py: 0.006s 154 | 155 | test_decode_int_short_size: 156 | rencode.pyx: 0.002s (+0.014s) 716.47% 157 | rencode.py: 0.016s 158 | 159 | test_decode_str: 160 | rencode.pyx: 0.010s (+0.026s) 364.51% 161 | rencode.py: 0.036s 162 | 163 | test_decode_int_int_size: 164 | rencode.pyx: 0.002s (+0.014s) 705.92% 165 | rencode.py: 0.016s 166 | 167 | Decode functions totals: 168 | rencode.pyx: 0.421s (+0.926s) 319.79% 169 | rencode.py: 1.348s 170 | ``` 171 | 172 | ### Overall functions 173 | 174 | ``` 175 | test_overall_encode: 176 | rencode.pyx: 0.069s (+0.120s) 274.42% 177 | rencode.py: 0.189s 178 | 179 | test_overall_decode: 180 | rencode.pyx: 0.051s (+0.153s) 400.57% 181 | rencode.py: 0.204s 182 | 183 | Overall functions totals: 184 | rencode.pyx: 0.120s (+0.273s) 327.98% 185 | rencode.py: 0.393s 186 | ``` 187 | 188 | 189 | ## Author 190 | * Andrew Resch 191 | * Website: https://github.com/aresch/rencode 192 | 193 | ## License 194 | See [COPYING](https://github.com/aresch/rencode/blob/master/COPYING) for license information. 195 | -------------------------------------------------------------------------------- /SPEC.md: -------------------------------------------------------------------------------- 1 | # rencode Data Format Specification 2 | 3 | ## Overview 4 | 5 | rencode uses a single-byte type code system to identify different data types, with some types having their values embedded directly in the type code for space efficiency. The format is designed to be compact while maintaining good performance. 6 | 7 | ## Type Codes 8 | 9 | ### Fixed Integers (Positive) 10 | - Range: 0 to 43 11 | - Type code: `0x00` to `0x2B` (INT_POS_FIXED_START to INT_POS_FIXED_START + INT_POS_FIXED_COUNT - 1) 12 | - Value is embedded in type code 13 | 14 | ### Fixed Integers (Negative) 15 | - Range: -1 to -32 16 | - Type code: `0x46` to `0x65` (INT_NEG_FIXED_START to INT_NEG_FIXED_START + INT_NEG_FIXED_COUNT - 1) 17 | - Value is embedded in type code 18 | 19 | ### Variable Length Integers 20 | - 8-bit signed integer: `0x3E` (CHR_INT1) followed by 1 byte 21 | - 16-bit signed integer: `0x3F` (CHR_INT2) followed by 2 bytes 22 | - 32-bit signed integer: `0x40` (CHR_INT4) followed by 4 bytes 23 | - 64-bit signed integer: `0x41` (CHR_INT8) followed by 8 bytes 24 | - Big number: `0x3D` (CHR_INT) followed by ASCII string and `0x7F` (CHR_TERM) 25 | 26 | ### Floating Point Numbers 27 | - 32-bit float: `0x42` (CHR_FLOAT32) followed by 4 bytes 28 | - 64-bit float: `0x2C` (CHR_FLOAT64) followed by 8 bytes 29 | 30 | ### Strings 31 | - Fixed length strings (1-64 bytes): `0x80` to `0xBF` (STR_FIXED_START to STR_FIXED_START + STR_FIXED_COUNT - 1) 32 | - Variable length strings: ASCII length followed by `:` and string data 33 | 34 | ### Lists 35 | - Fixed length lists (1-64 items): `0xC0` to `0xFF` (LIST_FIXED_START to LIST_FIXED_START + LIST_FIXED_COUNT - 1) 36 | - Variable length lists: `0x3B` (CHR_LIST) followed by items and `0x7F` (CHR_TERM) 37 | 38 | ### Dictionaries 39 | - Fixed length dictionaries (1-25 items): `0x66` to `0x7E` (DICT_FIXED_START to DICT_FIXED_START + DICT_FIXED_COUNT - 1) 40 | - Variable length dictionaries: `0x3C` (CHR_DICT) followed by key-value pairs and `0x7F` (CHR_TERM) 41 | 42 | ### Special Values 43 | - `None`: `0x45` (CHR_NONE) 44 | - `True`: `0x43` (CHR_TRUE) 45 | - `False`: `0x44` (CHR_FALSE) 46 | 47 | ## Byte Order 48 | 49 | All multi-byte values (integers, floats) are stored in network byte order (big-endian). The implementation automatically handles byte order conversion on little-endian systems. 50 | 51 | ## String Encoding 52 | 53 | - By default, strings (str) are stored as UTF-8 encoded bytes 54 | - When `decode_utf8=True` is specified, bytes are decoded from UTF-8 to Python strings (str) during decoding 55 | 56 | ## Limitations 57 | 58 | - Maximum integer length when written as ASCII string: 64 characters 59 | - Maximum fixed string length: 64 bytes 60 | - Maximum fixed list length: 64 items 61 | - Maximum fixed dictionary length: 25 items 62 | 63 | ## Examples 64 | 65 | ``` 66 | 1 -> 0x01 67 | 40 -> 0x28 68 | -10 -> 0x4F 69 | -29 -> 0x62 70 | 100 -> 0x3E 0x64 71 | -100 -> 0x3E 0x9C 72 | 27123 -> 0x3F 0x69 0xF3 73 | -27123 -> 0x3F 0x96 0x0D 74 | 7483648 -> 0x40 0x00 0x72 0x31 0x00 75 | -7483648 -> 0x40 0xFF 0x8D 0xCF 0x00 76 | 1234.56 -> 0x42 0x44 0x9A 0x51 0xEC 77 | "foobar" -> 0x86 0x66 0x6F 0x6F 0x62 0x61 0x72 78 | "f" * 255 -> "255:" + "f" * 255 79 | 80 | # Fixed length list (3 items) 81 | [1, 2, 3] -> 0xC3 0x01 0x02 0x03 82 | 83 | # Variable length list (terminated) 84 | [1, 2, 3] -> 0x3B 0x01 0x02 0x03 0x7F 85 | 86 | # Fixed length dict (1 item) 87 | {"a": 1} -> 0x67 0x81 0x61 0x01 88 | 89 | # Variable length dict (terminated) 90 | {"a": 1} -> 0x3C 0x81 0x61 0x01 0x7F 91 | 92 | None -> 0x45 93 | True -> 0x43 94 | False -> 0x44 95 | ``` 96 | 97 | -------------------------------------------------------------------------------- /build.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import shutil 5 | 6 | from pathlib import Path 7 | 8 | from Cython.Build import cythonize 9 | from setuptools import Distribution 10 | from setuptools import Extension 11 | from setuptools.command.build_ext import build_ext 12 | 13 | 14 | COMPILE_ARGS = ["-march=native", "-O3", "-msse", "-msse2", "-mfma", "-mfpmath=sse"] 15 | LINK_ARGS: list[str] = [] 16 | INCLUDE_DIRS: list[str] = [] 17 | LIBRARIES: list[str] = [] 18 | 19 | 20 | def build() -> None: 21 | extensions = [ 22 | Extension( 23 | "*", 24 | ["rencode/*.pyx"], 25 | extra_compile_args=COMPILE_ARGS, 26 | extra_link_args=LINK_ARGS, 27 | include_dirs=INCLUDE_DIRS, 28 | libraries=LIBRARIES, 29 | ) 30 | ] 31 | ext_modules = cythonize( 32 | extensions, 33 | include_path=INCLUDE_DIRS, 34 | compiler_directives={"binding": True, "language_level": 3}, 35 | ) 36 | 37 | distribution = Distribution({ 38 | "name": "rencode", 39 | "ext_modules": ext_modules 40 | }) 41 | 42 | cmd = build_ext(distribution) 43 | cmd.ensure_finalized() 44 | cmd.run() 45 | 46 | # Copy built extensions back to the project 47 | for output in cmd.get_outputs(): 48 | output = Path(output) 49 | relative_extension = output.relative_to(cmd.build_lib) 50 | for so in relative_extension.parent.glob('*.so'): 51 | so.unlink() 52 | shutil.copyfile(output, relative_extension) 53 | mode = os.stat(relative_extension).st_mode 54 | mode |= (mode & 0o444) >> 2 55 | os.chmod(relative_extension, mode) 56 | 57 | 58 | if __name__ == "__main__": 59 | build() 60 | -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | Cython 2 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "rencode" 3 | version = "1.0.8" 4 | description = "rencode is an object serialization library similar to bencode from the Bittorrent project." 5 | authors = ["Andrew Resch "] 6 | license = "GPLv3" 7 | include = [{path = "rencode/*.so", format = "wheel"}, {path = "rencode/*.c", format = "sdist"}] 8 | packages = [{include = "rencode"}] 9 | exclude = ['rencode/*.c'] 10 | 11 | [tool.poetry.build] 12 | script = "build.py" 13 | 14 | [tool.poetry.dependencies] 15 | python = "^3.9" 16 | 17 | [tool.poetry.group.dev.dependencies] 18 | black = "^21.9b0" 19 | cython = "^3.1.0" 20 | pytest = "^8.3.5" 21 | 22 | [tool.poetry.group.build.dependencies] 23 | setuptools = "^80.9.0" 24 | cython = "^3.1.1" 25 | poetry-core = "^2.1.3" 26 | 27 | [build-system] 28 | requires = ["poetry-core", "setuptools", "cython"] 29 | build-backend = "poetry.core.masonry.api" 30 | -------------------------------------------------------------------------------- /rencode/__init__.py: -------------------------------------------------------------------------------- 1 | try: 2 | from rencode._rencode import * 3 | from rencode._rencode import __version__ 4 | except ImportError: 5 | import rencode.rencode_orig 6 | prev_all = rencode.rencode_orig.__all__[:] 7 | del rencode.rencode_orig.__all__ 8 | from rencode.rencode_orig import * 9 | from rencode.rencode_orig import __version__ 10 | rencode.rencode_orig.__all__ = prev_all 11 | 12 | __all__ = ['dumps', 'loads'] 13 | -------------------------------------------------------------------------------- /rencode/_rencode.pyx: -------------------------------------------------------------------------------- 1 | # cython: language_level=3 2 | # 3 | # rencode.pyx 4 | # 5 | # Copyright (C) 2024 Andrew Resch 6 | # 7 | # rencode is free software. 8 | # 9 | # You may redistribute it and/or modify it under the terms of the 10 | # GNU General Public License, as published by the Free Software 11 | # Foundation; either version 3 of the License, or (at your option) 12 | # any later version. 13 | # 14 | # rencode is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 17 | # See the GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with deluge. If not, write to: 21 | # The Free Software Foundation, Inc., 22 | # 51 Franklin Street, Fifth Floor 23 | # Boston, MA 02110-1301, USA. 24 | # 25 | 26 | from cpython cimport bool 27 | from libc.stdlib cimport realloc, free 28 | from libc.string cimport memcpy 29 | 30 | __version__ = ("Cython", 1, 0, 8) 31 | 32 | cdef long long data_length = 0 33 | cdef bool _decode_utf8 = False 34 | 35 | # Determine host byte-order 36 | cdef bool big_endian = False 37 | cdef unsigned long number = 1 38 | cdef char *s = &number 39 | if s[0] == 0: 40 | big_endian = True 41 | 42 | cdef enum: 43 | # Default number of bits for serialized floats, either 32 or 64 (also a parameter for dumps()). 44 | DEFAULT_FLOAT_BITS = 32 45 | # Maximum length of integer when written as base 10 string. 46 | MAX_INT_LENGTH = 64 47 | # The bencode 'typecodes' such as i, d, etc have been extended and 48 | # relocated on the base-256 character set. 49 | CHR_LIST = 59 50 | CHR_DICT = 60 51 | CHR_INT = 61 52 | CHR_INT1 = 62 53 | CHR_INT2 = 63 54 | CHR_INT4 = 64 55 | CHR_INT8 = 65 56 | CHR_FLOAT32 = 66 57 | CHR_FLOAT64 = 44 58 | CHR_TRUE = 67 59 | CHR_FALSE = 68 60 | CHR_NONE = 69 61 | CHR_TERM = 127 62 | # Positive integers with value embedded in typecode. 63 | INT_POS_FIXED_START = 0 64 | INT_POS_FIXED_COUNT = 44 65 | # Dictionaries with length embedded in typecode. 66 | DICT_FIXED_START = 102 67 | DICT_FIXED_COUNT = 25 68 | # Negative integers with value embedded in typecode. 69 | INT_NEG_FIXED_START = 70 70 | INT_NEG_FIXED_COUNT = 32 71 | # Strings with length embedded in typecode. 72 | STR_FIXED_START = 128 73 | STR_FIXED_COUNT = 64 74 | # Lists with length embedded in typecode. 75 | LIST_FIXED_START = STR_FIXED_START+STR_FIXED_COUNT 76 | LIST_FIXED_COUNT = 64 77 | 78 | cdef char _float_bits 79 | 80 | cdef swap_byte_order_ushort(unsigned short *s): 81 | s[0] = (s[0] >> 8) | (s[0] << 8) 82 | 83 | cdef swap_byte_order_short(char *c): 84 | cdef short s 85 | cdef char *p = &s 86 | p[0] = c[1] 87 | p[1] = c[0] 88 | return s 89 | 90 | cdef swap_byte_order_uint(int *i): 91 | i[0] = (i[0] >> 24) | ((i[0] << 8) & 0x00FF0000) | ((i[0] >> 8) & 0x0000FF00) | (i[0] << 24) 92 | 93 | cdef swap_byte_order_int(char *c): 94 | cdef int i 95 | cdef char *p = &i 96 | p[0] = c[3] 97 | p[1] = c[2] 98 | p[2] = c[1] 99 | p[3] = c[0] 100 | return i 101 | 102 | cdef swap_byte_order_ulong_long(long long *l): 103 | l[0] = (l[0] >> 56) | \ 104 | ((l[0] << 40) & 0x00FF000000000000) | \ 105 | ((l[0] << 24) & 0x0000FF0000000000) | \ 106 | ((l[0] << 8) & 0x000000FF00000000) | \ 107 | ((l[0] >> 8) & 0x00000000FF000000) | \ 108 | ((l[0] >> 24) & 0x0000000000FF0000) | \ 109 | ((l[0] >> 40) & 0x000000000000FF00) | \ 110 | (l[0] << 56) 111 | 112 | cdef swap_byte_order_long_long(char *c): 113 | cdef long long l 114 | cdef char *p = &l 115 | p[0] = c[7] 116 | p[1] = c[6] 117 | p[2] = c[5] 118 | p[3] = c[4] 119 | p[4] = c[3] 120 | p[5] = c[2] 121 | p[6] = c[1] 122 | p[7] = c[0] 123 | return l 124 | 125 | cdef swap_byte_order_float(char *c): 126 | cdef float f 127 | cdef char *p = &f 128 | p[0] = c[3] 129 | p[1] = c[2] 130 | p[2] = c[1] 131 | p[3] = c[0] 132 | return f 133 | 134 | cdef swap_byte_order_double(char *c): 135 | cdef double d 136 | cdef char *p = &d 137 | p[0] = c[7] 138 | p[1] = c[6] 139 | p[2] = c[5] 140 | p[3] = c[4] 141 | p[4] = c[3] 142 | p[5] = c[2] 143 | p[6] = c[1] 144 | p[7] = c[0] 145 | return d 146 | 147 | cdef write_buffer_char(char **buf, unsigned int *pos, char c): 148 | buf[0] = realloc(buf[0], pos[0] + 1) 149 | if buf[0] == NULL: 150 | raise MemoryError("Error in realloc, 1 byte needed") 151 | memcpy(&buf[0][pos[0]], &c, 1) 152 | pos[0] += 1 153 | 154 | cdef write_buffer(char **buf, unsigned int *pos, void* data, int size): 155 | buf[0] = realloc(buf[0], pos[0] + size) 156 | if buf[0] == NULL: 157 | raise MemoryError("Error in realloc, %d bytes needed", size) 158 | memcpy(&buf[0][pos[0]], data, size) 159 | pos[0] += size 160 | 161 | cdef encode_char(char **buf, unsigned int *pos, signed char x): 162 | if 0 <= x < INT_POS_FIXED_COUNT: 163 | write_buffer_char(buf, pos, INT_POS_FIXED_START + x) 164 | elif -INT_NEG_FIXED_COUNT <= x < 0: 165 | write_buffer_char(buf, pos, INT_NEG_FIXED_START - 1 - x) 166 | elif -128 <= x < 128: 167 | write_buffer_char(buf, pos, CHR_INT1) 168 | write_buffer_char(buf, pos, x) 169 | 170 | cdef encode_short(char **buf, unsigned int *pos, short x): 171 | write_buffer_char(buf, pos, CHR_INT2) 172 | if not big_endian: 173 | if x > 0: 174 | swap_byte_order_ushort(&x) 175 | else: 176 | x = swap_byte_order_short(&x) 177 | 178 | write_buffer(buf, pos, &x, sizeof(x)) 179 | 180 | cdef encode_int(char **buf, unsigned int *pos, int x): 181 | write_buffer_char(buf, pos, CHR_INT4) 182 | if not big_endian: 183 | if x > 0: 184 | swap_byte_order_uint(&x) 185 | else: 186 | x = swap_byte_order_int(&x) 187 | write_buffer(buf, pos, &x, sizeof(x)) 188 | 189 | cdef encode_long_long(char **buf, unsigned int *pos, long long x): 190 | write_buffer_char(buf, pos, CHR_INT8) 191 | if not big_endian: 192 | if x > 0: 193 | swap_byte_order_ulong_long(&x) 194 | else: 195 | x = swap_byte_order_long_long(&x) 196 | write_buffer(buf, pos, &x, sizeof(x)) 197 | 198 | cdef encode_big_number(char **buf, unsigned int *pos, char *x): 199 | write_buffer_char(buf, pos, CHR_INT) 200 | write_buffer(buf, pos, x, len(x)) 201 | write_buffer_char(buf, pos, CHR_TERM) 202 | 203 | cdef encode_float32(char **buf, unsigned int *pos, float x): 204 | write_buffer_char(buf, pos, CHR_FLOAT32) 205 | if not big_endian: 206 | x = swap_byte_order_float(&x) 207 | write_buffer(buf, pos, &x, sizeof(x)) 208 | 209 | cdef encode_float64(char **buf, unsigned int *pos, double x): 210 | write_buffer_char(buf, pos, CHR_FLOAT64) 211 | if not big_endian: 212 | x = swap_byte_order_double(&x) 213 | write_buffer(buf, pos, &x, sizeof(x)) 214 | 215 | cdef encode_str(char **buf, unsigned int *pos, bytes x): 216 | cdef char *p 217 | cdef int lx = len(x) 218 | if lx < STR_FIXED_COUNT: 219 | write_buffer_char(buf, pos, STR_FIXED_START + lx) 220 | write_buffer(buf, pos, x, lx) 221 | else: 222 | s = str(lx) + ":" 223 | s = s.encode("ascii") 224 | p = s 225 | write_buffer(buf, pos, p, len(s)) 226 | write_buffer(buf, pos, x, lx) 227 | 228 | cdef encode_none(char **buf, unsigned int *pos): 229 | write_buffer_char(buf, pos, CHR_NONE) 230 | 231 | cdef encode_bool(char **buf, unsigned int *pos, bool x): 232 | if x: 233 | write_buffer_char(buf, pos, CHR_TRUE) 234 | else: 235 | write_buffer_char(buf, pos, CHR_FALSE) 236 | 237 | cdef encode_list(char **buf, unsigned int *pos, x): 238 | if len(x) < LIST_FIXED_COUNT: 239 | write_buffer_char(buf, pos, LIST_FIXED_START + len(x)) 240 | for i in x: 241 | encode(buf, pos, i) 242 | else: 243 | write_buffer_char(buf, pos, CHR_LIST) 244 | for i in x: 245 | encode(buf, pos, i) 246 | write_buffer_char(buf, pos, CHR_TERM) 247 | 248 | cdef encode_dict(char **buf, unsigned int *pos, x): 249 | if len(x) < DICT_FIXED_COUNT: 250 | write_buffer_char(buf, pos, DICT_FIXED_START + len(x)) 251 | for k, v in x.items(): 252 | encode(buf, pos, k) 253 | encode(buf, pos, v) 254 | else: 255 | write_buffer_char(buf, pos, CHR_DICT) 256 | for k, v in x.items(): 257 | encode(buf, pos, k) 258 | encode(buf, pos, v) 259 | write_buffer_char(buf, pos, CHR_TERM) 260 | 261 | cdef object MAX_SIGNED_INT = 2**31 262 | cdef object MIN_SIGNED_INT = -MAX_SIGNED_INT 263 | #note: negating the Python value avoids compiler problems 264 | #(negating the "long long" constant can make it unsigned with some compilers!) 265 | cdef object MAX_SIGNED_LONGLONG = int(2**63) 266 | cdef object MIN_SIGNED_LONGLONG = -MAX_SIGNED_LONGLONG 267 | 268 | cdef encode(char **buf, unsigned int *pos, data): 269 | t = type(data) 270 | if t == int: 271 | if -128 <= data < 128: 272 | encode_char(buf, pos, data) 273 | elif -32768 <= data < 32768: 274 | encode_short(buf, pos, data) 275 | elif MIN_SIGNED_INT <= data < MAX_SIGNED_INT: 276 | encode_int(buf, pos, data) 277 | elif MIN_SIGNED_LONGLONG <= data < MAX_SIGNED_LONGLONG: 278 | encode_long_long(buf, pos, data) 279 | else: 280 | s = str(data).encode("ascii") 281 | if len(s) >= MAX_INT_LENGTH: 282 | raise ValueError("Number is longer than %d characters" % MAX_INT_LENGTH) 283 | encode_big_number(buf, pos, s) 284 | elif t == float: 285 | if _float_bits == 32: 286 | encode_float32(buf, pos, data) 287 | elif _float_bits == 64: 288 | encode_float64(buf, pos, data) 289 | else: 290 | raise ValueError('Float bits (%d) is not 32 or 64' % _float_bits) 291 | elif t == bytes: 292 | encode_str(buf, pos, data) 293 | elif t == str: 294 | u = data.encode("utf8") 295 | encode_str(buf, pos, u) 296 | elif t == type(None): 297 | encode_none(buf, pos) 298 | elif t == bool: 299 | encode_bool(buf, pos, data) 300 | elif t == list or t == tuple: 301 | encode_list(buf, pos, data) 302 | elif t == dict: 303 | encode_dict(buf, pos, data) 304 | else: 305 | raise TypeError(f"type {t} not handled") 306 | 307 | def dumps(data, float_bits=DEFAULT_FLOAT_BITS): 308 | """ 309 | Encode the object data into a string. 310 | 311 | :param data: the object to encode 312 | :type data: object 313 | 314 | """ 315 | global _float_bits 316 | _float_bits = float_bits 317 | cdef char *buf = NULL 318 | cdef unsigned int pos = 0 319 | encode(&buf, &pos, data) 320 | ret = buf[:pos] 321 | free(buf) 322 | return ret 323 | 324 | cdef decode_char(char *data, unsigned int *pos): 325 | cdef signed char c 326 | check_pos(data, pos[0]+1) 327 | memcpy(&c, &data[pos[0]+1], 1) 328 | pos[0] += 2 329 | return c 330 | 331 | cdef decode_short(char *data, unsigned int *pos): 332 | cdef short s 333 | check_pos(data, pos[0]+2) 334 | memcpy(&s, &data[pos[0]+1], 2) 335 | pos[0] += 3 336 | if not big_endian: 337 | s = swap_byte_order_short(&s) 338 | return s 339 | 340 | cdef decode_int(char *data, unsigned int *pos): 341 | cdef int i 342 | check_pos(data, pos[0]+4) 343 | memcpy(&i, &data[pos[0]+1], 4) 344 | pos[0] += 5 345 | if not big_endian: 346 | i = swap_byte_order_int(&i) 347 | return i 348 | 349 | cdef decode_long_long(char *data, unsigned int *pos): 350 | cdef long long l 351 | check_pos(data, pos[0]+8) 352 | memcpy(&l, &data[pos[0]+1], 8) 353 | pos[0] += 9 354 | if not big_endian: 355 | l = swap_byte_order_long_long(&l) 356 | return l 357 | 358 | cdef decode_fixed_pos_int(char *data, unsigned int *pos): 359 | pos[0] += 1 360 | return data[pos[0] - 1] - INT_POS_FIXED_START 361 | 362 | cdef decode_fixed_neg_int(char *data, unsigned int *pos): 363 | pos[0] += 1 364 | return (data[pos[0] - 1] - INT_NEG_FIXED_START + 1)*-1 365 | 366 | cdef decode_big_number(char *data, unsigned int *pos): 367 | pos[0] += 1 368 | cdef int x = 18 369 | check_pos(data, pos[0]+x) 370 | while (data[pos[0]+x] != CHR_TERM): 371 | x += 1 372 | if x >= MAX_INT_LENGTH: 373 | raise ValueError( 374 | "Number is longer than %d characters" % MAX_INT_LENGTH) 375 | check_pos(data, pos[0]+x) 376 | 377 | big_number = int(data[pos[0]:pos[0]+x]) 378 | pos[0] += x + 1 379 | return big_number 380 | 381 | cdef decode_float32(char *data, unsigned int *pos): 382 | cdef float f 383 | check_pos(data, pos[0]+4) 384 | memcpy(&f, &data[pos[0]+1], 4) 385 | pos[0] += 5 386 | if not big_endian: 387 | f = swap_byte_order_float(&f) 388 | return f 389 | 390 | cdef decode_float64(char *data, unsigned int *pos): 391 | cdef double d 392 | check_pos(data, pos[0]+8) 393 | memcpy(&d, &data[pos[0]+1], 8) 394 | pos[0] += 9 395 | if not big_endian: 396 | d = swap_byte_order_double(&d) 397 | return d 398 | 399 | cdef decode_fixed_str(char *data, unsigned int *pos): 400 | cdef unsigned char size = data[pos[0]] - STR_FIXED_START + 1 401 | check_pos(data, pos[0] + size - 1) 402 | s = data[pos[0]+1:pos[0] + size] 403 | pos[0] += size 404 | return s 405 | 406 | cdef decode_str(char *data, unsigned int *pos): 407 | cdef unsigned int x = 1 408 | check_pos(data, pos[0]+x) 409 | while (data[pos[0]+x] != 58): 410 | x += 1 411 | check_pos(data, pos[0]+x) 412 | 413 | cdef int size = int(data[pos[0]:pos[0]+x]) 414 | pos[0] += x + 1 415 | check_pos(data, pos[0] + size - 1) 416 | s = data[pos[0]:pos[0] + size] 417 | pos[0] += size 418 | return s 419 | 420 | cdef decode_fixed_list(char *data, unsigned int *pos): 421 | l = [] 422 | size = data[pos[0]] - LIST_FIXED_START 423 | pos[0] += 1 424 | cdef int i 425 | for i in range(size): 426 | l.append(decode(data, pos)) 427 | return tuple(l) 428 | 429 | cdef decode_list(char *data, unsigned int *pos): 430 | l = [] 431 | pos[0] += 1 432 | while data[pos[0]] != CHR_TERM: 433 | l.append(decode(data, pos)) 434 | pos[0] += 1 435 | return tuple(l) 436 | 437 | cdef decode_fixed_dict(char *data, unsigned int *pos): 438 | d = {} 439 | size = data[pos[0]] - DICT_FIXED_START 440 | pos[0] += 1 441 | cdef int i 442 | for i in range(size): 443 | key = decode(data, pos) 444 | value = decode(data, pos) 445 | d[key] = value 446 | return d 447 | 448 | cdef decode_dict(char *data, unsigned int *pos): 449 | d = {} 450 | pos[0] += 1 451 | check_pos(data, pos[0]) 452 | while data[pos[0]] != CHR_TERM: 453 | key = decode(data, pos) 454 | value = decode(data, pos) 455 | d[key] = value 456 | pos[0] += 1 457 | return d 458 | 459 | cdef check_pos(char *data, unsigned int pos): 460 | if pos >= data_length: 461 | raise IndexError("Tried to access data[%d] but data len is: %d" % (pos, data_length)) 462 | 463 | cdef decode(char *data, unsigned int *pos): 464 | if pos[0] >= data_length: 465 | raise IndexError("Malformed rencoded string: data_length: %d pos: %d" % (data_length, pos[0])) 466 | 467 | cdef unsigned char typecode = data[pos[0]] 468 | if typecode == CHR_INT1: 469 | return decode_char(data, pos) 470 | elif typecode == CHR_INT2: 471 | return decode_short(data, pos) 472 | elif typecode == CHR_INT4: 473 | return decode_int(data, pos) 474 | elif typecode == CHR_INT8: 475 | return decode_long_long(data, pos) 476 | elif INT_POS_FIXED_START <= typecode < INT_POS_FIXED_START + INT_POS_FIXED_COUNT: 477 | return decode_fixed_pos_int(data, pos) 478 | elif INT_NEG_FIXED_START <= typecode < INT_NEG_FIXED_START + INT_NEG_FIXED_COUNT: 479 | return decode_fixed_neg_int(data, pos) 480 | elif typecode == CHR_INT: 481 | return decode_big_number(data, pos) 482 | elif typecode == CHR_FLOAT32: 483 | return decode_float32(data, pos) 484 | elif typecode == CHR_FLOAT64: 485 | return decode_float64(data, pos) 486 | elif STR_FIXED_START <= typecode < STR_FIXED_START + STR_FIXED_COUNT: 487 | s = decode_fixed_str(data, pos) 488 | if _decode_utf8: 489 | s = s.decode("utf8") 490 | return s 491 | elif 49 <= typecode <= 57: 492 | s = decode_str(data, pos) 493 | if _decode_utf8: 494 | s = s.decode("utf8") 495 | return s 496 | elif typecode == CHR_NONE: 497 | pos[0] += 1 498 | return None 499 | elif typecode == CHR_TRUE: 500 | pos[0] += 1 501 | return True 502 | elif typecode == CHR_FALSE: 503 | pos[0] += 1 504 | return False 505 | elif LIST_FIXED_START <= typecode < LIST_FIXED_START + LIST_FIXED_COUNT: 506 | return decode_fixed_list(data, pos) 507 | elif typecode == CHR_LIST: 508 | return decode_list(data, pos) 509 | elif DICT_FIXED_START <= typecode < DICT_FIXED_START + DICT_FIXED_COUNT: 510 | return decode_fixed_dict(data, pos) 511 | elif typecode == CHR_DICT: 512 | return decode_dict(data, pos) 513 | else: 514 | raise ValueError("Invalid typecode: %d at pos: %d" % (typecode, pos[0])) 515 | 516 | def loads(data, decode_utf8=False): 517 | """ 518 | Decodes the string into an object 519 | 520 | :param data: the string to decode 521 | :type data: bytes 522 | :param decode_utf8: if True, will attempt to decode all str into unicode 523 | objects using utf8 524 | :type decode_utf8: bool 525 | :return: The decoded object 526 | :rtype: object 527 | """ 528 | cdef unsigned int pos = 0 529 | global data_length 530 | data_length = len(data) 531 | global _decode_utf8 532 | _decode_utf8 = decode_utf8 533 | return decode(data, &pos) 534 | -------------------------------------------------------------------------------- /rencode/rencode_orig.py: -------------------------------------------------------------------------------- 1 | # Original bencode module by Petru Paler, et al. 2 | # 3 | # Modifications by Connelly Barnes: 4 | # 5 | # - Added support for floats (sent as 32-bit or 64-bit in network 6 | # order), bools, None. 7 | # - Allowed dict keys to be of any serializable type. 8 | # - Lists/tuples are always decoded as tuples (thus, tuples can be 9 | # used as dict keys). 10 | # - Embedded extra information in the 'typecodes' to save some space. 11 | # - Added a restriction on integer length, so that malicious hosts 12 | # cannot pass us large integers which take a long time to decode. 13 | # 14 | # Licensed by Bram Cohen under the "MIT license": 15 | # 16 | # "Copyright (C) 2001-2002 Bram Cohen 17 | # 18 | # Permission is hereby granted, free of charge, to any person 19 | # obtaining a copy of this software and associated documentation files 20 | # (the "Software"), to deal in the Software without restriction, 21 | # including without limitation the rights to use, copy, modify, merge, 22 | # publish, distribute, sublicense, and/or sell copies of the Software, 23 | # and to permit persons to whom the Software is furnished to do so, 24 | # subject to the following conditions: 25 | # 26 | # The above copyright notice and this permission notice shall be 27 | # included in all copies or substantial portions of the Software. 28 | # 29 | # The Software is provided "AS IS", without warranty of any kind, 30 | # express or implied, including but not limited to the warranties of 31 | # merchantability, fitness for a particular purpose and 32 | # noninfringement. In no event shall the authors or copyright holders 33 | # be liable for any claim, damages or other liability, whether in an 34 | # action of contract, tort or otherwise, arising from, out of or in 35 | # connection with the Software or the use or other dealings in the 36 | # Software." 37 | # 38 | # (The rencode module is licensed under the above license as well). 39 | # 40 | # pylint: disable=redefined-builtin 41 | 42 | """ 43 | rencode -- Web safe object pickling/unpickling. 44 | 45 | Public domain, Connelly Barnes 2006-2007. 46 | 47 | The rencode module is a modified version of bencode from the 48 | BitTorrent project. For complex, heterogeneous data structures with 49 | many small elements, r-encodings take up significantly less space than 50 | b-encodings: 51 | 52 | >>> len(rencode.dumps({'a':0, 'b':[1,2], 'c':99})) 53 | 13 54 | >>> len(bencode.bencode({'a':0, 'b':[1,2], 'c':99})) 55 | 26 56 | 57 | The rencode format is not standardized, and may change with different 58 | rencode module versions, so you should check that you are using the 59 | same rencode version throughout your project. 60 | """ 61 | 62 | import struct 63 | import sys 64 | from threading import Lock 65 | 66 | __version__ = ("Python", 1, 0, 8) 67 | __all__ = ("dumps", "loads") 68 | 69 | py3 = sys.version_info[0] >= 3 70 | if py3: 71 | long = int 72 | unicode = str 73 | 74 | def int2byte(c): 75 | return bytes([c]) 76 | 77 | 78 | else: 79 | 80 | def int2byte(c): 81 | return chr(c) 82 | 83 | 84 | # Default number of bits for serialized floats, either 32 or 64 (also a parameter for dumps()). 85 | DEFAULT_FLOAT_BITS = 32 86 | 87 | # Maximum length of integer when written as base 10 string. 88 | MAX_INT_LENGTH = 64 89 | 90 | # The bencode 'typecodes' such as i, d, etc have been extended and 91 | # relocated on the base-256 character set. 92 | CHR_LIST = int2byte(59) 93 | CHR_DICT = int2byte(60) 94 | CHR_INT = int2byte(61) 95 | CHR_INT1 = int2byte(62) 96 | CHR_INT2 = int2byte(63) 97 | CHR_INT4 = int2byte(64) 98 | CHR_INT8 = int2byte(65) 99 | CHR_FLOAT32 = int2byte(66) 100 | CHR_FLOAT64 = int2byte(44) 101 | CHR_TRUE = int2byte(67) 102 | CHR_FALSE = int2byte(68) 103 | CHR_NONE = int2byte(69) 104 | CHR_TERM = int2byte(127) 105 | 106 | # Positive integers with value embedded in typecode. 107 | INT_POS_FIXED_START = 0 108 | INT_POS_FIXED_COUNT = 44 109 | 110 | # Dictionaries with length embedded in typecode. 111 | DICT_FIXED_START = 102 112 | DICT_FIXED_COUNT = 25 113 | 114 | # Negative integers with value embedded in typecode. 115 | INT_NEG_FIXED_START = 70 116 | INT_NEG_FIXED_COUNT = 32 117 | 118 | # Strings with length embedded in typecode. 119 | STR_FIXED_START = 128 120 | STR_FIXED_COUNT = 64 121 | 122 | # Lists with length embedded in typecode. 123 | LIST_FIXED_START = STR_FIXED_START + STR_FIXED_COUNT 124 | LIST_FIXED_COUNT = 64 125 | 126 | # Whether strings should be decoded when loading 127 | _decode_utf8 = False 128 | 129 | 130 | def decode_int(x, f): 131 | f += 1 132 | newf = x.index(CHR_TERM, f) 133 | if newf - f >= MAX_INT_LENGTH: 134 | raise ValueError("overflow") 135 | try: 136 | n = int(x[f:newf]) 137 | except (OverflowError, ValueError): 138 | n = long(x[f:newf]) 139 | if x[f : f + 1] == "-": 140 | if x[f + 1 : f + 2] == "0": 141 | raise ValueError 142 | elif x[f : f + 1] == "0" and newf != f + 1: 143 | raise ValueError 144 | return (n, newf + 1) 145 | 146 | 147 | def decode_intb(x, f): 148 | f += 1 149 | return (struct.unpack("!b", x[f : f + 1])[0], f + 1) 150 | 151 | 152 | def decode_inth(x, f): 153 | f += 1 154 | return (struct.unpack("!h", x[f : f + 2])[0], f + 2) 155 | 156 | 157 | def decode_intl(x, f): 158 | f += 1 159 | 160 | return (struct.unpack("!l", x[f : f + 4])[0], f + 4) 161 | 162 | 163 | def decode_intq(x, f): 164 | f += 1 165 | return (struct.unpack("!q", x[f : f + 8])[0], f + 8) 166 | 167 | 168 | def decode_float32(x, f): 169 | f += 1 170 | n = struct.unpack("!f", x[f : f + 4])[0] 171 | return (n, f + 4) 172 | 173 | 174 | def decode_float64(x, f): 175 | f += 1 176 | n = struct.unpack("!d", x[f : f + 8])[0] 177 | return (n, f + 8) 178 | 179 | 180 | def decode_string(x, f): 181 | colon = x.index(b":", f) 182 | try: 183 | n = int(x[f:colon]) 184 | except (OverflowError, ValueError): 185 | n = long(x[f:colon]) 186 | if x[f] == "0" and colon != f + 1: 187 | raise ValueError 188 | colon += 1 189 | s = x[colon : colon + n] 190 | if _decode_utf8: 191 | s = s.decode("utf8") 192 | return (s, colon + n) 193 | 194 | 195 | def decode_list(x, f): 196 | r, f = [], f + 1 197 | while x[f : f + 1] != CHR_TERM: 198 | v, f = decode_func[x[f : f + 1]](x, f) 199 | r.append(v) 200 | return (tuple(r), f + 1) 201 | 202 | 203 | def decode_dict(x, f): 204 | r, f = {}, f + 1 205 | while x[f : f + 1] != CHR_TERM: 206 | k, f = decode_func[x[f : f + 1]](x, f) 207 | r[k], f = decode_func[x[f : f + 1]](x, f) 208 | return (r, f + 1) 209 | 210 | 211 | def decode_true(x, f): 212 | return (True, f + 1) 213 | 214 | 215 | def decode_false(x, f): 216 | return (False, f + 1) 217 | 218 | 219 | def decode_none(x, f): 220 | return (None, f + 1) 221 | 222 | 223 | decode_func = {} 224 | decode_func[b"0"] = decode_string 225 | decode_func[b"1"] = decode_string 226 | decode_func[b"2"] = decode_string 227 | decode_func[b"3"] = decode_string 228 | decode_func[b"4"] = decode_string 229 | decode_func[b"5"] = decode_string 230 | decode_func[b"6"] = decode_string 231 | decode_func[b"7"] = decode_string 232 | decode_func[b"8"] = decode_string 233 | decode_func[b"9"] = decode_string 234 | decode_func[CHR_LIST] = decode_list 235 | decode_func[CHR_DICT] = decode_dict 236 | decode_func[CHR_INT] = decode_int 237 | decode_func[CHR_INT1] = decode_intb 238 | decode_func[CHR_INT2] = decode_inth 239 | decode_func[CHR_INT4] = decode_intl 240 | decode_func[CHR_INT8] = decode_intq 241 | decode_func[CHR_FLOAT32] = decode_float32 242 | decode_func[CHR_FLOAT64] = decode_float64 243 | decode_func[CHR_TRUE] = decode_true 244 | decode_func[CHR_FALSE] = decode_false 245 | decode_func[CHR_NONE] = decode_none 246 | 247 | 248 | def make_fixed_length_string_decoders(): 249 | def make_decoder(slen): 250 | def f(x, f): 251 | s = x[f + 1 : f + 1 + slen] 252 | if _decode_utf8: 253 | s = s.decode("utf8") 254 | return (s, f + 1 + slen) 255 | 256 | return f 257 | 258 | for i in range(STR_FIXED_COUNT): 259 | decode_func[int2byte(STR_FIXED_START + i)] = make_decoder(i) 260 | 261 | 262 | make_fixed_length_string_decoders() 263 | 264 | 265 | def make_fixed_length_list_decoders(): 266 | def make_decoder(slen): 267 | def f(x, f): 268 | r, f = [], f + 1 269 | for _ in range(slen): 270 | v, f = decode_func[x[f : f + 1]](x, f) 271 | r.append(v) 272 | return (tuple(r), f) 273 | 274 | return f 275 | 276 | for i in range(LIST_FIXED_COUNT): 277 | decode_func[int2byte(LIST_FIXED_START + i)] = make_decoder(i) 278 | 279 | 280 | make_fixed_length_list_decoders() 281 | 282 | 283 | def make_fixed_length_int_decoders(): 284 | def make_decoder(j): 285 | def f(x, f): 286 | return (j, f + 1) 287 | 288 | return f 289 | 290 | for i in range(INT_POS_FIXED_COUNT): 291 | decode_func[int2byte(INT_POS_FIXED_START + i)] = make_decoder(i) 292 | for i in range(INT_NEG_FIXED_COUNT): 293 | decode_func[int2byte(INT_NEG_FIXED_START + i)] = make_decoder(-1 - i) 294 | 295 | 296 | make_fixed_length_int_decoders() 297 | 298 | 299 | def make_fixed_length_dict_decoders(): 300 | def make_decoder(slen): 301 | def f(x, f): 302 | r, f = {}, f + 1 303 | for _ in range(slen): 304 | k, f = decode_func[x[f : f + 1]](x, f) 305 | r[k], f = decode_func[x[f : f + 1]](x, f) 306 | return (r, f) 307 | 308 | return f 309 | 310 | for i in range(DICT_FIXED_COUNT): 311 | decode_func[int2byte(DICT_FIXED_START + i)] = make_decoder(i) 312 | 313 | 314 | make_fixed_length_dict_decoders() 315 | 316 | 317 | def loads(x, decode_utf8=False): 318 | global _decode_utf8 319 | _decode_utf8 = decode_utf8 320 | try: 321 | r, l = decode_func[x[0:1]](x, 0) 322 | except (IndexError, KeyError): 323 | raise ValueError 324 | if l != len(x): 325 | raise ValueError 326 | return r 327 | 328 | 329 | def encode_int(x, r): 330 | if 0 <= x < INT_POS_FIXED_COUNT: 331 | r.append(int2byte(INT_POS_FIXED_START + x)) 332 | elif -INT_NEG_FIXED_COUNT <= x < 0: 333 | r.append(int2byte(INT_NEG_FIXED_START - 1 - x)) 334 | elif -128 <= x < 128: 335 | r.extend((CHR_INT1, struct.pack("!b", x))) 336 | elif -32768 <= x < 32768: 337 | r.extend((CHR_INT2, struct.pack("!h", x))) 338 | elif -2147483648 <= x < 2147483648: 339 | r.extend((CHR_INT4, struct.pack("!l", x))) 340 | elif -9223372036854775808 <= x < 9223372036854775808: 341 | r.extend((CHR_INT8, struct.pack("!q", x))) 342 | else: 343 | s = str(x) 344 | if py3: 345 | s = bytes(s, "ascii") 346 | 347 | if len(s) >= MAX_INT_LENGTH: 348 | raise ValueError("overflow") 349 | r.extend((CHR_INT, s, CHR_TERM)) 350 | 351 | 352 | def encode_float32(x, r): 353 | r.extend((CHR_FLOAT32, struct.pack("!f", x))) 354 | 355 | 356 | def encode_float64(x, r): 357 | r.extend((CHR_FLOAT64, struct.pack("!d", x))) 358 | 359 | 360 | def encode_bool(x, r): 361 | r.append({False: CHR_FALSE, True: CHR_TRUE}[bool(x)]) 362 | 363 | 364 | def encode_none(x, r): 365 | r.append(CHR_NONE) 366 | 367 | 368 | def encode_string(x, r): 369 | if len(x) < STR_FIXED_COUNT: 370 | r.extend((int2byte(STR_FIXED_START + len(x)), x)) 371 | else: 372 | s = str(len(x)) 373 | if py3: 374 | s = bytes(s, "ascii") 375 | r.extend((s, b":", x)) 376 | 377 | 378 | def encode_unicode(x, r): 379 | encode_string(x.encode("utf8"), r) 380 | 381 | 382 | def encode_list(x, r): 383 | if len(x) < LIST_FIXED_COUNT: 384 | r.append(int2byte(LIST_FIXED_START + len(x))) 385 | for i in x: 386 | encode_func[type(i)](i, r) 387 | else: 388 | r.append(CHR_LIST) 389 | for i in x: 390 | encode_func[type(i)](i, r) 391 | r.append(CHR_TERM) 392 | 393 | 394 | def encode_dict(x, r): 395 | if len(x) < DICT_FIXED_COUNT: 396 | r.append(int2byte(DICT_FIXED_START + len(x))) 397 | for k, v in x.items(): 398 | encode_func[type(k)](k, r) 399 | encode_func[type(v)](v, r) 400 | else: 401 | r.append(CHR_DICT) 402 | for k, v in x.items(): 403 | encode_func[type(k)](k, r) 404 | encode_func[type(v)](v, r) 405 | r.append(CHR_TERM) 406 | 407 | 408 | encode_func = {} 409 | encode_func[int] = encode_int 410 | encode_func[long] = encode_int 411 | encode_func[bytes] = encode_string 412 | encode_func[list] = encode_list 413 | encode_func[tuple] = encode_list 414 | encode_func[dict] = encode_dict 415 | encode_func[type(None)] = encode_none 416 | encode_func[unicode] = encode_unicode 417 | encode_func[bool] = encode_bool 418 | 419 | lock = Lock() 420 | 421 | 422 | def dumps(x, float_bits=DEFAULT_FLOAT_BITS): 423 | """ 424 | Dump data structure to str. 425 | 426 | Here float_bits is either 32 or 64. 427 | """ 428 | with lock: 429 | if float_bits == 32: 430 | encode_func[float] = encode_float32 431 | elif float_bits == 64: 432 | encode_func[float] = encode_float64 433 | else: 434 | raise ValueError("Float bits (%d) is not 32 or 64" % float_bits) 435 | r = [] 436 | encode_func[type(x)](x, r) 437 | return b"".join(r) 438 | 439 | 440 | def test(): 441 | f1 = struct.unpack("!f", struct.pack("!f", 25.5))[0] 442 | f2 = struct.unpack("!f", struct.pack("!f", 29.3))[0] 443 | f3 = struct.unpack("!f", struct.pack("!f", -0.6))[0] 444 | ld = ( 445 | ( 446 | {b"a": 15, b"bb": f1, b"ccc": f2, b"": (f3, (), False, True, b"")}, 447 | (b"a", 10 ** 20), 448 | tuple(range(-100000, 100000)), 449 | b"b" * 31, 450 | b"b" * 62, 451 | b"b" * 64, 452 | 2 ** 30, 453 | 2 ** 33, 454 | 2 ** 62, 455 | 2 ** 64, 456 | 2 ** 30, 457 | 2 ** 33, 458 | 2 ** 62, 459 | 2 ** 64, 460 | False, 461 | False, 462 | True, 463 | -1, 464 | 2, 465 | 0, 466 | ), 467 | ) 468 | assert loads(dumps(ld)) == ld 469 | d = dict(zip(range(-100000, 100000), range(-100000, 100000))) 470 | d.update( 471 | {b"a": 20, 20: 40, 40: 41, f1: f2, f2: f3, f3: False, False: True, True: False} 472 | ) 473 | ld = (d, {}, {5: 6}, {7: 7, True: 8}, {9: 10, 22: 39, 49: 50, 44: b""}) 474 | assert loads(dumps(ld)) == ld 475 | ld = ( 476 | b"", 477 | b"a" * 10, 478 | b"a" * 100, 479 | b"a" * 1000, 480 | b"a" * 10000, 481 | b"a" * 100000, 482 | b"a" * 1000000, 483 | b"a" * 10000000, 484 | ) 485 | assert loads(dumps(ld)) == ld 486 | ld = tuple([dict(zip(range(n), range(n))) for n in range(100)]) + (b"b",) 487 | assert loads(dumps(ld)) == ld 488 | ld = tuple([dict(zip(range(n), range(-n, 0))) for n in range(100)]) + (b"b",) 489 | assert loads(dumps(ld)) == ld 490 | ld = tuple([tuple(range(n)) for n in range(100)]) + (b"b",) 491 | assert loads(dumps(ld)) == ld 492 | ld = tuple([b"a" * n for n in range(1000)]) + (b"b",) 493 | assert loads(dumps(ld)) == ld 494 | ld = tuple([b"a" * n for n in range(1000)]) + (None, True, None) 495 | assert loads(dumps(ld)) == ld 496 | assert loads(dumps(None)) is None 497 | assert loads(dumps({None: None})) == {None: None} 498 | assert 1e-10 < abs(loads(dumps(1.1)) - 1.1) < 1e-6 499 | assert 1e-10 < abs(loads(dumps(1.1, 32)) - 1.1) < 1e-6 500 | assert abs(loads(dumps(1.1, 64)) - 1.1) < 1e-12 501 | assert loads(dumps("Hello World!!"), decode_utf8=True) 502 | 503 | 504 | try: 505 | import psyco 506 | 507 | psyco.bind(dumps) 508 | psyco.bind(loads) 509 | except ImportError: 510 | pass 511 | 512 | 513 | if __name__ == "__main__": 514 | test() 515 | -------------------------------------------------------------------------------- /tests/test_rencode.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # test_rencode.py 4 | # 5 | # Copyright (C) 2025 Andrew Resch 6 | # 7 | # rencode is free software. 8 | # 9 | # You may redistribute it and/or modify it under the terms of the 10 | # GNU General Public License, as published by the Free Software 11 | # Foundation; either version 3 of the License, or (at your option) 12 | # any later version. 13 | # 14 | # rencode is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 17 | # See the GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with rencode. If not, write to: 21 | # The Free Software Foundation, Inc., 22 | # 51 Franklin Street, Fifth Floor 23 | # Boston, MA 02110-1301, USA. 24 | # 25 | 26 | import sys 27 | 28 | import unittest 29 | from rencode import _rencode as rencode 30 | 31 | 32 | class TestRencode(unittest.TestCase): 33 | def test_encode_fixed_pos_int(self): 34 | self.assertEqual(rencode.dumps(1), b'\x01') 35 | self.assertEqual(rencode.dumps(40), b'\x28') 36 | 37 | def test_encode_fixed_neg_int(self): 38 | self.assertEqual(rencode.dumps(-10), b'O') 39 | self.assertEqual(rencode.dumps(-29), b'b') 40 | 41 | def test_encode_int_char_size(self): 42 | self.assertEqual(rencode.dumps(100), b'\x3e\x64') 43 | self.assertEqual(rencode.dumps(-100), b'>\x9c') 44 | 45 | def test_encode_int_short_size(self): 46 | self.assertEqual(rencode.dumps(27123), b'\x3f\x69\xf3') 47 | self.assertEqual(rencode.dumps(-27123), b'?\x96\r') 48 | 49 | def test_encode_int_int_size(self): 50 | self.assertEqual(rencode.dumps(7483648), b'@\x00r1\x00') 51 | self.assertEqual(rencode.dumps(-7483648), b'@\xff\x8d\xcf\x00') 52 | 53 | def test_encode_int_long_long_size(self): 54 | self.assertEqual( 55 | rencode.dumps(8223372036854775808), b'Ar\x1fILX\x9c\x00\x00' 56 | ) 57 | self.assertEqual( 58 | rencode.dumps(-8223372036854775808), 59 | b'A\x8d\xe0\xb6\xb3\xa7d\x00\x00', 60 | ) 61 | 62 | def test_encode_int_big_number(self): 63 | n = int("9" * 62) 64 | self.assertEqual(rencode.dumps(n), b'=' + str(n).encode() + b'\x7f') 65 | self.assertRaises(ValueError, rencode.dumps, int("9" * 65)) 66 | 67 | def test_encode_float_32bit(self): 68 | self.assertEqual(rencode.dumps(1234.56), b'BD\x9aQ\xec') 69 | 70 | def test_encode_float_64bit(self): 71 | self.assertEqual(rencode.dumps(1234.56, 64), b',@\x93J=p\xa3\xd7\n') 72 | 73 | def test_encode_float_invalid_size(self): 74 | self.assertRaises(ValueError, rencode.dumps, 1234.56, 36) 75 | 76 | def test_encode_fixed_str(self): 77 | self.assertEqual(rencode.dumps(b"foobarbaz"), b'\x89foobarbaz') 78 | 79 | def test_encode_bytes(self): 80 | self.assertEqual(rencode.dumps(b"f" * 255), b'255:' + b'f' * 255) 81 | self.assertEqual(rencode.dumps(b"\0"), b'\x81\x00') 82 | 83 | def test_encode_str(self): 84 | self.assertEqual(rencode.dumps("fööbar"), b'\x88' + "fööbar".encode('utf-8')) 85 | 86 | def test_encode_none(self): 87 | self.assertEqual(rencode.dumps(None), b'E') 88 | 89 | def test_encode_bool(self): 90 | self.assertEqual(rencode.dumps(True), b'C') 91 | self.assertEqual(rencode.dumps(False), b'D') 92 | 93 | def test_encode_fixed_list(self): 94 | l = [100, -234.01, b"foobar", "bäz"] * 4 95 | self.assertEqual(rencode.dumps(l), b'\xd0' + b''.join([ 96 | b'\x3e\x64', # 100 97 | b'B\xc3j\x02\x8f', # -234.01 98 | b'\x86foobar', # "foobar" 99 | b'\x84' + "bäz".encode('utf-8') # "bäz" 100 | ]) * 4) 101 | 102 | def test_encode_list(self): 103 | l = [100, -234.01, b"foobar", "bäz"] * 80 104 | self.assertEqual(rencode.dumps(l), b';' + b''.join([ 105 | b'\x3e\x64', # 100 106 | b'B\xc3j\x02\x8f', # -234.01 107 | b'\x86foobar', # "foobar" 108 | b'\x84' + "bäz".encode('utf-8') # "bäz" 109 | ]) * 80 + b'\x7f') 110 | 111 | def test_encode_fixed_dict(self): 112 | s = b"abcdefghijk" 113 | d = dict(zip(s, [1234] * len(s))) 114 | self.assertEqual(rencode.dumps(d), b'q' + b''.join( 115 | b'>' + bytes([i]) + b'?\x04\xd2' for i in range(ord('a'), ord('k') + 1) 116 | )) 117 | 118 | def test_encode_dict(self): 119 | s = b"abcdefghijklmnopqrstuvwxyz1234567890" 120 | d = dict(zip(s, [1234] * len(s))) 121 | self.assertEqual(rencode.dumps(d), b'<' + b''.join( 122 | b'>' + bytes([i]) + b'?\x04\xd2' for i in range(ord('a'), ord('z') + 1) 123 | ) + b''.join( 124 | b'>' + bytes([i]) + b'?\x04\xd2' for i in range(ord('1'), ord('9') + 1) 125 | ) + b'>0?\x04\xd2' + b'\x7f') 126 | 127 | def test_decode_fixed_pos_int(self): 128 | self.assertEqual(rencode.loads(rencode.dumps(10)), 10) 129 | 130 | def test_decode_fixed_neg_int(self): 131 | self.assertEqual(rencode.loads(rencode.dumps(-10)), -10) 132 | 133 | def test_decode_char(self): 134 | self.assertEqual(rencode.loads(rencode.dumps(100)), 100) 135 | self.assertEqual(rencode.loads(rencode.dumps(-100)), -100) 136 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([62]))) 137 | 138 | def test_decode_short(self): 139 | self.assertEqual(rencode.loads(rencode.dumps(27123)), 27123) 140 | self.assertEqual(rencode.loads(rencode.dumps(-27123)), -27123) 141 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([63]))) 142 | 143 | def test_decode_int(self): 144 | self.assertEqual(rencode.loads(rencode.dumps(7483648)), 7483648) 145 | self.assertEqual(rencode.loads(rencode.dumps(-7483648)), -7483648) 146 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([64]))) 147 | 148 | def test_decode_long_long(self): 149 | self.assertEqual( 150 | rencode.loads(rencode.dumps(8223372036854775808)), 8223372036854775808 151 | ) 152 | self.assertEqual( 153 | rencode.loads(rencode.dumps(-8223372036854775808)), -8223372036854775808 154 | ) 155 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([65]))) 156 | 157 | def test_decode_int_big_number(self): 158 | n = int(b"9" * 62) 159 | toobig = "={x}\x7f".format(x="9" * 65).encode() 160 | self.assertEqual(rencode.loads(rencode.dumps(n)), n) 161 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([61]))) 162 | self.assertRaises(ValueError, rencode.loads, toobig) 163 | 164 | def test_decode_float_32bit(self): 165 | f = rencode.dumps(1234.56) 166 | self.assertEqual(rencode.loads(f), rencode_orig.loads(f)) 167 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([66]))) 168 | 169 | def test_decode_float_64bit(self): 170 | f = rencode.dumps(1234.56, 64) 171 | self.assertEqual(rencode.loads(f), rencode_orig.loads(f)) 172 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([44]))) 173 | 174 | def test_decode_fixed_bytes(self): 175 | self.assertEqual(rencode.loads(rencode.dumps(b"foobarbaz")), b"foobarbaz") 176 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([130]))) 177 | 178 | def test_decode_bytes(self): 179 | self.assertEqual(rencode.loads(rencode.dumps(b"f" * 255)), b"f" * 255) 180 | self.assertRaises(IndexError, rencode.loads, b"50") 181 | 182 | def test_decode_str(self): 183 | self.assertEqual( 184 | rencode.loads(rencode.dumps("fööbar")), "fööbar".encode("utf8") 185 | ) 186 | 187 | def test_decode_none(self): 188 | self.assertEqual(rencode.loads(rencode.dumps(None)), None) 189 | 190 | def test_decode_bool(self): 191 | self.assertEqual(rencode.loads(rencode.dumps(True)), True) 192 | self.assertEqual(rencode.loads(rencode.dumps(False)), False) 193 | 194 | def test_decode_fixed_list(self): 195 | l = [100, False, b"foobar", "bäz".encode("utf8")] * 4 196 | self.assertEqual(rencode.loads(rencode.dumps(l)), tuple(l)) 197 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([194]))) 198 | 199 | def test_decode_list(self): 200 | l = [100, False, b"foobar", "bäz".encode("utf8")] * 80 201 | self.assertEqual(rencode.loads(rencode.dumps(l)), tuple(l)) 202 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([59]))) 203 | 204 | def test_decode_fixed_dict(self): 205 | s = b"abcdefghijk" 206 | d = dict(zip(s, [1234] * len(s))) 207 | self.assertEqual(rencode.loads(rencode.dumps(d)), d) 208 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([104]))) 209 | 210 | def test_decode_dict(self): 211 | s = b"abcdefghijklmnopqrstuvwxyz1234567890" 212 | d = dict(zip(s, [b"foo" * 120] * len(s))) 213 | d2 = {b"foo": d, b"bar": d, b"baz": d} 214 | self.assertEqual(rencode.loads(rencode.dumps(d2)), d2) 215 | self.assertRaises(IndexError, rencode.loads, bytes(bytearray([60]))) 216 | 217 | def test_decode_str_bytes(self): 218 | b = [202, 132, 100, 114, 97, 119, 1, 0, 0, 63, 1, 242, 63] 219 | d = bytes(bytearray(b)) 220 | self.assertEqual(rencode.loads(rencode.dumps(d)), d) 221 | 222 | def test_decode_str_nullbytes(self): 223 | b = ( 224 | 202, 225 | 132, 226 | 100, 227 | 114, 228 | 97, 229 | 119, 230 | 1, 231 | 0, 232 | 0, 233 | 63, 234 | 1, 235 | 242, 236 | 63, 237 | 1, 238 | 60, 239 | 132, 240 | 120, 241 | 50, 242 | 54, 243 | 52, 244 | 49, 245 | 51, 246 | 48, 247 | 58, 248 | 0, 249 | 0, 250 | 0, 251 | 1, 252 | 65, 253 | 154, 254 | 35, 255 | 215, 256 | 48, 257 | 204, 258 | 4, 259 | 35, 260 | 242, 261 | 3, 262 | 122, 263 | 218, 264 | 67, 265 | 192, 266 | 127, 267 | 40, 268 | 241, 269 | 127, 270 | 2, 271 | 86, 272 | 240, 273 | 63, 274 | 135, 275 | 177, 276 | 23, 277 | 119, 278 | 63, 279 | 31, 280 | 226, 281 | 248, 282 | 19, 283 | 13, 284 | 192, 285 | 111, 286 | 74, 287 | 126, 288 | 2, 289 | 15, 290 | 240, 291 | 31, 292 | 239, 293 | 48, 294 | 85, 295 | 238, 296 | 159, 297 | 155, 298 | 197, 299 | 241, 300 | 23, 301 | 119, 302 | 63, 303 | 2, 304 | 23, 305 | 245, 306 | 63, 307 | 24, 308 | 240, 309 | 86, 310 | 36, 311 | 176, 312 | 15, 313 | 187, 314 | 185, 315 | 248, 316 | 242, 317 | 255, 318 | 0, 319 | 126, 320 | 123, 321 | 141, 322 | 206, 323 | 60, 324 | 188, 325 | 1, 326 | 27, 327 | 254, 328 | 141, 329 | 169, 330 | 132, 331 | 93, 332 | 220, 333 | 252, 334 | 121, 335 | 184, 336 | 8, 337 | 31, 338 | 224, 339 | 63, 340 | 244, 341 | 226, 342 | 75, 343 | 224, 344 | 119, 345 | 135, 346 | 229, 347 | 248, 348 | 3, 349 | 243, 350 | 248, 351 | 220, 352 | 227, 353 | 203, 354 | 193, 355 | 3, 356 | 224, 357 | 127, 358 | 47, 359 | 134, 360 | 59, 361 | 5, 362 | 99, 363 | 249, 364 | 254, 365 | 35, 366 | 196, 367 | 127, 368 | 17, 369 | 252, 370 | 71, 371 | 136, 372 | 254, 373 | 35, 374 | 196, 375 | 112, 376 | 4, 377 | 177, 378 | 3, 379 | 63, 380 | 5, 381 | 220, 382 | ) 383 | d = bytes(bytearray(b)) 384 | self.assertEqual(rencode.loads(rencode.dumps(d)), d) 385 | 386 | def test_decode_utf8(self): 387 | s = b"foobarbaz" 388 | d = rencode.loads(rencode.dumps(s), decode_utf8=True) 389 | self.assertIsInstance(d, str) 390 | s = rencode.dumps(b"\x56\xe4foo\xc3") 391 | self.assertRaises(UnicodeDecodeError, rencode.loads, s, decode_utf8=True) 392 | 393 | def test_version_exposed(self): 394 | assert rencode.__version__ 395 | assert rencode_orig.__version__ 396 | self.assertEqual( 397 | rencode.__version__[1:], 398 | rencode_orig.__version__[1:], 399 | "version number does not match", 400 | ) 401 | 402 | def test_invalid_typecode(self): 403 | s = b";\x2f\x7f" 404 | self.assertRaises(ValueError, rencode.loads, s) 405 | 406 | 407 | if __name__ == "__main__": 408 | unittest.main() 409 | -------------------------------------------------------------------------------- /tests/timetest.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # timetest.py 4 | # 5 | # Copyright (C) 2010 Andrew Resch 6 | # 7 | # rencode is free software. 8 | # 9 | # You may redistribute it and/or modify it under the terms of the 10 | # GNU General Public License, as published by the Free Software 11 | # Foundation; either version 3 of the License, or (at your option) 12 | # any later version. 13 | # 14 | # rencode is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 17 | # See the GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with rencode. If not, write to: 21 | # The Free Software Foundation, Inc., 22 | # 51 Franklin Street, Fifth Floor 23 | # Boston, MA 02110-1301, USA. 24 | # 25 | 26 | from rencode import _rencode as rencode 27 | from rencode import rencode_orig 28 | 29 | import sys 30 | 31 | # Hack to deal with python 2 and 3 differences with unicode literals. 32 | if sys.version < "3": 33 | import codecs 34 | 35 | def u(x): 36 | return codecs.unicode_escape_decode(x)[0] 37 | 38 | 39 | else: 40 | unicode = str 41 | 42 | def u(x): 43 | return x 44 | 45 | 46 | # Encode functions 47 | 48 | 49 | def test_encode_fixed_pos_int(): 50 | rencode.dumps(40) 51 | 52 | 53 | def test_encode_fixed_pos_int_orig(): 54 | rencode_orig.dumps(40) 55 | 56 | 57 | def test_encode_fixed_neg_int(): 58 | rencode.dumps(-29) 59 | 60 | 61 | def test_encode_fixed_neg_int_orig(): 62 | rencode_orig.dumps(-29) 63 | 64 | 65 | def test_encode_int_char_size(): 66 | rencode.dumps(100) 67 | rencode.dumps(-100) 68 | 69 | 70 | def test_encode_int_char_size_orig(): 71 | rencode_orig.dumps(100) 72 | rencode_orig.dumps(-100) 73 | 74 | 75 | def test_encode_int_short_size(): 76 | rencode.dumps(27123) 77 | rencode.dumps(-27123) 78 | 79 | 80 | def test_encode_int_short_size_orig(): 81 | rencode_orig.dumps(27123) 82 | rencode_orig.dumps(-27123) 83 | 84 | 85 | def test_encode_int_int_size(): 86 | rencode.dumps(7483648) 87 | rencode.dumps(-7483648) 88 | 89 | 90 | def test_encode_int_int_size_orig(): 91 | rencode_orig.dumps(7483648) 92 | rencode_orig.dumps(-7483648) 93 | 94 | 95 | def test_encode_int_long_long_size(): 96 | rencode.dumps(8223372036854775808) 97 | rencode.dumps(-8223372036854775808) 98 | 99 | 100 | def test_encode_int_long_long_size_orig(): 101 | rencode_orig.dumps(8223372036854775808) 102 | rencode_orig.dumps(-8223372036854775808) 103 | 104 | 105 | bn = int("9" * 62) 106 | 107 | 108 | def test_encode_int_big_number(): 109 | rencode.dumps(bn) 110 | 111 | 112 | def test_encode_int_big_number_orig(): 113 | rencode_orig.dumps(bn) 114 | 115 | 116 | def test_encode_float_32bit(): 117 | rencode.dumps(1234.56) 118 | 119 | 120 | def test_encode_float_32bit_orig(): 121 | rencode_orig.dumps(1234.56) 122 | 123 | 124 | def test_encode_float_64bit(): 125 | rencode.dumps(1234.56, 64) 126 | 127 | 128 | def test_encode_float_64bit_orig(): 129 | rencode_orig.dumps(1234.56, 64) 130 | 131 | 132 | def test_encode_fixed_str(): 133 | rencode.dumps(b"foobarbaz") 134 | 135 | 136 | def test_encode_fixed_str_orig(): 137 | rencode_orig.dumps(b"foobarbaz") 138 | 139 | 140 | s = b"f" * 255 141 | 142 | 143 | def test_encode_str(): 144 | rencode.dumps(s) 145 | 146 | 147 | def test_encode_str_orig(): 148 | rencode_orig.dumps(s) 149 | 150 | 151 | def test_encode_none(): 152 | rencode.dumps(None) 153 | 154 | 155 | def test_encode_none_orig(): 156 | rencode_orig.dumps(None) 157 | 158 | 159 | def test_encode_bool(): 160 | rencode.dumps(True) 161 | 162 | 163 | def test_encode_bool_orig(): 164 | rencode_orig.dumps(True) 165 | 166 | 167 | l = [None, None, None, None] 168 | 169 | 170 | def test_encode_fixed_list(): 171 | rencode.dumps(l) 172 | 173 | 174 | def test_encode_fixed_list_orig(): 175 | rencode_orig.dumps(l) 176 | 177 | 178 | ll = [None] * 80 179 | 180 | 181 | def test_encode_list(): 182 | rencode.dumps(ll) 183 | 184 | 185 | def test_encode_list_orig(): 186 | rencode_orig.dumps(ll) 187 | 188 | 189 | keys = b"abcdefghijk" 190 | d = dict(zip(keys, [None] * len(keys))) 191 | 192 | 193 | def test_encode_fixed_dict(): 194 | rencode.dumps(d) 195 | 196 | 197 | def test_encode_fixed_dict_orig(): 198 | rencode_orig.dumps(d) 199 | 200 | 201 | keys2 = b"abcdefghijklmnopqrstuvwxyz1234567890" 202 | d2 = dict(zip(keys2, [None] * len(keys2))) 203 | 204 | 205 | def test_encode_dict(): 206 | rencode.dumps(d2) 207 | 208 | 209 | def test_encode_dict_orig(): 210 | rencode_orig.dumps(d2) 211 | 212 | 213 | # Decode functions 214 | 215 | 216 | def test_decode_fixed_pos_int(): 217 | rencode.loads(b"(") 218 | 219 | 220 | def test_decode_fixed_pos_int_orig(): 221 | rencode_orig.loads(b"(") 222 | 223 | 224 | def test_decode_fixed_neg_int(): 225 | rencode.loads(b"b") 226 | 227 | 228 | def test_decode_fixed_neg_int_orig(): 229 | rencode_orig.loads(b"b") 230 | 231 | 232 | def test_decode_int_char_size(): 233 | rencode.loads(b">d") 234 | rencode.loads(b">\x9c") 235 | 236 | 237 | def test_decode_int_char_size_orig(): 238 | rencode_orig.loads(b">d") 239 | rencode_orig.loads(b">\x9c") 240 | 241 | 242 | def test_decode_int_short_size(): 243 | rencode.loads(b"?i\xf3") 244 | rencode.loads(b"?\x96\r") 245 | 246 | 247 | def test_decode_int_short_size_orig(): 248 | rencode_orig.loads(b"?i\xf3") 249 | rencode_orig.loads(b"?\x96\r") 250 | 251 | 252 | def test_decode_int_int_size(): 253 | rencode.loads(b"@\x00r1\x00") 254 | rencode.loads(b"@\xff\x8d\xcf\x00") 255 | 256 | 257 | def test_decode_int_int_size_orig(): 258 | rencode_orig.loads(b"@\x00r1\x00") 259 | rencode_orig.loads(b"@\xff\x8d\xcf\x00") 260 | 261 | 262 | def test_decode_int_long_long_size(): 263 | rencode.loads(b"Ar\x1fILX\x9c\x00\x00") 264 | rencode.loads(b"A\x8d\xe0\xb6\xb3\xa7d\x00\x00") 265 | 266 | 267 | def test_decode_int_long_long_size_orig(): 268 | rencode_orig.loads(b"Ar\x1fILX\x9c\x00\x00") 269 | rencode_orig.loads(b"A\x8d\xe0\xb6\xb3\xa7d\x00\x00") 270 | 271 | 272 | def test_decode_int_big_number(): 273 | rencode.loads( 274 | b"=99999999999999999999999999999999999999999999999999999999999999\x7f" 275 | ) 276 | 277 | 278 | def test_decode_int_big_number_orig(): 279 | rencode_orig.loads( 280 | b"=99999999999999999999999999999999999999999999999999999999999999\x7f" 281 | ) 282 | 283 | 284 | def test_decode_float_32bit(): 285 | rencode.loads(b"BD\x9aQ\xec") 286 | 287 | 288 | def test_decode_float_32bit_orig(): 289 | rencode_orig.loads(b"BD\x9aQ\xec") 290 | 291 | 292 | def test_decode_float_64bit(): 293 | rencode.loads(b",@\x93J=p\xa3\xd7\n") 294 | 295 | 296 | def test_decode_float_64bit_orig(): 297 | rencode_orig.loads(b",@\x93J=p\xa3\xd7\n") 298 | 299 | 300 | def test_decode_fixed_str(): 301 | rencode.loads(b"\x89foobarbaz") 302 | 303 | 304 | def test_decode_fixed_str_orig(): 305 | rencode_orig.loads(b"\x89foobarbaz") 306 | 307 | 308 | def test_decode_str(): 309 | rencode.loads( 310 | b"255:fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" 311 | ) 312 | 313 | 314 | def test_decode_str_orig(): 315 | rencode_orig.loads( 316 | b"255:fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" 317 | ) 318 | 319 | 320 | def test_decode_none(): 321 | rencode.loads(b"E") 322 | 323 | 324 | def test_decode_none_orig(): 325 | rencode_orig.loads(b"E") 326 | 327 | 328 | def test_decode_bool(): 329 | rencode.loads(b"C") 330 | 331 | 332 | def test_decode_bool_orig(): 333 | rencode_orig.loads(b"C") 334 | 335 | 336 | def test_decode_fixed_list(): 337 | rencode.loads(b"\xc4EEEE") 338 | 339 | 340 | def test_decode_fixed_list_orig(): 341 | rencode_orig.loads(b"\xc4EEEE") 342 | 343 | 344 | def test_decode_list(): 345 | rencode.loads( 346 | b";EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\x7f" 347 | ) 348 | 349 | 350 | def test_decode_list_orig(): 351 | rencode_orig.loads( 352 | b";EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\x7f" 353 | ) 354 | 355 | 356 | def test_decode_fixed_dict(): 357 | rencode.loads( 358 | b"q\x81aE\x81cE\x81bE\x81eE\x81dE\x81gE\x81fE\x81iE\x81hE\x81kE\x81jE" 359 | ) 360 | 361 | 362 | def test_decode_fixed_dict_orig(): 363 | rencode_orig.loads( 364 | b"q\x81aE\x81cE\x81bE\x81eE\x81dE\x81gE\x81fE\x81iE\x81hE\x81kE\x81jE" 365 | ) 366 | 367 | 368 | def test_decode_dict(): 369 | rencode.loads( 370 | b"<\x811E\x810E\x813E\x812E\x815E\x814E\x817E\x816E\x819E\x818E\x81aE\x81cE\x81bE\x81eE\x81dE\x81gE\x81fE\x81iE\x81hE\x81kE\x81jE\x81mE\x81lE\x81oE\x81nE\x81qE\x81pE\x81sE\x81rE\x81uE\x81tE\x81wE\x81vE\x81yE\x81xE\x81zE\x7f" 371 | ) 372 | 373 | 374 | def test_decode_dict_orig(): 375 | rencode_orig.loads( 376 | b"<\x811E\x810E\x813E\x812E\x815E\x814E\x817E\x816E\x819E\x818E\x81aE\x81cE\x81bE\x81eE\x81dE\x81gE\x81fE\x81iE\x81hE\x81kE\x81jE\x81mE\x81lE\x81oE\x81nE\x81qE\x81pE\x81sE\x81rE\x81uE\x81tE\x81wE\x81vE\x81yE\x81xE\x81zE\x7f" 377 | ) 378 | 379 | 380 | overall = [ 381 | b"5ce750f0954ce1537676c7a5fe38b0de30ba7eb65ce750f0954ce1537676c7a5fe38b0de30ba7eb6", 382 | b"fixedlength", 383 | u("unicodestring"), 384 | u( 385 | "5ce750f0954ce1537676c7a5fe38b0de30ba7eb65ce750f0954ce1537676c7a5fe38b0de30ba7eb6" 386 | ), 387 | -10, 388 | 10, 389 | 120, 390 | 15600, 391 | -15600, 392 | 7483648, 393 | -7483648, 394 | 8223372036854775808, 395 | -8223372036854775808, 396 | int("9" * 62), 397 | 1227688834.643409, 398 | None, 399 | True, 400 | ] 401 | 402 | 403 | def test_overall_encode(): 404 | rencode.dumps(overall) 405 | 406 | 407 | def test_overall_encode_orig(): 408 | rencode_orig.dumps(overall) 409 | 410 | 411 | overall_decode_str = rencode_orig.dumps(overall) 412 | 413 | 414 | def test_overall_decode(): 415 | rencode.loads(overall_decode_str) 416 | 417 | 418 | def test_overall_decode_orig(): 419 | rencode_orig.loads(overall_decode_str) 420 | 421 | 422 | if __name__ == "__main__": 423 | import timeit 424 | 425 | iterations = 10000 426 | # ANSI escape codes 427 | CSI = "\x1B[" 428 | reset = CSI + "m" 429 | 430 | def do_test(func): 431 | print("%s:" % func) 432 | new_time = timeit.Timer("%s()" % func, "from __main__ import %s" % func).timeit( 433 | iterations 434 | ) 435 | orig_time = timeit.Timer( 436 | "%s_orig()" % func, "from __main__ import %s_orig" % func 437 | ).timeit(iterations) 438 | if new_time > orig_time: 439 | new = CSI + "31m%.3fs%s" % (new_time, reset) 440 | orig = CSI + "32m%.3fs%s (%s34m+%.3fs%s) %.2f%%" % ( 441 | orig_time, 442 | reset, 443 | CSI, 444 | new_time - orig_time, 445 | reset, 446 | (new_time / orig_time) * 100, 447 | ) 448 | else: 449 | new = CSI + "32m%.3fs%s (%s34m+%.3fs%s) %.2f%%" % ( 450 | new_time, 451 | reset, 452 | CSI, 453 | orig_time - new_time, 454 | reset, 455 | (orig_time / new_time) * 100, 456 | ) 457 | orig = CSI + "31m%.3fs%s" % (orig_time, reset) 458 | 459 | print("\trencode.pyx: %s" % new) 460 | print("\trencode.py: %s" % orig) 461 | print("") 462 | return (new_time, orig_time) 463 | 464 | if len(sys.argv) == 1: 465 | loc = list(locals().keys()) 466 | 467 | for t in ("encode", "decode", "overall"): 468 | print("*" * 79) 469 | print("%s functions:" % (t.title())) 470 | print("*" * 79) 471 | print("") 472 | 473 | total_new = 0.0 474 | total_orig = 0.0 475 | for func in loc: 476 | if func.startswith("test_%s" % t) and not func.endswith("_orig"): 477 | n, o = do_test(func) 478 | total_new += n 479 | total_orig += o 480 | 481 | print("%s functions totals:" % (t.title())) 482 | if total_new > total_orig: 483 | new = CSI + "31m%.3fs%s" % (total_new, reset) 484 | orig = "%s32m%.3fs%s (%s34m+%.3fs%s) %.2f%%" % ( 485 | CSI, 486 | total_orig, 487 | reset, 488 | CSI, 489 | total_new - total_orig, 490 | reset, 491 | (total_new / total_orig) * 100, 492 | ) 493 | else: 494 | new = "%s32m%.3fs%s (%s34m+%.3fs%s) %.2f%%" % ( 495 | CSI, 496 | total_new, 497 | reset, 498 | CSI, 499 | total_orig - total_new, 500 | reset, 501 | (total_orig / total_new) * 100, 502 | ) 503 | orig = CSI + "31m%.3fs%s" % (total_orig, reset) 504 | 505 | print("\trencode.pyx: %s" % new) 506 | print("\trencode.py: %s" % orig) 507 | print("") 508 | else: 509 | for f in sys.argv[1:]: 510 | do_test(f) 511 | --------------------------------------------------------------------------------