feat: add display UI with splash screen, dashboard, and RSSI sparkline

Implement full SSD1306 OLED display support:
- Splash screen on boot (1.5s) with project name, version, board
- Dashboard showing radio state, config, counters, RSSI/SNR
- RSSI history sparkline (64-sample ring buffer, 2px-wide bars)
- DisplayOn/DisplayOff host commands routed via dedicated channel
- Pure render functions against generic DrawTarget (no hardware coupling)
- Display on/off control bypasses radio task entirely

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 4.6 committed 2026-03-29 20:42:54 -06:00
1 parent 7064110293
commit 3102fc747a
17624 files changed
+4564928 -38

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
use super::Error;
#[doc(hidden)]
pub struct SerializeValueArray {
values: Vec<crate::Item>,
}
impl SerializeValueArray {
pub(crate) fn seq(len: Option<usize>) -> Self {
let mut values = Vec::new();
if let Some(len) = len {
values.reserve(len);
}
Self { values }
}
}
impl serde::ser::SerializeSeq for SerializeValueArray {
type Ok = crate::Value;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
where
T: serde::ser::Serialize + ?Sized,
{
let value = value.serialize(super::ValueSerializer {})?;
self.values.push(crate::Item::Value(value));
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(crate::Value::Array(crate::Array::with_vec(self.values)))
}
}
impl serde::ser::SerializeTuple for SerializeValueArray {
type Ok = crate::Value;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
where
T: serde::ser::Serialize + ?Sized,
{
serde::ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
serde::ser::SerializeSeq::end(self)
}
}
impl serde::ser::SerializeTupleStruct for SerializeValueArray {
type Ok = crate::Value;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
where
T: serde::ser::Serialize + ?Sized,
{
serde::ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
serde::ser::SerializeSeq::end(self)
}
}
pub struct SerializeTupleVariant {
variant: &'static str,
inner: SerializeValueArray,
}
impl SerializeTupleVariant {
pub(crate) fn tuple(variant: &'static str, len: usize) -> Self {
Self {
variant,
inner: SerializeValueArray::seq(Some(len)),
}
}
}
impl serde::ser::SerializeTupleVariant for SerializeTupleVariant {
type Ok = crate::Value;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
where
T: serde::ser::Serialize + ?Sized,
{
serde::ser::SerializeSeq::serialize_element(&mut self.inner, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
let inner = serde::ser::SerializeSeq::end(self.inner)?;
let mut items = crate::table::KeyValuePairs::new();
let value = crate::Item::Value(inner);
items.insert(crate::Key::new(self.variant), value);
Ok(crate::Value::InlineTable(crate::InlineTable::with_pairs(
items,
)))
}
}
+173
View File
@@ -0,0 +1,173 @@
use crate::Key;
use super::Error;
pub(crate) struct KeySerializer;
impl serde::ser::Serializer for KeySerializer {
type Ok = Key;
type Error = Error;
type SerializeSeq = serde::ser::Impossible<Self::Ok, Error>;
type SerializeTuple = serde::ser::Impossible<Self::Ok, Error>;
type SerializeTupleStruct = serde::ser::Impossible<Self::Ok, Error>;
type SerializeTupleVariant = serde::ser::Impossible<Self::Ok, Error>;
type SerializeMap = serde::ser::Impossible<Self::Ok, Error>;
type SerializeStruct = serde::ser::Impossible<Self::Ok, Error>;
type SerializeStructVariant = serde::ser::Impossible<Self::Ok, Error>;
fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
Ok(Key::new(value))
}
fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
Err(Error::key_not_string())
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
Ok(variant.into())
}
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
value.serialize(self)
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
Err(Error::key_not_string())
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
Err(Error::key_not_string())
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
Err(Error::key_not_string())
}
}
+608
View File
@@ -0,0 +1,608 @@
use super::array::SerializeTupleVariant;
use super::array::SerializeValueArray;
use super::key::KeySerializer;
use super::value::ValueSerializer;
use super::Error;
#[doc(hidden)]
#[allow(clippy::large_enum_variant)]
pub enum SerializeMap {
Datetime(SerializeDatetime),
Table(SerializeInlineTable),
}
impl SerializeMap {
pub(crate) fn map(len: Option<usize>) -> Self {
Self::Table(SerializeInlineTable::map(len))
}
pub(crate) fn struct_(name: &'static str, len: Option<usize>) -> Self {
if name == toml_datetime::__unstable::NAME {
Self::Datetime(SerializeDatetime::new())
} else {
Self::map(len)
}
}
}
impl serde::ser::SerializeMap for SerializeMap {
type Ok = crate::Value;
type Error = Error;
fn serialize_key<T>(&mut self, input: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
match self {
Self::Datetime(s) => s.serialize_key(input),
Self::Table(s) => s.serialize_key(input),
}
}
fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
match self {
Self::Datetime(s) => s.serialize_value(value),
Self::Table(s) => s.serialize_value(value),
}
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match self {
Self::Datetime(s) => s.end().map(|items| items.into()),
Self::Table(s) => s.end().map(|items| items.into()),
}
}
}
impl serde::ser::SerializeStruct for SerializeMap {
type Ok = crate::Value;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
match self {
Self::Datetime(s) => s.serialize_field(key, value),
Self::Table(s) => s.serialize_field(key, value),
}
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match self {
Self::Datetime(s) => s.end().map(|items| items.into()),
Self::Table(s) => s.end().map(|items| items.into()),
}
}
}
#[doc(hidden)]
pub struct SerializeDatetime {
value: Option<crate::Datetime>,
}
impl SerializeDatetime {
pub(crate) fn new() -> Self {
Self { value: None }
}
}
impl serde::ser::SerializeMap for SerializeDatetime {
type Ok = crate::Datetime;
type Error = Error;
fn serialize_key<T>(&mut self, _input: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
unreachable!("datetimes should only be serialized as structs, not maps")
}
fn serialize_value<T>(&mut self, _value: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
unreachable!("datetimes should only be serialized as structs, not maps")
}
fn end(self) -> Result<Self::Ok, Self::Error> {
unreachable!("datetimes should only be serialized as structs, not maps")
}
}
impl serde::ser::SerializeStruct for SerializeDatetime {
type Ok = crate::Datetime;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
if key == toml_datetime::__unstable::FIELD {
self.value = Some(value.serialize(DatetimeFieldSerializer::default())?);
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
self.value.ok_or(Error::unsupported_none())
}
}
#[doc(hidden)]
pub struct SerializeInlineTable {
items: crate::table::KeyValuePairs,
key: Option<crate::Key>,
}
impl SerializeInlineTable {
pub(crate) fn map(len: Option<usize>) -> Self {
let mut items: crate::table::KeyValuePairs = Default::default();
let key = Default::default();
if let Some(len) = len {
items.reserve(len);
}
Self { items, key }
}
}
impl serde::ser::SerializeMap for SerializeInlineTable {
type Ok = crate::InlineTable;
type Error = Error;
fn serialize_key<T>(&mut self, input: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
self.key = Some(input.serialize(KeySerializer)?);
Ok(())
}
fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
let mut is_none = false;
let value_serializer = MapValueSerializer::new(&mut is_none);
let res = value.serialize(value_serializer);
match res {
Ok(item) => {
let key = self.key.take().unwrap();
let item = crate::Item::Value(item);
self.items.insert(key, item);
}
Err(e) => {
if !(e == Error::unsupported_none() && is_none) {
return Err(e);
}
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(crate::InlineTable::with_pairs(self.items))
}
}
impl serde::ser::SerializeStruct for SerializeInlineTable {
type Ok = crate::InlineTable;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
let mut is_none = false;
let value_serializer = MapValueSerializer::new(&mut is_none);
let res = value.serialize(value_serializer);
match res {
Ok(item) => {
let item = crate::Item::Value(item);
self.items.insert(crate::Key::new(key), item);
}
Err(e) => {
if !(e == Error::unsupported_none() && is_none) {
return Err(e);
}
}
};
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(crate::InlineTable::with_pairs(self.items))
}
}
#[derive(Default)]
struct DatetimeFieldSerializer {}
impl serde::ser::Serializer for DatetimeFieldSerializer {
type Ok = toml_datetime::Datetime;
type Error = Error;
type SerializeSeq = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeTuple = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeTupleStruct = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeTupleVariant = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeMap = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeStruct = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeStructVariant = serde::ser::Impossible<Self::Ok, Self::Error>;
fn serialize_bool(self, _value: bool) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_i8(self, _value: i8) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_i16(self, _value: i16) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_i32(self, _value: i32) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_i64(self, _value: i64) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_u8(self, _value: u8) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_u16(self, _value: u16) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_u32(self, _value: u32) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_u64(self, _value: u64) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_f32(self, _value: f32) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_f64(self, _value: f64) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_char(self, _value: char) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
v.parse::<toml_datetime::Datetime>().map_err(Error::custom)
}
fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
Err(Error::date_invalid())
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
_value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
Err(Error::date_invalid())
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
Err(Error::date_invalid())
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
Err(Error::date_invalid())
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
Err(Error::date_invalid())
}
}
struct MapValueSerializer<'d> {
is_none: &'d mut bool,
}
impl<'d> MapValueSerializer<'d> {
fn new(is_none: &'d mut bool) -> Self {
Self { is_none }
}
}
impl serde::ser::Serializer for MapValueSerializer<'_> {
type Ok = crate::Value;
type Error = Error;
type SerializeSeq = SerializeValueArray;
type SerializeTuple = SerializeValueArray;
type SerializeTupleStruct = SerializeValueArray;
type SerializeTupleVariant = SerializeTupleVariant;
type SerializeMap = SerializeMap;
type SerializeStruct = SerializeMap;
type SerializeStructVariant = SerializeStructVariant;
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_bool(v)
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_i8(v)
}
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_i16(v)
}
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_i32(v)
}
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_i64(v)
}
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_u8(v)
}
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_u16(v)
}
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_u32(v)
}
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_u64(v)
}
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_f32(v)
}
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_f64(v)
}
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_char(v)
}
fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_str(v)
}
fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_bytes(value)
}
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
*self.is_none = true;
Err(Error::unsupported_none())
}
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
ValueSerializer::new().serialize_some(value)
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_unit()
}
fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_unit_struct(name)
}
fn serialize_unit_variant(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
ValueSerializer::new().serialize_unit_variant(name, variant_index, variant)
}
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
value.serialize(self)
}
fn serialize_newtype_variant<T>(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
ValueSerializer::new().serialize_newtype_variant(name, variant_index, variant, value)
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
ValueSerializer::new().serialize_seq(len)
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
ValueSerializer::new().serialize_tuple(len)
}
fn serialize_tuple_struct(
self,
name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
ValueSerializer::new().serialize_tuple_struct(name, len)
}
fn serialize_tuple_variant(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
ValueSerializer::new().serialize_tuple_variant(name, variant_index, variant, len)
}
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
ValueSerializer::new().serialize_map(len)
}
fn serialize_struct(
self,
name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
ValueSerializer::new().serialize_struct(name, len)
}
fn serialize_struct_variant(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
ValueSerializer::new().serialize_struct_variant(name, variant_index, variant, len)
}
}
pub struct SerializeStructVariant {
variant: &'static str,
inner: SerializeInlineTable,
}
impl SerializeStructVariant {
pub(crate) fn struct_(variant: &'static str, len: usize) -> Self {
Self {
variant,
inner: SerializeInlineTable::map(Some(len)),
}
}
}
impl serde::ser::SerializeStructVariant for SerializeStructVariant {
type Ok = crate::Value;
type Error = Error;
#[inline]
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
serde::ser::SerializeStruct::serialize_field(&mut self.inner, key, value)
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
let inner = serde::ser::SerializeStruct::end(self.inner)?.into();
let mut items = crate::table::KeyValuePairs::new();
let value = crate::Item::Value(inner);
items.insert(crate::Key::new(self.variant), value);
Ok(crate::Value::InlineTable(crate::InlineTable::with_pairs(
items,
)))
}
}
+188
View File
@@ -0,0 +1,188 @@
//! Serializing Rust structures into TOML.
//!
//! This module contains all the Serde support for serializing Rust structures into TOML.
mod array;
mod key;
mod map;
mod pretty;
mod value;
use crate::visit_mut::VisitMut as _;
#[allow(clippy::wildcard_imports)]
use array::*;
#[allow(clippy::wildcard_imports)]
use map::*;
pub use value::ValueSerializer;
/// Serialize the given data structure as a TOML byte vector.
///
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, if `T` contains a map with non-string keys, or if `T` attempts to
/// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
#[cfg(feature = "display")]
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>, Error>
where
T: serde::ser::Serialize + ?Sized,
{
to_string(value).map(|e| e.into_bytes())
}
/// Serialize the given data structure as a String of TOML.
///
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, if `T` contains a map with non-string keys, or if `T` attempts to
/// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
///
/// # Examples
///
/// ```
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Config {
/// database: Database,
/// }
///
/// #[derive(Serialize)]
/// struct Database {
/// ip: String,
/// port: Vec<u16>,
/// connection_max: u32,
/// enabled: bool,
/// }
///
/// let config = Config {
/// database: Database {
/// ip: "192.168.1.1".to_string(),
/// port: vec![8001, 8002, 8003],
/// connection_max: 5000,
/// enabled: false,
/// },
/// };
///
/// let toml = toml_edit::ser::to_string(&config).unwrap();
/// println!("{}", toml)
/// ```
#[cfg(feature = "display")]
pub fn to_string<T>(value: &T) -> Result<String, Error>
where
T: serde::ser::Serialize + ?Sized,
{
to_document(value).map(|e| e.to_string())
}
/// Serialize the given data structure as a "pretty" String of TOML.
///
/// This is identical to `to_string` except the output string has a more
/// "pretty" output. See `ValueSerializer::pretty` for more details.
#[cfg(feature = "display")]
pub fn to_string_pretty<T>(value: &T) -> Result<String, Error>
where
T: serde::ser::Serialize + ?Sized,
{
let mut document = to_document(value)?;
pretty::Pretty::new().visit_document_mut(&mut document);
Ok(document.to_string())
}
/// Serialize the given data structure into a TOML document.
///
/// This would allow custom formatting to be applied, mixing with format preserving edits, etc.
pub fn to_document<T>(value: &T) -> Result<crate::DocumentMut, Error>
where
T: serde::ser::Serialize + ?Sized,
{
let value = value.serialize(ValueSerializer::new())?;
let item = crate::Item::Value(value);
let root = item
.into_table()
.map_err(|_| Error::UnsupportedType(None))?;
Ok(root.into())
}
/// Errors that can occur when deserializing a type.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
/// Type could not be serialized to TOML
UnsupportedType(Option<&'static str>),
/// Value was out of range for the given type
OutOfRange(Option<&'static str>),
/// `None` could not be serialized to TOML
UnsupportedNone,
/// Key was not convertible to `String` for serializing to TOML
KeyNotString,
/// A serialized date was invalid
DateInvalid,
/// Other serialization error
Custom(String),
}
impl Error {
pub(crate) fn custom<T>(msg: T) -> Self
where
T: std::fmt::Display,
{
Error::Custom(msg.to_string())
}
pub(crate) fn unsupported_type(t: Option<&'static str>) -> Self {
Error::UnsupportedType(t)
}
fn out_of_range(t: Option<&'static str>) -> Self {
Error::OutOfRange(t)
}
pub(crate) fn unsupported_none() -> Self {
Error::UnsupportedNone
}
pub(crate) fn key_not_string() -> Self {
Error::KeyNotString
}
fn date_invalid() -> Self {
Error::DateInvalid
}
}
impl serde::ser::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: std::fmt::Display,
{
Self::custom(msg)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UnsupportedType(Some(t)) => write!(formatter, "unsupported {t} type"),
Self::UnsupportedType(None) => write!(formatter, "unsupported rust type"),
Self::OutOfRange(Some(t)) => write!(formatter, "out-of-range value for {t} type"),
Self::OutOfRange(None) => write!(formatter, "out-of-range value"),
Self::UnsupportedNone => "unsupported None value".fmt(formatter),
Self::KeyNotString => "map key was not a string".fmt(formatter),
Self::DateInvalid => "a serialized date was invalid".fmt(formatter),
Self::Custom(s) => s.fmt(formatter),
}
}
}
impl From<crate::TomlError> for Error {
fn from(e: crate::TomlError) -> Error {
Self::custom(e)
}
}
impl From<Error> for crate::TomlError {
fn from(e: Error) -> crate::TomlError {
Self::custom(e.to_string(), None)
}
}
impl std::error::Error for Error {}
+58
View File
@@ -0,0 +1,58 @@
pub(crate) struct Pretty {
in_value: bool,
}
impl Pretty {
pub(crate) fn new() -> Self {
Self { in_value: false }
}
}
impl crate::visit_mut::VisitMut for Pretty {
fn visit_document_mut(&mut self, node: &mut crate::DocumentMut) {
crate::visit_mut::visit_document_mut(self, node);
}
fn visit_item_mut(&mut self, node: &mut crate::Item) {
if !self.in_value {
node.make_item();
}
crate::visit_mut::visit_item_mut(self, node);
}
fn visit_table_mut(&mut self, node: &mut crate::Table) {
node.decor_mut().clear();
// Empty tables could be semantically meaningful, so make sure they are not implicit
if !node.is_empty() {
node.set_implicit(true);
}
crate::visit_mut::visit_table_mut(self, node);
}
fn visit_value_mut(&mut self, node: &mut crate::Value) {
node.decor_mut().clear();
let old_in_value = self.in_value;
self.in_value = true;
crate::visit_mut::visit_value_mut(self, node);
self.in_value = old_in_value;
}
fn visit_array_mut(&mut self, node: &mut crate::Array) {
crate::visit_mut::visit_array_mut(self, node);
if (0..=1).contains(&node.len()) {
node.set_trailing("");
node.set_trailing_comma(false);
} else {
for item in node.iter_mut() {
item.decor_mut().set_prefix("\n ");
}
node.set_trailing("\n");
node.set_trailing_comma(true);
}
}
}
+249
View File
@@ -0,0 +1,249 @@
use super::Error;
use super::SerializeMap;
use super::SerializeStructVariant;
use super::SerializeTupleVariant;
use super::SerializeValueArray;
/// Serialization for TOML [values][crate::Value].
///
/// This structure implements serialization support for TOML to serialize an
/// arbitrary type to TOML. Note that the TOML format does not support all
/// datatypes in Rust, such as enums, tuples, and tuple structs. These types
/// will generate an error when serialized.
///
/// Currently a serializer always writes its output to an in-memory `String`,
/// which is passed in when creating the serializer itself.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "parse")] {
/// # #[cfg(feature = "display")] {
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Config {
/// database: Database,
/// }
///
/// #[derive(Serialize)]
/// struct Database {
/// ip: String,
/// port: Vec<u16>,
/// connection_max: u32,
/// enabled: bool,
/// }
///
/// let config = Config {
/// database: Database {
/// ip: "192.168.1.1".to_string(),
/// port: vec![8001, 8002, 8003],
/// connection_max: 5000,
/// enabled: false,
/// },
/// };
///
/// let value = serde::Serialize::serialize(
/// &config,
/// toml_edit::ser::ValueSerializer::new()
/// ).unwrap();
/// println!("{}", value)
/// # }
/// # }
/// ```
#[derive(Default)]
#[non_exhaustive]
pub struct ValueSerializer {}
impl ValueSerializer {
/// Creates a new serializer generate a TOML document.
pub fn new() -> Self {
Self {}
}
}
impl serde::ser::Serializer for ValueSerializer {
type Ok = crate::Value;
type Error = Error;
type SerializeSeq = SerializeValueArray;
type SerializeTuple = SerializeValueArray;
type SerializeTupleStruct = SerializeValueArray;
type SerializeTupleVariant = SerializeTupleVariant;
type SerializeMap = SerializeMap;
type SerializeStruct = SerializeMap;
type SerializeStructVariant = SerializeStructVariant;
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
Ok(v.into())
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
Ok(v.into())
}
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
let v: i64 = v
.try_into()
.map_err(|_err| Error::out_of_range(Some("u64")))?;
self.serialize_i64(v)
}
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
self.serialize_f64(v as f64)
}
fn serialize_f64(self, mut v: f64) -> Result<Self::Ok, Self::Error> {
// Discard sign of NaN when serialized using Serde.
//
// In all likelihood the sign of NaNs is not meaningful in the user's
// program. Ending up with `-nan` in the TOML document would usually be
// surprising and undesirable, when the sign of the NaN was not
// intentionally controlled by the caller, or may even be
// nondeterministic if it comes from arithmetic operations or a cast.
if v.is_nan() {
v = v.copysign(1.0);
}
Ok(v.into())
}
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
let mut buf = [0; 4];
self.serialize_str(v.encode_utf8(&mut buf))
}
fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
Ok(v.into())
}
fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
use serde::ser::Serialize;
value.serialize(self)
}
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Err(Error::unsupported_none())
}
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
value.serialize(self)
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
Err(Error::unsupported_type(Some("unit")))
}
fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
Err(Error::unsupported_type(Some(name)))
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
self.serialize_str(variant)
}
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
value.serialize(self)
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::ser::Serialize + ?Sized,
{
let value = value.serialize(self)?;
let mut table = crate::InlineTable::new();
table.insert(variant, value);
Ok(table.into())
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
Ok(SerializeValueArray::seq(len))
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
Ok(SerializeTupleVariant::tuple(variant, len))
}
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
Ok(SerializeMap::map(len))
}
fn serialize_struct(
self,
name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
Ok(SerializeMap::struct_(name, Some(len)))
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
Ok(SerializeStructVariant::struct_(variant, len))
}
}