├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── cpp └── libbolt.cpp ├── docs ├── bib.bib ├── bolt_design.pdf ├── bolt_design.tex └── myheader.tex ├── examples ├── bolt_test_bls12.rs └── bolt_test_bn256.rs ├── go ├── libbolt.go └── libbolt_test.go ├── include ├── ChannelClosure.h ├── ChannelToken.h ├── PublicKey.h ├── PublicParams.h ├── Wallet.h ├── libbolt.h └── rapidjson │ ├── allocators.h │ ├── cursorstreamwrapper.h │ ├── document.h │ ├── encodedstream.h │ ├── encodings.h │ ├── error │ ├── en.h │ └── error.h │ ├── filereadstream.h │ ├── filewritestream.h │ ├── fwd.h │ ├── internal │ ├── biginteger.h │ ├── diyfp.h │ ├── dtoa.h │ ├── ieee754.h │ ├── itoa.h │ ├── meta.h │ ├── pow10.h │ ├── regex.h │ ├── stack.h │ ├── strfunc.h │ ├── strtod.h │ └── swap.h │ ├── istreamwrapper.h │ ├── memorybuffer.h │ ├── memorystream.h │ ├── msinttypes │ ├── inttypes.h │ └── stdint.h │ ├── ostreamwrapper.h │ ├── pointer.h │ ├── prettywriter.h │ ├── rapidjson.h │ ├── reader.h │ ├── schema.h │ ├── stream.h │ ├── stringbuffer.h │ └── writer.h ├── py ├── libbolt.py ├── libbolt_bn256.py └── libbolt_tests.py └── src ├── ccs08.rs ├── channels.rs ├── cl.rs ├── ffishim.rs ├── ffishim_bn256.rs ├── lib.rs ├── nizk.rs ├── ped92.rs ├── util.rs └── wallet.rs /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | target 3 | Cargo.lock 4 | py/__pycache__/ -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | matrix: 7 | allow_failures: 8 | - rust: nightly 9 | fast_finish: true 10 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bolt" 3 | version = "0.3.0" 4 | authors = ["Bolt Labs, Inc "] 5 | description = "library for Blind Off-chain Lightweight Transactions (BOLT)" 6 | keywords = ["zcash", "payment channels", "bolt"] 7 | readme = "README.md" 8 | homepage = "https://github.com/ZcashFoundation/libbolt" 9 | repository = "https://github.com/ZcashFoundation/libbolt" 10 | license = "MIT License" 11 | 12 | [dependencies] 13 | rand = "0.7" 14 | ff_bl = { git = "https://github.com/boltlabs-inc/ff", branch = "master" } 15 | pairing_bl = { git = "https://github.com/boltlabs-inc/pairing", branch = "master", features = ["serde"] } 16 | libc = "*" 17 | serde = { version = "1.0", features = ["derive"] } 18 | serde_json = "1.0" 19 | serde_with = "1.0" 20 | serde_bytes = "0.11.2" 21 | time = "0.1" 22 | secp256k1 = { version = "0.17.1", features = ["serde"] } 23 | sha2 = { version = "0.8", default-features = false } 24 | hex = "0.3.2" 25 | 26 | [lib] 27 | crate-type = ["lib", "cdylib", "staticlib"] 28 | 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 J Ayo Akinyele 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all debug bench test update doc clean 2 | 3 | all: 4 | export RUSTFLAGS=-Awarnings 5 | cargo +nightly build 6 | cargo +nightly test 7 | cargo +nightly run --example bolt_test_bls12 8 | cargo +nightly run --example bolt_test_bn256 9 | 10 | debug: 11 | export RUST_BACKTRACE=1 12 | cargo +nightly build 13 | cargo +nightly run --example bolt_test_bls12 14 | 15 | release: 16 | cargo +nightly build --release 17 | cargo +nightly run --release --example bolt_test_bls12 18 | cargo +nightly run --release --example bolt_test_bn256 19 | 20 | bench: 21 | cargo +nightly bench 22 | 23 | test: 24 | # runs the unit test suite 25 | cargo +nightly test --release -- --nocapture 26 | 27 | update: 28 | cargo +nightly update 29 | 30 | doc: 31 | # generates the documentation 32 | cargo +nightly doc 33 | 34 | pythontests: 35 | cargo +nightly clean 36 | cargo +nightly update 37 | cargo +nightly build --release 38 | python py/libbolt.py 39 | python py/libbolt_tests.py 40 | 41 | cpptests: 42 | @cargo +nightly build --release 43 | @g++ cpp/libbolt.cpp -L ./target/release/ -lbolt -I ./include -o cpp_test 44 | @LD_LIBRARY_PATH=./target/release/ ./cpp_test 45 | @rm cpp_test 46 | 47 | gotests: 48 | cargo +nightly build --release 49 | go test go/libbolt.go go/libbolt_test.go 50 | 51 | alltests: 52 | cargo +nightly clean 53 | cargo +nightly update 54 | cargo +nightly build --release 55 | cargo +nightly test --release #-- --nocapture 56 | python py/libbolt.py 57 | python py/libbolt_tests.py 58 | go test go/libbolt.go go/libbolt_test.go 59 | 60 | clean: 61 | cargo +nightly clean 62 | -------------------------------------------------------------------------------- /cpp/libbolt.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #include "libbolt.h" 6 | //#include "ChannelToken.h" 7 | //#include "PublicKey.h" 8 | //#include "PublicParams.h" 9 | //#include "Wallet.h" 10 | //#include "ChannelClosure.h" 11 | 12 | int main() 13 | { 14 | // Test independent verification of customer close message 15 | string channel_token = "{\"pk_c\":\"0264eb63272c8d85710cbe6ef8229a658e3760ee7cebcc9e3edcfc61b35152a91b\",\"pk_m\":\"034c5b6bd4484d0d0bf326603a1a233e4355bc387e86e9a79e30c46af8a5fe63d3\",\"cl_pk_m\":{\"X\":\"99534f1842c1cbfe3deaea17706118d1174bddd93608aa9b0272daff8b437f4b3a8f494459225eef60fd876603f1ce4f15d4e0b9fb03c5a2794c811e9292891af50ad5376a2957597e5fba62dbd128b75537e2758012d2e30bebb7932bb840ed\",\"Y\":[\"b799fc236c3da7a853399574c88843778abb741909f86c292a3219370ac38f75a23a91e614e78cf1897917504baf937d046b1cd8b1174ef6af5679a88e39629c13d1d43b4ae4e3873939922b4eefd5615724840b68cc5a105c8dec95630036f6\",\"939d1534dfc80141cc0a899d3de005959042f468935964d3e9e32ffa39ca748d73a031d8bf341786bbf09935f600f2550c5824b8be916e1f932e5c5c91170c75b2428a0beec60f3ba2662a3af3c5f802d0bc2c70de7835453d176efcbf37945d\",\"a3de219da28620ed395390e548dad8fb77018c1980f6f27da01e108ab4c733dfc762a1a3eea13be8cdaa0dea3bb97a800fb93c302d5399df71795f1576537e480ce4e426c56a3005e0f941acef33ce55307f9845b5b38a7b609fb1693abd5c00\",\"95b13dd750dd0607a8ba57bfef66061fe3f36e1d44a6dc139981f3d1254b65ea13281bcb927d36ed131b21b2b0a57db90ea2c1bf0e3bd9bc91ae37b207964371f86d1be1f673ae4025e297f52ee050921ce9e84745bcdc90e6964e960e321502\",\"acf4148503d43a671f138866c3dfd0b1f3cdcbb72792c81a17cc1dc7c45f83d6ba0c6e48d0e7fcdcfd19ab580269189d1718fca84a504cdc8dc82ed050771fd241cb0760224fa32d32caf6dff099bb0401e1ba116c6345844c9daa379d65a212\"]},\"mpk\":{\"g1\":\"b63bbc7ec491fa7554b5e869a54348932e2f1a33c5609f38fa1a1a02673838aeb6e64ac9d9a9780918369fc261aac15a\",\"g2\":\"85b95bf5e2334ee60138a9cccf3a81ea9e9c6ea50363e5b4c177618f23a479b2f16508e5af724e86faeb14799c2c6d6416ef8bb1b543851ceeaa011ce4a428b393649d1233cdbdcc7396726bdb75164c9569c967ef1240ea0336168a5b45e543\"},\"comParams\":{\"pub_bases\":[\"b63bbc7ec491fa7554b5e869a54348932e2f1a33c5609f38fa1a1a02673838aeb6e64ac9d9a9780918369fc261aac15a\",\"8fedaf4d995cd200ec0a95169b1e62076d9a313e1e3112cc1638f8e73c8033132f3f26c3e456b643de1ac9d771dddb98\",\"91d41ebf58fea106c4fc8a1143592c6b3d9079b65973653bf583197bc3b0ae4819d95d77b854896c7f06cbb7596a901d\",\"8b9d2c8ab1e7e8dc14cb45c455d2a11fbc3567f85142aa060065b3b7f903cd35e9eb40715308fec4d03d6e7082f2192b\",\"82463691a20acdf8d04ab402f084357b2f76b91fb72b4084d458e945ab33047f1800193f1f332c4e99ccd6a78ab15cdb\",\"85c709721b23511f80f116ed2aa382b6605ba088485922fef22cb1ddf8461e0fdc46abc8ab850c073a22c3d51418560c\"]}}"; 16 | string wpk = "\"02db85f7008f01a1984594d853baebca47b32d41814c0cb2312667d64556b497d3\""; 17 | string cust_close = "{\"pkc\": [\"bbe4ec11548e83e7bd99aef03fae8deb0f31febcef4bd9e742dc24f50477f656\"], \"wpk\": [\"492cc33fae8d985ad8bc8c37d01f8b5a357a601cf141d9cc2aff15e359d5c0ae\"], \"bc\": 85, \"bm\": 25, \"close\": [\"bcd99a3e99e42360850e3e5eab0e5c8261fa14d6a47a20376be126a2f3ac5c0d\"]}"; 18 | string close_token = "{\"h\": \"b328d8e57391ed3b2a6844dbb51b21e3b59ae3a7b4c8960bb1c09800fd2a32c1fd7ae9e51a2f438ad0eed1614c2e303f\", \"H\": \"b31a760561e83fe3735f9af8c063e7501052df58dd17a469ee1be486c45f904cedf6b0f49be3f54499283f4dae2ee41a\"}"; 19 | 20 | int rc0 = wtp_verify_cust_close_message(channel_token.c_str(), wpk.c_str(), cust_close.c_str(), close_token.c_str()); 21 | 22 | cout << "wpk => " << wpk << endl; 23 | cout << "cust close token => " << close_token << endl; 24 | cout << "Valid WTP cust close message: " << (rc0 ? "true" : "false") << endl; 25 | 26 | //int rc1 = wtp_verify_merch_close_message(); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /docs/bib.bib: -------------------------------------------------------------------------------- 1 | @InProceedings{CL04, 2 | author="Camenisch, Jan 3 | and Lysyanskaya, Anna", 4 | editor="Franklin, Matt", 5 | title="Signature Schemes and Anonymous Credentials from Bilinear Maps", 6 | booktitle="Advances in Cryptology -- CRYPTO 2004", 7 | year="2004", 8 | publisher="Springer Berlin Heidelberg", 9 | address="Berlin, Heidelberg", 10 | pages="56--72", 11 | abstract="We propose a new and efficient signature scheme that is provably secure in the plain model. The security of our scheme is based on a discrete-logarithm-based assumption put forth by Lysyanskaya, Rivest, Sahai, and Wolf (LRSW) who also showed that it holds for generic groups and is independent of the decisional Diffie-Hellman assumption. We prove security of our scheme under the LRSW assumption for groups with bilinear maps. We then show how our scheme can be used to construct efficient anonymous credential systems as well as group signature and identity escrow schemes. To this end, we provide efficient protocols that allow one to prove in zero-knowledge the knowledge of a signature on a committed (or encrypted) message and to obtain a signature on a committed message.", 12 | isbn="978-3-540-28628-8" 13 | } 14 | 15 | 16 | @inproceedings{BoltCCS, 17 | author = {Green, Matthew and Miers, Ian}, 18 | title = {Bolt: Anonymous Payment Channels for Decentralized Currencies}, 19 | booktitle = {Proceedings of the 2017 ACM SIGSAC Conference on Computer and Communications Security}, 20 | series = {CCS '17}, 21 | year = {2017}, 22 | isbn = {978-1-4503-4946-8}, 23 | location = {Dallas, Texas, USA}, 24 | pages = {473--489}, 25 | numpages = {17}, 26 | url = {http://doi.acm.org/10.1145/3133956.3134093}, 27 | doi = {10.1145/3133956.3134093}, 28 | acmid = {3134093}, 29 | publisher = {ACM}, 30 | address = {New York, NY, USA}, 31 | keywords = {bitcoin, blockchain, off chain, payments}, 32 | } 33 | 34 | @inproceedings{Zerocash, 35 | author={E. B. Sasson and A. Chiesa and C. Garman and M. Green and I. Miers and E. Tromer and M. Virza}, 36 | booktitle={2014 IEEE Symposium on Security and Privacy}, 37 | title={Zerocash: Decentralized Anonymous Payments from Bitcoin}, 38 | year={2014}, 39 | volume={}, 40 | number={}, 41 | pages={459-474}, 42 | keywords={data privacy;electronic money;Bitcoin;DAP schemes;Zero cash;Zerocash;decentralized anonymous payment schemes;decentralized anonymous payments;full-fledged ledger-based digital currency;payment transactions;privacy guarantees;public decentralized ledger;zero-knowledge succinct noninteractive arguments of knowledge;zk-SNARKs;Logic gates;Online banking;Privacy;Protocols;Public key;Bitcoin;decentralized electronic cash;zero knowledge}, 43 | doi={10.1109/SP.2014.36}, 44 | ISSN={1081-6011}, 45 | month={May}, 46 | } 47 | 48 | @InProceedings{PedersenCommits, 49 | author="Pedersen, Torben Pryds", 50 | editor="Feigenbaum, Joan", 51 | title="Non-Interactive and Information-Theoretic Secure Verifiable Secret Sharing", 52 | booktitle="Advances in Cryptology --- CRYPTO '91", 53 | year="1992", 54 | publisher="Springer Berlin Heidelberg", 55 | address="Berlin, Heidelberg", 56 | pages="129--140", 57 | abstract="It is shown how to distribute a secret to n persons such that each person can verify that he has received correct information about the secret without talking with other persons. Any k of these persons can later find the secret (1 ≤ k ≤ n), whereas fewer than k persons get no (Shannon) information about the secret. The information rate of the scheme is 1/2 and the distribution as well as the verification requires approximately 2k modular multiplications pr. bit of the secret. It is also shown how a number of persons can choose a secret ``in the well'' and distribute it verifiably among themselves.", 58 | isbn="978-3-540-46766-3" 59 | } 60 | 61 | @InProceedings{CLSigs02, 62 | author="Camenisch, Jan 63 | and Lysyanskaya, Anna", 64 | editor="Cimato, Stelvio 65 | and Persiano, Giuseppe 66 | and Galdi, Clemente", 67 | title="A Signature Scheme with Efficient Protocols", 68 | booktitle="Security in Communication Networks", 69 | year="2003", 70 | publisher="Springer Berlin Heidelberg", 71 | address="Berlin, Heidelberg", 72 | pages="268--289", 73 | abstract="Digital signature schemes are a fundamental cryptographic primitive, of use both in its own right, and as a building block in cryptographic protocol design. In this paper, we propose a practical and provably secure signature scheme and show protocols (1) for issuing a signature on a committed value (so the signer has no information about the signed value), and (2) for proving knowledge of a signature on a committed value. This signature scheme and corresponding protocols are a building block for the design of anonymity-enhancing cryptographic systems, such as electronic cash, group signatures, and anonymous credential systems. The security of our signature scheme and protocols relies on the Strong RSA assumption. These results are a generalization of the anonymous credential system of Camenisch and Lysyanskaya.", 74 | isbn="978-3-540-36413-9" 75 | } 76 | 77 | @InProceedings{DY05, 78 | author="Dodis, Yevgeniy 79 | and Yampolskiy, Aleksandr", 80 | editor="Vaudenay, Serge", 81 | title="A Verifiable Random Function with Short Proofs and Keys", 82 | booktitle="Public Key Cryptography - PKC 2005", 83 | year="2005", 84 | publisher="Springer Berlin Heidelberg", 85 | address="Berlin, Heidelberg", 86 | pages="416--431", 87 | abstract="We give a simple and efficient construction of a verifiable random function (VRF) on bilinear groups. Our construction is direct. In contrast to prior VRF constructions [14,15], it avoids using an inefficient Goldreich-Levin transformation, thereby saving several factors in security. Our proofs of security are based on a decisional bilinear Diffie-Hellman inversion assumption, which seems reasonable given current state of knowledge. For small message spaces, our VRF's proofs and keys have constant size. By utilizing a collision-resistant hash function, our VRF can also be used with arbitrary message spaces. We show that our scheme can be instantiated with an elliptic group of very reasonable size. Furthermore, it can be made distributed and proactive.", 88 | isbn="978-3-540-30580-4" 89 | } 90 | 91 | -------------------------------------------------------------------------------- /docs/bolt_design.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/boltlabs-inc/libbolt/02c9f36bbd0226c99df1f0cb0f9d68130431d9b8/docs/bolt_design.pdf -------------------------------------------------------------------------------- /docs/myheader.tex: -------------------------------------------------------------------------------- 1 | %% Common header 2 | \usepackage{amsmath,amsfonts,amssymb,url} 3 | \usepackage{mdwlist} 4 | \usepackage{graphicx,graphpap} 5 | \usepackage{soul} 6 | 7 | \usepackage{color} 8 | \newcommand{\todo}[1]{\color{red}{\bf To do: #1} \color{black}} 9 | \newcommand{\myul}[2][red]{\setulcolor{#1}\ul{#2}\setulcolor{red}} 10 | 11 | \newcommand{\squish}{ 12 | \setlength{\topsep}{0pt} 13 | \setlength{\itemsep}{0ex} 14 | \vspace{-1ex} 15 | \setlength{\parskip}{0pt}} 16 | \newcommand{\squishend}{\vskip -1ex\relax} 17 | 18 | \newenvironment{gamequote} 19 | {\list{}{\rightmargin0pt\relax}\item\relax} 20 | {\endlist} 21 | 22 | \newcommand{\Adv}{\mathcal{A}} 23 | \newcommand{\game}{\mathrm{Game~}} 24 | \newcommand{\negl}{\mathit{negl}} 25 | 26 | \newcommand{\hash}{\ensuremath{F}} 27 | \newcommand{\hashone}{\ensuremath{H_1}} 28 | \newcommand{\hashtwo}{\ensuremath{H_2}} 29 | 30 | \newcommand{\bigO}{\ensuremath{\mathcal{O}}} 31 | \newcommand{\Z}{\ensuremath{\mathbb{Z}}} 32 | \newcommand{\F}{\ensuremath{\mathbb{F}}} 33 | \newcommand{\R}{\ensuremath{\mathbb{R}}} 34 | \newcommand{\C}{\ensuremath{\mathbb{C}}} 35 | \newcommand{\Q}{\ensuremath{\mathbb{Q}}} 36 | \newcommand{\G}{\ensuremath{\mathbb{G}}} 37 | \newcommand{\GT}{\ensuremath{\mathbb{G}_T}} 38 | \newcommand{\map}{e} 39 | \newcommand{\BMsetup}{\mathsf{BSetup}} 40 | 41 | \newtheorem{theorem}{Theorem}[section] 42 | \newtheorem{lemma}[theorem]{Lemma} 43 | \newtheorem{claim}[theorem]{Claim} 44 | \newtheorem{cor}[theorem]{Corollary} 45 | \newtheorem{fact}[theorem]{Fact} 46 | %\theoremstyle{definition} 47 | \newtheorem{definition}[theorem]{Definition} 48 | 49 | \newcommand{\bit}{\{0,1\}} 50 | \newcommand{\half}{{\frac{1}{2}}} 51 | \newcommand{\Zp}{\ensuremath{{\Z_p}}} 52 | \newcommand{\Zps}{\ensuremath{{\Z_p^*}}} 53 | \newcommand{\SSS}{\ensuremath{\Sigma}} 54 | \newcommand{\Attrmax}{\ensuremath{Attr_{\mathrm{max}}}} 55 | \newcommand{\lmax}{\ensuremath{\ell_{\mathrm{max}}}} 56 | \newcommand{\nmax}{\ensuremath{n_{\mathrm{max}}}} 57 | \newcommand{\kmax}{\ensuremath{k_{\mathrm{max}}}} 58 | \newcommand{\MM}{\ensuremath{\mathcal{M}}} 59 | \newcommand{\weil}{\ensuremath{\hat{e}}} 60 | \newcommand{\tuple}[1]{\langle #1 \rangle} 61 | \newcommand{\e}{\epsilon} 62 | %\newcommand{\st}{\;\;\mbox{s.t.}\;\;} 63 | \newcommand{\rgets}{\stackrel{\scriptscriptstyle{R}}{\leftarrow}} 64 | 65 | \newcommand{\Setup}{\mathsf{Setup}} 66 | \newcommand{\Encrypt}{\mathsf{Encrypt}} 67 | \newcommand{\Decrypt}{\mathsf{Decrypt}} 68 | \newcommand{\KeyGen}{\mathsf{KeyGen}} 69 | 70 | %\newcommand{\Pr}{\ensuremath{\mathrm{Pr}}} 71 | \newcommand{\CT}{\ensuremath{\mathrm{CT}}} 72 | \newcommand{\TK}{\ensuremath{\mathrm{TK}}} 73 | \newcommand{\SK}{\ensuremath{\mathrm{SK}}} 74 | \newcommand{\MK}{\ensuremath{\mathrm{MK}}} 75 | \newcommand{\PK}{\ensuremath{\mathrm{PK}}} 76 | \newcommand{\PP}{\ensuremath{\mathrm{PP}}} 77 | \newcommand{\MSK}{\ensuremath{\mathrm{MSK}}} 78 | \newcommand{\GP}{\ensuremath{\mathrm{GP}}} 79 | \newcommand{\ASK}{\ensuremath{\mathrm{ASK}}} 80 | \newcommand{\GID}{\ensuremath{\mathrm{GID}}} 81 | 82 | \newcommand{\Phve}{P^{\scriptscriptstyle{\mathrm{HVE}}}} 83 | \newcommand{\AlgA}{\ensuremath{{\cal A}}} 84 | \newcommand{\AlgB}{\ensuremath{{\cal B}}} 85 | \newcommand{\Pdist}[1]{{\cal P}_{#1}} 86 | \newcommand{\Rdist}[1]{{\cal R}_{#1}} 87 | \newcommand{\EXP}[1]{\mathsf{EXP}_{\scriptscriptstyle{\text{#1}}}} 88 | \newcommand{\deq}{\mathrel{:=}} 89 | \newcommand{\GG}{\ensuremath{\mathcal{G}}} 90 | \newcommand{\PhiHVE}{\ensuremath{\Phi_{\scriptscriptstyle \mathrm{HVE}}}} 91 | \newcommand{\PhiEq}{\ensuremath{\Phi_{\mathrm{eq}}}} 92 | \newcommand{\true}{\ensuremath{\textsf{true}}} 93 | 94 | \newcommand{\ID}{\ensuremath{\mathcal{I}}} 95 | \newcommand{\EE}{\ensuremath{\mathcal{E}}} 96 | \newcommand{\Etr}{\ensuremath{\mathcal{E}_{\scriptscriptstyle{\text{TR}}}}} 97 | 98 | \newcommand{\abort}{\ensuremath{\mathsf{abort}}} 99 | \newcommand{\valid}{\ensuremath{\mathsf{valid}}} 100 | \newcommand{\invalid}{\ensuremath{\mathsf{invalid}}} 101 | 102 | \newcommand{\eDBDH}{\ensuremath{\e_{\scriptscriptstyle{DBDH}}}} 103 | \newcommand{\eDTPDH}{\ensuremath{\e_{\scriptscriptstyle{D3DH}}}} 104 | \newcommand{\eSD}{\ensuremath{\e_{\scriptscriptstyle{SD}}}} 105 | \newcommand{\eBSD}{\ensuremath{\e_{\scriptscriptstyle{BSD}}}} 106 | \newcommand{\eDSTPDH}{\ensuremath{\e_{\scriptscriptstyle{DS3DH}}}} 107 | 108 | \newcommand{\inputenc}{I_{enc}} 109 | \newcommand{\inputkey}{I_{key}} 110 | 111 | \newtheorem{defn}{Definition} 112 | 113 | \def\x{{\vec{x}}} 114 | \def\y{{\vec{y}}} 115 | 116 | \newenvironment{tightenum} 117 | {\begin{enumerate} 118 | \setlength{\itemsep}{1pt} 119 | \setlength{\parskip}{0pt} 120 | \setlength{\parsep}{0pt}} 121 | {\end{enumerate}} 122 | 123 | \newcommand{\qed}{\hfill\Box} 124 | \newenvironment{proof}{ 125 | \vspace*{-\parskip}\noindent\textit{Proof.}}{$\qed$ 126 | 127 | \medskip 128 | } 129 | 130 | \newenvironment{proofsketch}{ 131 | \vspace*{-\parskip}\noindent\textit{Proof sketch.}}{$\qed$ 132 | 133 | \medskip 134 | } 135 | 136 | \newcommand{\ourparagraph}[1]{\smallskip\noindent {\bf #1} } 137 | \newcommand{\betterparagraph}[1]{\smallskip\noindent {\em #1.} } 138 | 139 | \newcommand{\etal}{{\em et al.}} 140 | \newcommand{\var}{\mathrm} 141 | -------------------------------------------------------------------------------- /examples/bolt_test_bls12.rs: -------------------------------------------------------------------------------- 1 | extern crate rand; 2 | extern crate bolt; 3 | extern crate ff_bl as ff; 4 | extern crate pairing_bl as pairing; 5 | extern crate time; 6 | extern crate secp256k1; 7 | 8 | use bolt::bidirectional; 9 | use std::time::Instant; 10 | use pairing::bls12_381::Bls12; 11 | use bolt::handle_bolt_result; 12 | 13 | macro_rules! measure_one_arg { 14 | ($x: expr) => { 15 | { 16 | let s = Instant::now(); 17 | let res = $x; 18 | let e = s.elapsed(); 19 | (res, e.as_millis()) 20 | }; 21 | } 22 | } 23 | 24 | macro_rules! measure_two_arg { 25 | ($x: expr) => { 26 | { 27 | let s = Instant::now(); 28 | let (res1, res2) = $x; 29 | let e = s.elapsed(); 30 | (res1, res2, e.as_millis()) 31 | }; 32 | } 33 | } 34 | 35 | 36 | //macro_rules! measure_ret_mut { 37 | // ($x: expr) => { 38 | // { 39 | // let s = Instant::now(); 40 | // let mut handle = $x; 41 | // let e = s.elapsed(); 42 | // (handle, s.as_millis()) 43 | // }; 44 | // } 45 | //} 46 | 47 | fn main() { 48 | println!("******************************************"); 49 | let mut channel_state = bidirectional::ChannelState::::new(String::from("Channel A -> B"), false); 50 | let rng = &mut rand::thread_rng(); 51 | 52 | let b0_customer = 150; 53 | let b0_merchant = 10; 54 | let pay_inc = 20; 55 | let pay_inc2 = 10; 56 | 57 | let (mut channel_token, mut merch_state, mut channel_state) = bidirectional::init_merchant(rng, &mut channel_state, "Merchant Bob"); 58 | 59 | let mut cust_state = bidirectional::init_customer(rng, &mut channel_token, b0_customer, b0_merchant, "Alice"); 60 | 61 | println!("{}", cust_state); 62 | 63 | // lets establish the channel 64 | let (com, com_proof, est_time) = measure_two_arg!(bidirectional::establish_customer_generate_proof(rng, &mut channel_token, &mut cust_state)); 65 | println!(">> Time to generate proof for establish: {} ms", est_time); 66 | 67 | // obtain close token for closing out channel 68 | let channel_id = channel_token.compute_channel_id(); 69 | let option = bidirectional::establish_merchant_issue_close_token(rng, &channel_state, &com, &com_proof, 70 | &channel_id, b0_customer, b0_merchant, &merch_state); 71 | let close_token= match option { 72 | Ok(n) => n.unwrap(), 73 | Err(e) => panic!("Failed - bidirectional::establish_merchant_issue_close_token(): {}", e) 74 | }; 75 | 76 | assert!(cust_state.verify_close_token(&channel_state, &close_token)); 77 | 78 | // wait for funding tx to be confirmed, etc 79 | 80 | // obtain payment token for pay protocol 81 | let pay_token = bidirectional::establish_merchant_issue_pay_token(rng, &channel_state, &com, &merch_state); 82 | //assert!(cust_state.verify_pay_token(&channel_state, &pay_token)); 83 | 84 | assert!(bidirectional::establish_customer_final(&mut channel_state, &mut cust_state, &pay_token)); 85 | println!("Channel established!"); 86 | 87 | let (payment, new_cust_state, pay_time) = measure_two_arg!(bidirectional::generate_payment_proof(rng, &channel_state, &cust_state, pay_inc)); 88 | println!(">> Time to generate payment proof: {} ms", pay_time); 89 | 90 | let (new_close_token, verify_time) = measure_one_arg!(bidirectional::verify_payment_proof(rng, &channel_state, &payment, &mut merch_state)); 91 | println!(">> Time to verify payment proof: {} ms", verify_time); 92 | 93 | let revoke_token = bidirectional::generate_revoke_token(&channel_state, &mut cust_state, new_cust_state, &new_close_token); 94 | 95 | // send revoke token and get pay-token in response 96 | let new_pay_token_result = bidirectional::verify_revoke_token(&revoke_token, &mut merch_state); 97 | let new_pay_token = handle_bolt_result!(new_pay_token_result); 98 | 99 | // verify the pay token and update internal state 100 | assert!(cust_state.verify_pay_token(&channel_state, &new_pay_token.unwrap())); 101 | 102 | println!("******************************************"); 103 | 104 | let (payment2, new_cust_state2, pay_time2) = measure_two_arg!(bidirectional::generate_payment_proof(rng, &channel_state, &cust_state, pay_inc2)); 105 | println!(">> Time to generate payment proof 2: {} ms", pay_time2); 106 | 107 | let (new_close_token2, verify_time2) = measure_one_arg!(bidirectional::verify_payment_proof(rng, &channel_state, &payment2, &mut merch_state)); 108 | println!(">> Time to verify payment proof 2: {} ms", verify_time2); 109 | 110 | let revoke_token2 = bidirectional::generate_revoke_token(&channel_state, &mut cust_state, new_cust_state2, &new_close_token2); 111 | 112 | // send revoke token and get pay-token in response 113 | let new_pay_token_result2 = bidirectional::verify_revoke_token(&revoke_token2, &mut merch_state); 114 | let new_pay_token2 = handle_bolt_result!(new_pay_token_result2); 115 | 116 | // verify the pay token and update internal state 117 | assert!(cust_state.verify_pay_token(&channel_state, &new_pay_token2.unwrap())); 118 | 119 | println!("Final Cust state: {}", cust_state); 120 | 121 | } 122 | -------------------------------------------------------------------------------- /examples/bolt_test_bn256.rs: -------------------------------------------------------------------------------- 1 | extern crate rand; 2 | extern crate bolt; 3 | extern crate ff_bl as ff; 4 | extern crate pairing_bl as pairing; 5 | extern crate time; 6 | extern crate secp256k1; 7 | 8 | use bolt::bidirectional; 9 | use std::time::Instant; 10 | use pairing::bn256::Bn256; 11 | use bolt::handle_bolt_result; 12 | 13 | macro_rules! measure_one_arg { 14 | ($x: expr) => { 15 | { 16 | let s = Instant::now(); 17 | let res = $x; 18 | let e = s.elapsed(); 19 | (res, e.as_millis()) 20 | }; 21 | } 22 | } 23 | 24 | macro_rules! measure_two_arg { 25 | ($x: expr) => { 26 | { 27 | let s = Instant::now(); 28 | let (res1, res2) = $x; 29 | let e = s.elapsed(); 30 | (res1, res2, e.as_millis()) 31 | }; 32 | } 33 | } 34 | 35 | 36 | //macro_rules! measure_ret_mut { 37 | // ($x: expr) => { 38 | // { 39 | // let s = Instant::now(); 40 | // let mut handle = $x; 41 | // let e = s.elapsed(); 42 | // (handle, s.as_millis()) 43 | // }; 44 | // } 45 | //} 46 | 47 | fn main() { 48 | println!("******************************************"); 49 | let mut channel_state = bidirectional::ChannelState::::new(String::from("Channel A -> B"), false); 50 | let rng = &mut rand::thread_rng(); 51 | 52 | let b0_customer = 150; 53 | let b0_merchant = 10; 54 | let pay_inc = 20; 55 | let pay_inc2 = 10; 56 | 57 | let (mut channel_token, mut merch_state, mut channel_state) = bidirectional::init_merchant(rng, &mut channel_state, "Merchant Bob"); 58 | 59 | let mut cust_state = bidirectional::init_customer(rng, &mut channel_token, b0_customer, b0_merchant, "Alice"); 60 | 61 | println!("{}", cust_state); 62 | 63 | // lets establish the channel 64 | let (com, com_proof, est_time) = measure_two_arg!(bidirectional::establish_customer_generate_proof(rng, &mut channel_token, &mut cust_state)); 65 | println!(">> Time to generate proof for establish: {} ms", est_time); 66 | 67 | // obtain close token for closing out channel 68 | let channel_id = channel_token.compute_channel_id(); 69 | let option = bidirectional::establish_merchant_issue_close_token(rng, &channel_state, &com, &com_proof, 70 | &channel_id, b0_customer, b0_merchant, &merch_state); 71 | let close_token= match option { 72 | Ok(n) => n.unwrap(), 73 | Err(e) => panic!("Failed - bidirectional::establish_merchant_issue_close_token(): {}", e) 74 | }; 75 | 76 | assert!(cust_state.verify_close_token(&channel_state, &close_token)); 77 | 78 | // wait for funding tx to be confirmed, etc 79 | 80 | // obtain payment token for pay protocol 81 | let pay_token = bidirectional::establish_merchant_issue_pay_token(rng, &channel_state, &com, &merch_state); 82 | //assert!(cust_state.verify_pay_token(&channel_state, &pay_token)); 83 | 84 | assert!(bidirectional::establish_customer_final(&mut channel_state, &mut cust_state, &pay_token)); 85 | println!("Channel established!"); 86 | 87 | let (payment, new_cust_state, pay_time) = measure_two_arg!(bidirectional::generate_payment_proof(rng, &channel_state, &cust_state, pay_inc)); 88 | println!(">> Time to generate payment proof: {} ms", pay_time); 89 | 90 | let (new_close_token, verify_time) = measure_one_arg!(bidirectional::verify_payment_proof(rng, &channel_state, &payment, &mut merch_state)); 91 | println!(">> Time to verify payment proof: {} ms", verify_time); 92 | 93 | let revoke_token = bidirectional::generate_revoke_token(&channel_state, &mut cust_state, new_cust_state, &new_close_token); 94 | 95 | // send revoke token and get pay-token in response 96 | let new_pay_token_result = bidirectional::verify_revoke_token(&revoke_token, &mut merch_state); 97 | let new_pay_token = handle_bolt_result!(new_pay_token_result); 98 | 99 | // verify the pay token and update internal state 100 | assert!(cust_state.verify_pay_token(&channel_state, &new_pay_token.unwrap())); 101 | 102 | println!("******************************************"); 103 | 104 | let (payment2, new_cust_state2, pay_time2) = measure_two_arg!(bidirectional::generate_payment_proof(rng, &channel_state, &cust_state, pay_inc2)); 105 | println!(">> Time to generate payment proof 2: {} ms", pay_time2); 106 | 107 | let (new_close_token2, verify_time2) = measure_one_arg!(bidirectional::verify_payment_proof(rng, &channel_state, &payment2, &mut merch_state)); 108 | println!(">> Time to verify payment proof 2: {} ms", verify_time2); 109 | 110 | let revoke_token2 = bidirectional::generate_revoke_token(&channel_state, &mut cust_state, new_cust_state2, &new_close_token2); 111 | 112 | // send revoke token and get pay-token in response 113 | let new_pay_token_result2 = bidirectional::verify_revoke_token(&revoke_token2, &mut merch_state); 114 | let new_pay_token2 = handle_bolt_result!(new_pay_token_result2); 115 | 116 | // verify the pay token and update internal state 117 | assert!(cust_state.verify_pay_token(&channel_state, &new_pay_token2.unwrap())); 118 | 119 | println!("Final Cust state: {}", cust_state); 120 | 121 | } 122 | -------------------------------------------------------------------------------- /go/libbolt_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func Test_ChannelSetup(t *testing.T) { 9 | _, channelToken, merchState, custState, err := setup(1000, 100) 10 | assert.Nil(t, err) 11 | 12 | assert.NotEqual(t, MerchState{}, merchState) 13 | assert.NotEqual(t, CustState{}, custState) 14 | assert.NotEqual(t, ChannelToken{}, channelToken) 15 | } 16 | 17 | func setup(b0Cust int, b0Merch int) (ChannelState, ChannelToken, MerchState, CustState, error) { 18 | channelState, err := BidirectionalChannelSetup("Test Channel", false) 19 | if err != nil { 20 | return ChannelState{}, ChannelToken{}, MerchState{}, CustState{}, err 21 | } 22 | channelToken, merchState, channelState, err := BidirectionalInitMerchant(channelState, "Bob") 23 | if err != nil { 24 | return ChannelState{}, ChannelToken{}, MerchState{}, CustState{}, err 25 | } 26 | channelToken, custState, err := BidirectionalInitCustomer(channelToken, b0Cust, b0Merch, "Alice") 27 | return channelState, channelToken, merchState, custState, err 28 | } 29 | 30 | func Test_Establish(t *testing.T) { 31 | b0Cust := 1000 32 | b0Merch := 100 33 | channelState, channelToken, merchState, custState, err := setup(b0Cust, b0Merch) 34 | assert.Nil(t, err) 35 | 36 | channelToken, custState, com, comProof, err := BidirectionalEstablishCustomerGenerateProof(channelToken, custState) 37 | assert.Nil(t, err) 38 | 39 | closeToken, err := BidirectionalEstablishMerchantIssueCloseToken(channelState, com, comProof, custState.Wallet.ChannelId, b0Cust, b0Merch, merchState) 40 | assert.Nil(t, err) 41 | assert.NotNil(t, closeToken) 42 | 43 | isTokenValid, channelState, custState, err := BidirectionalVerifyCloseToken(channelState, custState, closeToken) 44 | assert.Nil(t, err) 45 | assert.True(t, isTokenValid) 46 | 47 | payToken, err := BidirectionalEstablishMerchantIssuePayToken(channelState, com, merchState) 48 | assert.Nil(t, err) 49 | assert.NotNil(t, payToken) 50 | 51 | isChannelEstablished, channelState, custState, err := BidirectionalEstablishCustomerFinal(channelState, custState, payToken) 52 | assert.Nil(t, err) 53 | 54 | assert.True(t, isChannelEstablished) 55 | } 56 | 57 | func Test_Pay(t *testing.T) { 58 | b0Cust := 1000 59 | b0Merch := 100 60 | channelState, channelToken, merchState, custState, err := setup(b0Cust, b0Merch) 61 | assert.Nil(t, err) 62 | channelToken, custState, com, comProof, err := BidirectionalEstablishCustomerGenerateProof(channelToken, custState) 63 | assert.Nil(t, err) 64 | closeToken, err := BidirectionalEstablishMerchantIssueCloseToken(channelState, com, comProof, custState.Wallet.ChannelId, b0Cust, b0Merch, merchState) 65 | assert.Nil(t, err) 66 | _, channelState, custState, err = BidirectionalVerifyCloseToken(channelState, custState, closeToken) 67 | assert.Nil(t, err) 68 | payToken, err := BidirectionalEstablishMerchantIssuePayToken(channelState, com, merchState) 69 | assert.Nil(t, err) 70 | _, channelState, custState, err = BidirectionalEstablishCustomerFinal(channelState, custState, payToken) 71 | assert.Nil(t, err) 72 | 73 | payment, newCustState, err := BidirectionalPayGeneratePaymentProof(channelState, custState, 10) 74 | assert.Nil(t, err) 75 | closeToken, merchState, err = BidirectionalPayVerifyPaymentProof(channelState, payment, merchState) 76 | assert.Nil(t, err) 77 | revokeToken, custState, err := BidirectionalPayGenerateRevokeToken(channelState, custState, newCustState, closeToken) 78 | assert.Nil(t, err) 79 | payToken, merchState, err = BidirectionalPayVerifyRevokeToken(revokeToken, merchState) 80 | assert.Nil(t, err) 81 | custState, isTokenValid, err := BidirectionalPayVerifyPaymentToken(channelState, custState, payToken) 82 | assert.Nil(t, err) 83 | assert.True(t, isTokenValid) 84 | } 85 | 86 | func Test_IntermediaryPay(t *testing.T) { 87 | b0Alice := 1000 88 | b0Bob := 100 89 | b0Intermediary := 100 90 | channelState, err := BidirectionalChannelSetup("Test Channel", false) 91 | assert.Nil(t, err) 92 | channelToken, merchState, channelState, err := BidirectionalInitMerchant(channelState, "Hub") 93 | assert.Nil(t, err) 94 | channelToken, custStateAlice, err := BidirectionalInitCustomer(channelToken, b0Alice, b0Intermediary, "Alice") 95 | assert.Nil(t, err) 96 | channelToken, custStateAlice, com, comProof, err := BidirectionalEstablishCustomerGenerateProof(channelToken, custStateAlice) 97 | assert.Nil(t, err) 98 | closeToken, err := BidirectionalEstablishMerchantIssueCloseToken(channelState, com, comProof, custStateAlice.Wallet.ChannelId, b0Alice, b0Intermediary, merchState) 99 | assert.Nil(t, err) 100 | _, channelState, custStateAlice, err = BidirectionalVerifyCloseToken(channelState, custStateAlice, closeToken) 101 | assert.Nil(t, err) 102 | payToken, err := BidirectionalEstablishMerchantIssuePayToken(channelState, com, merchState) 103 | assert.Nil(t, err) 104 | _, channelState, custStateAlice, err = BidirectionalEstablishCustomerFinal(channelState, custStateAlice, payToken) 105 | assert.Nil(t, err) 106 | channelToken, custStateBob, err := BidirectionalInitCustomer(channelToken, b0Bob, b0Intermediary, "Bob") 107 | assert.Nil(t, err) 108 | channelToken, custStateBob, com, comProof, err = BidirectionalEstablishCustomerGenerateProof(channelToken, custStateBob) 109 | assert.Nil(t, err) 110 | closeToken, err = BidirectionalEstablishMerchantIssueCloseToken(channelState, com, comProof, custStateBob.Wallet.ChannelId, b0Bob, b0Intermediary, merchState) 111 | assert.Nil(t, err) 112 | _, channelState, custStateBob, err = BidirectionalVerifyCloseToken(channelState, custStateBob, closeToken) 113 | assert.Nil(t, err) 114 | payToken, err = BidirectionalEstablishMerchantIssuePayToken(channelState, com, merchState) 115 | assert.Nil(t, err) 116 | _, channelState, custStateBob, err = BidirectionalEstablishCustomerFinal(channelState, custStateBob, payToken) 117 | assert.Nil(t, err) 118 | 119 | paymentA, newCustStateAlice, err := BidirectionalPayGeneratePaymentProof(channelState, custStateAlice, 10) 120 | assert.Nil(t, err) 121 | paymentB, newCustStateBob, err := BidirectionalPayGeneratePaymentProof(channelState, custStateBob, -10) 122 | assert.Nil(t, err) 123 | closeTokenA, closeTokenB, merchState, err := BidirectionalPayVerifyMultiplePaymentProofs(channelState, paymentA, paymentB, merchState) 124 | assert.Nil(t, err) 125 | revokeTokenA, custStateAlice, err := BidirectionalPayGenerateRevokeToken(channelState, custStateAlice, newCustStateAlice, closeTokenA) 126 | assert.Nil(t, err) 127 | revokeTokenB, custStateBob, err := BidirectionalPayGenerateRevokeToken(channelState, custStateBob, newCustStateBob, closeTokenB) 128 | assert.Nil(t, err) 129 | payTokenA, payTokenB, merchState, err := BidirectionalPayVerifyMultipleRevokeTokens(revokeTokenA, revokeTokenB, merchState) 130 | assert.Nil(t, err) 131 | custStateAlice, isTokenValid, err := BidirectionalPayVerifyPaymentToken(channelState, custStateAlice, payTokenA) 132 | assert.Nil(t, err) 133 | assert.True(t, isTokenValid) 134 | custStateBob, isTokenValid, err = BidirectionalPayVerifyPaymentToken(channelState, custStateBob, payTokenB) 135 | assert.Nil(t, err) 136 | assert.True(t, isTokenValid) 137 | } 138 | 139 | func Test_Close(t *testing.T) { 140 | b0Cust := 1000 141 | b0Merch := 100 142 | channelState, channelToken, merchState, custState, err := setup(b0Cust, b0Merch) 143 | assert.Nil(t, err) 144 | channelToken, custState, com, comProof, err := BidirectionalEstablishCustomerGenerateProof(channelToken, custState) 145 | assert.Nil(t, err) 146 | closeToken, err := BidirectionalEstablishMerchantIssueCloseToken(channelState, com, comProof, custState.Wallet.ChannelId, b0Cust, b0Merch, merchState) 147 | assert.Nil(t, err) 148 | _, channelState, custState, err = BidirectionalVerifyCloseToken(channelState, custState, closeToken) 149 | assert.Nil(t, err) 150 | payToken, err := BidirectionalEstablishMerchantIssuePayToken(channelState, com, merchState) 151 | assert.Nil(t, err) 152 | _, channelState, custState, err = BidirectionalEstablishCustomerFinal(channelState, custState, payToken) 153 | assert.Nil(t, err) 154 | 155 | payment, newCustState, err := BidirectionalPayGeneratePaymentProof(channelState, custState, 10) 156 | assert.Nil(t, err) 157 | closeToken, merchState, err = BidirectionalPayVerifyPaymentProof(channelState, payment, merchState) 158 | assert.Nil(t, err) 159 | revokeToken, custState, err := BidirectionalPayGenerateRevokeToken(channelState, custState, newCustState, closeToken) 160 | assert.Nil(t, err) 161 | payToken, merchState, err = BidirectionalPayVerifyRevokeToken(revokeToken, merchState) 162 | assert.Nil(t, err) 163 | custState, _, err = BidirectionalPayVerifyPaymentToken(channelState, custState, payToken) 164 | assert.Nil(t, err) 165 | 166 | custClose, err := BidirectionalCustomerClose(channelState, custState) 167 | assert.Nil(t, err) 168 | _, _, Err, err := BidirectionalMerchantClose(channelState, channelToken, "onChainAddress", custClose, merchState) 169 | assert.Nil(t, err) 170 | assert.Equal(t, "merchant_close - Could not find entry for wpk & revoke token pair. Valid close!", Err) 171 | } 172 | 173 | -------------------------------------------------------------------------------- /include/ChannelClosure.h: -------------------------------------------------------------------------------- 1 | #ifndef __CHANNELCLOSURE_H__ 2 | #define __CHANNELCLOSURE_H__ 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "rapidjson/document.h" 12 | #include "rapidjson/writer.h" 13 | #include "rapidjson/stringbuffer.h" 14 | #include "rapidjson/prettywriter.h" 15 | 16 | #define HEX_CHARS "0123456789abcdefABCDEF" 17 | #define CHANNEL_CLOSURE_VECTOR_LENGTH 1426 18 | #define CHANNEL_CLOSURE_HEX_STRING_LENGTH CHANNEL_CLOSURE_VECTOR_LENGTH*2 19 | 20 | #define CHANNEL_CLOSURE_G2_LENGTH 129 21 | 22 | #define CHANNEL_CLOSURE_A_ARRAY_SIZE 4 //2 <--- TODO GABE I thought these are supposed to be 2 long? 23 | #define CHANNEL_CLOSURE_B_ARRAY_SIZE 4 //2 24 | 25 | using namespace rapidjson; 26 | 27 | class ChannelClosure : public std::vector { 28 | 29 | 30 | public: 31 | 32 | std::string toJson() { 33 | 34 | Document json; 35 | // allocator for memory management 36 | Document::AllocatorType& allocator = json.GetAllocator(); 37 | 38 | // define the document as an object rather than an array 39 | json.SetObject(); 40 | 41 | if( CHANNEL_CLOSURE_VECTOR_LENGTH != this->size()) 42 | return("{}"); 43 | 44 | // iterator we are going to be using the whole time 45 | std::vector::iterator it = this->begin(); 46 | 47 | // Double check the a length 48 | if( CHANNEL_CLOSURE_G2_LENGTH != *it ) 49 | return("{}"); 50 | it++; 51 | 52 | Value a(kArrayType); 53 | for( int j = 0; j< CHANNEL_CLOSURE_G2_LENGTH; j++) 54 | { 55 | a.PushBack(*it, allocator); 56 | it++; 57 | } 58 | 59 | // Double check the b length 60 | if( CHANNEL_CLOSURE_G2_LENGTH != *it ) 61 | return("{}"); 62 | it++; 63 | 64 | Value b(kArrayType); 65 | for( int j = 0; j< CHANNEL_CLOSURE_G2_LENGTH; j++) 66 | { 67 | b.PushBack(*it, allocator); 68 | it++; 69 | } 70 | 71 | // Double check the c length 72 | if( CHANNEL_CLOSURE_G2_LENGTH != *it ) 73 | return("{}"); 74 | it++; 75 | 76 | Value c(kArrayType); 77 | for( int j = 0; j< CHANNEL_CLOSURE_G2_LENGTH; j++) 78 | { 79 | c.PushBack(*it, allocator); 80 | it++; 81 | } 82 | 83 | json.AddMember("a", a, allocator); 84 | json.AddMember("b", b, allocator); 85 | json.AddMember("c", c, allocator); 86 | 87 | Value A(kArrayType); 88 | 89 | 90 | // Check how many things there are 91 | if( CHANNEL_CLOSURE_A_ARRAY_SIZE != *it ) 92 | return("{}"); 93 | it++; 94 | 95 | // Check the size of the things 96 | if( CHANNEL_CLOSURE_G2_LENGTH != *it ) 97 | return("{}"); 98 | it++; 99 | 100 | 101 | for (int i =0; i writer(sb); 141 | json.Accept(writer); 142 | return sb.GetString(); 143 | } 144 | 145 | 146 | bool fromJson(std::string s) { 147 | Document json; 148 | json.Parse(s.c_str()); 149 | 150 | eraseAll(); 151 | 152 | // // Make sure we arent going to get an error when indexing into the JSON 153 | if(!json.HasMember("a")) 154 | return false; 155 | if(!json.HasMember("b")) 156 | return false; 157 | if(!json.HasMember("c")) 158 | return false; 159 | if(!json.HasMember("A")) 160 | return false; 161 | if(!json.HasMember("B")) 162 | return false; 163 | 164 | 165 | const Value& a = json["a"]; 166 | const Value& b = json["b"]; 167 | const Value& c = json["c"]; 168 | const Value& A = json["A"]; 169 | const Value& B = json["B"]; 170 | 171 | if(!a.IsArray()) 172 | return false; 173 | if(!b.IsArray()) 174 | return false; 175 | if(!c.IsArray()) 176 | return false; 177 | if(!A.IsArray()) 178 | return false; 179 | if(!B.IsArray()) 180 | return false; 181 | 182 | if(!(a.Size() == SizeType(CHANNEL_CLOSURE_G2_LENGTH))) 183 | return false; 184 | if(!(b.Size() == SizeType(CHANNEL_CLOSURE_G2_LENGTH))) 185 | return false; 186 | if(!(c.Size() == SizeType(CHANNEL_CLOSURE_G2_LENGTH))) 187 | return false; 188 | 189 | if(!(A.Size() == SizeType(CHANNEL_CLOSURE_A_ARRAY_SIZE))) 190 | return false; 191 | if(!(B.Size() == SizeType(CHANNEL_CLOSURE_B_ARRAY_SIZE))) 192 | return false; 193 | 194 | // Add the header information 195 | // From here on out, make sure to call cleanupAndFalse() instead of false 196 | 197 | // a 198 | this->push_back(CHANNEL_CLOSURE_G2_LENGTH); 199 | 200 | for(SizeType j = 0; j < a.Size(); j++) 201 | this->push_back(a[j].GetUint64()); 202 | 203 | // b 204 | this->push_back(CHANNEL_CLOSURE_G2_LENGTH); 205 | 206 | for(SizeType j = 0; j < c.Size(); j++) 207 | this->push_back(b[j].GetUint64()); 208 | 209 | // c 210 | this->push_back(CHANNEL_CLOSURE_G2_LENGTH); 211 | 212 | for(SizeType j = 0; j < c.Size(); j++) 213 | this->push_back(c[j].GetUint64()); 214 | 215 | // A 216 | this->push_back(CHANNEL_CLOSURE_A_ARRAY_SIZE); 217 | this->push_back(CHANNEL_CLOSURE_G2_LENGTH); 218 | 219 | for (SizeType i = 0; i < A.Size(); i++) 220 | { 221 | const Value& vec = A[i]; 222 | if(!vec.IsArray()) 223 | return cleanupAndFalse(); 224 | if(!(vec.Size() == SizeType(CHANNEL_CLOSURE_G2_LENGTH))) 225 | return cleanupAndFalse(); 226 | 227 | for(SizeType j = 0; j < vec.Size(); j++) 228 | { 229 | this->push_back(vec[j].GetUint64()); 230 | } 231 | } 232 | 233 | // B 234 | this->push_back(CHANNEL_CLOSURE_B_ARRAY_SIZE); 235 | this->push_back(CHANNEL_CLOSURE_G2_LENGTH); 236 | for (SizeType i = 0; i < B.Size(); i++) 237 | { 238 | const Value& vec = B[i]; 239 | if(!vec.IsArray()) 240 | return cleanupAndFalse(); 241 | if(!(vec.Size() == SizeType(CHANNEL_CLOSURE_G2_LENGTH))) 242 | return cleanupAndFalse(); 243 | 244 | for(SizeType j = 0; j < vec.Size(); j++) 245 | { 246 | this->push_back(vec[j].GetUint64()); 247 | } 248 | } 249 | 250 | // Make sure the final length is good 251 | if(!(this->size() == CHANNEL_CLOSURE_VECTOR_LENGTH)) 252 | return cleanupAndFalse(); 253 | 254 | return true; 255 | } 256 | 257 | 258 | // Stolen from https://github.com/zeutro/openabe/blob/master/src/include/openabe/utils/zbytestring.h 259 | 260 | bool fromHex(std::string s) { 261 | if((s.find_first_not_of(HEX_CHARS) != std::string::npos) || 262 | (s.size() % 2 != 0)) { 263 | return false; 264 | } 265 | 266 | if ( s.length() != CHANNEL_CLOSURE_HEX_STRING_LENGTH) 267 | return false; 268 | 269 | std::string hex_str; 270 | std::stringstream ss; 271 | int tmp; 272 | 273 | this->clear(); 274 | for (size_t i = 0; i < s.size(); i += 2) { 275 | hex_str = s[i]; 276 | hex_str += s[i+1]; 277 | 278 | ss << hex_str; 279 | ss >> std::hex >> tmp; 280 | this->push_back(tmp & 0xFF); 281 | ss.clear(); 282 | } 283 | return true; 284 | } 285 | 286 | std::string toHex() const { 287 | std::stringstream ss; 288 | int hex_len = 2; 289 | char hex[hex_len+1]; 290 | std::memset(hex, 0, hex_len+1); 291 | 292 | for (std::vector::const_iterator it = this->begin(); 293 | it != this->end(); ++it) { 294 | sprintf(hex, "%02X", *it); 295 | ss << hex; 296 | } 297 | return ss.str(); 298 | } 299 | 300 | std::string toLowerHex() const { 301 | std::stringstream ss; 302 | int hex_len = 2; 303 | char hex[hex_len+1]; 304 | std::memset(hex, 0, hex_len+1); 305 | 306 | for (std::vector::const_iterator it = this->begin() ; it != this->end(); ++it) { 307 | sprintf(hex, "%02x", *it); 308 | ss << hex; 309 | } 310 | return ss.str(); 311 | } 312 | 313 | void eraseAll() { 314 | this->erase(this->begin(), this->end()); 315 | } 316 | 317 | private: 318 | 319 | bool cleanupAndFalse() { 320 | eraseAll(); 321 | return false; 322 | } 323 | 324 | }; 325 | 326 | 327 | #endif -------------------------------------------------------------------------------- /include/ChannelToken.h: -------------------------------------------------------------------------------- 1 | #ifndef __CHANNELTOKEN_H__ 2 | #define __CHANNELTOKEN_H__ 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "rapidjson/document.h" 12 | #include "rapidjson/writer.h" 13 | #include "rapidjson/stringbuffer.h" 14 | #include "rapidjson/prettywriter.h" 15 | 16 | #define HEX_CHARS "0123456789abcdefABCDEF" 17 | #define VECTOR_LENGTH 810 18 | #define HEX_STRING_LENGTH VECTOR_LENGTH*2 19 | 20 | #define CHANNEL_TOKEN_NUM_BASE_POINTS 5 21 | #define CHANNEL_TOKEN_LENGTH_POINT 129 22 | #define CHANNEL_TOKEN_LENGTH_R 32 23 | 24 | using namespace rapidjson; 25 | 26 | class ChannelToken : public std::vector { 27 | 28 | 29 | public: 30 | 31 | std::string toJson() { 32 | 33 | Document json; 34 | // allocator for memory management 35 | Document::AllocatorType& allocator = json.GetAllocator(); 36 | 37 | // define the document as an object rather than an array 38 | json.SetObject(); 39 | 40 | // 810 bytes => [g-count] [g-len] [g-bytes_i] [g-bytes_count] [c-len] [c-bytes] [r-len] [r-bytes] 41 | if( VECTOR_LENGTH != this->size()) 42 | return("{}"); 43 | 44 | // iterator we are going to be using the whole time 45 | std::vector::iterator it = this->begin(); 46 | 47 | // Double check the g-count 48 | if( CHANNEL_TOKEN_NUM_BASE_POINTS != *it ) 49 | return("{}"); 50 | it++; 51 | 52 | // Double check the g-len 53 | if( CHANNEL_TOKEN_LENGTH_POINT != *it ) 54 | return("{}"); 55 | it++; 56 | 57 | Value params(kObjectType); 58 | Value pub_bases(kArrayType); 59 | 60 | for( int i = 0; i< CHANNEL_TOKEN_NUM_BASE_POINTS; i++) 61 | { 62 | Value base(kArrayType); 63 | for( int j = 0; j< CHANNEL_TOKEN_LENGTH_POINT; j++) 64 | { 65 | base.PushBack(*it, allocator); 66 | it++; 67 | } 68 | pub_bases.PushBack(base, allocator); 69 | } 70 | 71 | params.AddMember("pub_bases", pub_bases, allocator); 72 | 73 | Value com(kObjectType); 74 | 75 | // double check c-len 76 | if( CHANNEL_TOKEN_LENGTH_POINT != *it ) 77 | return("{}"); 78 | it++; 79 | 80 | Value c(kArrayType); 81 | for( int j = 0; j< CHANNEL_TOKEN_LENGTH_POINT; j++) 82 | { 83 | c.PushBack(*it, allocator); 84 | it++; 85 | } 86 | 87 | com.AddMember("c",c,allocator); 88 | 89 | // double check r-len 90 | if( CHANNEL_TOKEN_LENGTH_R != *it ) 91 | return("{}"); 92 | it++; 93 | 94 | Value r(kArrayType); 95 | for( int j = 0; j< CHANNEL_TOKEN_LENGTH_R; j++) 96 | { 97 | r.PushBack(*it, allocator); 98 | it++; 99 | } 100 | 101 | com.AddMember("r",r,allocator); 102 | 103 | // build final json string 104 | json.AddMember("com", com, allocator); 105 | json.AddMember("params", params, allocator); 106 | 107 | StringBuffer sb; 108 | Writer writer(sb); 109 | json.Accept(writer); 110 | return sb.GetString(); 111 | } 112 | 113 | bool fromJson(std::string s) { 114 | Document json; 115 | json.Parse(s.c_str()); 116 | 117 | eraseAll(); 118 | 119 | // Make sure we arent going to get an error when indexing into the JSON 120 | if(!json.HasMember("params")) 121 | return false; 122 | 123 | const Value& params = json["params"]; 124 | 125 | if(!params.IsObject()) 126 | return false; 127 | if(!params.HasMember("pub_bases")) 128 | return false; 129 | 130 | 131 | const Value& pub_bases = params["pub_bases"]; 132 | 133 | if(!pub_bases.IsArray()) 134 | return false; 135 | if(!(pub_bases.Size() == SizeType(CHANNEL_TOKEN_NUM_BASE_POINTS))) 136 | return false; 137 | 138 | //Checking the formatting in com ahead of time before we edit the internal vector 139 | if(!json.HasMember("com")) 140 | return false; 141 | const Value& com = json["com"]; 142 | 143 | if(!com.IsObject()) 144 | return false; 145 | if(!com.HasMember("c")) 146 | return false; 147 | if(!com.HasMember("r")) 148 | return false; 149 | 150 | const Value& c = com["c"]; 151 | const Value& r = com["r"]; 152 | 153 | if(!c.IsArray()) 154 | return false; 155 | if(!r.IsArray()) 156 | return false; 157 | 158 | if(!(c.Size() == SizeType(CHANNEL_TOKEN_LENGTH_POINT))) 159 | return false; 160 | if(!(r.Size() == SizeType(CHANNEL_TOKEN_LENGTH_R))) 161 | return false; 162 | 163 | // Add the header information 164 | // From here on out, make sure to call cleanupAndFalse() instead of false 165 | this->push_back(CHANNEL_TOKEN_NUM_BASE_POINTS); 166 | this->push_back(CHANNEL_TOKEN_LENGTH_POINT); 167 | 168 | for (SizeType i = 0; i < pub_bases.Size(); i++) 169 | { 170 | const Value& basepoint = pub_bases[i]; 171 | if(!basepoint.IsArray()) 172 | return cleanupAndFalse(); 173 | if(!(basepoint.Size() == SizeType(CHANNEL_TOKEN_LENGTH_POINT))) 174 | return cleanupAndFalse(); 175 | 176 | for(SizeType j = 0; j < basepoint.Size(); j++) 177 | { 178 | this->push_back(basepoint[j].GetUint64()); 179 | } 180 | } 181 | 182 | this->push_back(CHANNEL_TOKEN_LENGTH_POINT); 183 | 184 | for(SizeType j = 0; j < c.Size(); j++) 185 | this->push_back(c[j].GetUint64()); 186 | 187 | this->push_back(CHANNEL_TOKEN_LENGTH_R); 188 | 189 | for(SizeType j = 0; j < r.Size(); j++) 190 | this->push_back(r[j].GetUint64()); 191 | 192 | // Make sure the final length is good 193 | if(!(this->size() == VECTOR_LENGTH)) 194 | return cleanupAndFalse(); 195 | 196 | return true; 197 | } 198 | 199 | 200 | // Stolen from https://github.com/zeutro/openabe/blob/master/src/include/openabe/utils/zbytestring.h 201 | 202 | bool fromHex(std::string s) { 203 | if((s.find_first_not_of(HEX_CHARS) != std::string::npos) || 204 | (s.size() % 2 != 0)) { 205 | return false; 206 | } 207 | 208 | if ( s.length() != HEX_STRING_LENGTH) 209 | return false; 210 | 211 | std::string hex_str; 212 | std::stringstream ss; 213 | int tmp; 214 | 215 | this->clear(); 216 | for (size_t i = 0; i < s.size(); i += 2) { 217 | hex_str = s[i]; 218 | hex_str += s[i+1]; 219 | 220 | ss << hex_str; 221 | ss >> std::hex >> tmp; 222 | this->push_back(tmp & 0xFF); 223 | ss.clear(); 224 | } 225 | return true; 226 | } 227 | 228 | std::string toHex() const { 229 | std::stringstream ss; 230 | int hex_len = 2; 231 | char hex[hex_len+1]; 232 | std::memset(hex, 0, hex_len+1); 233 | 234 | for (std::vector::const_iterator it = this->begin(); 235 | it != this->end(); ++it) { 236 | sprintf(hex, "%02X", *it); 237 | ss << hex; 238 | } 239 | return ss.str(); 240 | } 241 | 242 | std::string toLowerHex() const { 243 | std::stringstream ss; 244 | int hex_len = 2; 245 | char hex[hex_len+1]; 246 | std::memset(hex, 0, hex_len+1); 247 | 248 | for (std::vector::const_iterator it = this->begin() ; it != this->end(); ++it) { 249 | sprintf(hex, "%02x", *it); 250 | ss << hex; 251 | } 252 | return ss.str(); 253 | } 254 | 255 | void eraseAll() { 256 | this->erase(this->begin(), this->end()); 257 | } 258 | 259 | private: 260 | 261 | bool cleanupAndFalse() { 262 | eraseAll(); 263 | return false; 264 | } 265 | 266 | }; 267 | 268 | 269 | #endif -------------------------------------------------------------------------------- /include/PublicKey.h: -------------------------------------------------------------------------------- 1 | #ifndef __PUBLICKEY_H__ 2 | #define __PUBLICKEY_H__ 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "rapidjson/document.h" 12 | #include "rapidjson/writer.h" 13 | #include "rapidjson/stringbuffer.h" 14 | #include "rapidjson/prettywriter.h" 15 | 16 | #define HEX_CHARS "0123456789abcdefABCDEF" 17 | #define PUBLIC_KEY_VECTOR_LENGTH 1174 18 | #define PUBLIC_KEY_HEX_STRING_LENGTH PUBLIC_KEY_VECTOR_LENGTH*2 19 | 20 | #define PUBLIC_KEY_X_LENGTH 65 21 | #define PUBLIC_KEY_Y_LENGTH 65 22 | 23 | #define PUBLIC_KEY_Z_LENGTH 4 24 | #define PUBLIC_KEY_Z_POINT_LENGTH 65 25 | 26 | #define PUBLIC_KEY_Z2_LENGTH 4 27 | #define PUBLIC_KEY_Z2_POINT_LENGTH 129 28 | 29 | #define PUBLIC_KEY_W_LENGTH 4 //2 30 | #define PUBLIC_KEY_W_POINT_LENGTH 65//130 31 | 32 | using namespace rapidjson; 33 | 34 | class PublicKey : public std::vector { 35 | 36 | 37 | public: 38 | 39 | std::string toJson() { 40 | 41 | Document json; 42 | // allocator for memory management 43 | Document::AllocatorType& allocator = json.GetAllocator(); 44 | 45 | // define the document as an object rather than an array 46 | json.SetObject(); 47 | 48 | if( PUBLIC_KEY_VECTOR_LENGTH != this->size()) 49 | return("{}"); 50 | 51 | // iterator we are going to be using the whole time 52 | std::vector::iterator it = this->begin(); 53 | 54 | // Double check the X length 55 | if( PUBLIC_KEY_X_LENGTH != *it ) 56 | return("{}"); 57 | it++; 58 | 59 | Value X(kArrayType); 60 | for( int j = 0; j< PUBLIC_KEY_X_LENGTH; j++) 61 | { 62 | X.PushBack(*it, allocator); 63 | it++; 64 | } 65 | 66 | // Double check the Y length 67 | if( PUBLIC_KEY_Y_LENGTH != *it ) 68 | return("{}"); 69 | it++; 70 | 71 | Value Y(kArrayType); 72 | for( int j = 0; j< PUBLIC_KEY_Y_LENGTH; j++) 73 | { 74 | Y.PushBack(*it, allocator); 75 | it++; 76 | } 77 | 78 | // Double check the Z number 79 | if( PUBLIC_KEY_Z_LENGTH != *it ) 80 | return("{}"); 81 | it++; 82 | 83 | // ... and that they are the correct length 84 | if( PUBLIC_KEY_Z_POINT_LENGTH != *it ) 85 | return("{}"); 86 | it++; 87 | 88 | Value Z(kArrayType); 89 | for( int i = 0; i< PUBLIC_KEY_Z_LENGTH; i++) 90 | { 91 | Value vec(kArrayType); 92 | for( int j = 0; j< PUBLIC_KEY_Z_POINT_LENGTH; j++) 93 | { 94 | vec.PushBack(*it, allocator); 95 | it++; 96 | } 97 | Z.PushBack(vec, allocator); 98 | } 99 | 100 | // Double check the Z2 number 101 | if( PUBLIC_KEY_Z2_LENGTH != *it ) 102 | return("{}"); 103 | it++; 104 | 105 | // ... and that they are the correct length 106 | if( PUBLIC_KEY_Z2_POINT_LENGTH != *it ) 107 | return("{}"); 108 | it++; 109 | 110 | Value Z2(kArrayType); 111 | for( int i = 0; i< PUBLIC_KEY_Z2_LENGTH; i++) 112 | { 113 | Value vec(kArrayType); 114 | for( int j = 0; j< PUBLIC_KEY_Z2_POINT_LENGTH; j++) 115 | { 116 | vec.PushBack(*it, allocator); 117 | it++; 118 | } 119 | Z2.PushBack(vec, allocator); 120 | } 121 | 122 | // Double check the W number 123 | if( PUBLIC_KEY_W_LENGTH != *it ) 124 | return("{}"); 125 | it++; 126 | 127 | // ... and that they are the correct length 128 | if( PUBLIC_KEY_W_POINT_LENGTH != *it ) 129 | return("{}"); 130 | it++; 131 | 132 | Value W(kArrayType); 133 | for( int j = 0; j< PUBLIC_KEY_W_LENGTH; j++) 134 | { 135 | Value vec(kArrayType); 136 | for( int j = 0; j< PUBLIC_KEY_W_POINT_LENGTH; j++) 137 | { 138 | vec.PushBack(*it, allocator); 139 | it++; 140 | } 141 | W.PushBack(vec, allocator); 142 | } 143 | 144 | // build final json string 145 | json.AddMember("X", X, allocator); 146 | json.AddMember("Y", Y, allocator); 147 | json.AddMember("Z", Z, allocator); 148 | json.AddMember("Z2", Z2, allocator); 149 | json.AddMember("W", W, allocator); 150 | 151 | StringBuffer sb; 152 | Writer writer(sb); 153 | json.Accept(writer); 154 | return sb.GetString(); 155 | } 156 | 157 | 158 | bool fromJson(std::string s) { 159 | Document json; 160 | json.Parse(s.c_str()); 161 | 162 | eraseAll(); 163 | 164 | // Make sure we arent going to get an error when indexing into the JSON 165 | if(!json.HasMember("X")) 166 | return false; 167 | if(!json.HasMember("Y")) 168 | return false; 169 | if(!json.HasMember("Z")) 170 | return false; 171 | if(!json.HasMember("Z2")) 172 | return false; 173 | if(!json.HasMember("W")) 174 | return false; 175 | 176 | const Value& X = json["X"]; 177 | const Value& Y = json["Y"]; 178 | const Value& Z = json["Z"]; 179 | const Value& Z2 = json["Z2"]; 180 | const Value& W = json["W"]; 181 | 182 | if(!X.IsArray()) 183 | return false; 184 | if(!Y.IsArray()) 185 | return false; 186 | if(!Z.IsArray()) 187 | return false; 188 | if(!Z2.IsArray()) 189 | return false; 190 | if(!W.IsArray()) 191 | return false; 192 | 193 | if(!(Z.Size() == SizeType(PUBLIC_KEY_Z_LENGTH))) 194 | return false; 195 | if(!(Z2.Size() == SizeType(PUBLIC_KEY_Z2_LENGTH))) 196 | return false; 197 | if(!(W.Size() == SizeType(PUBLIC_KEY_W_LENGTH))) 198 | return false; 199 | 200 | // Add the header information 201 | // From here on out, make sure to call cleanupAndFalse() instead of false 202 | 203 | // X 204 | this->push_back(PUBLIC_KEY_X_LENGTH); 205 | 206 | for(SizeType j = 0; j < X.Size(); j++) 207 | this->push_back(X[j].GetUint64()); 208 | 209 | // Y 210 | this->push_back(PUBLIC_KEY_Y_LENGTH); 211 | 212 | for(SizeType j = 0; j < Y.Size(); j++) 213 | this->push_back(Y[j].GetUint64()); 214 | 215 | // Z 216 | this->push_back(PUBLIC_KEY_Z_LENGTH); 217 | 218 | this->push_back(PUBLIC_KEY_Z_POINT_LENGTH); 219 | 220 | for (SizeType i = 0; i < Z.Size(); i++) 221 | { 222 | const Value& vec = Z[i]; 223 | if(!vec.IsArray()) 224 | return cleanupAndFalse(); 225 | if(!(vec.Size() == SizeType(PUBLIC_KEY_Z_POINT_LENGTH))) 226 | return cleanupAndFalse(); 227 | 228 | for(SizeType j = 0; j < vec.Size(); j++) 229 | { 230 | this->push_back(vec[j].GetUint64()); 231 | } 232 | } 233 | 234 | //Z2 235 | this->push_back(PUBLIC_KEY_Z2_LENGTH); 236 | 237 | this->push_back(PUBLIC_KEY_Z2_POINT_LENGTH); 238 | 239 | for (SizeType i = 0; i < Z2.Size(); i++) 240 | { 241 | const Value& vec = Z2[i]; 242 | if(!vec.IsArray()) 243 | return cleanupAndFalse(); 244 | if(!(vec.Size() == SizeType(PUBLIC_KEY_Z2_POINT_LENGTH))) 245 | return cleanupAndFalse(); 246 | 247 | for(SizeType j = 0; j < vec.Size(); j++) 248 | { 249 | this->push_back(vec[j].GetUint64()); 250 | } 251 | } 252 | 253 | // W 254 | this->push_back(PUBLIC_KEY_W_LENGTH); 255 | 256 | this->push_back(PUBLIC_KEY_W_POINT_LENGTH); 257 | 258 | for (SizeType i = 0; i < W.Size(); i++) 259 | { 260 | const Value& vec = W[i]; 261 | if(!vec.IsArray()) 262 | return cleanupAndFalse(); 263 | if(!(vec.Size() == SizeType(PUBLIC_KEY_W_POINT_LENGTH))) 264 | return cleanupAndFalse(); 265 | 266 | for(SizeType j = 0; j < vec.Size(); j++) 267 | { 268 | this->push_back(vec[j].GetUint64()); 269 | } 270 | } 271 | 272 | // Make sure the final length is good 273 | if(!(this->size() == PUBLIC_KEY_VECTOR_LENGTH)) 274 | return cleanupAndFalse(); 275 | 276 | return true; 277 | } 278 | 279 | 280 | // Stolen from https://github.com/zeutro/openabe/blob/master/src/include/openabe/utils/zbytestring.h 281 | 282 | bool fromHex(std::string s) { 283 | if((s.find_first_not_of(HEX_CHARS) != std::string::npos) || 284 | (s.size() % 2 != 0)) { 285 | return false; 286 | } 287 | 288 | if ( s.length() != PUBLIC_KEY_HEX_STRING_LENGTH) 289 | return false; 290 | 291 | std::string hex_str; 292 | std::stringstream ss; 293 | int tmp; 294 | 295 | this->clear(); 296 | for (size_t i = 0; i < s.size(); i += 2) { 297 | hex_str = s[i]; 298 | hex_str += s[i+1]; 299 | 300 | ss << hex_str; 301 | ss >> std::hex >> tmp; 302 | this->push_back(tmp & 0xFF); 303 | ss.clear(); 304 | } 305 | return true; 306 | } 307 | 308 | std::string toHex() const { 309 | std::stringstream ss; 310 | int hex_len = 2; 311 | char hex[hex_len+1]; 312 | std::memset(hex, 0, hex_len+1); 313 | 314 | for (std::vector::const_iterator it = this->begin(); 315 | it != this->end(); ++it) { 316 | sprintf(hex, "%02X", *it); 317 | ss << hex; 318 | } 319 | return ss.str(); 320 | } 321 | 322 | std::string toLowerHex() const { 323 | std::stringstream ss; 324 | int hex_len = 2; 325 | char hex[hex_len+1]; 326 | std::memset(hex, 0, hex_len+1); 327 | 328 | for (std::vector::const_iterator it = this->begin() ; it != this->end(); ++it) { 329 | sprintf(hex, "%02x", *it); 330 | ss << hex; 331 | } 332 | return ss.str(); 333 | } 334 | 335 | void eraseAll() { 336 | this->erase(this->begin(), this->end()); 337 | } 338 | 339 | private: 340 | 341 | bool cleanupAndFalse() { 342 | eraseAll(); 343 | return false; 344 | } 345 | 346 | }; 347 | 348 | 349 | #endif -------------------------------------------------------------------------------- /include/PublicParams.h: -------------------------------------------------------------------------------- 1 | #ifndef __PUBLICPARAMS_H__ 2 | #define __PUBLICPARAMS_H__ 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "rapidjson/document.h" 12 | #include "rapidjson/writer.h" 13 | #include "rapidjson/stringbuffer.h" 14 | #include "rapidjson/prettywriter.h" 15 | 16 | #define HEX_CHARS "0123456789abcdefABCDEF" 17 | #define PUBLIC_PARAMS_VECTOR_LENGTH 196 18 | #define PUBLIC_PARAMS_HEX_STRING_LENGTH PUBLIC_PARAMS_VECTOR_LENGTH*2 19 | 20 | #define PUBLIC_PARAMS_G1_LENGTH 65 21 | #define PUBLIC_PARAMS_G2_LENGTH 129 22 | 23 | #define PUBLIC_PARAMS_BPGENS_LENGTH 2 24 | 25 | 26 | using namespace rapidjson; 27 | 28 | class PublicParams : public std::vector { 29 | 30 | 31 | public: 32 | 33 | std::string toJson() { 34 | 35 | Document json; 36 | // allocator for memory management 37 | Document::AllocatorType& allocator = json.GetAllocator(); 38 | 39 | // define the document as an object rather than an array 40 | json.SetObject(); 41 | 42 | if( PUBLIC_PARAMS_VECTOR_LENGTH != this->size()) 43 | return("{}"); 44 | 45 | // iterator we are going to be using the whole time 46 | std::vector::iterator it = this->begin(); 47 | 48 | Value cl_mpk(kObjectType); 49 | 50 | // Double check the G1 length 51 | if( PUBLIC_PARAMS_G1_LENGTH != *it ) 52 | return("{}"); 53 | it++; 54 | 55 | Value g1(kArrayType); 56 | for( int j = 0; j< PUBLIC_PARAMS_G1_LENGTH; j++) 57 | { 58 | g1.PushBack(*it, allocator); 59 | it++; 60 | } 61 | 62 | // Double check the Y length 63 | if( PUBLIC_PARAMS_G2_LENGTH != *it ) 64 | return("{}"); 65 | it++; 66 | 67 | Value g2(kArrayType); 68 | for( int j = 0; j< PUBLIC_PARAMS_G2_LENGTH; j++) 69 | { 70 | g2.PushBack(*it, allocator); 71 | it++; 72 | } 73 | 74 | cl_mpk.AddMember("g1", g1, allocator); 75 | cl_mpk.AddMember("g2", g2, allocator); 76 | json.AddMember("cl_mpk", cl_mpk, allocator); 77 | 78 | //Adding in the defaults TODO FIGURE OUT IS THESE ARE CONSTANT 79 | 80 | json.AddMember("l", 4, allocator); 81 | 82 | Value bp_gens(kArrayType); 83 | bp_gens.PushBack(64, allocator).PushBack(1, allocator); 84 | json.AddMember("bp_gens", bp_gens, allocator); 85 | 86 | json.AddMember("range_proof_bits",32, allocator); 87 | json.AddMember("extra_verify", false, allocator); 88 | 89 | StringBuffer sb; 90 | Writer writer(sb); 91 | json.Accept(writer); 92 | return sb.GetString(); 93 | } 94 | 95 | 96 | bool fromJson(std::string s) { 97 | Document json; 98 | json.Parse(s.c_str()); 99 | 100 | eraseAll(); 101 | 102 | // // Make sure we arent going to get an error when indexing into the JSON 103 | if(!json.HasMember("cl_mpk")) 104 | return false; 105 | 106 | // Defaults. We might be able to ignore? 107 | 108 | if(!json.HasMember("l")) 109 | return false; 110 | if(!json.HasMember("bp_gens")) 111 | return false; 112 | if(!json.HasMember("range_proof_bits")) 113 | return false; 114 | if(!json.HasMember("extra_verify")) 115 | return false; 116 | 117 | const Value& cl_mpk = json["cl_mpk"]; 118 | 119 | if(!cl_mpk.IsObject()) 120 | return false; 121 | 122 | if(!cl_mpk.HasMember("g1")) 123 | return false; 124 | if(!cl_mpk.HasMember("g2")) 125 | return false; 126 | 127 | const Value& g1 = cl_mpk["g1"]; 128 | const Value& g2 = cl_mpk["g2"]; 129 | 130 | if(!g1.IsArray()) 131 | return false; 132 | if(!g2.IsArray()) 133 | return false; 134 | 135 | if(!(g1.Size() == SizeType(PUBLIC_PARAMS_G1_LENGTH))) 136 | return false; 137 | if(!(g2.Size() == SizeType(PUBLIC_PARAMS_G2_LENGTH))) 138 | return false; 139 | 140 | // Add the header information 141 | // From here on out, make sure to call cleanupAndFalse() instead of false 142 | 143 | // g1 144 | this->push_back(PUBLIC_PARAMS_G1_LENGTH); 145 | 146 | for(SizeType j = 0; j < g1.Size(); j++) 147 | this->push_back(g1[j].GetUint64()); 148 | 149 | // Y 150 | this->push_back(PUBLIC_PARAMS_G2_LENGTH); 151 | 152 | for(SizeType j = 0; j < g2.Size(); j++) 153 | this->push_back(g2[j].GetUint64()); 154 | 155 | // Make sure the final length is good 156 | if(!(this->size() == PUBLIC_PARAMS_VECTOR_LENGTH)) 157 | return cleanupAndFalse(); 158 | 159 | return true; 160 | } 161 | 162 | 163 | // Stolen from https://github.com/zeutro/openabe/blob/master/src/include/openabe/utils/zbytestring.h 164 | 165 | bool fromHex(std::string s) { 166 | if((s.find_first_not_of(HEX_CHARS) != std::string::npos) || 167 | (s.size() % 2 != 0)) { 168 | return false; 169 | } 170 | 171 | if ( s.length() != PUBLIC_PARAMS_HEX_STRING_LENGTH) 172 | return false; 173 | 174 | std::string hex_str; 175 | std::stringstream ss; 176 | int tmp; 177 | 178 | this->clear(); 179 | for (size_t i = 0; i < s.size(); i += 2) { 180 | hex_str = s[i]; 181 | hex_str += s[i+1]; 182 | 183 | ss << hex_str; 184 | ss >> std::hex >> tmp; 185 | this->push_back(tmp & 0xFF); 186 | ss.clear(); 187 | } 188 | return true; 189 | } 190 | 191 | std::string toHex() const { 192 | std::stringstream ss; 193 | int hex_len = 2; 194 | char hex[hex_len+1]; 195 | std::memset(hex, 0, hex_len+1); 196 | 197 | for (std::vector::const_iterator it = this->begin(); 198 | it != this->end(); ++it) { 199 | sprintf(hex, "%02X", *it); 200 | ss << hex; 201 | } 202 | return ss.str(); 203 | } 204 | 205 | std::string toLowerHex() const { 206 | std::stringstream ss; 207 | int hex_len = 2; 208 | char hex[hex_len+1]; 209 | std::memset(hex, 0, hex_len+1); 210 | 211 | for (std::vector::const_iterator it = this->begin() ; it != this->end(); ++it) { 212 | sprintf(hex, "%02x", *it); 213 | ss << hex; 214 | } 215 | return ss.str(); 216 | } 217 | 218 | void eraseAll() { 219 | this->erase(this->begin(), this->end()); 220 | } 221 | 222 | private: 223 | 224 | bool cleanupAndFalse() { 225 | eraseAll(); 226 | return false; 227 | } 228 | 229 | }; 230 | 231 | 232 | #endif -------------------------------------------------------------------------------- /include/Wallet.h: -------------------------------------------------------------------------------- 1 | #ifndef __WALLET_H__ 2 | #define __WALLET_H__ 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "rapidjson/document.h" 12 | #include "rapidjson/writer.h" 13 | #include "rapidjson/stringbuffer.h" 14 | #include "rapidjson/prettywriter.h" 15 | 16 | #define HEX_CHARS "0123456789abcdefABCDEF" 17 | #define WALLET_VECTOR_LENGTH 130 18 | #define WALLET_HEX_STRING_LENGTH WALLET_VECTOR_LENGTH*2 19 | 20 | #define WALLET_LENGTH 4 21 | #define WALLET_POINT_LENGTH 32 22 | 23 | 24 | using namespace rapidjson; 25 | 26 | class Wallet : public std::vector { 27 | 28 | 29 | public: 30 | 31 | std::string toJson() { 32 | 33 | Document json; 34 | // allocator for memory management 35 | Document::AllocatorType& allocator = json.GetAllocator(); 36 | 37 | // define the document as an object rather than an array 38 | json.SetArray(); 39 | 40 | if( WALLET_VECTOR_LENGTH != this->size()) 41 | return("{}"); 42 | 43 | // iterator we are going to be using the whole time 44 | std::vector::iterator it = this->begin(); 45 | 46 | // Double check the Wallet length 47 | if( WALLET_LENGTH != *it ) 48 | return("{}"); 49 | it++; 50 | 51 | // Double check the Wallet element length 52 | if( WALLET_POINT_LENGTH != *it ) 53 | return("{}"); 54 | it++; 55 | 56 | for( int i = 0; i< WALLET_LENGTH; i++) 57 | { 58 | Value point(kArrayType); 59 | for( int j = 0; j< WALLET_POINT_LENGTH; j++) 60 | { 61 | point.PushBack(*it, allocator); 62 | it++; 63 | } 64 | json.PushBack(point, allocator); 65 | } 66 | 67 | StringBuffer sb; 68 | Writer writer(sb); 69 | json.Accept(writer); 70 | return sb.GetString(); 71 | } 72 | 73 | 74 | bool fromJson(std::string s) { 75 | Document json; 76 | json.Parse(s.c_str()); 77 | 78 | eraseAll(); 79 | 80 | // // Make sure we arent going to get an error when indexing into the JSON 81 | if(!json.IsArray()) 82 | return false; 83 | 84 | if(!(json.Size() == SizeType(WALLET_LENGTH))) 85 | return false; 86 | 87 | this->push_back(WALLET_LENGTH); 88 | this->push_back(WALLET_POINT_LENGTH); 89 | 90 | 91 | for( int i =0; i< WALLET_LENGTH; i++) 92 | { 93 | const Value& point = json[i]; 94 | 95 | if(!point.IsArray()) 96 | return false; 97 | 98 | if(!(point.Size() == SizeType(WALLET_POINT_LENGTH))) 99 | cleanupAndFalse(); 100 | 101 | for(SizeType j = 0; j < point.Size(); j++) 102 | this->push_back(point[j].GetUint64()); 103 | 104 | } 105 | 106 | // Make sure the final length is good 107 | if(!(this->size() == WALLET_VECTOR_LENGTH)) 108 | return cleanupAndFalse(); 109 | 110 | return true; 111 | } 112 | 113 | 114 | // Stolen from https://github.com/zeutro/openabe/blob/master/src/include/openabe/utils/zbytestring.h 115 | 116 | bool fromHex(std::string s) { 117 | if((s.find_first_not_of(HEX_CHARS) != std::string::npos) || 118 | (s.size() % 2 != 0)) { 119 | return false; 120 | } 121 | 122 | if ( s.length() != WALLET_HEX_STRING_LENGTH) 123 | return false; 124 | 125 | std::string hex_str; 126 | std::stringstream ss; 127 | int tmp; 128 | 129 | this->clear(); 130 | for (size_t i = 0; i < s.size(); i += 2) { 131 | hex_str = s[i]; 132 | hex_str += s[i+1]; 133 | 134 | ss << hex_str; 135 | ss >> std::hex >> tmp; 136 | this->push_back(tmp & 0xFF); 137 | ss.clear(); 138 | } 139 | return true; 140 | } 141 | 142 | std::string toHex() const { 143 | std::stringstream ss; 144 | int hex_len = 2; 145 | char hex[hex_len+1]; 146 | std::memset(hex, 0, hex_len+1); 147 | 148 | for (std::vector::const_iterator it = this->begin(); 149 | it != this->end(); ++it) { 150 | sprintf(hex, "%02X", *it); 151 | ss << hex; 152 | } 153 | return ss.str(); 154 | } 155 | 156 | std::string toLowerHex() const { 157 | std::stringstream ss; 158 | int hex_len = 2; 159 | char hex[hex_len+1]; 160 | std::memset(hex, 0, hex_len+1); 161 | 162 | for (std::vector::const_iterator it = this->begin() ; it != this->end(); ++it) { 163 | sprintf(hex, "%02x", *it); 164 | ss << hex; 165 | } 166 | return ss.str(); 167 | } 168 | 169 | void eraseAll() { 170 | this->erase(this->begin(), this->end()); 171 | } 172 | 173 | private: 174 | 175 | bool cleanupAndFalse() { 176 | eraseAll(); 177 | return false; 178 | } 179 | 180 | }; 181 | 182 | 183 | #endif -------------------------------------------------------------------------------- /include/libbolt.h: -------------------------------------------------------------------------------- 1 | #ifndef LIBBOLT_INCLUDE_H_ 2 | #define LIBBOLT_INCLUDE_H_ 3 | 4 | #include 5 | #include 6 | 7 | #ifdef __cplusplus 8 | 9 | #include "rapidjson/document.h" 10 | #include "rapidjson/writer.h" 11 | #include "rapidjson/stringbuffer.h" 12 | 13 | using namespace rapidjson; 14 | 15 | extern "C" { 16 | #endif 17 | 18 | // channel init 19 | char* ffishim_bls12_channel_setup(const char *channel_name, unsigned int third_party_support); 20 | char* ffishim_bls12_init_merchant(const char *ser_channel_state, const char *name_ptr); 21 | char* ffishim_bls12_init_customer(const char *ser_channel_token, long long int balance_customer, long long int balance_merchant, const char *name_ptr); 22 | 23 | // channel establish protocol routines 24 | char* ffishim_bls12_establish_customer_generate_proof(const char *ser_channel_token, const char *ser_customer_wallet); 25 | char* ffishim_bls12_generate_channel_id(const char *ser_channel_token); 26 | char* ffishim_bls12_establish_merchant_issue_close_token(const char *ser_channel_state, const char *ser_com, const char *ser_com_proof, const char *ser_pk_c, long long int init_cust_bal, long long int init_merch_bal, const char *ser_merch_state); 27 | char* ffishim_bls12_establish_merchant_issue_pay_token(const char *ser_channel_state, const char *ser_com, const char *ser_merch_state); 28 | char* ffishim_bls12_verify_close_token(const char *ser_channel_state, const char *ser_customer_wallet, const char *ser_close_token); 29 | char* ffishim_bls12_establish_customer_final(const char *ser_channel_state, const char *ser_customer_wallet, const char *ser_pay_token); 30 | 31 | // channel pay protocol routines 32 | char* ffishim_bls12_pay_generate_payment_proof(const char *ser_channel_state, const char *ser_customer_wallet, long long int amount); 33 | char* ffishim_bls12_pay_verify_payment_proof(const char *ser_channel_state, const char *ser_pay_proof, const char *ser_merch_state); 34 | char* ffishim_bls12_pay_verify_multiple_payment_proofs(const char *ser_channel_state, const char *ser_sender_pay_proof, const char *ser_receiver_pay_proof, const char *ser_merch_state); 35 | char* ffishim_bls12_pay_generate_revoke_token(const char *ser_channel_state, const char *ser_cust_state, const char *ser_new_cust_state, const char *ser_close_token); 36 | char* ffishim_bls12_pay_verify_revoke_token(const char *ser_revoke_token, const char *ser_merch_state); 37 | char* ffishim_bls12_pay_verify_multiple_revoke_tokens(const char *ser_sender_revoke_token, const char *ser_receiver_revoke_token, const char *ser_merch_state); 38 | char* ffishim_bls12_pay_verify_payment_token(const char *ser_channel_state, const char *ser_cust_state, const char *ser_pay_token); 39 | 40 | // closing routines for both sides 41 | char* ffishim_bls12_customer_close(const char *ser_channel_state, const char *ser_cust_state); 42 | char* ffishim_bls12_merchant_close(const char *ser_channel_state, const char *ser_channel_token, const char *ser_address, const char *ser_cust_close, const char *ser_merch_state); 43 | 44 | // WTP logic for on-chain validation of closing messages 45 | char* ffishim_bls12_wtp_verify_cust_close_message(const char *ser_channel_token, const char *ser_wpk, const char *ser_close_msg, const char *ser_close_token); 46 | char* ffishim_bls12_wtp_verify_merch_close_message(const char *ser_channel_token, const char *ser_wpk, const char *ser_merch_close); 47 | 48 | char* ffishim_bls12_wtp_check_wpk(const char *wpk); 49 | 50 | #ifdef __cplusplus 51 | 52 | const char* string_replace_all(const char* previous_string, char old_char, char new_char) 53 | { 54 | std::string s(previous_string); 55 | std::string old_c(1,old_char); 56 | std::string new_c(1,new_char); 57 | size_t index; 58 | while ((index = s.find(old_c)) != std::string::npos) { 59 | s.replace(index, 1, new_c); 60 | } 61 | 62 | printf("STRING: %s\n", s.c_str()); 63 | return s.c_str(); 64 | } 65 | 66 | int wtp_check_wpk(const char *wpk) 67 | { 68 | const char *ret = ffishim_bls12_wtp_check_wpk(wpk); 69 | printf("RESULT: %s\n", ret); 70 | return 0; 71 | } 72 | 73 | 74 | /* Purpose: verify cust close message 75 | * Arguments: take as input the channel token and wpk 76 | * 77 | * Returns: 0 (false) or 1 (true) 78 | */ 79 | int wtp_verify_cust_close_message(const char *channel_token, const char *wpk, const char *cust_close, const char *close_token) 80 | { 81 | // Call rust 82 | const char *return_json = ffishim_bls12_wtp_verify_cust_close_message(channel_token, wpk, cust_close, close_token); 83 | 84 | Document d; 85 | d.Parse(return_json); 86 | // Make sure we arent going to get an error when indexing into the JSON 87 | assert(d.HasMember("result")); 88 | Value& s = d["result"]; 89 | 90 | // If the return_value is true, then return 1. Otherwise, just assume 0 91 | if( std::string(s.GetString()).compare(std::string("true")) == 0) 92 | { 93 | return 1; 94 | } 95 | return 0; 96 | } 97 | 98 | /* Purpose: verify merch close message 99 | * Arguments: take as input the master pub params for CL (pp), serialized channel closure message (rc_c), 100 | * 101 | * Returns: 0 (false) or 1 (true) 102 | */ 103 | int wtp_verify_merch_close_message(const char *channel_token, const char *wpk, const char *merch_close) 104 | { 105 | // Call into Rust 106 | const char* return_json = string_replace_all(ffishim_bls12_wtp_verify_merch_close_message(channel_token, wpk, merch_close), '\'', '\"'); 107 | 108 | Document d; 109 | d.Parse(return_json); 110 | // Make sure we arent going to get an error when indexing into the JSON 111 | assert(d.HasMember("result")); 112 | Value& s = d["result"]; 113 | 114 | // If the return_value is true, then return 1. Otherwise, just assume 0 115 | if( std::string(s.GetString()).compare(std::string("true")) == 0) 116 | { 117 | return 1; 118 | } 119 | return 0; 120 | } 121 | } 122 | #endif // end c++ check 123 | 124 | #endif // LIBBOLT_INCLUDE_H_ 125 | -------------------------------------------------------------------------------- /include/rapidjson/cursorstreamwrapper.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_CURSORSTREAMWRAPPER_H_ 16 | #define RAPIDJSON_CURSORSTREAMWRAPPER_H_ 17 | 18 | #include "stream.h" 19 | 20 | #if defined(__GNUC__) 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(effc++) 23 | #endif 24 | 25 | #if defined(_MSC_VER) && _MSC_VER <= 1800 26 | RAPIDJSON_DIAG_PUSH 27 | RAPIDJSON_DIAG_OFF(4702) // unreachable code 28 | RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated 29 | #endif 30 | 31 | RAPIDJSON_NAMESPACE_BEGIN 32 | 33 | 34 | //! Cursor stream wrapper for counting line and column number if error exists. 35 | /*! 36 | \tparam InputStream Any stream that implements Stream Concept 37 | */ 38 | template > 39 | class CursorStreamWrapper : public GenericStreamWrapper { 40 | public: 41 | typedef typename Encoding::Ch Ch; 42 | 43 | CursorStreamWrapper(InputStream& is): 44 | GenericStreamWrapper(is), line_(1), col_(0) {} 45 | 46 | // counting line and column number 47 | Ch Take() { 48 | Ch ch = this->is_.Take(); 49 | if(ch == '\n') { 50 | line_ ++; 51 | col_ = 0; 52 | } else { 53 | col_ ++; 54 | } 55 | return ch; 56 | } 57 | 58 | //! Get the error line number, if error exists. 59 | size_t GetLine() const { return line_; } 60 | //! Get the error column number, if error exists. 61 | size_t GetColumn() const { return col_; } 62 | 63 | private: 64 | size_t line_; //!< Current Line 65 | size_t col_; //!< Current Column 66 | }; 67 | 68 | #if defined(_MSC_VER) && _MSC_VER <= 1800 69 | RAPIDJSON_DIAG_POP 70 | #endif 71 | 72 | #if defined(__GNUC__) 73 | RAPIDJSON_DIAG_POP 74 | #endif 75 | 76 | RAPIDJSON_NAMESPACE_END 77 | 78 | #endif // RAPIDJSON_CURSORSTREAMWRAPPER_H_ 79 | -------------------------------------------------------------------------------- /include/rapidjson/error/en.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_ERROR_EN_H_ 16 | #define RAPIDJSON_ERROR_EN_H_ 17 | 18 | #include "error.h" 19 | 20 | #ifdef __clang__ 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(switch-enum) 23 | RAPIDJSON_DIAG_OFF(covered-switch-default) 24 | #endif 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Maps error code of parsing into error message. 29 | /*! 30 | \ingroup RAPIDJSON_ERRORS 31 | \param parseErrorCode Error code obtained in parsing. 32 | \return the error message. 33 | \note User can make a copy of this function for localization. 34 | Using switch-case is safer for future modification of error codes. 35 | */ 36 | inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErrorCode) { 37 | switch (parseErrorCode) { 38 | case kParseErrorNone: return RAPIDJSON_ERROR_STRING("No error."); 39 | 40 | case kParseErrorDocumentEmpty: return RAPIDJSON_ERROR_STRING("The document is empty."); 41 | case kParseErrorDocumentRootNotSingular: return RAPIDJSON_ERROR_STRING("The document root must not be followed by other values."); 42 | 43 | case kParseErrorValueInvalid: return RAPIDJSON_ERROR_STRING("Invalid value."); 44 | 45 | case kParseErrorObjectMissName: return RAPIDJSON_ERROR_STRING("Missing a name for object member."); 46 | case kParseErrorObjectMissColon: return RAPIDJSON_ERROR_STRING("Missing a colon after a name of object member."); 47 | case kParseErrorObjectMissCommaOrCurlyBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or '}' after an object member."); 48 | 49 | case kParseErrorArrayMissCommaOrSquareBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or ']' after an array element."); 50 | 51 | case kParseErrorStringUnicodeEscapeInvalidHex: return RAPIDJSON_ERROR_STRING("Incorrect hex digit after \\u escape in string."); 52 | case kParseErrorStringUnicodeSurrogateInvalid: return RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid."); 53 | case kParseErrorStringEscapeInvalid: return RAPIDJSON_ERROR_STRING("Invalid escape character in string."); 54 | case kParseErrorStringMissQuotationMark: return RAPIDJSON_ERROR_STRING("Missing a closing quotation mark in string."); 55 | case kParseErrorStringInvalidEncoding: return RAPIDJSON_ERROR_STRING("Invalid encoding in string."); 56 | 57 | case kParseErrorNumberTooBig: return RAPIDJSON_ERROR_STRING("Number too big to be stored in double."); 58 | case kParseErrorNumberMissFraction: return RAPIDJSON_ERROR_STRING("Miss fraction part in number."); 59 | case kParseErrorNumberMissExponent: return RAPIDJSON_ERROR_STRING("Miss exponent in number."); 60 | 61 | case kParseErrorTermination: return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error."); 62 | case kParseErrorUnspecificSyntaxError: return RAPIDJSON_ERROR_STRING("Unspecific syntax error."); 63 | 64 | default: return RAPIDJSON_ERROR_STRING("Unknown error."); 65 | } 66 | } 67 | 68 | RAPIDJSON_NAMESPACE_END 69 | 70 | #ifdef __clang__ 71 | RAPIDJSON_DIAG_POP 72 | #endif 73 | 74 | #endif // RAPIDJSON_ERROR_EN_H_ 75 | -------------------------------------------------------------------------------- /include/rapidjson/error/error.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_ERROR_ERROR_H_ 16 | #define RAPIDJSON_ERROR_ERROR_H_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | #ifdef __clang__ 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(padded) 23 | #endif 24 | 25 | /*! \file error.h */ 26 | 27 | /*! \defgroup RAPIDJSON_ERRORS RapidJSON error handling */ 28 | 29 | /////////////////////////////////////////////////////////////////////////////// 30 | // RAPIDJSON_ERROR_CHARTYPE 31 | 32 | //! Character type of error messages. 33 | /*! \ingroup RAPIDJSON_ERRORS 34 | The default character type is \c char. 35 | On Windows, user can define this macro as \c TCHAR for supporting both 36 | unicode/non-unicode settings. 37 | */ 38 | #ifndef RAPIDJSON_ERROR_CHARTYPE 39 | #define RAPIDJSON_ERROR_CHARTYPE char 40 | #endif 41 | 42 | /////////////////////////////////////////////////////////////////////////////// 43 | // RAPIDJSON_ERROR_STRING 44 | 45 | //! Macro for converting string literial to \ref RAPIDJSON_ERROR_CHARTYPE[]. 46 | /*! \ingroup RAPIDJSON_ERRORS 47 | By default this conversion macro does nothing. 48 | On Windows, user can define this macro as \c _T(x) for supporting both 49 | unicode/non-unicode settings. 50 | */ 51 | #ifndef RAPIDJSON_ERROR_STRING 52 | #define RAPIDJSON_ERROR_STRING(x) x 53 | #endif 54 | 55 | RAPIDJSON_NAMESPACE_BEGIN 56 | 57 | /////////////////////////////////////////////////////////////////////////////// 58 | // ParseErrorCode 59 | 60 | //! Error code of parsing. 61 | /*! \ingroup RAPIDJSON_ERRORS 62 | \see GenericReader::Parse, GenericReader::GetParseErrorCode 63 | */ 64 | enum ParseErrorCode { 65 | kParseErrorNone = 0, //!< No error. 66 | 67 | kParseErrorDocumentEmpty, //!< The document is empty. 68 | kParseErrorDocumentRootNotSingular, //!< The document root must not follow by other values. 69 | 70 | kParseErrorValueInvalid, //!< Invalid value. 71 | 72 | kParseErrorObjectMissName, //!< Missing a name for object member. 73 | kParseErrorObjectMissColon, //!< Missing a colon after a name of object member. 74 | kParseErrorObjectMissCommaOrCurlyBracket, //!< Missing a comma or '}' after an object member. 75 | 76 | kParseErrorArrayMissCommaOrSquareBracket, //!< Missing a comma or ']' after an array element. 77 | 78 | kParseErrorStringUnicodeEscapeInvalidHex, //!< Incorrect hex digit after \\u escape in string. 79 | kParseErrorStringUnicodeSurrogateInvalid, //!< The surrogate pair in string is invalid. 80 | kParseErrorStringEscapeInvalid, //!< Invalid escape character in string. 81 | kParseErrorStringMissQuotationMark, //!< Missing a closing quotation mark in string. 82 | kParseErrorStringInvalidEncoding, //!< Invalid encoding in string. 83 | 84 | kParseErrorNumberTooBig, //!< Number too big to be stored in double. 85 | kParseErrorNumberMissFraction, //!< Miss fraction part in number. 86 | kParseErrorNumberMissExponent, //!< Miss exponent in number. 87 | 88 | kParseErrorTermination, //!< Parsing was terminated. 89 | kParseErrorUnspecificSyntaxError //!< Unspecific syntax error. 90 | }; 91 | 92 | //! Result of parsing (wraps ParseErrorCode) 93 | /*! 94 | \ingroup RAPIDJSON_ERRORS 95 | \code 96 | Document doc; 97 | ParseResult ok = doc.Parse("[42]"); 98 | if (!ok) { 99 | fprintf(stderr, "JSON parse error: %s (%u)", 100 | GetParseError_En(ok.Code()), ok.Offset()); 101 | exit(EXIT_FAILURE); 102 | } 103 | \endcode 104 | \see GenericReader::Parse, GenericDocument::Parse 105 | */ 106 | struct ParseResult { 107 | //!! Unspecified boolean type 108 | typedef bool (ParseResult::*BooleanType)() const; 109 | public: 110 | //! Default constructor, no error. 111 | ParseResult() : code_(kParseErrorNone), offset_(0) {} 112 | //! Constructor to set an error. 113 | ParseResult(ParseErrorCode code, size_t offset) : code_(code), offset_(offset) {} 114 | 115 | //! Get the error code. 116 | ParseErrorCode Code() const { return code_; } 117 | //! Get the error offset, if \ref IsError(), 0 otherwise. 118 | size_t Offset() const { return offset_; } 119 | 120 | //! Explicit conversion to \c bool, returns \c true, iff !\ref IsError(). 121 | operator BooleanType() const { return !IsError() ? &ParseResult::IsError : NULL; } 122 | //! Whether the result is an error. 123 | bool IsError() const { return code_ != kParseErrorNone; } 124 | 125 | bool operator==(const ParseResult& that) const { return code_ == that.code_; } 126 | bool operator==(ParseErrorCode code) const { return code_ == code; } 127 | friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; } 128 | 129 | bool operator!=(const ParseResult& that) const { return !(*this == that); } 130 | bool operator!=(ParseErrorCode code) const { return !(*this == code); } 131 | friend bool operator!=(ParseErrorCode code, const ParseResult & err) { return err != code; } 132 | 133 | //! Reset error code. 134 | void Clear() { Set(kParseErrorNone); } 135 | //! Update error code and offset. 136 | void Set(ParseErrorCode code, size_t offset = 0) { code_ = code; offset_ = offset; } 137 | 138 | private: 139 | ParseErrorCode code_; 140 | size_t offset_; 141 | }; 142 | 143 | //! Function pointer type of GetParseError(). 144 | /*! \ingroup RAPIDJSON_ERRORS 145 | 146 | This is the prototype for \c GetParseError_X(), where \c X is a locale. 147 | User can dynamically change locale in runtime, e.g.: 148 | \code 149 | GetParseErrorFunc GetParseError = GetParseError_En; // or whatever 150 | const RAPIDJSON_ERROR_CHARTYPE* s = GetParseError(document.GetParseErrorCode()); 151 | \endcode 152 | */ 153 | typedef const RAPIDJSON_ERROR_CHARTYPE* (*GetParseErrorFunc)(ParseErrorCode); 154 | 155 | RAPIDJSON_NAMESPACE_END 156 | 157 | #ifdef __clang__ 158 | RAPIDJSON_DIAG_POP 159 | #endif 160 | 161 | #endif // RAPIDJSON_ERROR_ERROR_H_ 162 | -------------------------------------------------------------------------------- /include/rapidjson/filereadstream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_FILEREADSTREAM_H_ 16 | #define RAPIDJSON_FILEREADSTREAM_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | RAPIDJSON_DIAG_PUSH 23 | RAPIDJSON_DIAG_OFF(padded) 24 | RAPIDJSON_DIAG_OFF(unreachable-code) 25 | RAPIDJSON_DIAG_OFF(missing-noreturn) 26 | #endif 27 | 28 | RAPIDJSON_NAMESPACE_BEGIN 29 | 30 | //! File byte stream for input using fread(). 31 | /*! 32 | \note implements Stream concept 33 | */ 34 | class FileReadStream { 35 | public: 36 | typedef char Ch; //!< Character type (byte). 37 | 38 | //! Constructor. 39 | /*! 40 | \param fp File pointer opened for read. 41 | \param buffer user-supplied buffer. 42 | \param bufferSize size of buffer in bytes. Must >=4 bytes. 43 | */ 44 | FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { 45 | RAPIDJSON_ASSERT(fp_ != 0); 46 | RAPIDJSON_ASSERT(bufferSize >= 4); 47 | Read(); 48 | } 49 | 50 | Ch Peek() const { return *current_; } 51 | Ch Take() { Ch c = *current_; Read(); return c; } 52 | size_t Tell() const { return count_ + static_cast(current_ - buffer_); } 53 | 54 | // Not implemented 55 | void Put(Ch) { RAPIDJSON_ASSERT(false); } 56 | void Flush() { RAPIDJSON_ASSERT(false); } 57 | Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 58 | size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } 59 | 60 | // For encoding detection only. 61 | const Ch* Peek4() const { 62 | return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; 63 | } 64 | 65 | private: 66 | void Read() { 67 | if (current_ < bufferLast_) 68 | ++current_; 69 | else if (!eof_) { 70 | count_ += readCount_; 71 | readCount_ = std::fread(buffer_, 1, bufferSize_, fp_); 72 | bufferLast_ = buffer_ + readCount_ - 1; 73 | current_ = buffer_; 74 | 75 | if (readCount_ < bufferSize_) { 76 | buffer_[readCount_] = '\0'; 77 | ++bufferLast_; 78 | eof_ = true; 79 | } 80 | } 81 | } 82 | 83 | std::FILE* fp_; 84 | Ch *buffer_; 85 | size_t bufferSize_; 86 | Ch *bufferLast_; 87 | Ch *current_; 88 | size_t readCount_; 89 | size_t count_; //!< Number of characters read 90 | bool eof_; 91 | }; 92 | 93 | RAPIDJSON_NAMESPACE_END 94 | 95 | #ifdef __clang__ 96 | RAPIDJSON_DIAG_POP 97 | #endif 98 | 99 | #endif // RAPIDJSON_FILESTREAM_H_ 100 | -------------------------------------------------------------------------------- /include/rapidjson/filewritestream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_FILEWRITESTREAM_H_ 16 | #define RAPIDJSON_FILEWRITESTREAM_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | RAPIDJSON_DIAG_PUSH 23 | RAPIDJSON_DIAG_OFF(unreachable-code) 24 | #endif 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Wrapper of C file stream for output using fwrite(). 29 | /*! 30 | \note implements Stream concept 31 | */ 32 | class FileWriteStream { 33 | public: 34 | typedef char Ch; //!< Character type. Only support char. 35 | 36 | FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) { 37 | RAPIDJSON_ASSERT(fp_ != 0); 38 | } 39 | 40 | void Put(char c) { 41 | if (current_ >= bufferEnd_) 42 | Flush(); 43 | 44 | *current_++ = c; 45 | } 46 | 47 | void PutN(char c, size_t n) { 48 | size_t avail = static_cast(bufferEnd_ - current_); 49 | while (n > avail) { 50 | std::memset(current_, c, avail); 51 | current_ += avail; 52 | Flush(); 53 | n -= avail; 54 | avail = static_cast(bufferEnd_ - current_); 55 | } 56 | 57 | if (n > 0) { 58 | std::memset(current_, c, n); 59 | current_ += n; 60 | } 61 | } 62 | 63 | void Flush() { 64 | if (current_ != buffer_) { 65 | size_t result = std::fwrite(buffer_, 1, static_cast(current_ - buffer_), fp_); 66 | if (result < static_cast(current_ - buffer_)) { 67 | // failure deliberately ignored at this time 68 | // added to avoid warn_unused_result build errors 69 | } 70 | current_ = buffer_; 71 | } 72 | } 73 | 74 | // Not implemented 75 | char Peek() const { RAPIDJSON_ASSERT(false); return 0; } 76 | char Take() { RAPIDJSON_ASSERT(false); return 0; } 77 | size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } 78 | char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 79 | size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; } 80 | 81 | private: 82 | // Prohibit copy constructor & assignment operator. 83 | FileWriteStream(const FileWriteStream&); 84 | FileWriteStream& operator=(const FileWriteStream&); 85 | 86 | std::FILE* fp_; 87 | char *buffer_; 88 | char *bufferEnd_; 89 | char *current_; 90 | }; 91 | 92 | //! Implement specialized version of PutN() with memset() for better performance. 93 | template<> 94 | inline void PutN(FileWriteStream& stream, char c, size_t n) { 95 | stream.PutN(c, n); 96 | } 97 | 98 | RAPIDJSON_NAMESPACE_END 99 | 100 | #ifdef __clang__ 101 | RAPIDJSON_DIAG_POP 102 | #endif 103 | 104 | #endif // RAPIDJSON_FILESTREAM_H_ 105 | -------------------------------------------------------------------------------- /include/rapidjson/fwd.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_FWD_H_ 16 | #define RAPIDJSON_FWD_H_ 17 | 18 | #include "rapidjson.h" 19 | 20 | RAPIDJSON_NAMESPACE_BEGIN 21 | 22 | // encodings.h 23 | 24 | template struct UTF8; 25 | template struct UTF16; 26 | template struct UTF16BE; 27 | template struct UTF16LE; 28 | template struct UTF32; 29 | template struct UTF32BE; 30 | template struct UTF32LE; 31 | template struct ASCII; 32 | template struct AutoUTF; 33 | 34 | template 35 | struct Transcoder; 36 | 37 | // allocators.h 38 | 39 | class CrtAllocator; 40 | 41 | template 42 | class MemoryPoolAllocator; 43 | 44 | // stream.h 45 | 46 | template 47 | struct GenericStringStream; 48 | 49 | typedef GenericStringStream > StringStream; 50 | 51 | template 52 | struct GenericInsituStringStream; 53 | 54 | typedef GenericInsituStringStream > InsituStringStream; 55 | 56 | // stringbuffer.h 57 | 58 | template 59 | class GenericStringBuffer; 60 | 61 | typedef GenericStringBuffer, CrtAllocator> StringBuffer; 62 | 63 | // filereadstream.h 64 | 65 | class FileReadStream; 66 | 67 | // filewritestream.h 68 | 69 | class FileWriteStream; 70 | 71 | // memorybuffer.h 72 | 73 | template 74 | struct GenericMemoryBuffer; 75 | 76 | typedef GenericMemoryBuffer MemoryBuffer; 77 | 78 | // memorystream.h 79 | 80 | struct MemoryStream; 81 | 82 | // reader.h 83 | 84 | template 85 | struct BaseReaderHandler; 86 | 87 | template 88 | class GenericReader; 89 | 90 | typedef GenericReader, UTF8, CrtAllocator> Reader; 91 | 92 | // writer.h 93 | 94 | template 95 | class Writer; 96 | 97 | // prettywriter.h 98 | 99 | template 100 | class PrettyWriter; 101 | 102 | // document.h 103 | 104 | template 105 | struct GenericMember; 106 | 107 | template 108 | class GenericMemberIterator; 109 | 110 | template 111 | struct GenericStringRef; 112 | 113 | template 114 | class GenericValue; 115 | 116 | typedef GenericValue, MemoryPoolAllocator > Value; 117 | 118 | template 119 | class GenericDocument; 120 | 121 | typedef GenericDocument, MemoryPoolAllocator, CrtAllocator> Document; 122 | 123 | // pointer.h 124 | 125 | template 126 | class GenericPointer; 127 | 128 | typedef GenericPointer Pointer; 129 | 130 | // schema.h 131 | 132 | template 133 | class IGenericRemoteSchemaDocumentProvider; 134 | 135 | template 136 | class GenericSchemaDocument; 137 | 138 | typedef GenericSchemaDocument SchemaDocument; 139 | typedef IGenericRemoteSchemaDocumentProvider IRemoteSchemaDocumentProvider; 140 | 141 | template < 142 | typename SchemaDocumentType, 143 | typename OutputHandler, 144 | typename StateAllocator> 145 | class GenericSchemaValidator; 146 | 147 | typedef GenericSchemaValidator, void>, CrtAllocator> SchemaValidator; 148 | 149 | RAPIDJSON_NAMESPACE_END 150 | 151 | #endif // RAPIDJSON_RAPIDJSONFWD_H_ 152 | -------------------------------------------------------------------------------- /include/rapidjson/internal/biginteger.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_BIGINTEGER_H_ 16 | #define RAPIDJSON_BIGINTEGER_H_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | #if defined(_MSC_VER) && !__INTEL_COMPILER && defined(_M_AMD64) 21 | #include // for _umul128 22 | #pragma intrinsic(_umul128) 23 | #endif 24 | 25 | RAPIDJSON_NAMESPACE_BEGIN 26 | namespace internal { 27 | 28 | class BigInteger { 29 | public: 30 | typedef uint64_t Type; 31 | 32 | BigInteger(const BigInteger& rhs) : count_(rhs.count_) { 33 | std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); 34 | } 35 | 36 | explicit BigInteger(uint64_t u) : count_(1) { 37 | digits_[0] = u; 38 | } 39 | 40 | BigInteger(const char* decimals, size_t length) : count_(1) { 41 | RAPIDJSON_ASSERT(length > 0); 42 | digits_[0] = 0; 43 | size_t i = 0; 44 | const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19 45 | while (length >= kMaxDigitPerIteration) { 46 | AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration); 47 | length -= kMaxDigitPerIteration; 48 | i += kMaxDigitPerIteration; 49 | } 50 | 51 | if (length > 0) 52 | AppendDecimal64(decimals + i, decimals + i + length); 53 | } 54 | 55 | BigInteger& operator=(const BigInteger &rhs) 56 | { 57 | if (this != &rhs) { 58 | count_ = rhs.count_; 59 | std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); 60 | } 61 | return *this; 62 | } 63 | 64 | BigInteger& operator=(uint64_t u) { 65 | digits_[0] = u; 66 | count_ = 1; 67 | return *this; 68 | } 69 | 70 | BigInteger& operator+=(uint64_t u) { 71 | Type backup = digits_[0]; 72 | digits_[0] += u; 73 | for (size_t i = 0; i < count_ - 1; i++) { 74 | if (digits_[i] >= backup) 75 | return *this; // no carry 76 | backup = digits_[i + 1]; 77 | digits_[i + 1] += 1; 78 | } 79 | 80 | // Last carry 81 | if (digits_[count_ - 1] < backup) 82 | PushBack(1); 83 | 84 | return *this; 85 | } 86 | 87 | BigInteger& operator*=(uint64_t u) { 88 | if (u == 0) return *this = 0; 89 | if (u == 1) return *this; 90 | if (*this == 1) return *this = u; 91 | 92 | uint64_t k = 0; 93 | for (size_t i = 0; i < count_; i++) { 94 | uint64_t hi; 95 | digits_[i] = MulAdd64(digits_[i], u, k, &hi); 96 | k = hi; 97 | } 98 | 99 | if (k > 0) 100 | PushBack(k); 101 | 102 | return *this; 103 | } 104 | 105 | BigInteger& operator*=(uint32_t u) { 106 | if (u == 0) return *this = 0; 107 | if (u == 1) return *this; 108 | if (*this == 1) return *this = u; 109 | 110 | uint64_t k = 0; 111 | for (size_t i = 0; i < count_; i++) { 112 | const uint64_t c = digits_[i] >> 32; 113 | const uint64_t d = digits_[i] & 0xFFFFFFFF; 114 | const uint64_t uc = u * c; 115 | const uint64_t ud = u * d; 116 | const uint64_t p0 = ud + k; 117 | const uint64_t p1 = uc + (p0 >> 32); 118 | digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32); 119 | k = p1 >> 32; 120 | } 121 | 122 | if (k > 0) 123 | PushBack(k); 124 | 125 | return *this; 126 | } 127 | 128 | BigInteger& operator<<=(size_t shift) { 129 | if (IsZero() || shift == 0) return *this; 130 | 131 | size_t offset = shift / kTypeBit; 132 | size_t interShift = shift % kTypeBit; 133 | RAPIDJSON_ASSERT(count_ + offset <= kCapacity); 134 | 135 | if (interShift == 0) { 136 | std::memmove(digits_ + offset, digits_, count_ * sizeof(Type)); 137 | count_ += offset; 138 | } 139 | else { 140 | digits_[count_] = 0; 141 | for (size_t i = count_; i > 0; i--) 142 | digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift)); 143 | digits_[offset] = digits_[0] << interShift; 144 | count_ += offset; 145 | if (digits_[count_]) 146 | count_++; 147 | } 148 | 149 | std::memset(digits_, 0, offset * sizeof(Type)); 150 | 151 | return *this; 152 | } 153 | 154 | bool operator==(const BigInteger& rhs) const { 155 | return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0; 156 | } 157 | 158 | bool operator==(const Type rhs) const { 159 | return count_ == 1 && digits_[0] == rhs; 160 | } 161 | 162 | BigInteger& MultiplyPow5(unsigned exp) { 163 | static const uint32_t kPow5[12] = { 164 | 5, 165 | 5 * 5, 166 | 5 * 5 * 5, 167 | 5 * 5 * 5 * 5, 168 | 5 * 5 * 5 * 5 * 5, 169 | 5 * 5 * 5 * 5 * 5 * 5, 170 | 5 * 5 * 5 * 5 * 5 * 5 * 5, 171 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 172 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 173 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 174 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 175 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 176 | }; 177 | if (exp == 0) return *this; 178 | for (; exp >= 27; exp -= 27) *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27 179 | for (; exp >= 13; exp -= 13) *this *= static_cast(1220703125u); // 5^13 180 | if (exp > 0) *this *= kPow5[exp - 1]; 181 | return *this; 182 | } 183 | 184 | // Compute absolute difference of this and rhs. 185 | // Assume this != rhs 186 | bool Difference(const BigInteger& rhs, BigInteger* out) const { 187 | int cmp = Compare(rhs); 188 | RAPIDJSON_ASSERT(cmp != 0); 189 | const BigInteger *a, *b; // Makes a > b 190 | bool ret; 191 | if (cmp < 0) { a = &rhs; b = this; ret = true; } 192 | else { a = this; b = &rhs; ret = false; } 193 | 194 | Type borrow = 0; 195 | for (size_t i = 0; i < a->count_; i++) { 196 | Type d = a->digits_[i] - borrow; 197 | if (i < b->count_) 198 | d -= b->digits_[i]; 199 | borrow = (d > a->digits_[i]) ? 1 : 0; 200 | out->digits_[i] = d; 201 | if (d != 0) 202 | out->count_ = i + 1; 203 | } 204 | 205 | return ret; 206 | } 207 | 208 | int Compare(const BigInteger& rhs) const { 209 | if (count_ != rhs.count_) 210 | return count_ < rhs.count_ ? -1 : 1; 211 | 212 | for (size_t i = count_; i-- > 0;) 213 | if (digits_[i] != rhs.digits_[i]) 214 | return digits_[i] < rhs.digits_[i] ? -1 : 1; 215 | 216 | return 0; 217 | } 218 | 219 | size_t GetCount() const { return count_; } 220 | Type GetDigit(size_t index) const { RAPIDJSON_ASSERT(index < count_); return digits_[index]; } 221 | bool IsZero() const { return count_ == 1 && digits_[0] == 0; } 222 | 223 | private: 224 | void AppendDecimal64(const char* begin, const char* end) { 225 | uint64_t u = ParseUint64(begin, end); 226 | if (IsZero()) 227 | *this = u; 228 | else { 229 | unsigned exp = static_cast(end - begin); 230 | (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u 231 | } 232 | } 233 | 234 | void PushBack(Type digit) { 235 | RAPIDJSON_ASSERT(count_ < kCapacity); 236 | digits_[count_++] = digit; 237 | } 238 | 239 | static uint64_t ParseUint64(const char* begin, const char* end) { 240 | uint64_t r = 0; 241 | for (const char* p = begin; p != end; ++p) { 242 | RAPIDJSON_ASSERT(*p >= '0' && *p <= '9'); 243 | r = r * 10u + static_cast(*p - '0'); 244 | } 245 | return r; 246 | } 247 | 248 | // Assume a * b + k < 2^128 249 | static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) { 250 | #if defined(_MSC_VER) && defined(_M_AMD64) 251 | uint64_t low = _umul128(a, b, outHigh) + k; 252 | if (low < k) 253 | (*outHigh)++; 254 | return low; 255 | #elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) 256 | __extension__ typedef unsigned __int128 uint128; 257 | uint128 p = static_cast(a) * static_cast(b); 258 | p += k; 259 | *outHigh = static_cast(p >> 64); 260 | return static_cast(p); 261 | #else 262 | const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32; 263 | uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1; 264 | x1 += (x0 >> 32); // can't give carry 265 | x1 += x2; 266 | if (x1 < x2) 267 | x3 += (static_cast(1) << 32); 268 | uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF); 269 | uint64_t hi = x3 + (x1 >> 32); 270 | 271 | lo += k; 272 | if (lo < k) 273 | hi++; 274 | *outHigh = hi; 275 | return lo; 276 | #endif 277 | } 278 | 279 | static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000 280 | static const size_t kCapacity = kBitCount / sizeof(Type); 281 | static const size_t kTypeBit = sizeof(Type) * 8; 282 | 283 | Type digits_[kCapacity]; 284 | size_t count_; 285 | }; 286 | 287 | } // namespace internal 288 | RAPIDJSON_NAMESPACE_END 289 | 290 | #endif // RAPIDJSON_BIGINTEGER_H_ 291 | -------------------------------------------------------------------------------- /include/rapidjson/internal/dtoa.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | // This is a C++ header-only implementation of Grisu2 algorithm from the publication: 16 | // Loitsch, Florian. "Printing floating-point numbers quickly and accurately with 17 | // integers." ACM Sigplan Notices 45.6 (2010): 233-243. 18 | 19 | #ifndef RAPIDJSON_DTOA_ 20 | #define RAPIDJSON_DTOA_ 21 | 22 | #include "itoa.h" // GetDigitsLut() 23 | #include "diyfp.h" 24 | #include "ieee754.h" 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | namespace internal { 28 | 29 | #ifdef __GNUC__ 30 | RAPIDJSON_DIAG_PUSH 31 | RAPIDJSON_DIAG_OFF(effc++) 32 | RAPIDJSON_DIAG_OFF(array-bounds) // some gcc versions generate wrong warnings https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124 33 | #endif 34 | 35 | inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) { 36 | while (rest < wp_w && delta - rest >= ten_kappa && 37 | (rest + ten_kappa < wp_w || /// closer 38 | wp_w - rest > rest + ten_kappa - wp_w)) { 39 | buffer[len - 1]--; 40 | rest += ten_kappa; 41 | } 42 | } 43 | 44 | inline int CountDecimalDigit32(uint32_t n) { 45 | // Simple pure C++ implementation was faster than __builtin_clz version in this situation. 46 | if (n < 10) return 1; 47 | if (n < 100) return 2; 48 | if (n < 1000) return 3; 49 | if (n < 10000) return 4; 50 | if (n < 100000) return 5; 51 | if (n < 1000000) return 6; 52 | if (n < 10000000) return 7; 53 | if (n < 100000000) return 8; 54 | // Will not reach 10 digits in DigitGen() 55 | //if (n < 1000000000) return 9; 56 | //return 10; 57 | return 9; 58 | } 59 | 60 | inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) { 61 | static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; 62 | const DiyFp one(uint64_t(1) << -Mp.e, Mp.e); 63 | const DiyFp wp_w = Mp - W; 64 | uint32_t p1 = static_cast(Mp.f >> -one.e); 65 | uint64_t p2 = Mp.f & (one.f - 1); 66 | int kappa = CountDecimalDigit32(p1); // kappa in [0, 9] 67 | *len = 0; 68 | 69 | while (kappa > 0) { 70 | uint32_t d = 0; 71 | switch (kappa) { 72 | case 9: d = p1 / 100000000; p1 %= 100000000; break; 73 | case 8: d = p1 / 10000000; p1 %= 10000000; break; 74 | case 7: d = p1 / 1000000; p1 %= 1000000; break; 75 | case 6: d = p1 / 100000; p1 %= 100000; break; 76 | case 5: d = p1 / 10000; p1 %= 10000; break; 77 | case 4: d = p1 / 1000; p1 %= 1000; break; 78 | case 3: d = p1 / 100; p1 %= 100; break; 79 | case 2: d = p1 / 10; p1 %= 10; break; 80 | case 1: d = p1; p1 = 0; break; 81 | default:; 82 | } 83 | if (d || *len) 84 | buffer[(*len)++] = static_cast('0' + static_cast(d)); 85 | kappa--; 86 | uint64_t tmp = (static_cast(p1) << -one.e) + p2; 87 | if (tmp <= delta) { 88 | *K += kappa; 89 | GrisuRound(buffer, *len, delta, tmp, static_cast(kPow10[kappa]) << -one.e, wp_w.f); 90 | return; 91 | } 92 | } 93 | 94 | // kappa = 0 95 | for (;;) { 96 | p2 *= 10; 97 | delta *= 10; 98 | char d = static_cast(p2 >> -one.e); 99 | if (d || *len) 100 | buffer[(*len)++] = static_cast('0' + d); 101 | p2 &= one.f - 1; 102 | kappa--; 103 | if (p2 < delta) { 104 | *K += kappa; 105 | int index = -kappa; 106 | GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[index] : 0)); 107 | return; 108 | } 109 | } 110 | } 111 | 112 | inline void Grisu2(double value, char* buffer, int* length, int* K) { 113 | const DiyFp v(value); 114 | DiyFp w_m, w_p; 115 | v.NormalizedBoundaries(&w_m, &w_p); 116 | 117 | const DiyFp c_mk = GetCachedPower(w_p.e, K); 118 | const DiyFp W = v.Normalize() * c_mk; 119 | DiyFp Wp = w_p * c_mk; 120 | DiyFp Wm = w_m * c_mk; 121 | Wm.f++; 122 | Wp.f--; 123 | DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K); 124 | } 125 | 126 | inline char* WriteExponent(int K, char* buffer) { 127 | if (K < 0) { 128 | *buffer++ = '-'; 129 | K = -K; 130 | } 131 | 132 | if (K >= 100) { 133 | *buffer++ = static_cast('0' + static_cast(K / 100)); 134 | K %= 100; 135 | const char* d = GetDigitsLut() + K * 2; 136 | *buffer++ = d[0]; 137 | *buffer++ = d[1]; 138 | } 139 | else if (K >= 10) { 140 | const char* d = GetDigitsLut() + K * 2; 141 | *buffer++ = d[0]; 142 | *buffer++ = d[1]; 143 | } 144 | else 145 | *buffer++ = static_cast('0' + static_cast(K)); 146 | 147 | return buffer; 148 | } 149 | 150 | inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) { 151 | const int kk = length + k; // 10^(kk-1) <= v < 10^kk 152 | 153 | if (0 <= k && kk <= 21) { 154 | // 1234e7 -> 12340000000 155 | for (int i = length; i < kk; i++) 156 | buffer[i] = '0'; 157 | buffer[kk] = '.'; 158 | buffer[kk + 1] = '0'; 159 | return &buffer[kk + 2]; 160 | } 161 | else if (0 < kk && kk <= 21) { 162 | // 1234e-2 -> 12.34 163 | std::memmove(&buffer[kk + 1], &buffer[kk], static_cast(length - kk)); 164 | buffer[kk] = '.'; 165 | if (0 > k + maxDecimalPlaces) { 166 | // When maxDecimalPlaces = 2, 1.2345 -> 1.23, 1.102 -> 1.1 167 | // Remove extra trailing zeros (at least one) after truncation. 168 | for (int i = kk + maxDecimalPlaces; i > kk + 1; i--) 169 | if (buffer[i] != '0') 170 | return &buffer[i + 1]; 171 | return &buffer[kk + 2]; // Reserve one zero 172 | } 173 | else 174 | return &buffer[length + 1]; 175 | } 176 | else if (-6 < kk && kk <= 0) { 177 | // 1234e-6 -> 0.001234 178 | const int offset = 2 - kk; 179 | std::memmove(&buffer[offset], &buffer[0], static_cast(length)); 180 | buffer[0] = '0'; 181 | buffer[1] = '.'; 182 | for (int i = 2; i < offset; i++) 183 | buffer[i] = '0'; 184 | if (length - kk > maxDecimalPlaces) { 185 | // When maxDecimalPlaces = 2, 0.123 -> 0.12, 0.102 -> 0.1 186 | // Remove extra trailing zeros (at least one) after truncation. 187 | for (int i = maxDecimalPlaces + 1; i > 2; i--) 188 | if (buffer[i] != '0') 189 | return &buffer[i + 1]; 190 | return &buffer[3]; // Reserve one zero 191 | } 192 | else 193 | return &buffer[length + offset]; 194 | } 195 | else if (kk < -maxDecimalPlaces) { 196 | // Truncate to zero 197 | buffer[0] = '0'; 198 | buffer[1] = '.'; 199 | buffer[2] = '0'; 200 | return &buffer[3]; 201 | } 202 | else if (length == 1) { 203 | // 1e30 204 | buffer[1] = 'e'; 205 | return WriteExponent(kk - 1, &buffer[2]); 206 | } 207 | else { 208 | // 1234e30 -> 1.234e33 209 | std::memmove(&buffer[2], &buffer[1], static_cast(length - 1)); 210 | buffer[1] = '.'; 211 | buffer[length + 1] = 'e'; 212 | return WriteExponent(kk - 1, &buffer[0 + length + 2]); 213 | } 214 | } 215 | 216 | inline char* dtoa(double value, char* buffer, int maxDecimalPlaces = 324) { 217 | RAPIDJSON_ASSERT(maxDecimalPlaces >= 1); 218 | Double d(value); 219 | if (d.IsZero()) { 220 | if (d.Sign()) 221 | *buffer++ = '-'; // -0.0, Issue #289 222 | buffer[0] = '0'; 223 | buffer[1] = '.'; 224 | buffer[2] = '0'; 225 | return &buffer[3]; 226 | } 227 | else { 228 | if (value < 0) { 229 | *buffer++ = '-'; 230 | value = -value; 231 | } 232 | int length, K; 233 | Grisu2(value, buffer, &length, &K); 234 | return Prettify(buffer, length, K, maxDecimalPlaces); 235 | } 236 | } 237 | 238 | #ifdef __GNUC__ 239 | RAPIDJSON_DIAG_POP 240 | #endif 241 | 242 | } // namespace internal 243 | RAPIDJSON_NAMESPACE_END 244 | 245 | #endif // RAPIDJSON_DTOA_ 246 | -------------------------------------------------------------------------------- /include/rapidjson/internal/ieee754.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_IEEE754_ 16 | #define RAPIDJSON_IEEE754_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | RAPIDJSON_NAMESPACE_BEGIN 21 | namespace internal { 22 | 23 | class Double { 24 | public: 25 | Double() {} 26 | Double(double d) : d_(d) {} 27 | Double(uint64_t u) : u_(u) {} 28 | 29 | double Value() const { return d_; } 30 | uint64_t Uint64Value() const { return u_; } 31 | 32 | double NextPositiveDouble() const { 33 | RAPIDJSON_ASSERT(!Sign()); 34 | return Double(u_ + 1).Value(); 35 | } 36 | 37 | bool Sign() const { return (u_ & kSignMask) != 0; } 38 | uint64_t Significand() const { return u_ & kSignificandMask; } 39 | int Exponent() const { return static_cast(((u_ & kExponentMask) >> kSignificandSize) - kExponentBias); } 40 | 41 | bool IsNan() const { return (u_ & kExponentMask) == kExponentMask && Significand() != 0; } 42 | bool IsInf() const { return (u_ & kExponentMask) == kExponentMask && Significand() == 0; } 43 | bool IsNanOrInf() const { return (u_ & kExponentMask) == kExponentMask; } 44 | bool IsNormal() const { return (u_ & kExponentMask) != 0 || Significand() == 0; } 45 | bool IsZero() const { return (u_ & (kExponentMask | kSignificandMask)) == 0; } 46 | 47 | uint64_t IntegerSignificand() const { return IsNormal() ? Significand() | kHiddenBit : Significand(); } 48 | int IntegerExponent() const { return (IsNormal() ? Exponent() : kDenormalExponent) - kSignificandSize; } 49 | uint64_t ToBias() const { return (u_ & kSignMask) ? ~u_ + 1 : u_ | kSignMask; } 50 | 51 | static int EffectiveSignificandSize(int order) { 52 | if (order >= -1021) 53 | return 53; 54 | else if (order <= -1074) 55 | return 0; 56 | else 57 | return order + 1074; 58 | } 59 | 60 | private: 61 | static const int kSignificandSize = 52; 62 | static const int kExponentBias = 0x3FF; 63 | static const int kDenormalExponent = 1 - kExponentBias; 64 | static const uint64_t kSignMask = RAPIDJSON_UINT64_C2(0x80000000, 0x00000000); 65 | static const uint64_t kExponentMask = RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000); 66 | static const uint64_t kSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF); 67 | static const uint64_t kHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000); 68 | 69 | union { 70 | double d_; 71 | uint64_t u_; 72 | }; 73 | }; 74 | 75 | } // namespace internal 76 | RAPIDJSON_NAMESPACE_END 77 | 78 | #endif // RAPIDJSON_IEEE754_ 79 | -------------------------------------------------------------------------------- /include/rapidjson/internal/meta.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_INTERNAL_META_H_ 16 | #define RAPIDJSON_INTERNAL_META_H_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | #ifdef __GNUC__ 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(effc++) 23 | #endif 24 | 25 | #if defined(_MSC_VER) && !defined(__clang__) 26 | RAPIDJSON_DIAG_PUSH 27 | RAPIDJSON_DIAG_OFF(6334) 28 | #endif 29 | 30 | #if RAPIDJSON_HAS_CXX11_TYPETRAITS 31 | #include 32 | #endif 33 | 34 | //@cond RAPIDJSON_INTERNAL 35 | RAPIDJSON_NAMESPACE_BEGIN 36 | namespace internal { 37 | 38 | // Helper to wrap/convert arbitrary types to void, useful for arbitrary type matching 39 | template struct Void { typedef void Type; }; 40 | 41 | /////////////////////////////////////////////////////////////////////////////// 42 | // BoolType, TrueType, FalseType 43 | // 44 | template struct BoolType { 45 | static const bool Value = Cond; 46 | typedef BoolType Type; 47 | }; 48 | typedef BoolType TrueType; 49 | typedef BoolType FalseType; 50 | 51 | 52 | /////////////////////////////////////////////////////////////////////////////// 53 | // SelectIf, BoolExpr, NotExpr, AndExpr, OrExpr 54 | // 55 | 56 | template struct SelectIfImpl { template struct Apply { typedef T1 Type; }; }; 57 | template <> struct SelectIfImpl { template struct Apply { typedef T2 Type; }; }; 58 | template struct SelectIfCond : SelectIfImpl::template Apply {}; 59 | template struct SelectIf : SelectIfCond {}; 60 | 61 | template struct AndExprCond : FalseType {}; 62 | template <> struct AndExprCond : TrueType {}; 63 | template struct OrExprCond : TrueType {}; 64 | template <> struct OrExprCond : FalseType {}; 65 | 66 | template struct BoolExpr : SelectIf::Type {}; 67 | template struct NotExpr : SelectIf::Type {}; 68 | template struct AndExpr : AndExprCond::Type {}; 69 | template struct OrExpr : OrExprCond::Type {}; 70 | 71 | 72 | /////////////////////////////////////////////////////////////////////////////// 73 | // AddConst, MaybeAddConst, RemoveConst 74 | template struct AddConst { typedef const T Type; }; 75 | template struct MaybeAddConst : SelectIfCond {}; 76 | template struct RemoveConst { typedef T Type; }; 77 | template struct RemoveConst { typedef T Type; }; 78 | 79 | 80 | /////////////////////////////////////////////////////////////////////////////// 81 | // IsSame, IsConst, IsMoreConst, IsPointer 82 | // 83 | template struct IsSame : FalseType {}; 84 | template struct IsSame : TrueType {}; 85 | 86 | template struct IsConst : FalseType {}; 87 | template struct IsConst : TrueType {}; 88 | 89 | template 90 | struct IsMoreConst 91 | : AndExpr::Type, typename RemoveConst::Type>, 92 | BoolType::Value >= IsConst::Value> >::Type {}; 93 | 94 | template struct IsPointer : FalseType {}; 95 | template struct IsPointer : TrueType {}; 96 | 97 | /////////////////////////////////////////////////////////////////////////////// 98 | // IsBaseOf 99 | // 100 | #if RAPIDJSON_HAS_CXX11_TYPETRAITS 101 | 102 | template struct IsBaseOf 103 | : BoolType< ::std::is_base_of::value> {}; 104 | 105 | #else // simplified version adopted from Boost 106 | 107 | template struct IsBaseOfImpl { 108 | RAPIDJSON_STATIC_ASSERT(sizeof(B) != 0); 109 | RAPIDJSON_STATIC_ASSERT(sizeof(D) != 0); 110 | 111 | typedef char (&Yes)[1]; 112 | typedef char (&No) [2]; 113 | 114 | template 115 | static Yes Check(const D*, T); 116 | static No Check(const B*, int); 117 | 118 | struct Host { 119 | operator const B*() const; 120 | operator const D*(); 121 | }; 122 | 123 | enum { Value = (sizeof(Check(Host(), 0)) == sizeof(Yes)) }; 124 | }; 125 | 126 | template struct IsBaseOf 127 | : OrExpr, BoolExpr > >::Type {}; 128 | 129 | #endif // RAPIDJSON_HAS_CXX11_TYPETRAITS 130 | 131 | 132 | ////////////////////////////////////////////////////////////////////////// 133 | // EnableIf / DisableIf 134 | // 135 | template struct EnableIfCond { typedef T Type; }; 136 | template struct EnableIfCond { /* empty */ }; 137 | 138 | template struct DisableIfCond { typedef T Type; }; 139 | template struct DisableIfCond { /* empty */ }; 140 | 141 | template 142 | struct EnableIf : EnableIfCond {}; 143 | 144 | template 145 | struct DisableIf : DisableIfCond {}; 146 | 147 | // SFINAE helpers 148 | struct SfinaeTag {}; 149 | template struct RemoveSfinaeTag; 150 | template struct RemoveSfinaeTag { typedef T Type; }; 151 | 152 | #define RAPIDJSON_REMOVEFPTR_(type) \ 153 | typename ::RAPIDJSON_NAMESPACE::internal::RemoveSfinaeTag \ 154 | < ::RAPIDJSON_NAMESPACE::internal::SfinaeTag&(*) type>::Type 155 | 156 | #define RAPIDJSON_ENABLEIF(cond) \ 157 | typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \ 158 | ::Type * = NULL 159 | 160 | #define RAPIDJSON_DISABLEIF(cond) \ 161 | typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \ 162 | ::Type * = NULL 163 | 164 | #define RAPIDJSON_ENABLEIF_RETURN(cond,returntype) \ 165 | typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \ 166 | ::Type 168 | 169 | #define RAPIDJSON_DISABLEIF_RETURN(cond,returntype) \ 170 | typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \ 171 | ::Type 173 | 174 | } // namespace internal 175 | RAPIDJSON_NAMESPACE_END 176 | //@endcond 177 | 178 | #if defined(_MSC_VER) && !defined(__clang__) 179 | RAPIDJSON_DIAG_POP 180 | #endif 181 | 182 | #ifdef __GNUC__ 183 | RAPIDJSON_DIAG_POP 184 | #endif 185 | 186 | #endif // RAPIDJSON_INTERNAL_META_H_ 187 | -------------------------------------------------------------------------------- /include/rapidjson/internal/pow10.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_POW10_ 16 | #define RAPIDJSON_POW10_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | RAPIDJSON_NAMESPACE_BEGIN 21 | namespace internal { 22 | 23 | //! Computes integer powers of 10 in double (10.0^n). 24 | /*! This function uses lookup table for fast and accurate results. 25 | \param n non-negative exponent. Must <= 308. 26 | \return 10.0^n 27 | */ 28 | inline double Pow10(int n) { 29 | static const double e[] = { // 1e-0...1e308: 309 * 8 bytes = 2472 bytes 30 | 1e+0, 31 | 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20, 32 | 1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40, 33 | 1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60, 34 | 1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80, 35 | 1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100, 36 | 1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120, 37 | 1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140, 38 | 1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160, 39 | 1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180, 40 | 1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200, 41 | 1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220, 42 | 1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240, 43 | 1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260, 44 | 1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280, 45 | 1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300, 46 | 1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308 47 | }; 48 | RAPIDJSON_ASSERT(n >= 0 && n <= 308); 49 | return e[n]; 50 | } 51 | 52 | } // namespace internal 53 | RAPIDJSON_NAMESPACE_END 54 | 55 | #endif // RAPIDJSON_POW10_ 56 | -------------------------------------------------------------------------------- /include/rapidjson/internal/stack.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_INTERNAL_STACK_H_ 16 | #define RAPIDJSON_INTERNAL_STACK_H_ 17 | 18 | #include "../allocators.h" 19 | #include "swap.h" 20 | #include 21 | 22 | #if defined(__clang__) 23 | RAPIDJSON_DIAG_PUSH 24 | RAPIDJSON_DIAG_OFF(c++98-compat) 25 | #endif 26 | 27 | RAPIDJSON_NAMESPACE_BEGIN 28 | namespace internal { 29 | 30 | /////////////////////////////////////////////////////////////////////////////// 31 | // Stack 32 | 33 | //! A type-unsafe stack for storing different types of data. 34 | /*! \tparam Allocator Allocator for allocating stack memory. 35 | */ 36 | template 37 | class Stack { 38 | public: 39 | // Optimization note: Do not allocate memory for stack_ in constructor. 40 | // Do it lazily when first Push() -> Expand() -> Resize(). 41 | Stack(Allocator* allocator, size_t stackCapacity) : allocator_(allocator), ownAllocator_(0), stack_(0), stackTop_(0), stackEnd_(0), initialCapacity_(stackCapacity) { 42 | } 43 | 44 | #if RAPIDJSON_HAS_CXX11_RVALUE_REFS 45 | Stack(Stack&& rhs) 46 | : allocator_(rhs.allocator_), 47 | ownAllocator_(rhs.ownAllocator_), 48 | stack_(rhs.stack_), 49 | stackTop_(rhs.stackTop_), 50 | stackEnd_(rhs.stackEnd_), 51 | initialCapacity_(rhs.initialCapacity_) 52 | { 53 | rhs.allocator_ = 0; 54 | rhs.ownAllocator_ = 0; 55 | rhs.stack_ = 0; 56 | rhs.stackTop_ = 0; 57 | rhs.stackEnd_ = 0; 58 | rhs.initialCapacity_ = 0; 59 | } 60 | #endif 61 | 62 | ~Stack() { 63 | Destroy(); 64 | } 65 | 66 | #if RAPIDJSON_HAS_CXX11_RVALUE_REFS 67 | Stack& operator=(Stack&& rhs) { 68 | if (&rhs != this) 69 | { 70 | Destroy(); 71 | 72 | allocator_ = rhs.allocator_; 73 | ownAllocator_ = rhs.ownAllocator_; 74 | stack_ = rhs.stack_; 75 | stackTop_ = rhs.stackTop_; 76 | stackEnd_ = rhs.stackEnd_; 77 | initialCapacity_ = rhs.initialCapacity_; 78 | 79 | rhs.allocator_ = 0; 80 | rhs.ownAllocator_ = 0; 81 | rhs.stack_ = 0; 82 | rhs.stackTop_ = 0; 83 | rhs.stackEnd_ = 0; 84 | rhs.initialCapacity_ = 0; 85 | } 86 | return *this; 87 | } 88 | #endif 89 | 90 | void Swap(Stack& rhs) RAPIDJSON_NOEXCEPT { 91 | internal::Swap(allocator_, rhs.allocator_); 92 | internal::Swap(ownAllocator_, rhs.ownAllocator_); 93 | internal::Swap(stack_, rhs.stack_); 94 | internal::Swap(stackTop_, rhs.stackTop_); 95 | internal::Swap(stackEnd_, rhs.stackEnd_); 96 | internal::Swap(initialCapacity_, rhs.initialCapacity_); 97 | } 98 | 99 | void Clear() { stackTop_ = stack_; } 100 | 101 | void ShrinkToFit() { 102 | if (Empty()) { 103 | // If the stack is empty, completely deallocate the memory. 104 | Allocator::Free(stack_); // NOLINT (+clang-analyzer-unix.Malloc) 105 | stack_ = 0; 106 | stackTop_ = 0; 107 | stackEnd_ = 0; 108 | } 109 | else 110 | Resize(GetSize()); 111 | } 112 | 113 | // Optimization note: try to minimize the size of this function for force inline. 114 | // Expansion is run very infrequently, so it is moved to another (probably non-inline) function. 115 | template 116 | RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) { 117 | // Expand the stack if needed 118 | if (RAPIDJSON_UNLIKELY(static_cast(sizeof(T) * count) > (stackEnd_ - stackTop_))) 119 | Expand(count); 120 | } 121 | 122 | template 123 | RAPIDJSON_FORCEINLINE T* Push(size_t count = 1) { 124 | Reserve(count); 125 | return PushUnsafe(count); 126 | } 127 | 128 | template 129 | RAPIDJSON_FORCEINLINE T* PushUnsafe(size_t count = 1) { 130 | RAPIDJSON_ASSERT(stackTop_); 131 | RAPIDJSON_ASSERT(static_cast(sizeof(T) * count) <= (stackEnd_ - stackTop_)); 132 | T* ret = reinterpret_cast(stackTop_); 133 | stackTop_ += sizeof(T) * count; 134 | return ret; 135 | } 136 | 137 | template 138 | T* Pop(size_t count) { 139 | RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T)); 140 | stackTop_ -= count * sizeof(T); 141 | return reinterpret_cast(stackTop_); 142 | } 143 | 144 | template 145 | T* Top() { 146 | RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); 147 | return reinterpret_cast(stackTop_ - sizeof(T)); 148 | } 149 | 150 | template 151 | const T* Top() const { 152 | RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); 153 | return reinterpret_cast(stackTop_ - sizeof(T)); 154 | } 155 | 156 | template 157 | T* End() { return reinterpret_cast(stackTop_); } 158 | 159 | template 160 | const T* End() const { return reinterpret_cast(stackTop_); } 161 | 162 | template 163 | T* Bottom() { return reinterpret_cast(stack_); } 164 | 165 | template 166 | const T* Bottom() const { return reinterpret_cast(stack_); } 167 | 168 | bool HasAllocator() const { 169 | return allocator_ != 0; 170 | } 171 | 172 | Allocator& GetAllocator() { 173 | RAPIDJSON_ASSERT(allocator_); 174 | return *allocator_; 175 | } 176 | 177 | bool Empty() const { return stackTop_ == stack_; } 178 | size_t GetSize() const { return static_cast(stackTop_ - stack_); } 179 | size_t GetCapacity() const { return static_cast(stackEnd_ - stack_); } 180 | 181 | private: 182 | template 183 | void Expand(size_t count) { 184 | // Only expand the capacity if the current stack exists. Otherwise just create a stack with initial capacity. 185 | size_t newCapacity; 186 | if (stack_ == 0) { 187 | if (!allocator_) 188 | ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); 189 | newCapacity = initialCapacity_; 190 | } else { 191 | newCapacity = GetCapacity(); 192 | newCapacity += (newCapacity + 1) / 2; 193 | } 194 | size_t newSize = GetSize() + sizeof(T) * count; 195 | if (newCapacity < newSize) 196 | newCapacity = newSize; 197 | 198 | Resize(newCapacity); 199 | } 200 | 201 | void Resize(size_t newCapacity) { 202 | const size_t size = GetSize(); // Backup the current size 203 | stack_ = static_cast(allocator_->Realloc(stack_, GetCapacity(), newCapacity)); 204 | stackTop_ = stack_ + size; 205 | stackEnd_ = stack_ + newCapacity; 206 | } 207 | 208 | void Destroy() { 209 | Allocator::Free(stack_); 210 | RAPIDJSON_DELETE(ownAllocator_); // Only delete if it is owned by the stack 211 | } 212 | 213 | // Prohibit copy constructor & assignment operator. 214 | Stack(const Stack&); 215 | Stack& operator=(const Stack&); 216 | 217 | Allocator* allocator_; 218 | Allocator* ownAllocator_; 219 | char *stack_; 220 | char *stackTop_; 221 | char *stackEnd_; 222 | size_t initialCapacity_; 223 | }; 224 | 225 | } // namespace internal 226 | RAPIDJSON_NAMESPACE_END 227 | 228 | #if defined(__clang__) 229 | RAPIDJSON_DIAG_POP 230 | #endif 231 | 232 | #endif // RAPIDJSON_STACK_H_ 233 | -------------------------------------------------------------------------------- /include/rapidjson/internal/strfunc.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_INTERNAL_STRFUNC_H_ 16 | #define RAPIDJSON_INTERNAL_STRFUNC_H_ 17 | 18 | #include "../stream.h" 19 | #include 20 | 21 | RAPIDJSON_NAMESPACE_BEGIN 22 | namespace internal { 23 | 24 | //! Custom strlen() which works on different character types. 25 | /*! \tparam Ch Character type (e.g. char, wchar_t, short) 26 | \param s Null-terminated input string. 27 | \return Number of characters in the string. 28 | \note This has the same semantics as strlen(), the return value is not number of Unicode codepoints. 29 | */ 30 | template 31 | inline SizeType StrLen(const Ch* s) { 32 | RAPIDJSON_ASSERT(s != 0); 33 | const Ch* p = s; 34 | while (*p) ++p; 35 | return SizeType(p - s); 36 | } 37 | 38 | template <> 39 | inline SizeType StrLen(const char* s) { 40 | return SizeType(std::strlen(s)); 41 | } 42 | 43 | template <> 44 | inline SizeType StrLen(const wchar_t* s) { 45 | return SizeType(std::wcslen(s)); 46 | } 47 | 48 | //! Returns number of code points in a encoded string. 49 | template 50 | bool CountStringCodePoint(const typename Encoding::Ch* s, SizeType length, SizeType* outCount) { 51 | RAPIDJSON_ASSERT(s != 0); 52 | RAPIDJSON_ASSERT(outCount != 0); 53 | GenericStringStream is(s); 54 | const typename Encoding::Ch* end = s + length; 55 | SizeType count = 0; 56 | while (is.src_ < end) { 57 | unsigned codepoint; 58 | if (!Encoding::Decode(is, &codepoint)) 59 | return false; 60 | count++; 61 | } 62 | *outCount = count; 63 | return true; 64 | } 65 | 66 | } // namespace internal 67 | RAPIDJSON_NAMESPACE_END 68 | 69 | #endif // RAPIDJSON_INTERNAL_STRFUNC_H_ 70 | -------------------------------------------------------------------------------- /include/rapidjson/internal/strtod.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_STRTOD_ 16 | #define RAPIDJSON_STRTOD_ 17 | 18 | #include "ieee754.h" 19 | #include "biginteger.h" 20 | #include "diyfp.h" 21 | #include "pow10.h" 22 | #include 23 | #include 24 | 25 | RAPIDJSON_NAMESPACE_BEGIN 26 | namespace internal { 27 | 28 | inline double FastPath(double significand, int exp) { 29 | if (exp < -308) 30 | return 0.0; 31 | else if (exp >= 0) 32 | return significand * internal::Pow10(exp); 33 | else 34 | return significand / internal::Pow10(-exp); 35 | } 36 | 37 | inline double StrtodNormalPrecision(double d, int p) { 38 | if (p < -308) { 39 | // Prevent expSum < -308, making Pow10(p) = 0 40 | d = FastPath(d, -308); 41 | d = FastPath(d, p + 308); 42 | } 43 | else 44 | d = FastPath(d, p); 45 | return d; 46 | } 47 | 48 | template 49 | inline T Min3(T a, T b, T c) { 50 | T m = a; 51 | if (m > b) m = b; 52 | if (m > c) m = c; 53 | return m; 54 | } 55 | 56 | inline int CheckWithinHalfULP(double b, const BigInteger& d, int dExp) { 57 | const Double db(b); 58 | const uint64_t bInt = db.IntegerSignificand(); 59 | const int bExp = db.IntegerExponent(); 60 | const int hExp = bExp - 1; 61 | 62 | int dS_Exp2 = 0, dS_Exp5 = 0, bS_Exp2 = 0, bS_Exp5 = 0, hS_Exp2 = 0, hS_Exp5 = 0; 63 | 64 | // Adjust for decimal exponent 65 | if (dExp >= 0) { 66 | dS_Exp2 += dExp; 67 | dS_Exp5 += dExp; 68 | } 69 | else { 70 | bS_Exp2 -= dExp; 71 | bS_Exp5 -= dExp; 72 | hS_Exp2 -= dExp; 73 | hS_Exp5 -= dExp; 74 | } 75 | 76 | // Adjust for binary exponent 77 | if (bExp >= 0) 78 | bS_Exp2 += bExp; 79 | else { 80 | dS_Exp2 -= bExp; 81 | hS_Exp2 -= bExp; 82 | } 83 | 84 | // Adjust for half ulp exponent 85 | if (hExp >= 0) 86 | hS_Exp2 += hExp; 87 | else { 88 | dS_Exp2 -= hExp; 89 | bS_Exp2 -= hExp; 90 | } 91 | 92 | // Remove common power of two factor from all three scaled values 93 | int common_Exp2 = Min3(dS_Exp2, bS_Exp2, hS_Exp2); 94 | dS_Exp2 -= common_Exp2; 95 | bS_Exp2 -= common_Exp2; 96 | hS_Exp2 -= common_Exp2; 97 | 98 | BigInteger dS = d; 99 | dS.MultiplyPow5(static_cast(dS_Exp5)) <<= static_cast(dS_Exp2); 100 | 101 | BigInteger bS(bInt); 102 | bS.MultiplyPow5(static_cast(bS_Exp5)) <<= static_cast(bS_Exp2); 103 | 104 | BigInteger hS(1); 105 | hS.MultiplyPow5(static_cast(hS_Exp5)) <<= static_cast(hS_Exp2); 106 | 107 | BigInteger delta(0); 108 | dS.Difference(bS, &delta); 109 | 110 | return delta.Compare(hS); 111 | } 112 | 113 | inline bool StrtodFast(double d, int p, double* result) { 114 | // Use fast path for string-to-double conversion if possible 115 | // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/ 116 | if (p > 22 && p < 22 + 16) { 117 | // Fast Path Cases In Disguise 118 | d *= internal::Pow10(p - 22); 119 | p = 22; 120 | } 121 | 122 | if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1 123 | *result = FastPath(d, p); 124 | return true; 125 | } 126 | else 127 | return false; 128 | } 129 | 130 | // Compute an approximation and see if it is within 1/2 ULP 131 | inline bool StrtodDiyFp(const char* decimals, int dLen, int dExp, double* result) { 132 | uint64_t significand = 0; 133 | int i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999 134 | for (; i < dLen; i++) { 135 | if (significand > RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || 136 | (significand == RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5')) 137 | break; 138 | significand = significand * 10u + static_cast(decimals[i] - '0'); 139 | } 140 | 141 | if (i < dLen && decimals[i] >= '5') // Rounding 142 | significand++; 143 | 144 | int remaining = dLen - i; 145 | const int kUlpShift = 3; 146 | const int kUlp = 1 << kUlpShift; 147 | int64_t error = (remaining == 0) ? 0 : kUlp / 2; 148 | 149 | DiyFp v(significand, 0); 150 | v = v.Normalize(); 151 | error <<= -v.e; 152 | 153 | dExp += remaining; 154 | 155 | int actualExp; 156 | DiyFp cachedPower = GetCachedPower10(dExp, &actualExp); 157 | if (actualExp != dExp) { 158 | static const DiyFp kPow10[] = { 159 | DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 0x00000000), -60), // 10^1 160 | DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 0x00000000), -57), // 10^2 161 | DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 0x00000000), -54), // 10^3 162 | DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), -50), // 10^4 163 | DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 0x00000000), -47), // 10^5 164 | DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 0x00000000), -44), // 10^6 165 | DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 0x00000000), -40) // 10^7 166 | }; 167 | int adjustment = dExp - actualExp; 168 | RAPIDJSON_ASSERT(adjustment >= 1 && adjustment < 8); 169 | v = v * kPow10[adjustment - 1]; 170 | if (dLen + adjustment > 19) // has more digits than decimal digits in 64-bit 171 | error += kUlp / 2; 172 | } 173 | 174 | v = v * cachedPower; 175 | 176 | error += kUlp + (error == 0 ? 0 : 1); 177 | 178 | const int oldExp = v.e; 179 | v = v.Normalize(); 180 | error <<= oldExp - v.e; 181 | 182 | const int effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e); 183 | int precisionSize = 64 - effectiveSignificandSize; 184 | if (precisionSize + kUlpShift >= 64) { 185 | int scaleExp = (precisionSize + kUlpShift) - 63; 186 | v.f >>= scaleExp; 187 | v.e += scaleExp; 188 | error = (error >> scaleExp) + 1 + kUlp; 189 | precisionSize -= scaleExp; 190 | } 191 | 192 | DiyFp rounded(v.f >> precisionSize, v.e + precisionSize); 193 | const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp; 194 | const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp; 195 | if (precisionBits >= halfWay + static_cast(error)) { 196 | rounded.f++; 197 | if (rounded.f & (DiyFp::kDpHiddenBit << 1)) { // rounding overflows mantissa (issue #340) 198 | rounded.f >>= 1; 199 | rounded.e++; 200 | } 201 | } 202 | 203 | *result = rounded.ToDouble(); 204 | 205 | return halfWay - static_cast(error) >= precisionBits || precisionBits >= halfWay + static_cast(error); 206 | } 207 | 208 | inline double StrtodBigInteger(double approx, const char* decimals, int dLen, int dExp) { 209 | RAPIDJSON_ASSERT(dLen >= 0); 210 | const BigInteger dInt(decimals, static_cast(dLen)); 211 | Double a(approx); 212 | int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp); 213 | if (cmp < 0) 214 | return a.Value(); // within half ULP 215 | else if (cmp == 0) { 216 | // Round towards even 217 | if (a.Significand() & 1) 218 | return a.NextPositiveDouble(); 219 | else 220 | return a.Value(); 221 | } 222 | else // adjustment 223 | return a.NextPositiveDouble(); 224 | } 225 | 226 | inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t length, size_t decimalPosition, int exp) { 227 | RAPIDJSON_ASSERT(d >= 0.0); 228 | RAPIDJSON_ASSERT(length >= 1); 229 | 230 | double result = 0.0; 231 | if (StrtodFast(d, p, &result)) 232 | return result; 233 | 234 | RAPIDJSON_ASSERT(length <= INT_MAX); 235 | int dLen = static_cast(length); 236 | 237 | RAPIDJSON_ASSERT(length >= decimalPosition); 238 | RAPIDJSON_ASSERT(length - decimalPosition <= INT_MAX); 239 | int dExpAdjust = static_cast(length - decimalPosition); 240 | 241 | RAPIDJSON_ASSERT(exp >= INT_MIN + dExpAdjust); 242 | int dExp = exp - dExpAdjust; 243 | 244 | // Make sure length+dExp does not overflow 245 | RAPIDJSON_ASSERT(dExp <= INT_MAX - dLen); 246 | 247 | // Trim leading zeros 248 | while (dLen > 0 && *decimals == '0') { 249 | dLen--; 250 | decimals++; 251 | } 252 | 253 | // Trim trailing zeros 254 | while (dLen > 0 && decimals[dLen - 1] == '0') { 255 | dLen--; 256 | dExp++; 257 | } 258 | 259 | if (dLen == 0) { // Buffer only contains zeros. 260 | return 0.0; 261 | } 262 | 263 | // Trim right-most digits 264 | const int kMaxDecimalDigit = 767 + 1; 265 | if (dLen > kMaxDecimalDigit) { 266 | dExp += dLen - kMaxDecimalDigit; 267 | dLen = kMaxDecimalDigit; 268 | } 269 | 270 | // If too small, underflow to zero. 271 | // Any x <= 10^-324 is interpreted as zero. 272 | if (dLen + dExp <= -324) 273 | return 0.0; 274 | 275 | // If too large, overflow to infinity. 276 | // Any x >= 10^309 is interpreted as +infinity. 277 | if (dLen + dExp > 309) 278 | return std::numeric_limits::infinity(); 279 | 280 | if (StrtodDiyFp(decimals, dLen, dExp, &result)) 281 | return result; 282 | 283 | // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison 284 | return StrtodBigInteger(result, decimals, dLen, dExp); 285 | } 286 | 287 | } // namespace internal 288 | RAPIDJSON_NAMESPACE_END 289 | 290 | #endif // RAPIDJSON_STRTOD_ 291 | -------------------------------------------------------------------------------- /include/rapidjson/internal/swap.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_INTERNAL_SWAP_H_ 16 | #define RAPIDJSON_INTERNAL_SWAP_H_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | #if defined(__clang__) 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(c++98-compat) 23 | #endif 24 | 25 | RAPIDJSON_NAMESPACE_BEGIN 26 | namespace internal { 27 | 28 | //! Custom swap() to avoid dependency on C++ header 29 | /*! \tparam T Type of the arguments to swap, should be instantiated with primitive C++ types only. 30 | \note This has the same semantics as std::swap(). 31 | */ 32 | template 33 | inline void Swap(T& a, T& b) RAPIDJSON_NOEXCEPT { 34 | T tmp = a; 35 | a = b; 36 | b = tmp; 37 | } 38 | 39 | } // namespace internal 40 | RAPIDJSON_NAMESPACE_END 41 | 42 | #if defined(__clang__) 43 | RAPIDJSON_DIAG_POP 44 | #endif 45 | 46 | #endif // RAPIDJSON_INTERNAL_SWAP_H_ 47 | -------------------------------------------------------------------------------- /include/rapidjson/istreamwrapper.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_ISTREAMWRAPPER_H_ 16 | #define RAPIDJSON_ISTREAMWRAPPER_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | RAPIDJSON_DIAG_PUSH 23 | RAPIDJSON_DIAG_OFF(padded) 24 | #elif defined(_MSC_VER) 25 | RAPIDJSON_DIAG_PUSH 26 | RAPIDJSON_DIAG_OFF(4351) // new behavior: elements of array 'array' will be default initialized 27 | #endif 28 | 29 | RAPIDJSON_NAMESPACE_BEGIN 30 | 31 | //! Wrapper of \c std::basic_istream into RapidJSON's Stream concept. 32 | /*! 33 | The classes can be wrapped including but not limited to: 34 | 35 | - \c std::istringstream 36 | - \c std::stringstream 37 | - \c std::wistringstream 38 | - \c std::wstringstream 39 | - \c std::ifstream 40 | - \c std::fstream 41 | - \c std::wifstream 42 | - \c std::wfstream 43 | 44 | \tparam StreamType Class derived from \c std::basic_istream. 45 | */ 46 | 47 | template 48 | class BasicIStreamWrapper { 49 | public: 50 | typedef typename StreamType::char_type Ch; 51 | 52 | //! Constructor. 53 | /*! 54 | \param stream stream opened for read. 55 | */ 56 | BasicIStreamWrapper(StreamType &stream) : stream_(stream), buffer_(peekBuffer_), bufferSize_(4), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { 57 | Read(); 58 | } 59 | 60 | //! Constructor. 61 | /*! 62 | \param stream stream opened for read. 63 | \param buffer user-supplied buffer. 64 | \param bufferSize size of buffer in bytes. Must >=4 bytes. 65 | */ 66 | BasicIStreamWrapper(StreamType &stream, char* buffer, size_t bufferSize) : stream_(stream), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { 67 | RAPIDJSON_ASSERT(bufferSize >= 4); 68 | Read(); 69 | } 70 | 71 | Ch Peek() const { return *current_; } 72 | Ch Take() { Ch c = *current_; Read(); return c; } 73 | size_t Tell() const { return count_ + static_cast(current_ - buffer_); } 74 | 75 | // Not implemented 76 | void Put(Ch) { RAPIDJSON_ASSERT(false); } 77 | void Flush() { RAPIDJSON_ASSERT(false); } 78 | Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 79 | size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } 80 | 81 | // For encoding detection only. 82 | const Ch* Peek4() const { 83 | return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; 84 | } 85 | 86 | private: 87 | BasicIStreamWrapper(); 88 | BasicIStreamWrapper(const BasicIStreamWrapper&); 89 | BasicIStreamWrapper& operator=(const BasicIStreamWrapper&); 90 | 91 | void Read() { 92 | if (current_ < bufferLast_) 93 | ++current_; 94 | else if (!eof_) { 95 | count_ += readCount_; 96 | readCount_ = bufferSize_; 97 | bufferLast_ = buffer_ + readCount_ - 1; 98 | current_ = buffer_; 99 | 100 | if (!stream_.read(buffer_, static_cast(bufferSize_))) { 101 | readCount_ = static_cast(stream_.gcount()); 102 | *(bufferLast_ = buffer_ + readCount_) = '\0'; 103 | eof_ = true; 104 | } 105 | } 106 | } 107 | 108 | StreamType &stream_; 109 | Ch peekBuffer_[4], *buffer_; 110 | size_t bufferSize_; 111 | Ch *bufferLast_; 112 | Ch *current_; 113 | size_t readCount_; 114 | size_t count_; //!< Number of characters read 115 | bool eof_; 116 | }; 117 | 118 | typedef BasicIStreamWrapper IStreamWrapper; 119 | typedef BasicIStreamWrapper WIStreamWrapper; 120 | 121 | #if defined(__clang__) || defined(_MSC_VER) 122 | RAPIDJSON_DIAG_POP 123 | #endif 124 | 125 | RAPIDJSON_NAMESPACE_END 126 | 127 | #endif // RAPIDJSON_ISTREAMWRAPPER_H_ 128 | -------------------------------------------------------------------------------- /include/rapidjson/memorybuffer.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_MEMORYBUFFER_H_ 16 | #define RAPIDJSON_MEMORYBUFFER_H_ 17 | 18 | #include "stream.h" 19 | #include "internal/stack.h" 20 | 21 | RAPIDJSON_NAMESPACE_BEGIN 22 | 23 | //! Represents an in-memory output byte stream. 24 | /*! 25 | This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream. 26 | 27 | It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file. 28 | 29 | Differences between MemoryBuffer and StringBuffer: 30 | 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer. 31 | 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator. 32 | 33 | \tparam Allocator type for allocating memory buffer. 34 | \note implements Stream concept 35 | */ 36 | template 37 | struct GenericMemoryBuffer { 38 | typedef char Ch; // byte 39 | 40 | GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} 41 | 42 | void Put(Ch c) { *stack_.template Push() = c; } 43 | void Flush() {} 44 | 45 | void Clear() { stack_.Clear(); } 46 | void ShrinkToFit() { stack_.ShrinkToFit(); } 47 | Ch* Push(size_t count) { return stack_.template Push(count); } 48 | void Pop(size_t count) { stack_.template Pop(count); } 49 | 50 | const Ch* GetBuffer() const { 51 | return stack_.template Bottom(); 52 | } 53 | 54 | size_t GetSize() const { return stack_.GetSize(); } 55 | 56 | static const size_t kDefaultCapacity = 256; 57 | mutable internal::Stack stack_; 58 | }; 59 | 60 | typedef GenericMemoryBuffer<> MemoryBuffer; 61 | 62 | //! Implement specialized version of PutN() with memset() for better performance. 63 | template<> 64 | inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) { 65 | std::memset(memoryBuffer.stack_.Push(n), c, n * sizeof(c)); 66 | } 67 | 68 | RAPIDJSON_NAMESPACE_END 69 | 70 | #endif // RAPIDJSON_MEMORYBUFFER_H_ 71 | -------------------------------------------------------------------------------- /include/rapidjson/memorystream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_MEMORYSTREAM_H_ 16 | #define RAPIDJSON_MEMORYSTREAM_H_ 17 | 18 | #include "stream.h" 19 | 20 | #ifdef __clang__ 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(unreachable-code) 23 | RAPIDJSON_DIAG_OFF(missing-noreturn) 24 | #endif 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Represents an in-memory input byte stream. 29 | /*! 30 | This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream. 31 | 32 | It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file. 33 | 34 | Differences between MemoryStream and StringStream: 35 | 1. StringStream has encoding but MemoryStream is a byte stream. 36 | 2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source. 37 | 3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4(). 38 | \note implements Stream concept 39 | */ 40 | struct MemoryStream { 41 | typedef char Ch; // byte 42 | 43 | MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {} 44 | 45 | Ch Peek() const { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_; } 46 | Ch Take() { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_++; } 47 | size_t Tell() const { return static_cast(src_ - begin_); } 48 | 49 | Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 50 | void Put(Ch) { RAPIDJSON_ASSERT(false); } 51 | void Flush() { RAPIDJSON_ASSERT(false); } 52 | size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } 53 | 54 | // For encoding detection only. 55 | const Ch* Peek4() const { 56 | return Tell() + 4 <= size_ ? src_ : 0; 57 | } 58 | 59 | const Ch* src_; //!< Current read position. 60 | const Ch* begin_; //!< Original head of the string. 61 | const Ch* end_; //!< End of stream. 62 | size_t size_; //!< Size of the stream. 63 | }; 64 | 65 | RAPIDJSON_NAMESPACE_END 66 | 67 | #ifdef __clang__ 68 | RAPIDJSON_DIAG_POP 69 | #endif 70 | 71 | #endif // RAPIDJSON_MEMORYBUFFER_H_ 72 | -------------------------------------------------------------------------------- /include/rapidjson/msinttypes/inttypes.h: -------------------------------------------------------------------------------- 1 | // ISO C9x compliant inttypes.h for Microsoft Visual Studio 2 | // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 3 | // 4 | // Copyright (c) 2006-2013 Alexander Chemeris 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are met: 8 | // 9 | // 1. Redistributions of source code must retain the above copyright notice, 10 | // this list of conditions and the following disclaimer. 11 | // 12 | // 2. Redistributions in binary form must reproduce the above copyright 13 | // notice, this list of conditions and the following disclaimer in the 14 | // documentation and/or other materials provided with the distribution. 15 | // 16 | // 3. Neither the name of the product nor the names of its contributors may 17 | // be used to endorse or promote products derived from this software 18 | // without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 21 | // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 22 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 23 | // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 25 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 26 | // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 27 | // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 28 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 29 | // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | // 31 | /////////////////////////////////////////////////////////////////////////////// 32 | 33 | // The above software in this distribution may have been modified by 34 | // THL A29 Limited ("Tencent Modifications"). 35 | // All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. 36 | 37 | #ifndef _MSC_VER // [ 38 | #error "Use this header only with Microsoft Visual C++ compilers!" 39 | #endif // _MSC_VER ] 40 | 41 | #ifndef _MSC_INTTYPES_H_ // [ 42 | #define _MSC_INTTYPES_H_ 43 | 44 | #if _MSC_VER > 1000 45 | #pragma once 46 | #endif 47 | 48 | #include "stdint.h" 49 | 50 | // miloyip: VC supports inttypes.h since VC2013 51 | #if _MSC_VER >= 1800 52 | #include 53 | #else 54 | 55 | // 7.8 Format conversion of integer types 56 | 57 | typedef struct { 58 | intmax_t quot; 59 | intmax_t rem; 60 | } imaxdiv_t; 61 | 62 | // 7.8.1 Macros for format specifiers 63 | 64 | #if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 65 | 66 | // The fprintf macros for signed integers are: 67 | #define PRId8 "d" 68 | #define PRIi8 "i" 69 | #define PRIdLEAST8 "d" 70 | #define PRIiLEAST8 "i" 71 | #define PRIdFAST8 "d" 72 | #define PRIiFAST8 "i" 73 | 74 | #define PRId16 "hd" 75 | #define PRIi16 "hi" 76 | #define PRIdLEAST16 "hd" 77 | #define PRIiLEAST16 "hi" 78 | #define PRIdFAST16 "hd" 79 | #define PRIiFAST16 "hi" 80 | 81 | #define PRId32 "I32d" 82 | #define PRIi32 "I32i" 83 | #define PRIdLEAST32 "I32d" 84 | #define PRIiLEAST32 "I32i" 85 | #define PRIdFAST32 "I32d" 86 | #define PRIiFAST32 "I32i" 87 | 88 | #define PRId64 "I64d" 89 | #define PRIi64 "I64i" 90 | #define PRIdLEAST64 "I64d" 91 | #define PRIiLEAST64 "I64i" 92 | #define PRIdFAST64 "I64d" 93 | #define PRIiFAST64 "I64i" 94 | 95 | #define PRIdMAX "I64d" 96 | #define PRIiMAX "I64i" 97 | 98 | #define PRIdPTR "Id" 99 | #define PRIiPTR "Ii" 100 | 101 | // The fprintf macros for unsigned integers are: 102 | #define PRIo8 "o" 103 | #define PRIu8 "u" 104 | #define PRIx8 "x" 105 | #define PRIX8 "X" 106 | #define PRIoLEAST8 "o" 107 | #define PRIuLEAST8 "u" 108 | #define PRIxLEAST8 "x" 109 | #define PRIXLEAST8 "X" 110 | #define PRIoFAST8 "o" 111 | #define PRIuFAST8 "u" 112 | #define PRIxFAST8 "x" 113 | #define PRIXFAST8 "X" 114 | 115 | #define PRIo16 "ho" 116 | #define PRIu16 "hu" 117 | #define PRIx16 "hx" 118 | #define PRIX16 "hX" 119 | #define PRIoLEAST16 "ho" 120 | #define PRIuLEAST16 "hu" 121 | #define PRIxLEAST16 "hx" 122 | #define PRIXLEAST16 "hX" 123 | #define PRIoFAST16 "ho" 124 | #define PRIuFAST16 "hu" 125 | #define PRIxFAST16 "hx" 126 | #define PRIXFAST16 "hX" 127 | 128 | #define PRIo32 "I32o" 129 | #define PRIu32 "I32u" 130 | #define PRIx32 "I32x" 131 | #define PRIX32 "I32X" 132 | #define PRIoLEAST32 "I32o" 133 | #define PRIuLEAST32 "I32u" 134 | #define PRIxLEAST32 "I32x" 135 | #define PRIXLEAST32 "I32X" 136 | #define PRIoFAST32 "I32o" 137 | #define PRIuFAST32 "I32u" 138 | #define PRIxFAST32 "I32x" 139 | #define PRIXFAST32 "I32X" 140 | 141 | #define PRIo64 "I64o" 142 | #define PRIu64 "I64u" 143 | #define PRIx64 "I64x" 144 | #define PRIX64 "I64X" 145 | #define PRIoLEAST64 "I64o" 146 | #define PRIuLEAST64 "I64u" 147 | #define PRIxLEAST64 "I64x" 148 | #define PRIXLEAST64 "I64X" 149 | #define PRIoFAST64 "I64o" 150 | #define PRIuFAST64 "I64u" 151 | #define PRIxFAST64 "I64x" 152 | #define PRIXFAST64 "I64X" 153 | 154 | #define PRIoMAX "I64o" 155 | #define PRIuMAX "I64u" 156 | #define PRIxMAX "I64x" 157 | #define PRIXMAX "I64X" 158 | 159 | #define PRIoPTR "Io" 160 | #define PRIuPTR "Iu" 161 | #define PRIxPTR "Ix" 162 | #define PRIXPTR "IX" 163 | 164 | // The fscanf macros for signed integers are: 165 | #define SCNd8 "d" 166 | #define SCNi8 "i" 167 | #define SCNdLEAST8 "d" 168 | #define SCNiLEAST8 "i" 169 | #define SCNdFAST8 "d" 170 | #define SCNiFAST8 "i" 171 | 172 | #define SCNd16 "hd" 173 | #define SCNi16 "hi" 174 | #define SCNdLEAST16 "hd" 175 | #define SCNiLEAST16 "hi" 176 | #define SCNdFAST16 "hd" 177 | #define SCNiFAST16 "hi" 178 | 179 | #define SCNd32 "ld" 180 | #define SCNi32 "li" 181 | #define SCNdLEAST32 "ld" 182 | #define SCNiLEAST32 "li" 183 | #define SCNdFAST32 "ld" 184 | #define SCNiFAST32 "li" 185 | 186 | #define SCNd64 "I64d" 187 | #define SCNi64 "I64i" 188 | #define SCNdLEAST64 "I64d" 189 | #define SCNiLEAST64 "I64i" 190 | #define SCNdFAST64 "I64d" 191 | #define SCNiFAST64 "I64i" 192 | 193 | #define SCNdMAX "I64d" 194 | #define SCNiMAX "I64i" 195 | 196 | #ifdef _WIN64 // [ 197 | # define SCNdPTR "I64d" 198 | # define SCNiPTR "I64i" 199 | #else // _WIN64 ][ 200 | # define SCNdPTR "ld" 201 | # define SCNiPTR "li" 202 | #endif // _WIN64 ] 203 | 204 | // The fscanf macros for unsigned integers are: 205 | #define SCNo8 "o" 206 | #define SCNu8 "u" 207 | #define SCNx8 "x" 208 | #define SCNX8 "X" 209 | #define SCNoLEAST8 "o" 210 | #define SCNuLEAST8 "u" 211 | #define SCNxLEAST8 "x" 212 | #define SCNXLEAST8 "X" 213 | #define SCNoFAST8 "o" 214 | #define SCNuFAST8 "u" 215 | #define SCNxFAST8 "x" 216 | #define SCNXFAST8 "X" 217 | 218 | #define SCNo16 "ho" 219 | #define SCNu16 "hu" 220 | #define SCNx16 "hx" 221 | #define SCNX16 "hX" 222 | #define SCNoLEAST16 "ho" 223 | #define SCNuLEAST16 "hu" 224 | #define SCNxLEAST16 "hx" 225 | #define SCNXLEAST16 "hX" 226 | #define SCNoFAST16 "ho" 227 | #define SCNuFAST16 "hu" 228 | #define SCNxFAST16 "hx" 229 | #define SCNXFAST16 "hX" 230 | 231 | #define SCNo32 "lo" 232 | #define SCNu32 "lu" 233 | #define SCNx32 "lx" 234 | #define SCNX32 "lX" 235 | #define SCNoLEAST32 "lo" 236 | #define SCNuLEAST32 "lu" 237 | #define SCNxLEAST32 "lx" 238 | #define SCNXLEAST32 "lX" 239 | #define SCNoFAST32 "lo" 240 | #define SCNuFAST32 "lu" 241 | #define SCNxFAST32 "lx" 242 | #define SCNXFAST32 "lX" 243 | 244 | #define SCNo64 "I64o" 245 | #define SCNu64 "I64u" 246 | #define SCNx64 "I64x" 247 | #define SCNX64 "I64X" 248 | #define SCNoLEAST64 "I64o" 249 | #define SCNuLEAST64 "I64u" 250 | #define SCNxLEAST64 "I64x" 251 | #define SCNXLEAST64 "I64X" 252 | #define SCNoFAST64 "I64o" 253 | #define SCNuFAST64 "I64u" 254 | #define SCNxFAST64 "I64x" 255 | #define SCNXFAST64 "I64X" 256 | 257 | #define SCNoMAX "I64o" 258 | #define SCNuMAX "I64u" 259 | #define SCNxMAX "I64x" 260 | #define SCNXMAX "I64X" 261 | 262 | #ifdef _WIN64 // [ 263 | # define SCNoPTR "I64o" 264 | # define SCNuPTR "I64u" 265 | # define SCNxPTR "I64x" 266 | # define SCNXPTR "I64X" 267 | #else // _WIN64 ][ 268 | # define SCNoPTR "lo" 269 | # define SCNuPTR "lu" 270 | # define SCNxPTR "lx" 271 | # define SCNXPTR "lX" 272 | #endif // _WIN64 ] 273 | 274 | #endif // __STDC_FORMAT_MACROS ] 275 | 276 | // 7.8.2 Functions for greatest-width integer types 277 | 278 | // 7.8.2.1 The imaxabs function 279 | #define imaxabs _abs64 280 | 281 | // 7.8.2.2 The imaxdiv function 282 | 283 | // This is modified version of div() function from Microsoft's div.c found 284 | // in %MSVC.NET%\crt\src\div.c 285 | #ifdef STATIC_IMAXDIV // [ 286 | static 287 | #else // STATIC_IMAXDIV ][ 288 | _inline 289 | #endif // STATIC_IMAXDIV ] 290 | imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) 291 | { 292 | imaxdiv_t result; 293 | 294 | result.quot = numer / denom; 295 | result.rem = numer % denom; 296 | 297 | if (numer < 0 && result.rem > 0) { 298 | // did division wrong; must fix up 299 | ++result.quot; 300 | result.rem -= denom; 301 | } 302 | 303 | return result; 304 | } 305 | 306 | // 7.8.2.3 The strtoimax and strtoumax functions 307 | #define strtoimax _strtoi64 308 | #define strtoumax _strtoui64 309 | 310 | // 7.8.2.4 The wcstoimax and wcstoumax functions 311 | #define wcstoimax _wcstoi64 312 | #define wcstoumax _wcstoui64 313 | 314 | #endif // _MSC_VER >= 1800 315 | 316 | #endif // _MSC_INTTYPES_H_ ] 317 | -------------------------------------------------------------------------------- /include/rapidjson/msinttypes/stdint.h: -------------------------------------------------------------------------------- 1 | // ISO C9x compliant stdint.h for Microsoft Visual Studio 2 | // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 3 | // 4 | // Copyright (c) 2006-2013 Alexander Chemeris 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are met: 8 | // 9 | // 1. Redistributions of source code must retain the above copyright notice, 10 | // this list of conditions and the following disclaimer. 11 | // 12 | // 2. Redistributions in binary form must reproduce the above copyright 13 | // notice, this list of conditions and the following disclaimer in the 14 | // documentation and/or other materials provided with the distribution. 15 | // 16 | // 3. Neither the name of the product nor the names of its contributors may 17 | // be used to endorse or promote products derived from this software 18 | // without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 21 | // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 22 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 23 | // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 25 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 26 | // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 27 | // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 28 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 29 | // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | // 31 | /////////////////////////////////////////////////////////////////////////////// 32 | 33 | // The above software in this distribution may have been modified by 34 | // THL A29 Limited ("Tencent Modifications"). 35 | // All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. 36 | 37 | #ifndef _MSC_VER // [ 38 | #error "Use this header only with Microsoft Visual C++ compilers!" 39 | #endif // _MSC_VER ] 40 | 41 | #ifndef _MSC_STDINT_H_ // [ 42 | #define _MSC_STDINT_H_ 43 | 44 | #if _MSC_VER > 1000 45 | #pragma once 46 | #endif 47 | 48 | // miloyip: Originally Visual Studio 2010 uses its own stdint.h. However it generates warning with INT64_C(), so change to use this file for vs2010. 49 | #if _MSC_VER >= 1600 // [ 50 | #include 51 | 52 | #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 53 | 54 | #undef INT8_C 55 | #undef INT16_C 56 | #undef INT32_C 57 | #undef INT64_C 58 | #undef UINT8_C 59 | #undef UINT16_C 60 | #undef UINT32_C 61 | #undef UINT64_C 62 | 63 | // 7.18.4.1 Macros for minimum-width integer constants 64 | 65 | #define INT8_C(val) val##i8 66 | #define INT16_C(val) val##i16 67 | #define INT32_C(val) val##i32 68 | #define INT64_C(val) val##i64 69 | 70 | #define UINT8_C(val) val##ui8 71 | #define UINT16_C(val) val##ui16 72 | #define UINT32_C(val) val##ui32 73 | #define UINT64_C(val) val##ui64 74 | 75 | // 7.18.4.2 Macros for greatest-width integer constants 76 | // These #ifndef's are needed to prevent collisions with . 77 | // Check out Issue 9 for the details. 78 | #ifndef INTMAX_C // [ 79 | # define INTMAX_C INT64_C 80 | #endif // INTMAX_C ] 81 | #ifndef UINTMAX_C // [ 82 | # define UINTMAX_C UINT64_C 83 | #endif // UINTMAX_C ] 84 | 85 | #endif // __STDC_CONSTANT_MACROS ] 86 | 87 | #else // ] _MSC_VER >= 1700 [ 88 | 89 | #include 90 | 91 | // For Visual Studio 6 in C++ mode and for many Visual Studio versions when 92 | // compiling for ARM we have to wrap include with 'extern "C++" {}' 93 | // or compiler would give many errors like this: 94 | // error C2733: second C linkage of overloaded function 'wmemchr' not allowed 95 | #if defined(__cplusplus) && !defined(_M_ARM) 96 | extern "C" { 97 | #endif 98 | # include 99 | #if defined(__cplusplus) && !defined(_M_ARM) 100 | } 101 | #endif 102 | 103 | // Define _W64 macros to mark types changing their size, like intptr_t. 104 | #ifndef _W64 105 | # if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 106 | # define _W64 __w64 107 | # else 108 | # define _W64 109 | # endif 110 | #endif 111 | 112 | 113 | // 7.18.1 Integer types 114 | 115 | // 7.18.1.1 Exact-width integer types 116 | 117 | // Visual Studio 6 and Embedded Visual C++ 4 doesn't 118 | // realize that, e.g. char has the same size as __int8 119 | // so we give up on __intX for them. 120 | #if (_MSC_VER < 1300) 121 | typedef signed char int8_t; 122 | typedef signed short int16_t; 123 | typedef signed int int32_t; 124 | typedef unsigned char uint8_t; 125 | typedef unsigned short uint16_t; 126 | typedef unsigned int uint32_t; 127 | #else 128 | typedef signed __int8 int8_t; 129 | typedef signed __int16 int16_t; 130 | typedef signed __int32 int32_t; 131 | typedef unsigned __int8 uint8_t; 132 | typedef unsigned __int16 uint16_t; 133 | typedef unsigned __int32 uint32_t; 134 | #endif 135 | typedef signed __int64 int64_t; 136 | typedef unsigned __int64 uint64_t; 137 | 138 | 139 | // 7.18.1.2 Minimum-width integer types 140 | typedef int8_t int_least8_t; 141 | typedef int16_t int_least16_t; 142 | typedef int32_t int_least32_t; 143 | typedef int64_t int_least64_t; 144 | typedef uint8_t uint_least8_t; 145 | typedef uint16_t uint_least16_t; 146 | typedef uint32_t uint_least32_t; 147 | typedef uint64_t uint_least64_t; 148 | 149 | // 7.18.1.3 Fastest minimum-width integer types 150 | typedef int8_t int_fast8_t; 151 | typedef int16_t int_fast16_t; 152 | typedef int32_t int_fast32_t; 153 | typedef int64_t int_fast64_t; 154 | typedef uint8_t uint_fast8_t; 155 | typedef uint16_t uint_fast16_t; 156 | typedef uint32_t uint_fast32_t; 157 | typedef uint64_t uint_fast64_t; 158 | 159 | // 7.18.1.4 Integer types capable of holding object pointers 160 | #ifdef _WIN64 // [ 161 | typedef signed __int64 intptr_t; 162 | typedef unsigned __int64 uintptr_t; 163 | #else // _WIN64 ][ 164 | typedef _W64 signed int intptr_t; 165 | typedef _W64 unsigned int uintptr_t; 166 | #endif // _WIN64 ] 167 | 168 | // 7.18.1.5 Greatest-width integer types 169 | typedef int64_t intmax_t; 170 | typedef uint64_t uintmax_t; 171 | 172 | 173 | // 7.18.2 Limits of specified-width integer types 174 | 175 | #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 176 | 177 | // 7.18.2.1 Limits of exact-width integer types 178 | #define INT8_MIN ((int8_t)_I8_MIN) 179 | #define INT8_MAX _I8_MAX 180 | #define INT16_MIN ((int16_t)_I16_MIN) 181 | #define INT16_MAX _I16_MAX 182 | #define INT32_MIN ((int32_t)_I32_MIN) 183 | #define INT32_MAX _I32_MAX 184 | #define INT64_MIN ((int64_t)_I64_MIN) 185 | #define INT64_MAX _I64_MAX 186 | #define UINT8_MAX _UI8_MAX 187 | #define UINT16_MAX _UI16_MAX 188 | #define UINT32_MAX _UI32_MAX 189 | #define UINT64_MAX _UI64_MAX 190 | 191 | // 7.18.2.2 Limits of minimum-width integer types 192 | #define INT_LEAST8_MIN INT8_MIN 193 | #define INT_LEAST8_MAX INT8_MAX 194 | #define INT_LEAST16_MIN INT16_MIN 195 | #define INT_LEAST16_MAX INT16_MAX 196 | #define INT_LEAST32_MIN INT32_MIN 197 | #define INT_LEAST32_MAX INT32_MAX 198 | #define INT_LEAST64_MIN INT64_MIN 199 | #define INT_LEAST64_MAX INT64_MAX 200 | #define UINT_LEAST8_MAX UINT8_MAX 201 | #define UINT_LEAST16_MAX UINT16_MAX 202 | #define UINT_LEAST32_MAX UINT32_MAX 203 | #define UINT_LEAST64_MAX UINT64_MAX 204 | 205 | // 7.18.2.3 Limits of fastest minimum-width integer types 206 | #define INT_FAST8_MIN INT8_MIN 207 | #define INT_FAST8_MAX INT8_MAX 208 | #define INT_FAST16_MIN INT16_MIN 209 | #define INT_FAST16_MAX INT16_MAX 210 | #define INT_FAST32_MIN INT32_MIN 211 | #define INT_FAST32_MAX INT32_MAX 212 | #define INT_FAST64_MIN INT64_MIN 213 | #define INT_FAST64_MAX INT64_MAX 214 | #define UINT_FAST8_MAX UINT8_MAX 215 | #define UINT_FAST16_MAX UINT16_MAX 216 | #define UINT_FAST32_MAX UINT32_MAX 217 | #define UINT_FAST64_MAX UINT64_MAX 218 | 219 | // 7.18.2.4 Limits of integer types capable of holding object pointers 220 | #ifdef _WIN64 // [ 221 | # define INTPTR_MIN INT64_MIN 222 | # define INTPTR_MAX INT64_MAX 223 | # define UINTPTR_MAX UINT64_MAX 224 | #else // _WIN64 ][ 225 | # define INTPTR_MIN INT32_MIN 226 | # define INTPTR_MAX INT32_MAX 227 | # define UINTPTR_MAX UINT32_MAX 228 | #endif // _WIN64 ] 229 | 230 | // 7.18.2.5 Limits of greatest-width integer types 231 | #define INTMAX_MIN INT64_MIN 232 | #define INTMAX_MAX INT64_MAX 233 | #define UINTMAX_MAX UINT64_MAX 234 | 235 | // 7.18.3 Limits of other integer types 236 | 237 | #ifdef _WIN64 // [ 238 | # define PTRDIFF_MIN _I64_MIN 239 | # define PTRDIFF_MAX _I64_MAX 240 | #else // _WIN64 ][ 241 | # define PTRDIFF_MIN _I32_MIN 242 | # define PTRDIFF_MAX _I32_MAX 243 | #endif // _WIN64 ] 244 | 245 | #define SIG_ATOMIC_MIN INT_MIN 246 | #define SIG_ATOMIC_MAX INT_MAX 247 | 248 | #ifndef SIZE_MAX // [ 249 | # ifdef _WIN64 // [ 250 | # define SIZE_MAX _UI64_MAX 251 | # else // _WIN64 ][ 252 | # define SIZE_MAX _UI32_MAX 253 | # endif // _WIN64 ] 254 | #endif // SIZE_MAX ] 255 | 256 | // WCHAR_MIN and WCHAR_MAX are also defined in 257 | #ifndef WCHAR_MIN // [ 258 | # define WCHAR_MIN 0 259 | #endif // WCHAR_MIN ] 260 | #ifndef WCHAR_MAX // [ 261 | # define WCHAR_MAX _UI16_MAX 262 | #endif // WCHAR_MAX ] 263 | 264 | #define WINT_MIN 0 265 | #define WINT_MAX _UI16_MAX 266 | 267 | #endif // __STDC_LIMIT_MACROS ] 268 | 269 | 270 | // 7.18.4 Limits of other integer types 271 | 272 | #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 273 | 274 | // 7.18.4.1 Macros for minimum-width integer constants 275 | 276 | #define INT8_C(val) val##i8 277 | #define INT16_C(val) val##i16 278 | #define INT32_C(val) val##i32 279 | #define INT64_C(val) val##i64 280 | 281 | #define UINT8_C(val) val##ui8 282 | #define UINT16_C(val) val##ui16 283 | #define UINT32_C(val) val##ui32 284 | #define UINT64_C(val) val##ui64 285 | 286 | // 7.18.4.2 Macros for greatest-width integer constants 287 | // These #ifndef's are needed to prevent collisions with . 288 | // Check out Issue 9 for the details. 289 | #ifndef INTMAX_C // [ 290 | # define INTMAX_C INT64_C 291 | #endif // INTMAX_C ] 292 | #ifndef UINTMAX_C // [ 293 | # define UINTMAX_C UINT64_C 294 | #endif // UINTMAX_C ] 295 | 296 | #endif // __STDC_CONSTANT_MACROS ] 297 | 298 | #endif // _MSC_VER >= 1600 ] 299 | 300 | #endif // _MSC_STDINT_H_ ] 301 | -------------------------------------------------------------------------------- /include/rapidjson/ostreamwrapper.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_OSTREAMWRAPPER_H_ 16 | #define RAPIDJSON_OSTREAMWRAPPER_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | RAPIDJSON_DIAG_PUSH 23 | RAPIDJSON_DIAG_OFF(padded) 24 | #endif 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Wrapper of \c std::basic_ostream into RapidJSON's Stream concept. 29 | /*! 30 | The classes can be wrapped including but not limited to: 31 | 32 | - \c std::ostringstream 33 | - \c std::stringstream 34 | - \c std::wpstringstream 35 | - \c std::wstringstream 36 | - \c std::ifstream 37 | - \c std::fstream 38 | - \c std::wofstream 39 | - \c std::wfstream 40 | 41 | \tparam StreamType Class derived from \c std::basic_ostream. 42 | */ 43 | 44 | template 45 | class BasicOStreamWrapper { 46 | public: 47 | typedef typename StreamType::char_type Ch; 48 | BasicOStreamWrapper(StreamType& stream) : stream_(stream) {} 49 | 50 | void Put(Ch c) { 51 | stream_.put(c); 52 | } 53 | 54 | void Flush() { 55 | stream_.flush(); 56 | } 57 | 58 | // Not implemented 59 | char Peek() const { RAPIDJSON_ASSERT(false); return 0; } 60 | char Take() { RAPIDJSON_ASSERT(false); return 0; } 61 | size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } 62 | char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 63 | size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; } 64 | 65 | private: 66 | BasicOStreamWrapper(const BasicOStreamWrapper&); 67 | BasicOStreamWrapper& operator=(const BasicOStreamWrapper&); 68 | 69 | StreamType& stream_; 70 | }; 71 | 72 | typedef BasicOStreamWrapper OStreamWrapper; 73 | typedef BasicOStreamWrapper WOStreamWrapper; 74 | 75 | #ifdef __clang__ 76 | RAPIDJSON_DIAG_POP 77 | #endif 78 | 79 | RAPIDJSON_NAMESPACE_END 80 | 81 | #endif // RAPIDJSON_OSTREAMWRAPPER_H_ 82 | -------------------------------------------------------------------------------- /include/rapidjson/stream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #include "rapidjson.h" 16 | 17 | #ifndef RAPIDJSON_STREAM_H_ 18 | #define RAPIDJSON_STREAM_H_ 19 | 20 | #include "encodings.h" 21 | 22 | RAPIDJSON_NAMESPACE_BEGIN 23 | 24 | /////////////////////////////////////////////////////////////////////////////// 25 | // Stream 26 | 27 | /*! \class rapidjson::Stream 28 | \brief Concept for reading and writing characters. 29 | 30 | For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd(). 31 | 32 | For write-only stream, only need to implement Put() and Flush(). 33 | 34 | \code 35 | concept Stream { 36 | typename Ch; //!< Character type of the stream. 37 | 38 | //! Read the current character from stream without moving the read cursor. 39 | Ch Peek() const; 40 | 41 | //! Read the current character from stream and moving the read cursor to next character. 42 | Ch Take(); 43 | 44 | //! Get the current read cursor. 45 | //! \return Number of characters read from start. 46 | size_t Tell(); 47 | 48 | //! Begin writing operation at the current read pointer. 49 | //! \return The begin writer pointer. 50 | Ch* PutBegin(); 51 | 52 | //! Write a character. 53 | void Put(Ch c); 54 | 55 | //! Flush the buffer. 56 | void Flush(); 57 | 58 | //! End the writing operation. 59 | //! \param begin The begin write pointer returned by PutBegin(). 60 | //! \return Number of characters written. 61 | size_t PutEnd(Ch* begin); 62 | } 63 | \endcode 64 | */ 65 | 66 | //! Provides additional information for stream. 67 | /*! 68 | By using traits pattern, this type provides a default configuration for stream. 69 | For custom stream, this type can be specialized for other configuration. 70 | See TEST(Reader, CustomStringStream) in readertest.cpp for example. 71 | */ 72 | template 73 | struct StreamTraits { 74 | //! Whether to make local copy of stream for optimization during parsing. 75 | /*! 76 | By default, for safety, streams do not use local copy optimization. 77 | Stream that can be copied fast should specialize this, like StreamTraits. 78 | */ 79 | enum { copyOptimization = 0 }; 80 | }; 81 | 82 | //! Reserve n characters for writing to a stream. 83 | template 84 | inline void PutReserve(Stream& stream, size_t count) { 85 | (void)stream; 86 | (void)count; 87 | } 88 | 89 | //! Write character to a stream, presuming buffer is reserved. 90 | template 91 | inline void PutUnsafe(Stream& stream, typename Stream::Ch c) { 92 | stream.Put(c); 93 | } 94 | 95 | //! Put N copies of a character to a stream. 96 | template 97 | inline void PutN(Stream& stream, Ch c, size_t n) { 98 | PutReserve(stream, n); 99 | for (size_t i = 0; i < n; i++) 100 | PutUnsafe(stream, c); 101 | } 102 | 103 | /////////////////////////////////////////////////////////////////////////////// 104 | // GenericStreamWrapper 105 | 106 | //! A Stream Wrapper 107 | /*! \tThis string stream is a wrapper for any stream by just forwarding any 108 | \treceived message to the origin stream. 109 | \note implements Stream concept 110 | */ 111 | 112 | #if defined(_MSC_VER) && _MSC_VER <= 1800 113 | RAPIDJSON_DIAG_PUSH 114 | RAPIDJSON_DIAG_OFF(4702) // unreachable code 115 | RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated 116 | #endif 117 | 118 | template > 119 | class GenericStreamWrapper { 120 | public: 121 | typedef typename Encoding::Ch Ch; 122 | GenericStreamWrapper(InputStream& is): is_(is) {} 123 | 124 | Ch Peek() const { return is_.Peek(); } 125 | Ch Take() { return is_.Take(); } 126 | size_t Tell() { return is_.Tell(); } 127 | Ch* PutBegin() { return is_.PutBegin(); } 128 | void Put(Ch ch) { is_.Put(ch); } 129 | void Flush() { is_.Flush(); } 130 | size_t PutEnd(Ch* ch) { return is_.PutEnd(ch); } 131 | 132 | // wrapper for MemoryStream 133 | const Ch* Peek4() const { return is_.Peek4(); } 134 | 135 | // wrapper for AutoUTFInputStream 136 | UTFType GetType() const { return is_.GetType(); } 137 | bool HasBOM() const { return is_.HasBOM(); } 138 | 139 | protected: 140 | InputStream& is_; 141 | }; 142 | 143 | #if defined(_MSC_VER) && _MSC_VER <= 1800 144 | RAPIDJSON_DIAG_POP 145 | #endif 146 | 147 | /////////////////////////////////////////////////////////////////////////////// 148 | // StringStream 149 | 150 | //! Read-only string stream. 151 | /*! \note implements Stream concept 152 | */ 153 | template 154 | struct GenericStringStream { 155 | typedef typename Encoding::Ch Ch; 156 | 157 | GenericStringStream(const Ch *src) : src_(src), head_(src) {} 158 | 159 | Ch Peek() const { return *src_; } 160 | Ch Take() { return *src_++; } 161 | size_t Tell() const { return static_cast(src_ - head_); } 162 | 163 | Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 164 | void Put(Ch) { RAPIDJSON_ASSERT(false); } 165 | void Flush() { RAPIDJSON_ASSERT(false); } 166 | size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } 167 | 168 | const Ch* src_; //!< Current read position. 169 | const Ch* head_; //!< Original head of the string. 170 | }; 171 | 172 | template 173 | struct StreamTraits > { 174 | enum { copyOptimization = 1 }; 175 | }; 176 | 177 | //! String stream with UTF8 encoding. 178 | typedef GenericStringStream > StringStream; 179 | 180 | /////////////////////////////////////////////////////////////////////////////// 181 | // InsituStringStream 182 | 183 | //! A read-write string stream. 184 | /*! This string stream is particularly designed for in-situ parsing. 185 | \note implements Stream concept 186 | */ 187 | template 188 | struct GenericInsituStringStream { 189 | typedef typename Encoding::Ch Ch; 190 | 191 | GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} 192 | 193 | // Read 194 | Ch Peek() { return *src_; } 195 | Ch Take() { return *src_++; } 196 | size_t Tell() { return static_cast(src_ - head_); } 197 | 198 | // Write 199 | void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; } 200 | 201 | Ch* PutBegin() { return dst_ = src_; } 202 | size_t PutEnd(Ch* begin) { return static_cast(dst_ - begin); } 203 | void Flush() {} 204 | 205 | Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; } 206 | void Pop(size_t count) { dst_ -= count; } 207 | 208 | Ch* src_; 209 | Ch* dst_; 210 | Ch* head_; 211 | }; 212 | 213 | template 214 | struct StreamTraits > { 215 | enum { copyOptimization = 1 }; 216 | }; 217 | 218 | //! Insitu string stream with UTF8 encoding. 219 | typedef GenericInsituStringStream > InsituStringStream; 220 | 221 | RAPIDJSON_NAMESPACE_END 222 | 223 | #endif // RAPIDJSON_STREAM_H_ 224 | -------------------------------------------------------------------------------- /include/rapidjson/stringbuffer.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_STRINGBUFFER_H_ 16 | #define RAPIDJSON_STRINGBUFFER_H_ 17 | 18 | #include "stream.h" 19 | #include "internal/stack.h" 20 | 21 | #if RAPIDJSON_HAS_CXX11_RVALUE_REFS 22 | #include // std::move 23 | #endif 24 | 25 | #include "internal/stack.h" 26 | 27 | #if defined(__clang__) 28 | RAPIDJSON_DIAG_PUSH 29 | RAPIDJSON_DIAG_OFF(c++98-compat) 30 | #endif 31 | 32 | RAPIDJSON_NAMESPACE_BEGIN 33 | 34 | //! Represents an in-memory output stream. 35 | /*! 36 | \tparam Encoding Encoding of the stream. 37 | \tparam Allocator type for allocating memory buffer. 38 | \note implements Stream concept 39 | */ 40 | template 41 | class GenericStringBuffer { 42 | public: 43 | typedef typename Encoding::Ch Ch; 44 | 45 | GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} 46 | 47 | #if RAPIDJSON_HAS_CXX11_RVALUE_REFS 48 | GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {} 49 | GenericStringBuffer& operator=(GenericStringBuffer&& rhs) { 50 | if (&rhs != this) 51 | stack_ = std::move(rhs.stack_); 52 | return *this; 53 | } 54 | #endif 55 | 56 | void Put(Ch c) { *stack_.template Push() = c; } 57 | void PutUnsafe(Ch c) { *stack_.template PushUnsafe() = c; } 58 | void Flush() {} 59 | 60 | void Clear() { stack_.Clear(); } 61 | void ShrinkToFit() { 62 | // Push and pop a null terminator. This is safe. 63 | *stack_.template Push() = '\0'; 64 | stack_.ShrinkToFit(); 65 | stack_.template Pop(1); 66 | } 67 | 68 | void Reserve(size_t count) { stack_.template Reserve(count); } 69 | Ch* Push(size_t count) { return stack_.template Push(count); } 70 | Ch* PushUnsafe(size_t count) { return stack_.template PushUnsafe(count); } 71 | void Pop(size_t count) { stack_.template Pop(count); } 72 | 73 | const Ch* GetString() const { 74 | // Push and pop a null terminator. This is safe. 75 | *stack_.template Push() = '\0'; 76 | stack_.template Pop(1); 77 | 78 | return stack_.template Bottom(); 79 | } 80 | 81 | //! Get the size of string in bytes in the string buffer. 82 | size_t GetSize() const { return stack_.GetSize(); } 83 | 84 | //! Get the length of string in Ch in the string buffer. 85 | size_t GetLength() const { return stack_.GetSize() / sizeof(Ch); } 86 | 87 | static const size_t kDefaultCapacity = 256; 88 | mutable internal::Stack stack_; 89 | 90 | private: 91 | // Prohibit copy constructor & assignment operator. 92 | GenericStringBuffer(const GenericStringBuffer&); 93 | GenericStringBuffer& operator=(const GenericStringBuffer&); 94 | }; 95 | 96 | //! String buffer with UTF8 encoding 97 | typedef GenericStringBuffer > StringBuffer; 98 | 99 | template 100 | inline void PutReserve(GenericStringBuffer& stream, size_t count) { 101 | stream.Reserve(count); 102 | } 103 | 104 | template 105 | inline void PutUnsafe(GenericStringBuffer& stream, typename Encoding::Ch c) { 106 | stream.PutUnsafe(c); 107 | } 108 | 109 | //! Implement specialized version of PutN() with memset() for better performance. 110 | template<> 111 | inline void PutN(GenericStringBuffer >& stream, char c, size_t n) { 112 | std::memset(stream.stack_.Push(n), c, n * sizeof(c)); 113 | } 114 | 115 | RAPIDJSON_NAMESPACE_END 116 | 117 | #if defined(__clang__) 118 | RAPIDJSON_DIAG_POP 119 | #endif 120 | 121 | #endif // RAPIDJSON_STRINGBUFFER_H_ 122 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use pairing::Engine; 3 | use ff::{PrimeField}; 4 | use sha2::Digest; 5 | 6 | pub fn is_vec_fr_equal(a: &Vec, b: &Vec) -> bool { 7 | (a.len() == b.len()) && 8 | a.iter() 9 | .zip(b) 10 | .all(|(a, b)| a == b) 11 | } 12 | 13 | pub fn is_vec_g1_equal(a: &Vec, b: &Vec) -> bool { 14 | (a.len() == b.len()) && 15 | a.iter() 16 | .zip(b) 17 | .all(|(a, b)| a == b) 18 | } 19 | 20 | pub fn is_vec_g2_equal(a: &Vec, b: &Vec) -> bool { 21 | (a.len() == b.len()) && 22 | a.iter() 23 | .zip(b) 24 | .all(|(a, b)| a == b) 25 | } 26 | 27 | pub fn encode_as_hexstring(bytes: &Vec) -> String { 28 | let mut ser_hex = hex::encode(bytes); 29 | ser_hex.insert(0, '"'); 30 | ser_hex.push('"'); 31 | return ser_hex; 32 | } 33 | 34 | pub fn hash_g1_to_fr(x: &Vec) -> E::Fr { 35 | let mut x_vec: Vec = Vec::new(); 36 | for i in x.iter() { 37 | x_vec.extend(format!("{}", i).bytes()); 38 | } 39 | hash_to_fr::(x_vec) 40 | } 41 | 42 | pub fn hash_g2_to_fr(x: &E::G2) -> E::Fr { 43 | let mut x_vec: Vec = Vec::new(); 44 | x_vec.extend(format!("{}", x).bytes()); 45 | hash_to_fr::(x_vec) 46 | } 47 | 48 | pub fn fmt_bytes_to_int(bytearray: [u8; 32]) -> String { 49 | let mut result: String = "".to_string(); 50 | for byte in bytearray.iter() { 51 | // Decide if you want upper- or lowercase results, 52 | // padding the values to two characters, spaces 53 | // between bytes, etc. 54 | let s = format!("{}", *byte as u8); 55 | result = result + &s; 56 | } 57 | let s = match result.starts_with('0') { 58 | true => result[1..].to_string(), 59 | false => result.to_string() 60 | }; 61 | return s; 62 | } 63 | 64 | 65 | pub fn compute_the_hash(bytes: &Vec) -> E::Fr { 66 | let mut hasher = sha2::Sha256::new(); 67 | hasher.input(&bytes.as_slice()); 68 | let sha2_digest = hasher.result(); 69 | let mut hash_buf: [u8; 32] = [0; 32]; 70 | hash_buf.copy_from_slice(&sha2_digest); 71 | let hexresult = fmt_bytes_to_int(hash_buf); 72 | return E::Fr::from_str(&hexresult).unwrap(); 73 | } 74 | 75 | pub fn hash_to_fr(byteVec: Vec) -> E::Fr { 76 | return compute_the_hash::(&byteVec); 77 | } 78 | 79 | pub fn hash_pubkey_to_fr(wpk: &secp256k1::PublicKey) -> E::Fr { 80 | let x_slice = wpk.serialize_uncompressed(); 81 | return compute_the_hash::(&x_slice.to_vec()); 82 | } 83 | 84 | pub fn convert_int_to_fr(value: i64) -> E::Fr { 85 | if value > 0 { 86 | return E::Fr::from_str(value.to_string().as_str()).unwrap(); 87 | } else { 88 | // negative value 89 | let value2 = value * -1; 90 | let mut res = E::Fr::zero(); 91 | let val = E::Fr::from_str(value2.to_string().as_str()).unwrap(); 92 | res.sub_assign(&val); 93 | return res; 94 | } 95 | } 96 | 97 | pub fn compute_pub_key_fingerprint(wpk: &secp256k1::PublicKey) -> String { 98 | let x_slice = wpk.serialize(); 99 | let mut hasher = sha2::Sha256::new(); 100 | hasher.input(&x_slice.to_vec()); 101 | let sha2_digest = hasher.result(); 102 | let h = format!("{:x}", HexSlice::new(&sha2_digest[0..16])); 103 | return h; 104 | } 105 | 106 | pub fn hash_buffer_to_fr<'a, E: Engine>(prefix: &'a str, buf: &[u8; 64]) -> E::Fr { 107 | let mut input_buf = Vec::new(); 108 | input_buf.extend_from_slice(prefix.as_bytes()); 109 | input_buf.extend_from_slice(buf); 110 | return compute_the_hash::(&input_buf); 111 | } 112 | 113 | pub fn hash_to_slice(input_buf: &Vec) -> [u8; 32] { 114 | let mut hasher = sha2::Sha256::new(); 115 | hasher.input(&input_buf.as_slice()); 116 | let sha2_digest = hasher.result(); 117 | 118 | let mut hash_buf: [u8; 32] = [0; 32]; 119 | hash_buf.copy_from_slice(&sha2_digest); 120 | return hash_buf; 121 | } 122 | 123 | #[derive(Clone, Serialize, Deserialize)] 124 | pub struct RevokedMessage { 125 | pub msgtype: String, 126 | pub wpk: secp256k1::PublicKey 127 | } 128 | 129 | impl RevokedMessage { 130 | pub fn new(_msgtype: String, _wpk: secp256k1::PublicKey) -> RevokedMessage { 131 | RevokedMessage { 132 | msgtype: _msgtype, wpk: _wpk 133 | } 134 | } 135 | 136 | pub fn hash(&self) -> Vec { 137 | let mut v: Vec = Vec::new(); 138 | let mut input_buf = Vec::new(); 139 | input_buf.extend_from_slice(self.msgtype.as_bytes()); 140 | v.push(hash_to_fr::(input_buf)); 141 | v.push(hash_pubkey_to_fr::(&self.wpk)); 142 | return v; 143 | } 144 | 145 | // return a message digest (32-bytes) 146 | pub fn hash_to_slice(&self) -> [u8; 32] { 147 | let mut input_buf = Vec::new(); 148 | input_buf.extend_from_slice(self.msgtype.as_bytes()); 149 | input_buf.extend_from_slice(&self.wpk.serialize_uncompressed()); 150 | 151 | return hash_to_slice(&input_buf); 152 | } 153 | } 154 | 155 | 156 | #[cfg(test)] 157 | mod tests { 158 | use super::*; 159 | use pairing::bls12_381::{Bls12, G2}; 160 | use pairing::CurveProjective; 161 | 162 | #[test] 163 | fn hash_g2_to_fr_works() { 164 | let mut two = G2::one(); 165 | two.double(); 166 | assert_eq!(format!("{}", hash_g2_to_fr::(&two).into_repr()), 167 | "0x6550a1431236024424ac8e7f65781f244b70a38e5b3c275000a2b91089706868"); 168 | } 169 | 170 | #[test] 171 | fn hash_to_fr_works() { 172 | let mut two = G2::one(); 173 | two.double(); 174 | let mut x_vec: Vec = Vec::new(); 175 | x_vec.extend(format!("{}", two).bytes()); 176 | assert_eq!(format!("{}", hash_to_fr::(x_vec).into_repr()), 177 | "0x6550a1431236024424ac8e7f65781f244b70a38e5b3c275000a2b91089706868"); 178 | } 179 | 180 | #[test] 181 | fn fmt_byte_to_int_works() { 182 | assert_eq!(fmt_bytes_to_int([12, 235, 23, 123, 13, 43, 12, 235, 23, 123, 13, 43, 12, 235, 23, 123, 13, 43, 12, 235, 23, 123, 13, 43, 12, 235, 23, 123, 13, 43, 12, 235]), // , 23, 123, 13, 43, 12, 235, 23, 123, 13, 43, 12, 235, 23, 123, 13, 43, 12, 235, 23, 123, 13, 43, 12, 235, 23, 123, 13, 43, 12, 235, 23, 123]), 183 | "122352312313431223523123134312235231231343122352312313431223523123134312235"); 184 | } 185 | 186 | #[test] 187 | fn convert_int_to_fr_works() { 188 | assert_eq!(format!("{}", convert_int_to_fr::(1).into_repr()), 189 | "0x0000000000000000000000000000000000000000000000000000000000000001"); 190 | assert_eq!(format!("{}", convert_int_to_fr::(-1).into_repr()), 191 | "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"); 192 | assert_eq!(format!("{}", convert_int_to_fr::(365).into_repr()), 193 | "0x000000000000000000000000000000000000000000000000000000000000016d"); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/wallet.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use pairing::Engine; 3 | use ff::PrimeField; 4 | use util::hash_to_fr; 5 | use std::fmt; 6 | 7 | #[derive(Clone, Serialize, Deserialize)] 8 | #[serde(bound(serialize = "::Fr: serde::Serialize"))] 9 | #[serde(bound(deserialize = "::Fr: serde::Deserialize<'de>"))] 10 | pub struct Wallet { 11 | pub channelId: E::Fr, 12 | pub wpk: E::Fr, 13 | pub bc: i64, 14 | pub bm: i64, 15 | pub close: Option, 16 | } 17 | 18 | impl Wallet { 19 | pub fn as_fr_vec(&self) -> Vec { 20 | if self.close.is_some() { 21 | vec!(self.channelId, self.wpk, E::Fr::from_str(&self.bc.to_string()).unwrap(), E::Fr::from_str(&self.bm.to_string()).unwrap(), self.close.unwrap()) 22 | } else { 23 | vec!(self.channelId, self.wpk, E::Fr::from_str(&self.bc.to_string()).unwrap(), E::Fr::from_str(&self.bm.to_string()).unwrap()) 24 | } 25 | } 26 | 27 | pub fn without_close(&self) -> Vec { 28 | vec!(self.channelId, self.wpk, E::Fr::from_str(&self.bc.to_string()).unwrap(), E::Fr::from_str(&self.bm.to_string()).unwrap()) 29 | } 30 | 31 | pub fn with_close(&mut self, msg: String) -> Vec { 32 | let m = hash_to_fr::(msg.into_bytes() ); 33 | self.close = Some(m.clone()); 34 | return self.as_fr_vec(); 35 | } 36 | } 37 | 38 | impl fmt::Display for Wallet { 39 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 40 | if self.close.is_some() { 41 | let close_str = self.close.unwrap(); 42 | write!(f, "Wallet : (\nchannelId={}\nwpk={}\nbc={}\nbm={}\nclose={}\n)", &self.channelId, &self.wpk, &self.bc, &self.bm, close_str) 43 | } else { 44 | write!(f, "Wallet : (\nchannelId={}\nwpk={}\nbc={}\nbm={}\nclose=None\n)", &self.channelId, &self.wpk, &self.bc, &self.bm) 45 | } 46 | } 47 | } 48 | 49 | --------------------------------------------------------------------------------