coap-zero 0.3.0

CoAP protocol implementation for no_std without alloc
Documentation
// Copyright Open Logistics Foundation
//
// Licensed under the Open Logistics Foundation License 1.3.
// For details on the licensing terms, see the LICENSE file.
// SPDX-License-Identifier: OLFL-1.3

#[allow(clippy::enum_variant_names)] // Clippy doesn't like that all variants have the same suffix "Bit", but I think that's fine here
pub(crate) enum EncodedValue {
    FourBit(u8),
    EightBit(u8),
    SixteenBit([u8; 2]),
}

impl EncodedValue {
    pub(crate) fn encode(v: u16) -> EncodedValue {
        if v < 13 {
            EncodedValue::FourBit(v as u8)
        } else if v < 269 {
            EncodedValue::EightBit((v as u8) - 13)
        } else {
            EncodedValue::SixteenBit(u16::to_be_bytes(v - 269))
        }
    }

    pub(crate) fn header_value(&self) -> u8 {
        match *self {
            EncodedValue::FourBit(x) => x,
            EncodedValue::EightBit(_) => 13,
            EncodedValue::SixteenBit(_) => 14,
        }
    }

    pub(crate) fn write_into(&self, buf: &mut [u8]) -> usize {
        match *self {
            EncodedValue::FourBit(_) => 0,
            EncodedValue::EightBit(x) => {
                buf[0] = x;
                1
            }
            EncodedValue::SixteenBit(x) => {
                buf[0] = x[0];
                buf[1] = x[1];
                2
            }
        }
    }
}