
# This file was @generated by crate2nix 0.15.0 with the command:
#   "generate"
# See https://github.com/kolloch/crate2nix for more info.

{ nixpkgs ? <nixpkgs>
, pkgs ? import nixpkgs { config = {}; }
, fetchurl ? pkgs.fetchurl
, lib ? pkgs.lib
, stdenv ? pkgs.stdenv
, buildRustCrateForPkgs ? pkgs: pkgs.buildRustCrate
  # This is used as the `crateOverrides` argument for `buildRustCrate`.
, defaultCrateOverrides ? pkgs.defaultCrateOverrides
  # The features to enable for the root_crate or the workspace_members.
, rootFeatures ? [ "default" ]
  # If true, throw errors instead of issueing deprecation warnings.
, strictDeprecation ? false
  # Elements to add to the `-C target-feature=` argument passed to `rustc`
  # (separated by `,`, prefixed with `+`).
  # Used for conditional compilation based on CPU feature detection.
, targetFeatures ? []
  # Additional target attributes for conditional dependencies.
  # Use this for custom cfg flags that are passed via rustcflags but need to
  # be known at Nix evaluation time for dependency resolution.
  # Example: { tracing_unstable = true; } for crates using cfg(tracing_unstable).
, extraTargetFlags ? {}
  # Whether to perform release builds: longer compile times, faster binaries.
, release ? true
  # Additional crate2nix configuration if it exists.
, crateConfig
  ? if builtins.pathExists ./crate-config.nix
    then pkgs.callPackage ./crate-config.nix {}
    else {}
}:

