CodeSampleX

Exemplo

serde_derive 1.0.229: Serialize

Amostra verificada para cargo serde_derive 1.0.229: Serialize. O contrato rodou em rust 1 · linux alpine/x64 · docker e passou.

sha256:83f26ba2a72c793d977b873933d5b18a35fa72e62ca5445eb39ca77b68aab175

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux · alpine · musl x64 cargo

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-09-14

Caso

HOW
Objetivo
verify Serialize in pkg:cargo/serde_derive@1.0.229
Pacotes
Símbolos
  • Serialize
Criado
2026-09-14T21:32:10Z

Contrato

  1. Serialize derives serde::Serialize for struct with primitive and string fields
  2. Serialize derives serde::Serialize for enum unit variants
  3. derived serialize outputs correct field names and values in struct sequence

Arquivos

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • src/main.rs
  • tests/contract.rs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
 "serde_core",
]

[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
 "serde_derive",
]

[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "syn"
version = "3.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"

[[package]]
name = "verify-serde-derive"
version = "0.1.0"
dependencies = [
 "serde",
 "serde_derive",
]
Cargo.toml
[package]
name = "verify-serde-derive"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0.229", default-features = false }
serde_derive = "1.0.229"
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify Serialize in pkg:cargo/serde_derive@1.0.229
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/serde_derive@1.0.229
Demonstrate these symbols/APIs:
  - Serialize

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:5ca8b77f5148ed6c9e21102d19439cdf9c95d70c20b89bc5220dd57c9ad46b19","contract":["Serialize derives serde::Serialize for struct with primitive and string fields","Serialize derives serde::Serialize for enum unit variants","derived serialize outputs correct field names and values in struct sequence"],"goal":"verify Serialize in pkg:cargo/serde_derive@1.0.229","kind":"HOW","packages":["pkg:cargo/serde_derive@1.0.229"],"schemaVersion":1,"symbols":["Serialize"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/serde_derive@1.0.229"],"schemaVersion":1,"subject":"pkg:cargo/serde_derive@1.0.229","symbols":["Serialize"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Serialize in pkg:cargo/serde_derive@1.0.229",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/serde_derive@1.0.229"
  ],
  "symbols": [
    "Serialize"
  ]
}
src/lib.rs
use std::fmt;
use serde::ser::{self, Serialize, SerializeStruct, Serializer};
use serde_derive::Serialize;

#[derive(Debug)]
pub struct CustomError(pub String);

impl fmt::Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for CustomError {}

impl ser::Error for CustomError {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        CustomError(msg.to_string())
    }
}

pub struct JsonSerializer {
    output: String,
}

impl JsonSerializer {
    pub fn new() -> Self {
        Self {
            output: String::new(),
        }
    }

    pub fn into_string(self) -> String {
        self.output
    }
}

impl<'a> Serializer for &'a mut JsonSerializer {
    type Ok = ();
    type Error = CustomError;
    type SerializeSeq = ser::Impossible<(), CustomError>;
    type SerializeTuple = ser::Impossible<(), CustomError>;
    type SerializeTupleStruct = ser::Impossible<(), CustomError>;
    type SerializeTupleVariant = ser::Impossible<(), CustomError>;
    type SerializeMap = ser::Impossible<(), CustomError>;
    type SerializeStruct = StructSerializer<'a>;
    type SerializeStructVariant = ser::Impossible<(), CustomError>;

    fn serialize_bool(self, v: bool) -> Result<(), CustomError> {
        self.output.push_str(if v { "true" } else { "false" });
        Ok(())
    }

    fn serialize_i8(self, v: i8) -> Result<(), CustomError> {
        self.serialize_i64(v as i64)
    }

    fn serialize_i16(self, v: i16) -> Result<(), CustomError> {
        self.serialize_i64(v as i64)
    }

    fn serialize_i32(self, v: i32) -> Result<(), CustomError> {
        self.serialize_i64(v as i64)
    }

    fn serialize_i64(self, v: i64) -> Result<(), CustomError> {
        self.output.push_str(&v.to_string());
        Ok(())
    }

    fn serialize_u8(self, v: u8) -> Result<(), CustomError> {
        self.serialize_u64(v as u64)
    }

    fn serialize_u16(self, v: u16) -> Result<(), CustomError> {
        self.serialize_u64(v as u64)
    }

    fn serialize_u32(self, v: u32) -> Result<(), CustomError> {
        self.serialize_u64(v as u64)
    }

    fn serialize_u64(self, v: u64) -> Result<(), CustomError> {
        self.output.push_str(&v.to_string());
        Ok(())
    }

