CodeSampleX

示例

chrono 0.4.45: Disabling chrono default features strips Utc::now and Local which require the clock feature rather than std, while serde support requires an explicit opt-in serde feature and serializes DateTime as an RFC 3339 string

已验证示例 — cargo chrono 0.4.45: Disabling chrono default features strips Utc::now and Local which require the clock feature rather than std, while serde support…

sha256:861889cfdd0a5dd5ceeb51b6ec6359baf342d7c5c30f7d1fbc598a53e175fac2

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
3
构建过它的签名密钥
2
声明的环境 rust linux x64 rust rust cargo

验证运行环境

环境 契约 阶段 运行日期
rust 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-15
rust 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-18
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-09-08

案例

HOW
目标
Disabling chrono default features strips Utc::now and Local which require the clock feature rather than std, while serde support requires an explicit opt-in serde feature and serializes DateTime as an RFC 3339 string
包
符号
  • chrono::DateTime
  • chrono::Utc
  • chrono::NaiveDate
  • chrono::NaiveTime
  • chrono::NaiveDateTime
  • chrono::Duration
环境
rust
创建时间
2026-08-15T15:21:11Z

契约

  1. assert chrono with default-features=false and alloc/serde features serializes DateTime<Utc> to RFC 3339 string format without clock or std
  2. assert deserialization strictly validates calendar dates and rejects invalid leap year dates
  3. assert arithmetic and date math on DateTime<Utc> execute deterministically without system clock access

文件

  • .gitignore
  • Cargo.lock
  • Cargo.toml
  • NOTES.md
  • csx.json
  • src/lib.rs

下载源代码构件 (tar.gz)

源代码

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

