***Description:*** ${{github.event.release.body}} "
server: "matrix.parity.io"
parity-scale-codec-3.6.4/.gitignore 0000644 0000000 0000000 00000000067 10461020230 0015301 0 ustar 0000000 0000000 target/
.DS*
.*.swp
.idea
.vscode
.DS_Store
Cargo.lock
parity-scale-codec-3.6.4/.gitlab-ci.yml 0000644 0000000 0000000 00000013271 10461020230 0015746 0 ustar 0000000 0000000 # .gitlab-ci.yml
#
stages:
- check
- test
- build
variables:
GIT_STRATEGY: fetch
GIT_DEPTH: "100"
CARGO_INCREMENTAL: 0
CI_IMAGE: "paritytech/ci-unified:bullseye-1.70.0-2023-05-23"
default:
cache: {}
interruptible: true
retry:
max: 2
when:
- runner_system_failure
- unknown_failure
- api_failure
.docker-env: &docker-env
image: $CI_IMAGE
before_script:
- cargo -vV
- rustc -vV
- rustup show
- bash --version
rules:
- if: $CI_PIPELINE_SOURCE == "trigger"
- if: $CI_PIPELINE_SOURCE == "web"
- if: $CI_PIPELINE_SOURCE == "schedule"
- if: $CI_COMMIT_REF_NAME == "master"
- if: $CI_COMMIT_REF_NAME == "tags"
- if: $CI_COMMIT_REF_NAME =~ /^[0-9]+$/ # PRs
- if: $CI_COMMIT_REF_NAME =~ /^v[0-9]+\.[0-9]+.*$/ # i.e. v1.0, v2.1rc1
tags:
- linux-docker-vm-c2
#### stage: check
check-clippy:
stage: check
<<: *docker-env
script:
- rustup component add clippy --toolchain stable-x86_64-unknown-linux-gnu
- time cargo +stable clippy --locked -- -Dwarnings
- time cargo +stable clippy --locked -p parity-scale-codec-derive -- -Dwarnings
- time cargo +stable clippy --locked --test clippy -- -Dwarnings
check-rust-stable-no_derive_no_std:
stage: check
<<: *docker-env
variables:
RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings"
script:
- time cargo +stable check --verbose --no-default-features --features bit-vec,bytes,generic-array
check-rust-stable-no_std-chain-error:
stage: check
<<: *docker-env
variables:
RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings"
script:
- time cargo +stable check --verbose --no-default-features --features chain-error
check-rust-stable-no_derive:
stage: check
<<: *docker-env
variables:
RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings"
script:
- time cargo +stable check --verbose --features bit-vec,bytes,generic-array
check-rust-stable-only_mel:
stage: check
<<: *docker-env
variables:
RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings"
script:
- time cargo +stable check --verbose --features max-encoded-len
#### stage: test
test-rust-stable:
stage: test
<<: *docker-env
variables:
RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings"
script:
- time cargo +stable test --verbose --all --features bit-vec,bytes,generic-array,derive,max-encoded-len
test-rust-stable-no_derive:
stage: test
<<: *docker-env
variables:
RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings"
script:
- time cargo +stable test --verbose --features bit-vec,bytes,generic-array
test-rust-stable-only_mel:
stage: test
<<: *docker-env
variables:
RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings"
script:
- time cargo +stable test --verbose --features max-encoded-len
test-rust-stable-only_mel-no_default_std:
stage: test
<<: *docker-env
variables:
RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings"
script:
- time cargo +stable test --verbose --features max-encoded-len,std --no-default-features
bench-rust-nightly:
stage: test
<<: *docker-env
script:
- time cargo +nightly bench --features bit-vec,bytes,generic-array,derive
miri:
stage: test
<<: *docker-env
variables:
RUST_BACKTRACE: 1
MIRIFLAGS: "-Zmiri-disable-isolation"
script:
- time cargo +nightly miri test --features bit-vec,bytes,generic-array,arbitrary --release
# check that build is no_std compatible
# more info: https://github.com/paritytech/parity-scale-codec/pull/389
build-no-std:
stage: test
<<: *docker-env
variables:
RUST_BACKTRACE: 1
script:
# this target doesn't support std envs; it should flag any unexpected uses of std
- rustup target add thumbv6m-none-eabi
- time cargo build --target thumbv6m-none-eabi --no-default-features
build-no-atomic-ptrs:
stage: test
<<: *docker-env
variables:
RUST_BACKTRACE: 1
script:
# this target doesn't have atomic ptrs. Some parts of alloc are not available there
# we want to make sure that this crate still works on those targets
- cargo +nightly check --target bpfel-unknown-none -Zbuild-std="core,alloc" --no-default-features --features generic-array,derive,max-encoded-len,chain-error
#### stage: build
build-linux-ubuntu-amd64:
stage: build
<<: *docker-env
rules:
- if: $CI_PIPELINE_SOURCE == "web"
- if: $CI_PIPELINE_SOURCE == "schedule"
- if: $CI_COMMIT_REF_NAME == "master"
- if: $CI_COMMIT_REF_NAME == "tags"
script:
- cargo build --verbose --release --features bit-vec,bytes,generic-array,derive
parity-scale-codec-3.6.4/CHANGELOG.md 0000644 0000000 0000000 00000020015 10461020230 0015115 0 ustar 0000000 0000000 # Changelog
All notable changes to this crate are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this crate adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [3.6.4] - 2023-07-14
### Added
- Now `#[derive(Encode)]` implements the `size_hint()` method for structures and enumerations.
This improves the performance of the `encode()` method by pre-allocating memory.
## [3.6.3] - 2023-07-03
### Fixed
- Provide full path to elements from `::core` in `Decode` derivation (caused compilation error when
`no-implicit-prelude` was used).
## [3.6.2] - 2023-06-30
### Fixed
- Trying to deserialize a boxed newtype containing a big array won't overflow the stack anymore.
## [3.6.1] - 2023-06-19
### Fixed
- Deriving `Decode` will not trigger clippy warnings anymore
## [3.6.0] - 2023-06-15
### Added
- Added `Decode::decode_into` to allow deserializing into unitialized memory.
- Added a `DecodeFinished` type to be used with `Decode::decode_into`.
### Fixed
- Trying to deserialize a big boxed array (e.g. `Box<[u8; 1024 * 1024 * 1024]>`) won't overflow the stack anymore.
- Trying to deserialize big nested enums with many variants won't overflow the stack anymore.
- Elements of partially read arrays will now be properly dropped if the whole array wasn't decoded.
### Changed
- The derive macros will now be reexported only when the `derive` feature is enabled,
as opposed to how it was previously where enabling `parity-scale-codec-derive` would suffice.
- The `max-encoded-len` feature won't automatically enable the derive macros nor pull in the
`parity-scale-codec-derive` dependency.
## [3.5.0]
### Added
- `ConstEncodedLen` marker trait for types that implement `MaxEncodedLen`. [#428](https://github.com/paritytech/parity-scale-codec/pull/428)
## [3.4.0]
This release renders the `full` feature defunct. The implementations guarded behind
this feature are now always provided.
### Changes
- All implementations guarded behind `full` are not unconditionally implemented.
## [3.3.0]
This release exports `decode_vec_with_len` to support custom decoding of `Vec`s.
### Added
- Export `decode_vec_with_len`.
## [3.2.1] - 2022-09-14
This release fixes compilation on no-std envs.
### Changed
- Use core RangeInclusive instead of std [#378](https://github.com/paritytech/parity-scale-codec/pull/378)
## [3.2.0] - 2022-09-13
This release (specifically [#375](https://github.com/paritytech/parity-scale-codec/pull/375)) bumps the MSRV to 1.60.0 as it depends on the Cargo.toml weak dependency feature.
### Changed
- Don't include bitvec with std feature unless asked for explicitly. [#375](https://github.com/paritytech/parity-scale-codec/pull/375)
- Implement `MaxEncodedLen` on more core lib types. [#350](https://github.com/paritytech/parity-scale-codec/pull/350)
## [3.1.5] - 2022-06-11
A quick release to fix an issue introduced in 3.1.4 that broke compiling on no-std.
### Changed
- Fix compiling on no-std. (see https://github.com/paritytech/parity-scale-codec/commit/c25f14a46546c75e4208363ced9d89aa81c85e7f)
## [3.1.3] - 2022-06-10
### Changed
- Impl `MaxEncodedLen` for `Box`. [#349](https://github.com/paritytech/parity-scale-codec/pull/349)
- Add `decode_from_bytes`. [#342](https://github.com/paritytech/parity-scale-codec/pull/342)
## [3.1.2] - 2022-03-22
Be aware that version 3.0.0. up to 3.1.1 contained some bugs in the `BitVec` encoder that could lead to an invalid encoding. Thus, we yanked these crate version and it is advised to upgrade to 3.1.2. Any release before 3.0.0 wasn't affected by this bug.
### Changed
- Optimised the `Decode::decode` for `[T; N]` by @xgreenx. [#299](https://github.com/paritytech/parity-scale-codec/pull/299)
- Add some doc for the derive macro by @thiolliere. [#301](https://github.com/paritytech/parity-scale-codec/pull/301)
- Add bytes::Bytes implementation by @vorot93. [#309](https://github.com/paritytech/parity-scale-codec/pull/309)
- Upgrade to BitVec 1.0 by @bkchr. [#311](https://github.com/paritytech/parity-scale-codec/pull/311)
- BREAKING CHANGE: DecodeLimit and DecodeAll extensions now advance input by @wigy-opensource-developer. [#314](https://github.com/paritytech/parity-scale-codec/pull/314)
- Make `CompactRef` public by @andrenth. [#321](https://github.com/paritytech/parity-scale-codec/pull/321)
- Add ability to re-export parity-scale-codec crate by @gshep. [#325](https://github.com/paritytech/parity-scale-codec/pull/325)
- BitVec: Improve the encoding and consolidate the implementations by @bkchr. [#327](https://github.com/paritytech/parity-scale-codec/pull/327)
- Fix crate access by putting a leading `::` by @bkchr. [#328](https://github.com/paritytech/parity-scale-codec/pull/328)
## [3.0.0] - 2022-02-02
### Fix
- Optimised the Decode::decode for [T; N] [#299](https://github.com/paritytech/parity-scale-codec/pull/299)
### Changed
- Migrated to 2021 edition, enforcing MSRV of `1.56.1`. [#298](https://github.com/paritytech/parity-scale-codec/pull/298)
- Upgrade to BitVec 1.0 [#311](https://github.com/paritytech/parity-scale-codec/pull/311)
- DecodeLimit and DecodeAll extensions now advance input [#314](https://github.com/paritytech/parity-scale-codec/pull/314)
### Added
- Add bytes::Bytes implementation [#309](https://github.com/paritytech/parity-scale-codec/pull/309)
## [2.3.1] - 2021-09-28
### Fix
- Improve macro hygiene of `Encode` and `Decode` proc. macro expansions. ([#291](https://github.com/paritytech/parity-scale-codec/pull/291), [#293](https://github.com/paritytech/parity-scale-codec/pull/293))
## [2.3.0] - 2021-09-11
### Added
- `decode_and_advance_with_depth_limit` to the `DecodeLimit` trait. This allows advancing the cursor while decoding the input. PR #286
## [2.2.0] - 2021-07-02
### Added
- Add support for custom where bounds `codec(mel_bound(T: MaxEncodedLen))` when deriving the traits. PR #279
- `MaxEncodedLen` trait for items that have a statically known maximum encoded size. ([#268](https://github.com/paritytech/parity-scale-codec/pull/268))
- `#[codec(crate = )]` top-level attribute to be used with the new `MaxEncodedLen`
trait, which allows to specify a different path to the crate that contains the `MaxEncodedLen` trait.
Useful when using generating a type through a macro and this type should implement `MaxEncodedLen` and the final crate doesn't have `parity-scale-codec` as dependency.
## [2.1.3] - 2021-06-14
### Changed
- Lint attributes now pass through to the derived impls of `Encode`, `Decode` and `CompactAs`. PR #272
## [2.1.0] - 2021-04-06
### Fix
- Add support for custom where bounds `codec(encode_bound(T: Encode))` and `codec(decode_bound(T: Decode))` when
deriving the traits. Pr #262
- Switch to const generics for array implementations. Pr #261
## [2.0.1] - 2021-02-26
### Fix
- Fix type inference issue in `Decode` derive macro. Pr #254
## [2.0.0] - 2021-01-26
### Added
- `Decode::skip` allows to skip some encoded types. Pr #243
- `Decode::encoded_fixed_size` allows to get the fixed encoded size of a type. PR #243
- `Error` now contains a chain of causes. This full error description can also be activated on
no std using the feature `chain-error`. PR #242
- `Encode::encoded_size` allows to get the encoded size of a type more efficiently. PR #245
### Changed
- `CompactAs::decode_from` now returns result. This allow for decoding to fail from their compact
form.
- derive macro use literal index e.g. `#[codec(index = 15)]` instead of `#[codec(index = "15")]`
- Version of crates `bitvec` and `generic-array` is updated.
- `Encode::encode_to` now bounds the generic `W: Output + ?Sized` instead of `W: Output`.
- `Output` can now be used as a trait object.
### Removed
- `EncodeAppend::append` is removed in favor of `EncodeAppend::append_or_new`.
- `Output::push` is removed in favor of `Encode::encode_to`.
- Some bounds on `HasCompact::Type` are removed.
- `Error::what` is removed in favor of `Error::to_string` (implemented through trait `Display`).
- `Error::description` is removed in favor of `Error::to_string` (implemented through trait `Display`).
parity-scale-codec-3.6.4/CODEOWNERS 0000644 0000000 0000000 00000001652 10461020230 0014705 0 ustar 0000000 0000000 # Lists some code owners.
#
# A codeowner just oversees some part of the codebase. If an owned file is changed then the
# corresponding codeowner receives a review request. An approval of the codeowner might be
# required for merging a PR (depends on repository settings).
#
# For details about syntax, see:
# https://help.github.com/en/articles/about-code-owners
# But here are some important notes:
#
# - Glob syntax is git-like, e.g. `/core` means the core directory in the root, unlike `core`
# which can be everywhere.
# - Multiple owners are supported.
# - Either handle (e.g, @github_user or @github_org/team) or email can be used. Keep in mind,
# that handles might work better because they are more recognizable on GitHub,
# eyou can use them for mentioning unlike an email.
# - The latest matching rule, if multiple, takes precedence.
# CI
/.github/ @paritytech/ci
/scripts/ @paritytech/ci
/.gitlab-ci.yml @paritytech/ci
parity-scale-codec-3.6.4/Cargo.toml 0000644 00000004154 00000000001 0012520 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.60.0"
name = "parity-scale-codec"
version = "3.6.4"
authors = ["Parity Technologies "]
description = "SCALE - Simple Concatenating Aggregated Little Endians"
readme = "README.md"
categories = ["encoding"]
license = "Apache-2.0"
repository = "https://github.com/paritytech/parity-scale-codec"
[lib]
bench = false
[[bench]]
name = "benches"
harness = false
[dependencies.arbitrary]
version = "1.0.1"
features = ["derive"]
optional = true
[dependencies.arrayvec]
version = "0.7"
default-features = false
[dependencies.bitvec]
version = "1"
features = ["alloc"]
optional = true
default-features = false
[dependencies.byte-slice-cast]
version = "1.2.2"
default-features = false
[dependencies.bytes]
version = "1"
optional = true
default-features = false
[dependencies.generic-array]
version = "0.14.7"
optional = true
[dependencies.impl-trait-for-tuples]
version = "0.2.2"
[dependencies.parity-scale-codec-derive]
version = ">= 3.6.4"
optional = true
default-features = false
[dependencies.serde]
version = "1.0.171"
optional = true
[dev-dependencies.criterion]
version = "0.4.0"
[dev-dependencies.paste]
version = "1"
[dev-dependencies.proptest]
version = "1.2.0"
[dev-dependencies.quickcheck]
version = "1.0"
[dev-dependencies.serde_derive]
version = "1.0"
[dev-dependencies.trybuild]
version = "1.0.81"
[features]
bit-vec = ["bitvec"]
chain-error = []
default = ["std"]
derive = ["parity-scale-codec-derive"]
full = []
fuzz = [
"std",
"arbitrary",
]
max-encoded-len = ["parity-scale-codec-derive?/max-encoded-len"]
std = [
"serde",
"bitvec?/std",
"byte-slice-cast/std",
"chain-error",
]
parity-scale-codec-3.6.4/Cargo.toml.orig 0000644 0000000 0000000 00000003627 10461020230 0016205 0 ustar 0000000 0000000 [package]
name = "parity-scale-codec"
description = "SCALE - Simple Concatenating Aggregated Little Endians"
version = "3.6.4"
authors = ["Parity Technologies "]
license = "Apache-2.0"
repository = "https://github.com/paritytech/parity-scale-codec"
categories = ["encoding"]
edition = "2021"
rust-version = "1.60.0"
[dependencies]
arrayvec = { version = "0.7", default-features = false }
serde = { version = "1.0.171", optional = true }
parity-scale-codec-derive = { path = "derive", version = ">= 3.6.4", default-features = false, optional = true }
bitvec = { version = "1", default-features = false, features = [ "alloc" ], optional = true }
bytes = { version = "1", default-features = false, optional = true }
byte-slice-cast = { version = "1.2.2", default-features = false }
generic-array = { version = "0.14.7", optional = true }
arbitrary = { version = "1.0.1", features = ["derive"], optional = true }
impl-trait-for-tuples = "0.2.2"
[dev-dependencies]
criterion = "0.4.0"
serde_derive = { version = "1.0" }
parity-scale-codec-derive = { path = "derive", default-features = false }
quickcheck = "1.0"
proptest = "1.2.0"
trybuild = "1.0.81"
paste = "1"
[[bench]]
name = "benches"
harness = false
[lib]
bench = false
[features]
default = ["std"]
derive = ["parity-scale-codec-derive"]
std = ["serde", "bitvec?/std", "byte-slice-cast/std", "chain-error"]
bit-vec = ["bitvec"]
fuzz = ["std", "arbitrary"]
# Enables the new `MaxEncodedLen` trait.
# NOTE: This is still considered experimental and is exempt from the usual
# SemVer guarantees. We do not guarantee no code breakage when using this.
max-encoded-len = ["parity-scale-codec-derive?/max-encoded-len"]
# Make error fully descriptive with chaining error message.
# Should not be used in a constrained environment.
chain-error = []
# This does not do anthing anymore. Remove with the next major release.
full = []
[workspace]
members = ["derive", "fuzzer"]
parity-scale-codec-3.6.4/LICENSE 0000644 0000000 0000000 00000026135 10461020230 0014322 0 ustar 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
parity-scale-codec-3.6.4/README.md 0000644 0000000 0000000 00000020335 10461020230 0014570 0 ustar 0000000 0000000 # Parity SCALE Codec
Rust implementation of the SCALE (Simple Concatenated Aggregate Little-Endian) data format
for types used in the Parity Substrate framework.
SCALE is a light-weight format which allows encoding (and decoding) which makes it highly
suitable for resource-constrained execution environments like blockchain runtimes and low-power,
low-memory devices.
It is important to note that the encoding context (knowledge of how the types and data
structures look) needs to be known separately at both encoding and decoding ends.
The encoded data does not include this contextual information.
To get a better understanding of how the encoding is done for different types,
take a look at the ["Type encoding (SCALE)" page in Substrate docs](https://docs.substrate.io/reference/scale-codec/).
## Implementation
The codec is implemented using the following traits:
### Encode
The `Encode` trait is used for encoding of data into the SCALE format. The `Encode` trait
contains the following functions:
* `size_hint(&self) -> usize`: Gets the capacity (in bytes) required for the encoded data.
This is to avoid double-allocation of memory needed for the encoding. It can be an estimate
and does not need to be an exact number. If the size is not known, even no good maximum, then
we can skip this function from the trait implementation. This is required to be a cheap operation,
so should not involve iterations etc.
* `encode_to(&self, dest: &mut T)`: Encodes the value and appends it to a destination
buffer.
* `encode(&self) -> Vec`: Encodes the type data and returns a slice.
* `using_encoded R>(&self, f: F) -> R`: Encodes the type data and
executes a closure on the encoded value. Returns the result from the executed closure.
**Note:** Implementations should override `using_encoded` for value types and `encode_to` for
allocating types. `size_hint` should be implemented for all types, wherever possible. Wrapper
types should override all methods.
### Decode
The `Decode` trait is used for deserialization/decoding of encoded data into the respective
types.
* `fn decode(value: &mut I) -> Result`: Tries to decode the value from
SCALE format to the type it is called on. Returns an `Err` if the decoding fails.
### CompactAs
The `CompactAs` trait is used for wrapping custom types/structs as compact types, which makes
them even more space/memory efficient. The compact encoding is described [here](https://docs.substrate.io/reference/scale-codec/#fn-1).
* `encode_as(&self) -> &Self::As`: Encodes the type (self) as a compact type.
The type `As` is defined in the same trait and its implementation should be compact encode-able.
* `decode_from(_: Self::As) -> Result`: Decodes the type (self) from a compact
encode-able type.
### HasCompact
The `HasCompact` trait, if implemented, tells that the corresponding type is a compact
encode-able type.
### EncodeLike
The `EncodeLike` trait needs to be implemented for each type manually. When using derive, it is
done automatically for you. Basically the trait gives you the opportunity to accept multiple
types to a function that all encode to the same representation.
## Usage Examples
Following are some examples to demonstrate usage of the codec.
### Simple types
```rust
# // Import macros if derive feature is not used.
# #[cfg(not(feature="derive"))]
# use parity_scale_codec_derive::{Encode, Decode};
use parity_scale_codec::{Encode, Decode};
#[derive(Debug, PartialEq, Encode, Decode)]
enum EnumType {
#[codec(index = 15)]
A,
B(u32, u64),
C {
a: u32,
b: u64,
},
}
let a = EnumType::A;
let b = EnumType::B(1, 2);
let c = EnumType::C { a: 1, b: 2 };
a.using_encoded(|ref slice| {
assert_eq!(slice, &b"\x0f");
});
b.using_encoded(|ref slice| {
assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0");
});
c.using_encoded(|ref slice| {
assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0");
});
let mut da: &[u8] = b"\x0f";
assert_eq!(EnumType::decode(&mut da).ok(), Some(a));
let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0";
assert_eq!(EnumType::decode(&mut db).ok(), Some(b));
let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0";
assert_eq!(EnumType::decode(&mut dc).ok(), Some(c));
let mut dz: &[u8] = &[0];
assert_eq!(EnumType::decode(&mut dz).ok(), None);
# fn main() { }
```
### Compact type with HasCompact
```rust
# // Import macros if derive feature is not used.
# #[cfg(not(feature="derive"))]
# use parity_scale_codec_derive::{Encode, Decode};
use parity_scale_codec::{Encode, Decode, Compact, HasCompact};
#[derive(Debug, PartialEq, Encode, Decode)]
struct Test1CompactHasCompact {
#[codec(compact)]
bar: T,
}
#[derive(Debug, PartialEq, Encode, Decode)]
struct Test1HasCompact {
#[codec(encoded_as = "::Type")]
bar: T,
}
let test_val: (u64, usize) = (0u64, 1usize);
let encoded = Test1HasCompact { bar: test_val.0 }.encode();
assert_eq!(encoded.len(), test_val.1);
assert_eq!(>::decode(&mut &encoded[..]).unwrap().bar, test_val.0);
# fn main() { }
```
### Type with CompactAs
```rust
# // Import macros if derive feature is not used.
# #[cfg(not(feature="derive"))]
# use parity_scale_codec_derive::{Encode, Decode};
use serde_derive::{Serialize, Deserialize};
use parity_scale_codec::{Encode, Decode, Compact, HasCompact, CompactAs, Error};
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[derive(PartialEq, Eq, Clone)]
struct StructHasCompact(u32);
impl CompactAs for StructHasCompact {
type As = u32;
fn encode_as(&self) -> &Self::As {
&12
}
fn decode_from(_: Self::As) -> Result {
Ok(StructHasCompact(12))
}
}
impl From> for StructHasCompact {
fn from(_: Compact) -> Self {
StructHasCompact(12)
}
}
#[derive(Debug, PartialEq, Encode, Decode)]
enum TestGenericHasCompact {
A {
#[codec(compact)] a: T
},
}
let a = TestGenericHasCompact::A:: {
a: StructHasCompact(12325678),
};
let encoded = a.encode();
assert_eq!(encoded.len(), 2);
# fn main() { }
```
## Derive attributes
The derive implementation supports the following attributes:
- `codec(dumb_trait_bound)`: This attribute needs to be placed above the type that one of the
trait should be implemented for. It will make the algorithm that determines the to-add trait
bounds fall back to just use the type parameters of the type. This can be useful for situation
where the algorithm includes private types in the public interface. By using this attribute,
you should not get this error/warning again.
- `codec(skip)`: Needs to be placed above a field or variant and makes it to be skipped while
encoding/decoding.
- `codec(compact)`: Needs to be placed above a field and makes the field use compact encoding.
(The type needs to support compact encoding.)
- `codec(encoded_as = "OtherType")`: Needs to be placed above a field and makes the field being
encoded by using `OtherType`.
- `codec(index = 0)`: Needs to be placed above an enum variant to make the variant use the given
index when encoded. By default the index is determined by counting from `0` beginning wth the
first variant.
- `codec(encode_bound)`, `codec(decode_bound)` and `codec(mel_bound)`: All 3 attributes take
in a `where` clause for the `Encode`, `Decode` and `MaxEncodedLen` trait implementation for
the annotated type respectively.
- `codec(encode_bound(skip_type_params))`, `codec(decode_bound(skip_type_params))` and
`codec(mel_bound(skip_type_params))`: All 3 sub-attributes take in types as arguments to skip
trait derivation of the corresponding trait, e.g. T in
`codec(encode_bound(skip_type_params(T)))` will not contain a `Encode` trait bound while
`Encode` is being derived for the annotated type.
## Known issues
Even though this crate supports deserialization of arbitrarily sized array (e.g. `[T; 1024 * 1024 * 1024]`)
using such types is not recommended and will most likely result in a stack overflow. If you have a big
array inside of your structure which you want to decode you should wrap it in a `Box`, e.g. `Box<[T; 1024 * 1024 * 1024]>`.
-------------------------
License: Apache-2.0
parity-scale-codec-3.6.4/benches/benches.rs 0000644 0000000 0000000 00000016354 10461020230 0016703 0 ustar 0000000 0000000 // Copyright 2019 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{time::Duration, any::type_name, convert::{TryFrom, TryInto}};
#[cfg(feature = "bit-vec")]
use bitvec::{vec::BitVec, order::Lsb0};
use criterion::{Criterion, black_box, Bencher, criterion_group, criterion_main};
use parity_scale_codec::*;
use parity_scale_codec_derive::{Encode, Decode};
fn array_vec_write_u128(b: &mut Bencher) {
b.iter(|| {
for b in 0..black_box(1_000_000) {
let a = 0xffff_ffff_ffff_ffff_ffff_u128;
Compact(a ^ b).using_encoded(|x| {
black_box(x).len()
});
}
});
}
fn test_vec, &[u8])>(b: &mut Bencher, f: F) {
let f = black_box(f);
let x = black_box([0xff; 10240]);
b.iter(|| {
for _b in 0..black_box(10_000) {
let mut vec = Vec::::new();
f(&mut vec, &x);
}
});
}
fn vec_write_as_output(b: &mut Bencher) {
test_vec(b, |vec, a| {
Output::write(vec, a);
});
}
fn vec_extend(b: &mut Bencher) {
test_vec(b, |vec, a| {
vec.extend(a);
});
}
fn vec_extend_from_slice(b: &mut Bencher) {
test_vec(b, |vec, a| {
vec.extend_from_slice(a);
});
}
struct NoLimitInput<'a>(&'a [u8]);
impl<'a> Input for NoLimitInput<'a> {
fn remaining_len(&mut self) -> Result