Encoding Package - Rust Implementation

Crate: giztoy-encoding

📚 Rust Documentation

Types

StdBase64Data

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct StdBase64Data(Vec<u8>);
}

A newtype wrapper around Vec<u8> that serializes to/from standard Base64.

Methods:

MethodSignatureDescription
newfn new(data: Vec<u8>) -> SelfCreate from Vec
emptyfn empty() -> SelfCreate empty
as_bytesfn as_bytes(&self) -> &[u8]Get byte slice reference
as_bytes_mutfn as_bytes_mut(&mut self) -> &mut Vec<u8>Get mutable reference
into_bytesfn into_bytes(self) -> Vec<u8>Consume and return Vec
is_emptyfn is_empty(&self) -> boolCheck if empty
lenfn len(&self) -> usizeGet length
encodefn encode(&self) -> StringEncode to Base64 string
decodefn decode(s: &str) -> Result<Self, DecodeError>Decode from Base64

Trait Implementations:

  • Serialize / Deserialize (serde)
  • Display (formats as Base64)
  • Deref<Target=[u8]> / DerefMut
  • From<Vec<u8>>, From<&[u8]>, From<[u8; N]>
  • AsRef<[u8]>

HexData

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct HexData(Vec<u8>);
}

A newtype wrapper around Vec<u8> that serializes to/from hexadecimal.

Methods:

Same API as StdBase64Data, but with hex encoding:

MethodSignatureDescription
encodefn encode(&self) -> StringEncode to hex string
decodefn decode(s: &str) -> Result<Self, FromHexError>Decode from hex

Usage

In Struct Fields

#![allow(unused)]
fn main() {
use giztoy_encoding::{StdBase64Data, HexData};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Message {
    id: String,
    payload: StdBase64Data,
    hash: HexData,
}

let msg = Message {
    id: "msg-123".to_string(),
    payload: StdBase64Data::from(b"hello world".as_slice()),
    hash: HexData::from(vec![0xab, 0xcd, 0xef]),
};

// Serializes to:
// {"id":"msg-123","payload":"aGVsbG8gd29ybGQ=","hash":"abcdef"}
let json = serde_json::to_string(&msg).unwrap();
}

Standalone Encoding

#![allow(unused)]
fn main() {
// Base64
let data = StdBase64Data::from(b"hello".as_slice());
println!("{}", data);  // "aGVsbG8="
println!("{}", data.encode());  // "aGVsbG8="

// Hex
let hash = HexData::from(vec![0xde, 0xad]);
println!("{}", hash);  // "dead"
}

Deref Coercion

#![allow(unused)]
fn main() {
let data = StdBase64Data::from(vec![1, 2, 3]);

// Can use as &[u8] directly
fn process(bytes: &[u8]) { /* ... */ }
process(&data);  // Deref coercion

// Access slice methods
println!("len: {}", data.len());
println!("first: {:?}", data.first());
}

Null Handling

#![allow(unused)]
fn main() {
// Null deserializes to empty
let data: StdBase64Data = serde_json::from_str("null").unwrap();
assert!(data.is_empty());

// Empty string also empty
let data: StdBase64Data = serde_json::from_str(r#""""#).unwrap();
assert!(data.is_empty());
}

Dependencies

  • base64 crate (for Base64 encoding)
  • hex crate (for hex encoding)
  • serde crate (for serialization)

Differences from Go

AspectGoRust
Type structureType alias []byteNewtype struct(Vec<u8>)
Conversion to bytesDirect cast.as_bytes() or Deref
Additional methodsNoneis_empty(), len(), encode(), decode()
Hash/Eq traitsN/A (slice)Implemented
CloneImplicitExplicit (implemented)