scale_encode/impls/
bits.rs

1// Copyright (C) 2023 Parity Technologies (UK) Ltd. (admin@parity.io)
2// This file is a part of the scale-encode crate.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//         http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::{
17    error::{Error, ErrorKind, Kind},
18    EncodeAsType,
19};
20use alloc::{format, vec::Vec};
21use scale_type_resolver::{visitor, TypeResolver};
22
23impl EncodeAsType for scale_bits::Bits {
24    fn encode_as_type_to<R: TypeResolver>(
25        &self,
26        type_id: R::TypeId,
27        types: &R,
28        out: &mut Vec<u8>,
29    ) -> Result<(), crate::Error> {
30        let type_id = super::find_single_entry_with_same_repr(type_id, types);
31
32        let v = visitor::new((type_id.clone(), out), |(type_id, _out), _| {
33            Err(wrong_shape(type_id))
34        })
35        .visit_bit_sequence(|(_type_id, out), store, order| {
36            let format = scale_bits::Format { store, order };
37            scale_bits::encode_using_format_to(self.iter(), format, out);
38            Ok(())
39        });
40
41        super::resolve_type_and_encode(types, type_id, v)
42    }
43}
44
45fn wrong_shape(type_id: impl core::fmt::Debug) -> Error {
46    Error::new(ErrorKind::WrongShape {
47        actual: Kind::BitSequence,
48        expected_id: format!("{type_id:?}"),
49    })
50}