1 /* 2 * Copyright (c) 2024 Kelly Helmut Lord 3 * 4 * SPDX-License-Identifier: Apache-2.0 5 */ 6 7 #ifndef ZEPHYR_INCLUDE_DATA_COBS_H_ 8 #define ZEPHYR_INCLUDE_DATA_COBS_H_ 9 10 #include <stddef.h> 11 #include <sys/types.h> 12 #include <zephyr/sys/util.h> 13 #include <zephyr/net_buf.h> 14 15 #ifdef __cplusplus 16 extern "C" { 17 #endif 18 19 #define COBS_DEFAULT_DELIMITER 0x00 20 21 /** 22 * Flag indicating that encode and decode should include an implicit end delimiter 23 */ 24 #define COBS_FLAG_TRAILING_DELIMITER BIT(8) 25 26 /** 27 * Macro for extracting delimiter from flags. 8 LSB of "flags" is used for the delimiter 28 * Example usage: 29 * cobs_encode(src_buf, dst_buf, COBS_FLAG_TRAILING_DELIMITER | COBS_FLAG_CUSTOM_DELIMITER(0x7F)); 30 */ 31 #define COBS_FLAG_CUSTOM_DELIMITER(x) ((x) & 0xff) 32 33 /** 34 * @defgroup cobs COBS (Consistent Overhead Byte Stuffing) 35 * @ingroup utilities 36 * @{ 37 * 38 * @brief COBS encoding and decoding functions with custom delimiter support 39 * 40 * Provides functions for COBS encoding/decoding with configurable delimiters. 41 * The implementation handles both standard zero-delimited COBS and custom 42 * delimiter variants. 43 */ 44 45 /** 46 * @brief Calculate maximum encoded buffer size 47 * 48 * @param decoded_size Size of input data to be encoded 49 * @param flags COBS_FLAG_TRAILING_DELIMITER to include termination byte in calculation 50 * 51 * @return Required buffer size for worst-case encoding scenario 52 */ cobs_max_encoded_len(size_t decoded_size,uint32_t flags)53static inline size_t cobs_max_encoded_len(size_t decoded_size, uint32_t flags) 54 { 55 if (flags & COBS_FLAG_TRAILING_DELIMITER) { 56 return decoded_size + decoded_size / 254 + 1 + 1; 57 } else { 58 return decoded_size + decoded_size / 254 + 1; 59 } 60 } 61 62 /** 63 * @brief Standard COBS encoding 64 * 65 * @param src Source buffer to decode 66 * @param dst Destination buffer for decoded data 67 * @param flags Decoding flags (reserved) 68 * 69 * @retval 0 Success 70 * @retval -ENOMEM Insufficient destination space 71 * @retval -EINVAL Invalid COBS structure or parameters 72 */ 73 74 int cobs_encode(struct net_buf *src, struct net_buf *dst, uint32_t flags); 75 76 /** 77 * @brief Standard COBS decoding 78 * 79 * @param src Source buffer to decode 80 * @param dst Destination buffer for decoded data 81 * @param flags Decoding flags (reserved) 82 * 83 * @retval 0 Success 84 * @retval -ENOMEM Insufficient destination space 85 * @retval -EINVAL Invalid COBS structure or parameters 86 */ 87 int cobs_decode(struct net_buf *src, struct net_buf *dst, uint32_t flags); 88 89 /** @} */ 90 91 #ifdef __cplusplus 92 } 93 #endif 94 95 #endif /* ZEPHYR_INCLUDE_DATA_COBS_H_ */ 96