rec {
  #
  # "public" attributes that we attempt to keep stable with new versions of crate2nix.
  #

  rootCrate = rec {
    packageId = "tsuuchi";

    # Use this attribute to refer to the derivation building your root crate package.
    # You can override the features with rootCrate.build.override { features = [ "default" "feature1" ... ]; }.
    build = internal.buildRustCrateWithFeatures {
      inherit packageId;
    };

    # Debug support which might change between releases.
    # File a bug if you depend on any for non-debug work!
    debug = internal.debugCrate { inherit packageId; };
  };
  # Refer your crate build derivation by name here.
  # You can override the features with
  # workspaceMembers."${crateName}".build.override { features = [ "default" "feature1" ... ]; }.
  workspaceMembers = {
    "tsuuchi" = rec {
      packageId = "tsuuchi";
      build = internal.buildRustCrateWithFeatures {
        packageId = "tsuuchi";
      };

      # Debug support which might change between releases.
      # File a bug if you depend on any for non-debug work!
      debug = internal.debugCrate { inherit packageId; };
    };
  };



  # A derivation that joins the outputs of all workspace members together.
  allWorkspaceMembers = pkgs.symlinkJoin {
      name = "all-workspace-members";
      paths =
        let members = builtins.attrValues workspaceMembers;
        in builtins.map (m: m.build) members;
  };

  #
  # "internal" ("private") attributes that may change in every new version of crate2nix.
  #

  internal = rec {
    # Build and dependency information for crates.
    # Many of the fields are passed one-to-one to buildRustCrate.
    #
    # Noteworthy:
    # * `dependencies`/`buildDependencies`: similar to the corresponding fields for buildRustCrate.
    #   but with additional information which is used during dependency/feature resolution.
    # * `resolvedDependencies`: the selected default features reported by cargo - only included for debugging.
    # * `devDependencies` as of now not used by `buildRustCrate` but used to
    #   inject test dependencies into the build

    crates = {
      "itoa" = rec {
        crateName = "itoa";
        version = "1.0.17";
        edition = "2021";
        sha256 = "1lh93xydrdn1g9x547bd05g0d3hra7pd1k4jfd2z1pl1h5hwdv4j";
        authors = [
          "David Tolnay <dtolnay@gmail.com>"
        ];
        features = {
          "no-panic" = [ "dep:no-panic" ];
        };
      };
      "memchr" = rec {
        crateName = "memchr";
        version = "2.8.0";
        edition = "2021";
        sha256 = "0y9zzxcqxvdqg6wyag7vc3h0blhdn7hkq164bxyx2vph8zs5ijpq";
        authors = [
          "Andrew Gallant <jamslam@gmail.com>"
          "bluss"
        ];
        features = {
          "core" = [ "dep:core" ];
          "default" = [ "std" ];
          "logging" = [ "dep:log" ];
          "rustc-dep-of-std" = [ "core" ];
          "std" = [ "alloc" ];
          "use_std" = [ "std" ];
        };
        resolvedDefaultFeatures = [ "alloc" "std" ];
      };
      "once_cell" = rec {
        crateName = "once_cell";
        version = "1.21.3";
        edition = "2021";
        sha256 = "0b9x77lb9f1j6nqgf5aka4s2qj0nly176bpbrv6f9iakk5ff3xa2";
        authors = [
          "Aleksey Kladov <aleksey.kladov@gmail.com>"
        ];
        features = {
          "alloc" = [ "race" ];
          "atomic-polyfill" = [ "critical-section" ];
          "critical-section" = [ "dep:critical-section" "portable-atomic" ];
          "default" = [ "std" ];
          "parking_lot" = [ "dep:parking_lot_core" ];
          "portable-atomic" = [ "dep:portable-atomic" ];
          "std" = [ "alloc" ];
        };
        resolvedDefaultFeatures = [ "alloc" "default" "race" "std" ];
      };
      "pin-project-lite" = rec {
        crateName = "pin-project-lite";
        version = "0.2.17";
        edition = "2018";
        sha256 = "1kfmwvs271si96zay4mm8887v5khw0c27jc9srw1a75ykvgj54x8";
        libName = "pin_project_lite";

      };
      "proc-macro2" = rec {
        crateName = "proc-macro2";
        version = "1.0.106";
        edition = "2021";
        sha256 = "0d09nczyaj67x4ihqr5p7gxbkz38gxhk4asc0k8q23g9n85hzl4g";
        libName = "proc_macro2";
        authors = [
          "David Tolnay <dtolnay@gmail.com>"
          "Alex Crichton <alex@alexcrichton.com>"
        ];
        dependencies = [
          {
            name = "unicode-ident";
            packageId = "unicode-ident";
          }
        ];
        features = {
          "default" = [ "proc-macro" ];
        };
        resolvedDefaultFeatures = [ "default" "proc-macro" ];
      };
      "quote" = rec {
        crateName = "quote";
        version = "1.0.45";
        edition = "2021";
        sha256 = "095rb5rg7pbnwdp6v8w5jw93wndwyijgci1b5lw8j1h5cscn3wj1";
        authors = [
          "David Tolnay <dtolnay@gmail.com>"
        ];
        dependencies = [
          {
            name = "proc-macro2";
            packageId = "proc-macro2";
            usesDefaultFeatures = false;
          }
        ];
        features = {
          "default" = [ "proc-macro" ];
          "proc-macro" = [ "proc-macro2/proc-macro" ];
        };
        resolvedDefaultFeatures = [ "default" "proc-macro" ];
      };
      "serde" = rec {
        crateName = "serde";
        version = "1.0.228";
        edition = "2021";
        sha256 = "17mf4hhjxv5m90g42wmlbc61hdhlm6j9hwfkpcnd72rpgzm993ls";
        authors = [
          "Erick Tryzelaar <erick.tryzelaar@gmail.com>"
          "David Tolnay <dtolnay@gmail.com>"
        ];
        dependencies = [
          {
            name = "serde_core";
            packageId = "serde_core";
            usesDefaultFeatures = false;
            features = [ "result" ];
          }
          {
            name = "serde_derive";
            packageId = "serde_derive";
            optional = true;
          }
        ];
        features = {
          "alloc" = [ "serde_core/alloc" ];
          "default" = [ "std" ];
          "derive" = [ "serde_derive" ];
          "rc" = [ "serde_core/rc" ];
          "serde_derive" = [ "dep:serde_derive" ];
          "std" = [ "serde_core/std" ];
          "unstable" = [ "serde_core/unstable" ];
        };
        resolvedDefaultFeatures = [ "default" "derive" "serde_derive" "std" ];
      };
      "serde_core" = rec {
        crateName = "serde_core";
        version = "1.0.228";
        edition = "2021";
        sha256 = "1bb7id2xwx8izq50098s5j2sqrrvk31jbbrjqygyan6ask3qbls1";
        authors = [
          "Erick Tryzelaar <erick.tryzelaar@gmail.com>"
          "David Tolnay <dtolnay@gmail.com>"
        ];
        dependencies = [
          {
            name = "serde_derive";
            packageId = "serde_derive";
            target = { target, features }: false;
          }
        ];
        devDependencies = [
          {
            name = "serde_derive";
            packageId = "serde_derive";
          }
        ];
        features = {
          "default" = [ "std" "result" ];
        };
        resolvedDefaultFeatures = [ "result" "std" ];
      };
      "serde_derive" = rec {
        crateName = "serde_derive";
        version = "1.0.228";
        edition = "2021";
        sha256 = "0y8xm7fvmr2kjcd029g9fijpndh8csv5m20g4bd76w8qschg4h6m";
        procMacro = true;
        authors = [
          "Erick Tryzelaar <erick.tryzelaar@gmail.com>"
          "David Tolnay <dtolnay@gmail.com>"
        ];
        dependencies = [
          {
            name = "proc-macro2";
            packageId = "proc-macro2";
            usesDefaultFeatures = false;
            features = [ "proc-macro" ];
          }
          {
            name = "quote";
            packageId = "quote";
            usesDefaultFeatures = false;
            features = [ "proc-macro" ];
          }
          {
            name = "syn";
            packageId = "syn";
            usesDefaultFeatures = false;
            features = [ "clone-impls" "derive" "parsing" "printing" "proc-macro" ];
          }
        ];
        features = {
        };
        resolvedDefaultFeatures = [ "default" ];
      };
      "serde_json" = rec {
        crateName = "serde_json";
        version = "1.0.149";
        edition = "2021";
        sha256 = "11jdx4vilzrjjd1dpgy67x5lgzr0laplz30dhv75lnf5ffa07z43";
        authors = [
          "Erick Tryzelaar <erick.tryzelaar@gmail.com>"
          "David Tolnay <dtolnay@gmail.com>"
        ];
        dependencies = [
          {
            name = "itoa";
            packageId = "itoa";
          }
          {
            name = "memchr";
            packageId = "memchr";
            usesDefaultFeatures = false;
          }
          {
            name = "serde";
            packageId = "serde";
            usesDefaultFeatures = false;
            target = { target, features }: false;
          }
          {
            name = "serde_core";
            packageId = "serde_core";
            usesDefaultFeatures = false;
          }
          {
            name = "zmij";
            packageId = "zmij";
          }
        ];
        devDependencies = [
          {
            name = "serde";
            packageId = "serde";
            features = [ "derive" ];
          }
        ];
        features = {
          "alloc" = [ "serde_core/alloc" ];
          "default" = [ "std" ];
          "indexmap" = [ "dep:indexmap" ];
          "preserve_order" = [ "indexmap" "std" ];
          "std" = [ "memchr/std" "serde_core/std" ];
        };
        resolvedDefaultFeatures = [ "default" "std" ];
      };
      "syn" = rec {
        crateName = "syn";
        version = "2.0.117";
        edition = "2021";
        sha256 = "16cv7c0wbn8amxc54n4w15kxlx5ypdmla8s0gxr2l7bv7s0bhrg6";
        authors = [
          "David Tolnay <dtolnay@gmail.com>"
        ];
        dependencies = [
          {
            name = "proc-macro2";
            packageId = "proc-macro2";
            usesDefaultFeatures = false;
          }
          {
            name = "quote";
            packageId = "quote";
            optional = true;
            usesDefaultFeatures = false;
          }
          {
            name = "unicode-ident";
            packageId = "unicode-ident";
          }
        ];
        features = {
          "default" = [ "derive" "parsing" "printing" "clone-impls" "proc-macro" ];
          "printing" = [ "dep:quote" ];
          "proc-macro" = [ "proc-macro2/proc-macro" "quote?/proc-macro" ];
          "test" = [ "syn-test-suite/all-features" ];
        };
        resolvedDefaultFeatures = [ "clone-impls" "default" "derive" "extra-traits" "full" "parsing" "printing" "proc-macro" "visit-mut" ];
      };
      "thiserror" = rec {
        crateName = "thiserror";
        version = "2.0.18";
        edition = "2021";
        sha256 = "1i7vcmw9900bvsmay7mww04ahahab7wmr8s925xc083rpjybb222";
        authors = [
          "David Tolnay <dtolnay@gmail.com>"
        ];
        dependencies = [
          {
            name = "thiserror-impl";
            packageId = "thiserror-impl";
          }
        ];
        features = {
          "default" = [ "std" ];
        };
        resolvedDefaultFeatures = [ "default" "std" ];
      };
      "thiserror-impl" = rec {
        crateName = "thiserror-impl";
        version = "2.0.18";
        edition = "2021";
        sha256 = "1mf1vrbbimj1g6dvhdgzjmn6q09yflz2b92zs1j9n3k7cxzyxi7b";
        procMacro = true;
        libName = "thiserror_impl";
        authors = [
          "David Tolnay <dtolnay@gmail.com>"
        ];
        dependencies = [
          {
            name = "proc-macro2";
            packageId = "proc-macro2";
          }
          {
            name = "quote";
            packageId = "quote";
          }
          {
            name = "syn";
            packageId = "syn";
          }
        ];

      };
      "tracing" = rec {
        crateName = "tracing";
        version = "0.1.44";
        edition = "2018";
        sha256 = "006ilqkg1lmfdh3xhg3z762izfwmxcvz0w7m4qx2qajbz9i1drv3";
        authors = [
          "Eliza Weisman <eliza@buoyant.io>"
          "Tokio Contributors <team@tokio.rs>"
        ];
        dependencies = [
          {
            name = "pin-project-lite";
            packageId = "pin-project-lite";
          }
          {
            name = "tracing-attributes";
            packageId = "tracing-attributes";
            optional = true;
          }
          {
            name = "tracing-core";
            packageId = "tracing-core";
            usesDefaultFeatures = false;
          }
        ];
        features = {
          "attributes" = [ "tracing-attributes" ];
          "default" = [ "std" "attributes" ];
          "log" = [ "dep:log" ];
          "log-always" = [ "log" ];
          "std" = [ "tracing-core/std" ];
          "tracing-attributes" = [ "dep:tracing-attributes" ];
          "valuable" = [ "tracing-core/valuable" ];
        };
        resolvedDefaultFeatures = [ "attributes" "default" "std" "tracing-attributes" ];
      };
      "tracing-attributes" = rec {
        crateName = "tracing-attributes";
        version = "0.1.31";
        edition = "2018";
        sha256 = "1np8d77shfvz0n7camx2bsf1qw0zg331lra0hxb4cdwnxjjwz43l";
        procMacro = true;
        libName = "tracing_attributes";
        authors = [
          "Tokio Contributors <team@tokio.rs>"
          "Eliza Weisman <eliza@buoyant.io>"
          "David Barsky <dbarsky@amazon.com>"
        ];
        dependencies = [
          {
            name = "proc-macro2";
            packageId = "proc-macro2";
          }
          {
            name = "quote";
            packageId = "quote";
          }
          {
            name = "syn";
            packageId = "syn";
            usesDefaultFeatures = false;
            features = [ "full" "parsing" "printing" "visit-mut" "clone-impls" "extra-traits" "proc-macro" ];
          }
        ];
        features = {
        };
      };
      "tracing-core" = rec {
        crateName = "tracing-core";
        version = "0.1.36";
        edition = "2018";
        sha256 = "16mpbz6p8vd6j7sf925k9k8wzvm9vdfsjbynbmaxxyq6v7wwm5yv";
        libName = "tracing_core";
        authors = [
          "Tokio Contributors <team@tokio.rs>"
        ];
        dependencies = [
          {
            name = "once_cell";
            packageId = "once_cell";
            optional = true;
          }
        ];
        features = {
          "default" = [ "std" "valuable?/std" ];
          "once_cell" = [ "dep:once_cell" ];
          "std" = [ "once_cell" ];
          "valuable" = [ "dep:valuable" ];
        };
        resolvedDefaultFeatures = [ "once_cell" "std" ];
      };
      "tsuuchi" = rec {
        crateName = "tsuuchi";
        version = "0.1.0";
        edition = "2024";
        src = lib.cleanSourceWith { filter = sourceFilter;  src = ./.; };
        dependencies = [
          {
            name = "serde";
            packageId = "serde";
            features = [ "derive" ];
          }
          {
            name = "thiserror";
            packageId = "thiserror";
          }
          {
            name = "tracing";
            packageId = "tracing";
          }
        ];
        devDependencies = [
          {
            name = "serde_json";
            packageId = "serde_json";
          }
        ];

      };
      "unicode-ident" = rec {
        crateName = "unicode-ident";
        version = "1.0.24";
        edition = "2021";
        sha256 = "0xfs8y1g7syl2iykji8zk5hgfi5jw819f5zsrbaxmlzwsly33r76";
        libName = "unicode_ident";
        authors = [
          "David Tolnay <dtolnay@gmail.com>"
        ];

      };
      "zmij" = rec {
        crateName = "zmij";
        version = "1.0.21";
        edition = "2021";
        sha256 = "1amb5i6gz7yjb0dnmz5y669674pqmwbj44p4yfxfv2ncgvk8x15q";
        authors = [
          "David Tolnay <dtolnay@gmail.com>"
        ];
        features = {
          "no-panic" = [ "dep:no-panic" ];
        };
      };
    };

    #
# crate2nix/default.nix (excerpt start)
#

  /*
    Target (platform) data for conditional dependencies.
    This corresponds roughly to what buildRustCrate is setting.
  */
  makeDefaultTarget = platform: {
    name = platform.rust.rustcTarget;

    unix = platform.isUnix;
    windows = platform.isWindows;
    fuchsia = true;
    test = false;

    inherit (platform.rust.platform)
      arch
      os
      vendor
      ;
    family = platform.rust.platform.target-family;
    env = "gnu";
    endian = if platform.parsed.cpu.significantByte.name == "littleEndian" then "little" else "big";
    pointer_width = toString platform.parsed.cpu.bits;
    debug_assertions = false;
  } // extraTargetFlags;

  registryUrl =
    { registries
    , url
    , crate
    , version
    , sha256
    ,
    }:
    let
      dl = registries.${url}.dl;
      tmpl = [
        "{crate}"
        "{version}"
        "{prefix}"
        "{lowerprefix}"
        "{sha256-checksum}"
      ];
    in
    with lib.strings;
    if lib.lists.any (i: hasInfix "{}" dl) tmpl then
      let
        prefix =
          if builtins.stringLength crate == 1 then
            "1"
          else if builtins.stringLength crate == 2 then
            "2"
          else
            "${builtins.substring 0 2 crate}/${builtins.substring 2 (builtins.stringLength crate - 2) crate}";
      in
      builtins.replaceStrings tmpl [
        crate
        version
        prefix
        (lib.strings.toLower prefix)
        sha256
      ]
    else
      "${dl}/${crate}/${version}/download";

  # Filters common temp files and build files.
  # TODO(pkolloch): Substitute with gitignore filter
  sourceFilter =
    name: type:
    let
      baseName = builtins.baseNameOf (builtins.toString name);
    in
      !(
        # Filter out git
        baseName == ".gitignore"
        || (type == "directory" && baseName == ".git")

        # Filter out build results
        || (
          type == "directory"
          && (
            baseName == "target"
            || baseName == "_site"
            || baseName == ".sass-cache"
            || baseName == ".jekyll-metadata"
            || baseName == "build-artifacts"
          )
        )

        # Filter out nix-build result symlinks
        || (type == "symlink" && lib.hasPrefix "result" baseName)

        # Filter out IDE config
        || (type == "directory" && (baseName == ".idea" || baseName == ".vscode"))
        || lib.hasSuffix ".iml" baseName

        # Filter out nix build files
        || baseName == "Cargo.nix"

        # Filter out editor backup / swap files.
        || lib.hasSuffix "~" baseName
        || builtins.match "^\\.sw[a-z]$$" baseName != null
        || builtins.match "^\\..*\\.sw[a-z]$$" baseName != null
        || lib.hasSuffix ".tmp" baseName
        || lib.hasSuffix ".bak" baseName
        || baseName == "tests.nix"
      );

  /*
    Returns a crate which depends on successful test execution
    of crate given as the second argument.

    testCrateFlags: list of flags to pass to the test exectuable
    testInputs: list of packages that should be available during test execution
  */
  crateWithTest =
    { crate
    , testCrate
    , testCrateFlags
    , testInputs
    , testPreRun
    , testPostRun
    ,
    }:
      assert builtins.typeOf testCrateFlags == "list";
      assert builtins.typeOf testInputs == "list";
      assert builtins.typeOf testPreRun == "string";
      assert builtins.typeOf testPostRun == "string";
      let
        # override the `crate` so that it will build and execute tests instead of
        # building the actual lib and bin targets We just have to pass `--test`
        # to rustc and it will do the right thing.  We execute the tests and copy
        # their log and the test executables to $out for later inspection.
        test =
          let
            drv = testCrate.override (_: {
              buildTests = true;
            });
            # If the user hasn't set any pre/post commands, we don't want to
            # insert empty lines. This means that any existing users of crate2nix
            # don't get a spurious rebuild unless they set these explicitly.
            testCommand = pkgs.lib.concatStringsSep "\n" (
              pkgs.lib.filter (s: s != "") [
                testPreRun
                "$f $testCrateFlags 2>&1 | tee -a $out"
                testPostRun
              ]
            );
          in
          pkgs.stdenvNoCC.mkDerivation {
            name = "run-tests-${testCrate.name}";

            inherit (crate) src;

            inherit testCrateFlags;

            buildInputs = testInputs;

            buildPhase = ''
              set -e
              export RUST_BACKTRACE=1

              # build outputs
              testRoot=target/debug
              mkdir -p $testRoot

              # executables of the crate
              # we copy to prevent std::env::current_exe() to resolve to a store location
              for i in ${crate}/bin/*; do
                cp "$i" "$testRoot"
              done
              chmod +w -R .

              # test harness executables are suffixed with a hash, like cargo does
              # this allows to prevent name collision with the main
              # executables of the crate
              hash=$(basename $out)
              for file in ${drv}/tests/*; do
                f=$testRoot/$(basename $file)-$hash
                cp $file $f
                ${testCommand}
              done
            '';
          };
      in
      pkgs.runCommand "${crate.name}-linked"
        {
          inherit (crate) outputs crateName meta;
          passthru = (crate.passthru or { }) // {
            inherit test;
          };
        }
        (
          lib.optionalString (stdenv.buildPlatform.canExecute stdenv.hostPlatform) ''
            echo tested by ${test}
          ''
          + ''
            ${lib.concatMapStringsSep "\n" (output: "ln -s ${crate.${output}} ${"$"}${output}") crate.outputs}
          ''
        );

  # A restricted overridable version of builtRustCratesWithFeatures.
  buildRustCrateWithFeatures =
    { packageId
    , features ? rootFeatures
    , crateOverrides ? defaultCrateOverrides
    , buildRustCrateForPkgsFunc ? null
    , runTests ? false
    , testCrateFlags ? [ ]
    , testInputs ? [ ]
    , # Any command to run immediatelly before a test is executed.
      testPreRun ? ""
    , # Any command run immediatelly after a test is executed.
      testPostRun ? ""
    ,
    }:
    lib.makeOverridable
      (
        { features
        , crateOverrides
        , runTests
        , testCrateFlags
        , testInputs
        , testPreRun
        , testPostRun
        ,
        }:
        let
          buildRustCrateForPkgsFuncOverriden =
            if buildRustCrateForPkgsFunc != null then
              buildRustCrateForPkgsFunc
            else
              (
                if crateOverrides == pkgs.defaultCrateOverrides then
                  buildRustCrateForPkgs
                else
                  pkgs:
                  (buildRustCrateForPkgs pkgs).override {
                    defaultCrateOverrides = crateOverrides;
                  }
              );
          builtRustCrates = builtRustCratesWithFeatures {
            inherit packageId features;
            buildRustCrateForPkgsFunc = buildRustCrateForPkgsFuncOverriden;
            runTests = false;
          };
          builtTestRustCrates = builtRustCratesWithFeatures {
            inherit packageId features;
            buildRustCrateForPkgsFunc = buildRustCrateForPkgsFuncOverriden;
            runTests = true;
          };
          drv = builtRustCrates.crates.${packageId};
          testDrv = builtTestRustCrates.crates.${packageId};
          derivation =
            if runTests then
              crateWithTest
                {
                  crate = drv;
                  testCrate = testDrv;
                  inherit
                    testCrateFlags
                    testInputs
                    testPreRun
                    testPostRun
                    ;
                }
            else
              drv;
        in
        derivation
      )
      {
        inherit
          features
          crateOverrides
          runTests
          testCrateFlags
          testInputs
          testPreRun
          testPostRun
          ;
      };

  /*
    Returns an attr set with packageId mapped to the result of buildRustCrateForPkgsFunc
    for the corresponding crate.
  */
  builtRustCratesWithFeatures =
    { packageId
    , features
    , crateConfigs ? crates
    , buildRustCrateForPkgsFunc
    , runTests
    , makeTarget ? makeDefaultTarget
    ,
    }@args:
      assert (builtins.isAttrs crateConfigs);
      assert (builtins.isString packageId);
      assert (builtins.isList features);
      assert (builtins.isAttrs (makeTarget stdenv.hostPlatform));
      assert (builtins.isBool runTests);
      let
        rootPackageId = packageId;
        mergedFeatures = mergePackageFeatures (
          args
          // {
            inherit rootPackageId;
            target = makeTarget stdenv.hostPlatform // {
              test = runTests;
            };
          }
        );
        # Memoize built packages so that reappearing packages are only built once.
        builtByPackageIdByPkgs = mkBuiltByPackageIdByPkgs pkgs;
        mkBuiltByPackageIdByPkgs =
          pkgs:
          let
            self = {
              crates = lib.mapAttrs
                (
                  packageId: value: buildByPackageIdForPkgsImpl self pkgs packageId
                )
                crateConfigs;
              target = makeTarget pkgs.stdenv.hostPlatform;
              build = mkBuiltByPackageIdByPkgs pkgs.buildPackages;
            };
          in
          self;
        buildByPackageIdForPkgsImpl =
          self: pkgs: packageId:
          let
            features = mergedFeatures."${packageId}" or [ ];
            crateConfig' = crateConfigs."${packageId}";
            crateConfig = builtins.removeAttrs crateConfig' [
              "resolvedDefaultFeatures"
              "devDependencies"
            ];
            devDependencies = lib.optionals (runTests && packageId == rootPackageId) (
              crateConfig'.devDependencies or [ ]
            );
            dependencies = dependencyDerivations {
              inherit features;
              inherit (self) target;
              buildByPackageId =
                depPackageId:
                # proc_macro crates must be compiled for the build architecture
                if crateConfigs.${depPackageId}.procMacro or false then
                  self.build.crates.${depPackageId}
                else
                  self.crates.${depPackageId};
              dependencies = (crateConfig.dependencies or [ ]) ++ devDependencies;
            };
            buildDependencies = dependencyDerivations {
              inherit features;
              inherit (self.build) target;
              buildByPackageId = depPackageId: self.build.crates.${depPackageId};
              dependencies = crateConfig.buildDependencies or [ ];
            };
            dependenciesWithRenames =
              let
                buildDeps = filterEnabledDependencies {
                  inherit features;
                  inherit (self) target;
                  dependencies = crateConfig.dependencies or [ ] ++ devDependencies;
                };
                hostDeps = filterEnabledDependencies {
                  inherit features;
                  inherit (self.build) target;
                  dependencies = crateConfig.buildDependencies or [ ];
                };
              in
              lib.filter (d: d ? "rename") (hostDeps ++ buildDeps);
            # Crate renames have the form:
            #
            # {
            #    crate_name = [
            #       { version = "1.2.3"; rename = "crate_name01"; }
            #    ];
            #    # ...
            # }
            crateRenames =
              let
                grouped = lib.groupBy (dependency: dependency.name) dependenciesWithRenames;
                versionAndRename =
                  dep:
                  let
                    package = crateConfigs."${dep.packageId}";
                  in
                  {
                    inherit (dep) rename;
                    inherit (package) version;
                  };
              in
              lib.mapAttrs (name: builtins.map versionAndRename) grouped;
          in
          buildRustCrateForPkgsFunc pkgs (
            crateConfig
            // {
              src =
                crateConfig.src or (fetchurl rec {
                  name = "${crateConfig.crateName}-${crateConfig.version}.tar.gz";
                  # https://www.pietroalbini.org/blog/downloading-crates-io/
                  # Not rate-limited, CDN URL.
                  url = "https://static.crates.io/crates/${crateConfig.crateName}/${crateConfig.crateName}-${crateConfig.version}.crate";
                  sha256 =
                    assert (lib.assertMsg (crateConfig ? sha256) "Missing sha256 for ${name}");
                    crateConfig.sha256;
                });
              extraRustcOpts =
                lib.lists.optional (targetFeatures != [ ])
                  "-C target-feature=${lib.concatMapStringsSep "," (x: "+${x}") targetFeatures}";
              inherit
                features
                dependencies
                buildDependencies
                crateRenames
                release
                ;
            }
          );
      in
      builtByPackageIdByPkgs;

  # Returns the actual derivations for the given dependencies.
  dependencyDerivations =
    { buildByPackageId
    , features
    , dependencies
    , target
    ,
    }:
      assert (builtins.isList features);
      assert (builtins.isList dependencies);
      assert (builtins.isAttrs target);
      let
        enabledDependencies = filterEnabledDependencies {
          inherit dependencies features target;
        };
        depDerivation = dependency: buildByPackageId dependency.packageId;
      in
      map depDerivation enabledDependencies;

  /*
    Returns a sanitized version of val with all values substituted that cannot
    be serialized as JSON.
  */
  sanitizeForJson =
    val:
    if builtins.isAttrs val then
      lib.mapAttrs (n: sanitizeForJson) val
    else if builtins.isList val then
      builtins.map sanitizeForJson val
    else if builtins.isFunction val then
      "function"
    else
      val;

  # Returns various tools to debug a crate.
  debugCrate =
    { packageId
    , target ? makeDefaultTarget stdenv.hostPlatform
    ,
    }:
      assert (builtins.isString packageId);
      let
        debug = rec {
          # The built tree as passed to buildRustCrate.
          buildTree = buildRustCrateWithFeatures {
            buildRustCrateForPkgsFunc = _: lib.id;
            inherit packageId;
          };
          sanitizedBuildTree = sanitizeForJson buildTree;
          dependencyTree = sanitizeForJson (buildRustCrateWithFeatures {
            buildRustCrateForPkgsFunc = _: crate: {
              "01_crateName" = crate.crateName or false;
              "02_features" = crate.features or [ ];
              "03_dependencies" = crate.dependencies or [ ];
            };
            inherit packageId;
          });
          mergedPackageFeatures = mergePackageFeatures {
            features = rootFeatures;
            inherit packageId target;
          };
          diffedDefaultPackageFeatures = diffDefaultPackageFeatures {
            inherit packageId target;
          };
        };
      in
      {
        internal = debug;
      };

  /*
    Returns differences between cargo default features and crate2nix default
    features.

    This is useful for verifying the feature resolution in crate2nix.
  */
  diffDefaultPackageFeatures =
    { crateConfigs ? crates
    , packageId
    , target
    ,
    }:
      assert (builtins.isAttrs crateConfigs);
      let
        prefixValues = prefix: lib.mapAttrs (n: v: { "${prefix}" = v; });
        mergedFeatures = prefixValues "crate2nix" (mergePackageFeatures {
          inherit crateConfigs packageId target;
          features = [ "default" ];
        });
        configs = prefixValues "cargo" crateConfigs;
        combined = lib.foldAttrs (a: b: a // b) { } [
          mergedFeatures
          configs
        ];
        onlyInCargo = builtins.attrNames (
          lib.filterAttrs (n: v: !(v ? "crate2nix") && (v ? "cargo")) combined
        );
        onlyInCrate2Nix = builtins.attrNames (
          lib.filterAttrs (n: v: (v ? "crate2nix") && !(v ? "cargo")) combined
        );
        differentFeatures = lib.filterAttrs
          (
            n: v:
              (v ? "crate2nix")
              && (v ? "cargo")
              && (v.crate2nix.features or [ ]) != (v."cargo".resolved_default_features or [ ])
          )
          combined;
      in
      builtins.toJSON {
        inherit onlyInCargo onlyInCrate2Nix differentFeatures;
      };

  /*
    Returns an attrset mapping packageId to the list of enabled features.

    If multiple paths to a dependency enable different features, the
    corresponding feature sets are merged. Features in rust are additive.
  */
  mergePackageFeatures =
    { crateConfigs ? crates
    , packageId
    , rootPackageId ? packageId
    , features ? rootFeatures
    , dependencyPath ? [ crates.${packageId}.crateName ]
    , featuresByPackageId ? { }
    , target
    , # Adds devDependencies to the crate with rootPackageId.
      runTests ? false
    , ...
    }@args:
      assert (builtins.isAttrs crateConfigs);
      assert (builtins.isString packageId);
      assert (builtins.isString rootPackageId);
      assert (builtins.isList features);
      assert (builtins.isList dependencyPath);
      assert (builtins.isAttrs featuresByPackageId);
      assert (builtins.isAttrs target);
      assert (builtins.isBool runTests);
      let
        crateConfig = crateConfigs."${packageId}" or (builtins.throw "Package not found: ${packageId}");
        expandedFeatures = expandFeatures (crateConfig.features or { }) features;
        enabledFeatures = enableFeatures (crateConfig.dependencies or [ ]) expandedFeatures;
        depWithResolvedFeatures =
          dependency:
          let
            inherit (dependency) packageId;
            features = dependencyFeatures enabledFeatures dependency;
          in
          {
            inherit packageId features;
          };
        resolveDependencies =
          cache: path: dependencies:
            assert (builtins.isAttrs cache);
            assert (builtins.isList dependencies);
            let
              enabledDependencies = filterEnabledDependencies {
                inherit dependencies target;
                features = enabledFeatures;
              };
              directDependencies = map depWithResolvedFeatures enabledDependencies;
              foldOverCache = op: lib.foldl op cache directDependencies;
            in
            foldOverCache (
              cache:
              { packageId, features }:
              let
                cacheFeatures = cache.${packageId} or [ ];
                combinedFeatures = sortedUnique (cacheFeatures ++ features);
              in
              if cache ? ${packageId} && cache.${packageId} == combinedFeatures then
                cache
              else
                mergePackageFeatures {
                  features = combinedFeatures;
                  featuresByPackageId = cache;
                  inherit
                    crateConfigs
                    packageId
                    target
                    runTests
                    rootPackageId
                    ;
                }
            );
        cacheWithSelf =
          let
            cacheFeatures = featuresByPackageId.${packageId} or [ ];
            combinedFeatures = sortedUnique (cacheFeatures ++ enabledFeatures);
          in
          featuresByPackageId
          // {
            "${packageId}" = combinedFeatures;
          };
        cacheWithDependencies = resolveDependencies cacheWithSelf "dep" (
          crateConfig.dependencies or [ ]
          ++ lib.optionals (runTests && packageId == rootPackageId) (crateConfig.devDependencies or [ ])
        );
        cacheWithAll = resolveDependencies cacheWithDependencies "build" (
          crateConfig.buildDependencies or [ ]
        );
      in
      cacheWithAll;

  # Returns the enabled dependencies given the enabled features.
  filterEnabledDependencies =
    { dependencies
    , features
    , target
    ,
    }:
      assert (builtins.isList dependencies);
      assert (builtins.isList features);
      assert (builtins.isAttrs target);

      lib.filter
        (
          dep:
          let
            targetFunc = dep.target or (features: true);
          in
          targetFunc { inherit features target; }
          && (!(dep.optional or false) || builtins.any (doesFeatureEnableDependency dep) features)
        )
        dependencies;

  # Returns whether the given feature should enable the given dependency.
  doesFeatureEnableDependency =
    dependency: feature:
    let
      name = dependency.rename or dependency.name;
      prefix = "${name}/";
      len = builtins.stringLength prefix;
      startsWithPrefix = builtins.substring 0 len feature == prefix;
    in
    feature == name || feature == "dep:" + name || startsWithPrefix;

  /*
    Returns the expanded features for the given inputFeatures by applying the
    rules in featureMap.

    featureMap is an attribute set which maps feature names to lists of further
    feature names to enable in case this feature is selected.
  */
  expandFeatures =
    featureMap: inputFeatures:
      assert (builtins.isAttrs featureMap);
      assert (builtins.isList inputFeatures);
      let
        expandFeaturesNoCycle =
          oldSeen: inputFeatures:
          if inputFeatures != [ ] then
            let
              # The feature we're currently expanding.
              feature = builtins.head inputFeatures;
              # All the features we've seen/expanded so far, including the one
              # we're currently processing.
              seen = oldSeen // {
                ${feature} = 1;
              };
              # Expand the feature but be careful to not re-introduce a feature
              # that we've already seen: this can easily cause a cycle, see issue
              # #209.
              enables = builtins.filter (f: !(seen ? "${f}")) (featureMap."${feature}" or [ ]);
            in
            [ feature ] ++ (expandFeaturesNoCycle seen (builtins.tail inputFeatures ++ enables))
          # No more features left, nothing to expand to.
          else
            [ ];
        outFeatures = expandFeaturesNoCycle { } inputFeatures;
      in
      sortedUnique outFeatures;

  /*
    This function adds optional dependencies as features if they are enabled
    indirectly by dependency features. This function mimics Cargo's behavior
    described in a note at:
    https://doc.rust-lang.org/nightly/cargo/reference/features.html#dependency-features
  */
  enableFeatures =
    dependencies: features:
      assert (builtins.isList features);
      assert (builtins.isList dependencies);
      let
        additionalFeatures = lib.concatMap
          (
            dependency:
              assert (builtins.isAttrs dependency);
              let
                enabled = builtins.any (doesFeatureEnableDependency dependency) features;
              in
              if (dependency.optional or false) && enabled then
                [ (dependency.rename or dependency.name) ]
              else
                [ ]
          )
          dependencies;
      in
      sortedUnique (features ++ additionalFeatures);

  /*
    Returns the actual features for the given dependency.

    features: The features of the crate that refers this dependency.
  */
  dependencyFeatures =
    features: dependency:
      assert (builtins.isList features);
      assert (builtins.isAttrs dependency);
      let
        defaultOrNil = if dependency.usesDefaultFeatures or true then [ "default" ] else [ ];
        explicitFeatures = dependency.features or [ ];
        additionalDependencyFeatures =
          let
            name = dependency.rename or dependency.name;
            stripPrefixMatch = prefix: s: if lib.hasPrefix prefix s then lib.removePrefix prefix s else null;
            extractFeature =
              feature:
              lib.findFirst (f: f != null) null (
                map (prefix: stripPrefixMatch prefix feature) [
                  (name + "/")
                  (name + "?/")
                ]
              );
            dependencyFeatures = lib.filter (f: f != null) (map extractFeature features);
          in
          dependencyFeatures;
      in
      defaultOrNil ++ explicitFeatures ++ additionalDependencyFeatures;

  # Sorts and removes duplicates from a list of strings.
  sortedUnique =
    features:
      assert (builtins.isList features);
      assert (builtins.all builtins.isString features);
      let
        outFeaturesSet = lib.foldl (set: feature: set // { "${feature}" = 1; }) { } features;
        outFeaturesUnique = builtins.attrNames outFeaturesSet;
      in
      builtins.sort (a: b: a < b) outFeaturesUnique;

  deprecationWarning =
    message: value:
    if strictDeprecation then
      builtins.throw "strictDeprecation enabled, aborting: ${message}"
    else
      builtins.trace message value;

  #
  # crate2nix/default.nix (excerpt end)
  #
  };
}