[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"

[[package]]
name = "cargo-chrono-default-features"
version = "0.1.0"
dependencies = [
 "chrono",
 "serde",
 "serde_json",
]

[[package]]
name = "chrono"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [
 "num-traits",
 "serde",
]

[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"

[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"

[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
 "autocfg",
]

[[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",
 "serde_derive",
]

[[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 = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
 "itoa",
 "memchr",
 "serde",
 "serde_core",
 "zmij",
]

[[package]]
name = "syn"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
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 = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
Cargo.toml
[package]
name = "cargo-chrono-default-features"
version = "0.1.0"
edition = "2024"

[dependencies]
chrono = { version = "0.4.45", default-features = false, features = ["alloc", "serde"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
NOTES.md
# CodeSampleX Notes: chrono feature gating with default-features = false

## Search Result
`search_known_solution` returned **MISS** (no match for `chrono` default features / feature gating; only unrelated generic serde and pillow samples were present).

## What a Model Would Have Written Instead
A naive model would configure `chrono = { version = "0.4", default-features = false, features = ["std"] }` expecting `Utc::now()` / `chrono::Local` to be available with `std`, and assume `DateTime<Utc>` automatically serializes with serde (or serializes to an integer Unix timestamp).

## How the Wrong Version Fails
- **Loud compile failure for clock**: Calling `Utc::now()` without `"clock"` fails with `error[E0599]: no associated function or constant named 'now' found for struct 'Utc'` (gated behind the `clock` feature, not `std`).
- **Loud compile failure for Local**: Importing `chrono::Local` fails with `error[E0432]: unresolved import 'chrono::Local'`.
- **Loud compile failure for Serde**: Omitting `features = ["serde"]` fails at compile-time with `error[E0277]: the trait bound 'DateTime<Utc>: serde::Serialize' is not satisfied` (serde is not in default features).
- **Format mismatch**: When enabled, `serde` serializes `DateTime<Utc>` into an RFC 3339 formatted string (e.g. `"2024-05-17T12:30:45Z"`), causing runtime deserialization failures if downstream systems expect numeric epoch timestamps.
csx.json
{"case":{"caseId":"case:sha256:bec36d0008d8c4459deec5e9292d968b8e0988c329ae6ded445dba3a527415ba","constraints":{"runtime":"rust"},"contract":["assert chrono with default-features=false and alloc/serde features serializes DateTime\u003cUtc\u003e to RFC 3339 string format without clock or std","assert deserialization strictly validates calendar dates and rejects invalid leap year dates","assert arithmetic and date math on DateTime\u003cUtc\u003e execute deterministically without system clock access"],"goal":"Disabling chrono default features strips Utc::now and Local which require the clock feature rather than std, while serde support requires an explicit opt-in serde feature and serializes DateTime as an RFC 3339 string","kind":"HOW","packages":["pkg:cargo/chrono@0.4.45","pkg:cargo/serde@1.0.229","pkg:cargo/serde_json@1.0.151"],"schemaVersion":1,"symbols":["chrono::DateTime","chrono::Utc","chrono::NaiveDate","chrono::NaiveTime","chrono::NaiveDateTime","chrono::Duration"]},"contractCommand":["cargo","test","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","executionContext":"rust","language":"rust","os":"linux","packageManager":"cargo","runtime":"rust","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/chrono@0.4.45","pkg:cargo/serde@1.0.229","pkg:cargo/serde_json@1.0.151"],"schemaVersion":1,"symbols":["chrono::DateTime","chrono::Utc","chrono::NaiveDate","chrono::NaiveTime","chrono::NaiveDateTime","chrono::Duration"],"verifierAdapter":"cargo@1"}
src/lib.rs
use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, Utc};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Record {
    pub id: u64,
    pub created_at: DateTime<Utc>,
    pub valid_date: NaiveDate,
}

pub fn make_deterministic_utc(
    year: i32,
    month: u32,
    day: u32,
    hour: u32,
    min: u32,
    sec: u32,
) -> Option<DateTime<Utc>> {
    let date = NaiveDate::from_ymd_opt(year, month, day)?;
    let time = NaiveTime::from_hms_opt(hour, min, sec)?;
    let naive_dt = NaiveDateTime::new(date, time);
    Some(DateTime::<Utc>::from_naive_utc_and_offset(naive_dt, Utc))
}

pub fn add_days(dt: DateTime<Utc>, days: i64) -> DateTime<Utc> {
    dt + Duration::days(days)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_serde_serializes_chrono_types_as_iso_strings() {
        let dt = make_deterministic_utc(2024, 5, 17, 12, 30, 45).expect("valid datetime");
        let record = Record {
            id: 42,
            created_at: dt,
            valid_date: NaiveDate::from_ymd_opt(2024, 5, 17).unwrap(),
        };

        let json_str = serde_json::to_string(&record).expect("serialization succeeds");

        // Chrono with serde feature serializes DateTime<Utc> to RFC 3339 string format,
        // not Unix epoch seconds and not a struct { secs, nanos }.
        assert!(
            json_str.contains(r#""created_at":"2024-05-17T12:30:45Z""#),
            "DateTime<Utc> must serialize to RFC 3339 string format, got: {json_str}"
        );
        assert!(
            json_str.contains(r#""valid_date":"2024-05-17""#),
            "NaiveDate must serialize to YYYY-MM-DD string format, got: {json_str}"
        );

        let deserialized: Record = serde_json::from_str(&json_str).expect("deserialization succeeds");
        assert_eq!(deserialized, record);
    }

    #[test]
    fn test_deserialization_rejects_invalid_calendar_dates() {
        // 2023 is not a leap year: Feb 29 must fail deserialization
        let invalid_leap_year_json = r#"{"id":1,"created_at":"2023-02-29T12:00:00Z","valid_date":"2023-02-29"}"#;
        let res = serde_json::from_str::<Record>(invalid_leap_year_json);
        assert!(res.is_err(), "Non-leap year Feb 29 must fail deserialization");

        // 2024 IS a leap year: Feb 29 must succeed deserialization
        let valid_leap_year_json = r#"{"id":1,"created_at":"2024-02-29T12:00:00Z","valid_date":"2024-02-29"}"#;
        let res: Result<Record, _> = serde_json::from_str(valid_leap_year_json);
        assert!(res.is_ok(), "Leap year Feb 29 must succeed deserialization");
    }

    #[test]
    fn test_pure_arithmetic_without_system_clock() {
        let base = make_deterministic_utc(2024, 2, 28, 23, 0, 0).expect("valid datetime");
        let next_day = add_days(base, 1);

        // Leap year addition rolls over to 2024-02-29
        assert_eq!(next_day.to_rfc3339(), "2024-02-29T23:00:00+00:00");
    }

    #[test]
    fn test_rfc3339_parsing_and_formatting() {
        let parsed: DateTime<Utc> = DateTime::parse_from_rfc3339("2024-12-31T23:59:59Z")
            .expect("parse valid RFC 3339")
            .with_timezone(&Utc);

        assert_eq!(parsed.timestamp(), 1735689599);
    }
}

原始种子者

anonymous