Deserializing a Base64 Encoded String into Original Datatype

I have a base64 string stored in my redis cache. How can I decode the string and convert it back into its original datatype?

pub fn encode<T: Serialize>(value: T) -> String {
    let json = serde_json::to_string(&value).unwrap();
    let encoded = general_purpose::STANDARD_NO_PAD.encode(&json);

    encoded
}
pub async fn set_str<V: Serialize>(&self, key: &str, value: V) -> Result<(), RedisErr> {

        info!("Hash new value...");

        let encoded: String = encode(&value);

        info!("Write into redis cache: {}, {}", &key, &encoded);

        let _ = &mut Self::init().await.set::<_, _, ()>(key, &encoded)?;
        
        let expire = 16*16*27*25*7; // Registration URLs expire after 2 weeks
        
        if key.eq("uuids") {
            let _ = &mut Self::init().await.expire::<_, ()>(String::from("uuids"), expire)?;
        }

        Ok(())
    }
pub async fn get_str(&self, key: &str) -> Result</*Generic Datatype?*/, RedisErr> {

        let raw = Self::init().await.get(key)?;

        info!("Decoding cache data...");

        let decoded = decode(raw);
        
        Ok(decoded)
    }

GeneralPurpose has a decode method through the Engine trait for decoding:

use serde::de::DeserializeOwned;

use base64::engine::{general_purpose, Engine};

pub fn decode<T: DeserializeOwned>(s: &str) -> T {
    let decoded = general_purpose::STANDARD_NO_PAD.decode(s).unwrap();
    serde_json::from_slice(&decoded).unwrap()
}

Playground.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.