serde_path_serializer 1.0.0

A Serde serializer for Path
Documentation
use std::{ffi::OsString, path::PathBuf};

use serde::{ser::Serializer, Serialize};

/**
 * Serialize a Vec<u8> as a PathBuf.
 *
 * # Example
 *
 * ```
 * use std::path::PathBuf;
 * use serde::Serialize;
 * use serde_path::serialize_path;
 *
 * let bytes = vec![b'/', b't', b'm', b'p'];
 * let path = PathBuf::from("/tmp");
 * let serialized = serde_json::to_string(&path).unwrap();
 * assert_eq!(serialized, r#""/tmp""#);
 * ```
 *
 * # Errors
 *
 * If the bytes are not valid UTF-8, an error will be returned.
 *
 * # Safety
 *
 * This function is unsafe because it creates an OsString from the bytes without checking if the bytes are valid UTF-8.
 *
 */
pub fn serialize_path<S>(bytes: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let osstring = unsafe { OsString::from_encoded_bytes_unchecked(bytes.to_owned()) };
    let path = PathBuf::from(osstring);
    path.serialize(serializer)
}