{"id":13477597,"url":"https://github.com/paritytech/parity-scale-codec","last_synced_at":"2025-12-12T16:33:44.094Z","repository":{"id":37862224,"uuid":"148650739","full_name":"paritytech/parity-scale-codec","owner":"paritytech","description":"Lightweight, efficient, binary serialization and deserialization codec","archived":false,"fork":false,"pushed_at":"2025-04-28T20:05:56.000Z","size":1121,"stargazers_count":271,"open_issues_count":61,"forks_count":98,"subscribers_count":19,"default_branch":"master","last_synced_at":"2025-05-08T00:13:02.300Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/paritytech.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":"CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-09-13T14:31:38.000Z","updated_at":"2025-05-06T13:30:28.000Z","dependencies_parsed_at":"2022-07-09T03:47:03.015Z","dependency_job_id":"8f9a19f1-2aa7-4339-9b4c-91ff28dfad06","html_url":"https://github.com/paritytech/parity-scale-codec","commit_stats":{"total_commits":291,"total_committers":66,"mean_commits":4.409090909090909,"dds":0.7938144329896908,"last_synced_commit":"b0099e80b1f6f09ab5cffe27794a11e134403b49"},"previous_names":["paritytech/parity-codec"],"tags_count":80,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paritytech%2Fparity-scale-codec","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paritytech%2Fparity-scale-codec/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paritytech%2Fparity-scale-codec/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paritytech%2Fparity-scale-codec/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/paritytech","download_url":"https://codeload.github.com/paritytech/parity-scale-codec/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254059519,"owners_count":22007771,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T16:01:44.956Z","updated_at":"2025-12-12T16:33:44.029Z","avatar_url":"https://github.com/paritytech.png","language":"Rust","funding_links":[],"categories":["Rust","SCALE Codec","Smart Contract Platforms"],"sub_categories":[],"readme":"# Parity SCALE Codec\n\nRust implementation of the SCALE (Simple Concatenated Aggregate Little-Endian) data format\nfor types used in the Parity Substrate framework.\n\nSCALE is a light-weight format which allows encoding (and decoding) which makes it highly\nsuitable for resource-constrained execution environments like blockchain runtimes and low-power,\nlow-memory devices.\n\nIt is important to note that the encoding context (knowledge of how the types and data\nstructures look) needs to be known separately at both encoding and decoding ends.\nThe encoded data does not include this contextual information.\n\nTo get a better understanding of how the encoding is done for different types,\ntake a look at the [\"Type encoding (SCALE)\" page in Substrate docs](https://docs.substrate.io/reference/scale-codec/).\n\n## Implementation\n\nThe codec is implemented using the following traits:\n\n### Encode\n\nThe `Encode` trait is used for encoding of data into the SCALE format. The `Encode` trait\ncontains the following functions:\n\n* `size_hint(\u0026self) -\u003e usize`: Gets the capacity (in bytes) required for the encoded data.\n  This is to avoid double-allocation of memory needed for the encoding. It can be an estimate\n  and does not need to be an exact number. If the size is not known, even no good maximum, then\n  we can skip this function from the trait implementation. This is required to be a cheap operation,\n  so should not involve iterations etc.\n* `encode_to\u003cT: Output\u003e(\u0026self, dest: \u0026mut T)`: Encodes the value and appends it to a destination\n  buffer.\n* `encode(\u0026self) -\u003e Vec\u003cu8\u003e`: Encodes the type data and returns a slice.\n* `using_encoded\u003cR, F: FnOnce(\u0026[u8]) -\u003e R\u003e(\u0026self, f: F) -\u003e R`: Encodes the type data and\n  executes a closure on the encoded value. Returns the result from the executed closure.\n\n**Note:** Implementations should override `using_encoded` for value types and `encode_to` for\nallocating types. `size_hint` should be implemented for all types, wherever possible. Wrapper\ntypes should override all methods.\n\n### Decode\n\nThe `Decode` trait is used for deserialization/decoding of encoded data into the respective\ntypes.\n\n* `fn decode\u003cI: Input\u003e(value: \u0026mut I) -\u003e Result\u003cSelf, Error\u003e`: Tries to decode the value from\n  SCALE format to the type it is called on. Returns an `Err` if the decoding fails.\n\n### CompactAs\n\nThe `CompactAs` trait is used for wrapping custom types/structs as compact types, which makes\nthem even more space/memory efficient. The compact encoding is described [here](https://docs.substrate.io/reference/scale-codec/#fn-1).\n\n* `encode_as(\u0026self) -\u003e \u0026Self::As`: Encodes the type (self) as a compact type.\n  The type `As` is defined in the same trait and its implementation should be compact encode-able.\n* `decode_from(_: Self::As) -\u003e Result\u003cSelf, Error\u003e`: Decodes the type (self) from a compact\n  encode-able type.\n\n### HasCompact\n\nThe `HasCompact` trait, if implemented, tells that the corresponding type is a compact\nencode-able type.\n\n### EncodeLike\n\nThe `EncodeLike` trait needs to be implemented for each type manually. When using derive, it is\ndone automatically for you. Basically the trait gives you the opportunity to accept multiple\ntypes to a function that all encode to the same representation.\n\n## Usage Examples\n\nFollowing are some examples to demonstrate usage of the codec.\n\n### Simple types\n\n```rust\n# // Import macros if derive feature is not used.\n# #[cfg(not(feature=\"derive\"))]\n# use parity_scale_codec_derive::{Encode, Decode};\n\nuse parity_scale_codec::{Encode, Decode};\n\n#[derive(Debug, PartialEq, Encode, Decode)]\nenum EnumType {\n    #[codec(index = 15)]\n    A,\n    B(u32, u64),\n    C {\n        a: u32,\n        b: u64,\n    },\n}\n\nlet a = EnumType::A;\nlet b = EnumType::B(1, 2);\nlet c = EnumType::C { a: 1, b: 2 };\n\na.using_encoded(|ref slice| {\n    assert_eq!(slice, \u0026b\"\\x0f\");\n});\n\nb.using_encoded(|ref slice| {\n    assert_eq!(slice, \u0026b\"\\x01\\x01\\0\\0\\0\\x02\\0\\0\\0\\0\\0\\0\\0\");\n});\n\nc.using_encoded(|ref slice| {\n    assert_eq!(slice, \u0026b\"\\x02\\x01\\0\\0\\0\\x02\\0\\0\\0\\0\\0\\0\\0\");\n});\n\nlet mut da: \u0026[u8] = b\"\\x0f\";\nassert_eq!(EnumType::decode(\u0026mut da).ok(), Some(a));\n\nlet mut db: \u0026[u8] = b\"\\x01\\x01\\0\\0\\0\\x02\\0\\0\\0\\0\\0\\0\\0\";\nassert_eq!(EnumType::decode(\u0026mut db).ok(), Some(b));\n\nlet mut dc: \u0026[u8] = b\"\\x02\\x01\\0\\0\\0\\x02\\0\\0\\0\\0\\0\\0\\0\";\nassert_eq!(EnumType::decode(\u0026mut dc).ok(), Some(c));\n\nlet mut dz: \u0026[u8] = \u0026[0];\nassert_eq!(EnumType::decode(\u0026mut dz).ok(), None);\n\n# fn main() { }\n```\n\n### Compact type with HasCompact\n\n```rust\n# // Import macros if derive feature is not used.\n# #[cfg(not(feature=\"derive\"))]\n# use parity_scale_codec_derive::{Encode, Decode};\n\nuse parity_scale_codec::{Encode, Decode, Compact, HasCompact};\n\n#[derive(Debug, PartialEq, Encode, Decode)]\nstruct Test1CompactHasCompact\u003cT: HasCompact\u003e {\n    #[codec(compact)]\n    bar: T,\n}\n\n#[derive(Debug, PartialEq, Encode, Decode)]\nstruct Test1HasCompact\u003cT: HasCompact\u003e {\n    #[codec(encoded_as = \"\u003cT as HasCompact\u003e::Type\")]\n    bar: T,\n}\n\nlet test_val: (u64, usize) = (0u64, 1usize);\n\nlet encoded = Test1HasCompact { bar: test_val.0 }.encode();\nassert_eq!(encoded.len(), test_val.1);\nassert_eq!(\u003cTest1CompactHasCompact\u003cu64\u003e\u003e::decode(\u0026mut \u0026encoded[..]).unwrap().bar, test_val.0);\n\n# fn main() { }\n```\n\n### Type with CompactAs\n\n```rust\n# // Import macros if derive feature is not used.\n# #[cfg(not(feature=\"derive\"))]\n# use parity_scale_codec_derive::{Encode, Decode};\n\nuse serde_derive::{Serialize, Deserialize};\nuse parity_scale_codec::{Encode, Decode, Compact, HasCompact, CompactAs, Error};\n\n#[cfg_attr(feature = \"std\", derive(Serialize, Deserialize, Debug))]\n#[derive(PartialEq, Eq, Clone)]\nstruct StructHasCompact(u32);\n\nimpl CompactAs for StructHasCompact {\n    type As = u32;\n\n    fn encode_as(\u0026self) -\u003e \u0026Self::As {\n        \u002612\n    }\n\n    fn decode_from(_: Self::As) -\u003e Result\u003cSelf, Error\u003e {\n        Ok(StructHasCompact(12))\n    }\n}\n\nimpl From\u003cCompact\u003cStructHasCompact\u003e\u003e for StructHasCompact {\n    fn from(_: Compact\u003cStructHasCompact\u003e) -\u003e Self {\n        StructHasCompact(12)\n    }\n}\n\n#[derive(Debug, PartialEq, Encode, Decode)]\nenum TestGenericHasCompact\u003cT\u003e {\n    A {\n        #[codec(compact)] a: T\n    },\n}\n\nlet a = TestGenericHasCompact::A::\u003cStructHasCompact\u003e {\n    a: StructHasCompact(12325678),\n};\n\nlet encoded = a.encode();\nassert_eq!(encoded.len(), 2);\n\n# fn main() { }\n```\n\n## Derive attributes\n\nThe derive implementation supports the following attributes:\n- `codec(dumb_trait_bound)`: This attribute needs to be placed above the type that one of the\n  trait should be implemented for. It will make the algorithm that determines the to-add trait\n  bounds fall back to just use the type parameters of the type. This can be useful for situation\n  where the algorithm includes private types in the public interface. By using this attribute,\n  you should not get this error/warning again.\n- `codec(skip)`: Needs to be placed above a field  or variant and makes it to be skipped while\n  encoding/decoding.\n- `codec(compact)`: Needs to be placed above a field and makes the field use compact encoding.\n  (The type needs to support compact encoding.)\n- `codec(encoded_as = \"OtherType\")`: Needs to be placed above a field and makes the field being\n  encoded by using `OtherType`.\n- `codec(index = 0)`: Needs to be placed above an enum variant to make the variant use the given\n  index when encoded. By default the index is determined by counting from `0` beginning wth the\n  first variant.\n- `codec(encode_bound)`, `codec(decode_bound)` and `codec(mel_bound)`: All 3 attributes take\n  in a `where` clause for the `Encode`, `Decode` and `MaxEncodedLen` trait implementation for\n  the annotated type respectively.\n- `codec(encode_bound(skip_type_params))`, `codec(decode_bound(skip_type_params))` and\n  `codec(mel_bound(skip_type_params))`: All 3 sub-attributes take in types as arguments to skip\n  trait derivation of the corresponding trait, e.g. T in\n  `codec(encode_bound(skip_type_params(T)))` will not contain a `Encode` trait bound while\n  `Encode` is being derived for the annotated type.\n\n## Known issues\n\nEven though this crate supports deserialization of arbitrarily sized array (e.g. `[T; 1024 * 1024 * 1024]`)\nusing such types is not recommended and will most likely result in a stack overflow. If you have a big\narray inside of your structure which you want to decode you should wrap it in a `Box`, e.g. `Box\u003c[T; 1024 * 1024 * 1024]\u003e`.\n\n-------------------------\n\nLicense: Apache-2.0\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparitytech%2Fparity-scale-codec","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fparitytech%2Fparity-scale-codec","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparitytech%2Fparity-scale-codec/lists"}