1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

//! Module describing the indexation payload.

mod padded;

use alloc::boxed::Box;
use core::ops::RangeInclusive;

use bee_common::packable::{Packable, Read, Write};

pub use self::padded::{PaddedIndex, INDEXATION_PADDED_INDEX_LENGTH};
use crate::{Error, MESSAGE_LENGTH_MAX};

/// Valid lengths for an indexation payload index.
pub const INDEXATION_INDEX_LENGTH_RANGE: RangeInclusive<usize> = 1..=INDEXATION_PADDED_INDEX_LENGTH;

/// A payload which holds an index and associated data.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IndexationPayload {
    index: Box<[u8]>,
    data: Box<[u8]>,
}

impl IndexationPayload {
    /// The payload kind of an `IndexationPayload`.
    pub const KIND: u32 = 2;

    /// Creates a new `IndexationPayload`.
    pub fn new(index: &[u8], data: &[u8]) -> Result<Self, Error> {
        if !INDEXATION_INDEX_LENGTH_RANGE.contains(&index.len()) {
            return Err(Error::InvalidIndexationIndexLength(index.len()));
        }

        if data.len() > MESSAGE_LENGTH_MAX {
            return Err(Error::InvalidIndexationDataLength(data.len()));
        }

        Ok(Self {
            index: index.into(),
            data: data.into(),
        })
    }

    /// Returns the index of an `IndexationPayload`.
    pub fn index(&self) -> &[u8] {
        &self.index
    }

    /// Returns the padded index of an `IndexationPayload`.
    pub fn padded_index(&self) -> PaddedIndex {
        let mut padded_index = [0u8; INDEXATION_PADDED_INDEX_LENGTH];
        padded_index[..self.index.len()].copy_from_slice(&self.index);
        PaddedIndex::from(padded_index)
    }

    /// Returns the data of an `IndexationPayload`.
    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

impl Packable for IndexationPayload {
    type Error = Error;

    fn packed_len(&self) -> usize {
        0u16.packed_len() + self.index.len() + 0u32.packed_len() + self.data.len()
    }

    fn pack<W: Write>(&self, writer: &mut W) -> Result<(), Self::Error> {
        (self.index.len() as u16).pack(writer)?;
        writer.write_all(&self.index)?;

        (self.data.len() as u32).pack(writer)?;
        writer.write_all(&self.data)?;

        Ok(())
    }

    fn unpack_inner<R: Read + ?Sized, const CHECK: bool>(reader: &mut R) -> Result<Self, Self::Error> {
        let index_len = u16::unpack_inner::<R, CHECK>(reader)? as usize;

        if CHECK && !INDEXATION_INDEX_LENGTH_RANGE.contains(&index_len) {
            return Err(Error::InvalidIndexationIndexLength(index_len));
        }

        let mut index = vec![0u8; index_len];
        reader.read_exact(&mut index)?;

        let data_len = u32::unpack_inner::<R, CHECK>(reader)? as usize;

        if CHECK && data_len > MESSAGE_LENGTH_MAX {
            return Err(Error::InvalidIndexationDataLength(data_len));
        }

        let mut data = vec![0u8; data_len];
        reader.read_exact(&mut data)?;

        Ok(Self {
            index: index.into(),
            data: data.into(),
        })
    }
}