serde_bindgen_core/
lib.rs

1// This file is part of the serde-bindgen-core libraries
2// Copyright (C) 2022  Altronix Corp. <thomas.chiantia@gmail.com>
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17// @author Thomas Chiantia <thomas.chiantia@gmail.com>
18// @date 2022
19
20#![no_builtins]
21#![feature(lang_items)]
22#![cfg_attr(not(test), no_std)]
23
24pub use serde;
25pub use serde_bindgen_core_derive::binding;
26pub use serde_json_core;
27pub use serde_json_core::heapless;
28
29#[inline]
30fn safe_copy<T: Copy + Default, const N: usize>(src: &[T]) -> [T; N] {
31    let mut ret: [T; N] = [Default::default(); N];
32    if src.len() < N {
33        ret[..src.len()].copy_from_slice(&src[..src.len()]);
34    } else {
35        ret.copy_from_slice(&src[..N]);
36    }
37    ret
38}
39
40pub trait SafeCopy<Item, const N: usize> {
41    fn safe_copy(&self) -> [Item; N];
42}
43
44macro_rules! impl_safe_copy_for_slice {
45    ($t:ty) => {
46        impl<const N: usize> SafeCopy<$t, N> for &[$t] {
47            #[inline]
48            fn safe_copy(&self) -> [$t; N] {
49                safe_copy(self)
50            }
51        }
52    };
53}
54impl_safe_copy_for_slice!(u8);
55impl_safe_copy_for_slice!(i8);
56
57impl<const N: usize> SafeCopy<u8, N> for &str {
58    #[inline]
59    fn safe_copy(&self) -> [u8; N] {
60        let mut ret = self.as_bytes().safe_copy();
61        // handle case when N == 0.
62        // Probably a better way to do this
63        if N > 0 {
64            ret[N - 1] = 0;
65        }
66        ret
67    }
68}
69
70#[cfg(not(feature = "testing"))]
71#[cfg(not(feature = "full"))]
72#[lang = "eh_personality"]
73fn eh_personality() {}
74
75#[cfg(not(feature = "testing"))]
76#[cfg(not(feature = "full"))]
77#[panic_handler]
78fn panic(_info: &core::panic::PanicInfo) -> ! {
79    loop {}
80}