    fn serialize_f32(self, v: f32) -> Result<(), CustomError> {
        self.output.push_str(&v.to_string());
        Ok(())
    }

    fn serialize_f64(self, v: f64) -> Result<(), CustomError> {
        self.output.push_str(&v.to_string());
        Ok(())
    }

    fn serialize_char(self, v: char) -> Result<(), CustomError> {
        self.serialize_str(&v.to_string())
    }

    fn collect_str<T: ?Sized + fmt::Display>(self, value: &T) -> Result<(), CustomError> {
        self.serialize_str(&value.to_string())
    }

    fn serialize_str(self, v: &str) -> Result<(), CustomError> {
        self.output.push('"');
        self.output.push_str(v);
        self.output.push('"');
        Ok(())
    }

    fn serialize_bytes(self, _v: &[u8]) -> Result<(), CustomError> {
        Err(CustomError("unsupported bytes".into()))
    }

    fn serialize_none(self) -> Result<(), CustomError> {
        self.output.push_str("null");
        Ok(())
    }

    fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<(), CustomError> {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<(), CustomError> {
        self.output.push_str("null");
        Ok(())
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<(), CustomError> {
        self.serialize_unit()
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<(), CustomError> {
        self.serialize_str(variant)
    }

    fn serialize_newtype_struct<T: ?Sized + Serialize>(
        self,
        _name: &'static str,
        value: &T,
    ) -> Result<(), CustomError> {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T: ?Sized + Serialize>(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _value: &T,
    ) -> Result<(), CustomError> {
        Err(CustomError("unsupported newtype variant".into()))
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, CustomError> {
        Err(CustomError("unsupported seq".into()))
    }

    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, CustomError> {
        Err(CustomError("unsupported tuple".into()))
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct, CustomError> {
        Err(CustomError("unsupported tuple struct".into()))
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, CustomError> {
        Err(CustomError("unsupported tuple variant".into()))
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, CustomError> {
        Err(CustomError("unsupported map".into()))
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, CustomError> {
        self.output.push('{');
        Ok(StructSerializer {
            serializer: self,
            first: true,
        })
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, CustomError> {
        Err(CustomError("unsupported struct variant".into()))
    }
}

pub struct StructSerializer<'a> {
    serializer: &'a mut JsonSerializer,
    first: bool,
}

impl<'a> SerializeStruct for StructSerializer<'a> {
    type Ok = ();
    type Error = CustomError;

    fn serialize_field<T: ?Sized + Serialize>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> Result<(), CustomError> {
        if !self.first {
            self.serializer.output.push(',');
        }
        self.first = false;
        self.serializer.output.push('"');
        self.serializer.output.push_str(key);
        self.serializer.output.push_str("\":");
        value.serialize(&mut *self.serializer)
    }

    fn end(self) -> Result<(), CustomError> {
        self.serializer.output.push('}');
        Ok(())
    }
}

pub fn to_json<T: Serialize>(value: &T) -> Result<String, CustomError> {
    let mut serializer = JsonSerializer::new();
    value.serialize(&mut serializer)?;
    Ok(serializer.into_string())
}

#[derive(Serialize, Debug, PartialEq)]
pub struct UserProfile {
    pub id: u64,
    pub username: &'static str,
    pub is_active: bool,
}

#[derive(Serialize, Debug, PartialEq)]
pub enum UserRole {
    Admin,
    Member,
}

pub fn run_contract_assertions() {
    let profile = UserProfile {
        id: 101,
        username: "developer",
        is_active: true,
    };
    let json = to_json(&profile).expect("struct serialization failed");
    assert_eq!(
        json,
        r#"{"id":101,"username":"developer","is_active":true}"#,
        "struct serialization mismatch"
    );

    let role = UserRole::Admin;
    let role_json = to_json(&role).expect("enum unit variant serialization failed");
    assert_eq!(role_json, r#""Admin""#, "enum unit variant mismatch");

    let member = UserRole::Member;
    let member_json = to_json(&member).expect("enum member serialization failed");
    assert_eq!(member_json, r#""Member""#, "enum member mismatch");
}
src/main.rs
use verify_serde_derive::run_contract_assertions;

fn main() {
    run_contract_assertions();
    println!("Contract passed: Serialize in pkg:cargo/serde_derive@1.0.229 verified");
}
tests/contract.rs
use verify_serde_derive::run_contract_assertions;

#[test]
fn test_contract_serialize() {
    run_contract_assertions();
}

Seeder de origem

anônimo