openrtc-netcode-core 0.1.0

Shared protocol types for OpenRTC netcode clients.
Documentation
use openrtc_netcode_core::{
    decode_envelope, encode_envelope, EnvelopeKind, NetcodeEnvelope, NETCODE_PROTOCOL,
    NETCODE_PROTOCOL_VERSION,
};
use serde_json::json;

#[test]
fn decodes_shared_user_message_fixture() {
    let fixture = include_str!("../fixtures/user_message.json");
    let envelope = decode_envelope(fixture).expect("fixture decodes");
    envelope.validate().expect("fixture is valid");

    assert_eq!(envelope.protocol, NETCODE_PROTOCOL);
    assert_eq!(envelope.v, NETCODE_PROTOCOL_VERSION);
    assert_eq!(envelope.kind, EnvelopeKind::User);
    assert_eq!(envelope.lobby_id, "LOBBY1");
    assert_eq!(envelope.from, "node-a");
    assert_eq!(envelope.target.as_deref(), Some("node-b"));
    assert_eq!(envelope.body["type"], "chat");
    assert_eq!(envelope.body["payload"]["text"], "hello");
}

#[test]
fn encodes_valid_state_patch_envelope() {
    let envelope = NetcodeEnvelope::new(
        EnvelopeKind::StatePatch,
        "LOBBY1",
        "node-a",
        8,
        1_700_000_000_001,
        json!({
            "key": "score",
            "value": 10,
            "owner": "node-a"
        }),
    );

    let encoded = encode_envelope(&envelope).expect("encodes");
    let decoded = decode_envelope(&encoded).expect("decodes");
    decoded.validate().expect("validates");

    assert_eq!(decoded.kind, EnvelopeKind::StatePatch);
    assert_eq!(decoded.body["key"], "score");
    assert_eq!(decoded.body["value"], 10);
}

#[test]
fn rejects_protocol_mismatch() {
    let mut envelope =
        NetcodeEnvelope::new(EnvelopeKind::Ping, "LOBBY1", "node-a", 1, 1, json!({}));
    envelope.protocol = "other".to_string();

    assert!(envelope.validate().is_err());
}