[lib] Implement serializing/deserializing UserPreferences

This commit is contained in:
Emi Simpson 2021-10-30 10:31:58 -04:00
parent 7f3b9ef2ec
commit 7fb9ed0119
Signed by: Emi
GPG Key ID: A12F2C2FFDC3D847
2 changed files with 24 additions and 2 deletions

View File

@ -6,12 +6,14 @@
pub mod v0;
mod error;
use core::convert::TryFrom;
pub use error::ParseError;
use crate::user_preferences::v0::UserPreferencesV0;
use crate::{InstanceSettings, Pronoun, WeightedTable};
use data_encoding::BASE32_NOPAD;
use serde;
/// A user's preferences for the probabilities of certain pronouns
///
@ -25,7 +27,8 @@ use data_encoding::BASE32_NOPAD;
/// Because parsing a prefstring must be done in relation to an [`InstanceSettings`], the
/// `UserPreferences` struct shares a lifetime with the settings it was created with.
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "Intermediary", into = "Intermediary")]
pub enum UserPreferences {
V0(v0::UserPreferencesV0)
}
@ -142,6 +145,25 @@ impl Preference for UserPreferences {
}
}
/// Serves as an intermediary for serializing and deserializing [`Preference`] objects
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
struct Intermediary(String);
impl From<UserPreferences> for Intermediary {
fn from(prefs: UserPreferences) -> Intermediary {
Intermediary(prefs.as_prefstring())
}
}
impl TryFrom<Intermediary> for UserPreferences {
type Error = ParseError;
fn try_from(prefs: Intermediary) -> Result<UserPreferences, ParseError> {
UserPreferences::from_prefstring(prefs.0.as_str())
}
}
#[cfg(test)]
mod test {
use super::*;

View File

@ -17,7 +17,7 @@ use std::{
/// See the [prefstring specification][1] for more information about how this is interpretted.
///
/// [1]: https://fem.mint.lgbt/Emi/PronounsToday/raw/branch/main/doc/User-Preference-String-Spec.txt
#[derive(Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UserPreferencesV0 {
pub default_weight: u8,
pub default_enabled: bool,