📦 msgpack
MessagePack Binary Serialization - Kompakt and Hızlı
~500 lines
~40 function
30-50% Daha Küçük
📖 Overview
MessagePack, JSON'dan %30-50 daha küçük and 2-3x daha hızlı binary serialization formatıdır. Network protokolleri, cache sistemleri and IPC for idealdir.
🔑 Key Features
- JSON'dan %30-50 daha küçük boyut
- 2-3x daha hızlı serialization/deserialization
- Type-safe encoding/decoding
- Integers, floats, strings, binary, arrays, maps
- Nil/null value support
- Extension types
- Streaming API
- Zero-copy where possible
🚀 Quick Start
import msgpack
// Serialize
let data = do
name: "Alice",
age: 30,
scores: [95, 87, 92]
end
let bytes = msgpack.encode(data)
io.println("Encoded: {} bytes", bytes.uzunluk())
// Deserialize
let decoded = msgpack.decode(bytes)?
io.println("Name: {}", decoded["name"])
💡 Example: Redis-Style Cache with MessagePack
import msgpack, redis, time
struct CacheEntry[T] do
value: T,
expires_at: time.Instant
end
struct MessagePackCache do
redis: redis.Client
end
function cache_new(redis_url: str) -> Result[MessagePackCache, Error] do
return Ok(MessagePackCache do
redis: redis.connect(redis_url)?
end)
end
function cache_set[T](cache: MessagePackCache, key: str, value: T, ttl_secs: int)
-> Result[None, Error] do
// Wrap with expiry
let entry = CacheEntry do
value: value,
expires_at: time.now() + time.seconds(ttl_secs)
end
// Serialize with MessagePack (much smaller than JSON)
let bytes = msgpack.encode(entry)
// Store in Redis
cache.redis.setex(key, ttl_secs, bytes)?
return Ok(None)
end
function cache_get[T](cache: MessagePackCache, key: str)
-> Result[Optional[T], Error] do
// Get from Redis
let bytes = cache.redis.get(key)?
if bytes.is_none() do
return Ok(None)
end
// Deserialize
let entry: CacheEntry[T] = msgpack.decode(bytes.unwrap())?
// Check expiry
if time.now() > entry.expires_at do
cache.redis.del(key)?
return Ok(None)
end
return Ok(Some(entry.value))
end
// useım
function main() do
let cache = cache_new("redis://localhost:6379")?
// Store user data
let user = do
id: 123,
name: "Alice",
email: "alice@example.com",
roles: ["admin", "user"]
end
cache_set(cache, "user:123", user, 3600)? // 1 hour TTL
// Retrieve
let cached_user = cache_get(cache, "user:123")?
if cached_user.is_some() do
io.println("Cache hit: {}", cached_user.unwrap().name)
end
end
📊 Boyut Karşılaştırması
// Test data
let data = do
users: [
do id: 1, name: "Alice", age: 30, active: true end,
do id: 2, name: "Bob", age: 25, active: true end,
do id: 3, name: "Charlie", age: 35, active: false end
]
end
// JSON: 189 bytes
let json_bytes = json.encode(data)
io.println("JSON: {} bytes", json_bytes.uzunluk())
// MessagePack: 98 bytes (48% smaller!)
let msgpack_bytes = msgpack.encode(data)
io.println("MessagePack: {} bytes", msgpack_bytes.uzunluk())
io.println("Savings: {}%", (1.0 - msgpack_bytes.uzunluk().float() / json_bytes.uzunluk().float()) * 100.0)
🔗 Related Modules
json- JSON serializationredis- Redis cachenetwork- Binary protocols