Rust API guidelines

Related tags

Cryptography rust
Overview

Rust API guidelines

This is a set of recommendations on how to design and present APIs for the Rust programming language. They are authored largely by the Rust library team, based on experiences building the Rust standard library and other crates in the Rust ecosystem.

Read them here.

Join the discussion

See the Discussions tab for proposing new API guidelines, asking questions about how to apply them, and for proposing new ones.

License

This project is licensed under either of Apache License, Version 2.0 or MIT license, at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache 2.0 license, shall be dual licensed as above, without any additional terms or conditions.

See CONTRIBUTING.md.

Comments
  • Justification of html_root_url is missing nuance

    Justification of html_root_url is missing nuance

    cc https://github.com/rust-lang/api-guidelines/issues/75, @dtolnay

    From https://github.com/env-logger-rs/env_logger/issues/185:

    The scenario where this goes wrong (assuming you're the author of env_logger and not using html_root_url) is:

    1. Another downstream crate uses env_logger as a dependency
    2. downstream re-exports or in some other way links to env_logger
    3. A user or developer of downstream builds documentation locally with cargo doc --no-deps (without --extern-html-root-url, because in practice no one but docs.rs does that).

    Then the links to env_logger will be broken. But there's a simple fix and the fix is to remove --no-deps. Is this really so common that it's worth recommending that library authors use html_root_url?

    Note that I'm hoping to fix this properly in cargo instead: https://github.com/rust-lang/cargo/issues/8296

    amendment T-libs disposition-merge proposed-final-comment-period finished-final-comment-period 
    opened by jyn514 24
  • Guidance for what to write in Error::description()

    Guidance for what to write in Error::description()

    My understanding is that nothing should ever use description(). Most errors will have a significantly more helpful Display representation than what the signature of description() allows.

    Nevertheless, description() is there and has to return something.

    new guideline 
    opened by dtolnay 9
  • Discourage trait bounds on data structures

    Discourage trait bounds on data structures

    Closes #6

    This is an attempt at a guideline for discouraging trait bounds on data structures. It looks like the discussion has run its course, but it might be a bit premature to capture this in a guideline. If so I guess we can move the discussion back to #6.

    I thought I'd open this as a PR and get some general feedback on what we expect guidelines to look like, so I can align them better in the future. Some things I'm not sure about:

    • Should all guidelines have an advantages and disadvantages section?
    • Should all examples be self-contained or can they depend on previous ones?
    • Should we keep discussion points succinct or expand on them a bit?
    • How strict should our wording be about conforming to the guideline?
    opened by KodrAus 8
  • Send and Sync errors guideline should call attention to trait objects

    Send and Sync errors guideline should call attention to trait objects

    reqwest::Error::get_ref returns Option<&(Error + 'static)> which is an error that is not Send and Sync. This is easy to miss and should be noted in C-SEND-SYNC-ERR.

    opened by dtolnay 7
  • Suggest MSRV policy

    Suggest MSRV policy

    I don't think there's a strong consensus here yet.

    However, there seems to be a weak consensus, and also de-facto practice for many popular crates (cfg-if, lazy-static). Additionally, there's a lot of continuous discussion and re-litigation across various forums and issue trackers.

    So it seems like tentatively documenting current practice might make sense?

    opened by matklad 5
  • Test for Send/Sync/other traits with where Self: Send + Sync + ...

    Test for Send/Sync/other traits with where Self: Send + Sync + ...

    I think it is better to add a where clause to the struct/enum/union definition which is required to be Send/Sync/any other trait. First, of all, it becomes part of the item declaration and second, it doesn't require compiling the crate with cfg(test) for verifying the implementation of the auto traits.

    Compare this (taken from this paragraph):

    #[test]
    fn test_send() {
        fn assert_send<T: Send>() {}
        assert_send::<MyStrangeType>();
    }
    
    #[test]
    fn test_sync() {
        fn assert_sync<T: Sync>() {}
        assert_sync::<MyStrangeType>();
    }
    

    To this:

    struct MyStrangeType
    where
        Self: Send + Sync
    {
        // ...
    }
    

    This style doesn't conflict with clippy and rustc lints. So how about amending that paragraph with the new guideline?

    opened by Veetaha 5
  • Convention for Naming Getters

    Convention for Naming Getters

    I noticed that the guidelines don't recommend a way to name getters.

    fn get_member(&self) -> &Member
    

    vs

    fn member(&self) -> &Member
    

    Might be nice to recommend something here.

    I'd be strongly in favor of the second option without get_.

    new guideline 
    opened by theduke 5
  • Exceptions for setting html_root_url and documentation to docs.rs

    Exceptions for setting html_root_url and documentation to docs.rs

    The main one I know of is docs.rs only supports documenting the default feature set: https://github.com/onur/docs.rs/issues/29.

    Dependency on system libraries may also be a problem.

    clarification 
    opened by dtolnay 5
  • Discourage trait bounds on data structures unless necessary

    Discourage trait bounds on data structures unless necessary

    Example from flate2:

    pub struct EncoderReader<R: Read> {
        inner: EncoderReaderBuf<BufReader<R>>,
    }
    

    Bounds like this are annoying because they transitively infect any structs containing this type. Usually trait bounds should go just on impl blocks, not on data structures.

    There are two exceptions where trait bounds on data structures are required.

    1. The data structure refers to an associated type of the trait. Cow is an example of this.
    2. The data structure has a Drop impl that requires trait bounds. Rust currently requires all bounds on the Drop impl to also be present on the data structure.

    Relevant flate2 issue: https://github.com/alexcrichton/flate2-rs/issues/88

    important 
    opened by dtolnay 5
  • What is the reason for `C-RW-VALUE`?

    What is the reason for `C-RW-VALUE`?

    Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE).

    https://rust-lang-nursery.github.io/api-guidelines/interoperability.html#c-rw-value https://github.com/rust-lang-nursery/api-guidelines/blob/05a1d5e5568606442c770919d167513dbbf78024/src/interoperability.md#generic-readerwriter-functions-take-r-read-and-w-write-by-value-c-rw-value

    opened by tbu- 4
  • Steps for checking that your html_root_url is correct

    Steps for checking that your html_root_url is correct

    Hyper has been using a bad html_root_url since 0.10.7 (https://github.com/hyperium/hyper/issues/1193). Let's explain or link to an explanation of how to pick the right html_root_url so users are not forced to guess.

    clarification 
    opened by dtolnay 4
  • Update sealed traits pattern

    Update sealed traits pattern

    There's no need to have a doc-hidden method to simulate private trait items. They can be placed in the supertrait that performs the sealing. The advantage here is that the compiler enforces that it's not used downstream. I personally use this pattern in a few places.

    opened by jhpratt 0
  • C-COMMON-TRAITS favors implementing traits too eagerly

    C-COMMON-TRAITS favors implementing traits too eagerly

    C-COMMON-TRAITS says that "crates that define new types should eagerly implement all applicable, common traits." The problem with this comes with the vague definition of applicable, which may indicate that one should simply implement as many common traits as it can, such as Eq and Org. The drawbacks of this:

    • If a struct deriving Eq or Ord adds a private field which does not implement one of these, we have to drop that implementation, leading to a major breaking change in the API. It does not seem reasonable to fully impose this guideline and cause that certain future changes to public structs turn into API changes.
      • This has caught my attention because the recently added Clippy trait derive_partial_eq_without_eq is leaving potentially unwanted warnings on any project with a public type deriving PartialEq but not Eq (https://github.com/rust-lang/rust-clippy/issues/9063).
    • See also #99: Deriving Ord might not have a meaningful implementation on enums, and it is unclear what benefits are attained from demanding these types to implement Ord and Default when there isn't a meaningful order between variants or a variant which could be considered the default one.

    I suggest that the guideline is rephrased to drop the idea of "eagerly" implementing traits, and let developers understand that they should strike a balance between attaining interoperability with the ecosystem and writing a stable API that won't break due to a premature derive.

    opened by Enet4 0
  • C-STABLE too restrictive?

    C-STABLE too restrictive?

    C-STABLE says:

    A crate cannot be stable (>=1.0.0) without all of its public dependencies being stable.

    However, Cargo treats unstable versions in a special way:

    The version 0.0.x is not considered compatible with any other version.

    Since this means that Cargo will not allow any updates of an unstable dependency specified as version 0.0.x because it might contain breaking changes, it seems to me that a stable crate can have an unstable dependency that is specified as version 0.0.x, and that C-STABLE should only apply to crates that have dependencies on the forms 0.x or 0.

    opened by tobiasvl 4
  • C-METADATA: Change `authors` field to optional

    C-METADATA: Change `authors` field to optional

    Per RFC 3052, the authors field in Cargo.toml is now optional, and this fact should be widely communicated.

    See also:

    • https://github.com/rust-lang/rfcs/pull/3052
    • https://github.com/rust-lang/rust/issues/83227
    opened by tobiasvl 4
  • Elaborate the C-DEREF guideline

    Elaborate the C-DEREF guideline

    The motivation for the C-DEREF guideline and the potential problems resulting from ignoring it are (imho) not self explaning. The strongest clue I can find is from the guideline being filed in the Predictability section.

    Neither the guideline, the doc or the smart pointer section of The Book explicitly define the difference between smart pointers and general applications of the newtype pattern. Outside the std library contributors there does seem to be confusion (see this old reddit thread). Maybe just referencing C-SMART-PTR would suffice.

    Ideally the guideline shouldn't just describe what not to do, but what to do instead: When to impl AsRef/AsMut? What other options are there?

    opened by NeverGivinUp 1
Owner
The Rust Programming Language
The Rust Programming Language
Rust NACL Wrapper API

Rust NACL Wrapper API NaCl (pronounced "salt") is a new easy-to-use high-speed software library for network communication, encryption, decryption, sig

Júlio César de Brito Gardona 1 Jan 19, 2022
Rust API Client for ImageKit.io a file storage and image processing service

Rust API Client for ImageKit.io a file storage and image processing service Usage You must retrieve your Public and Private Keys from the ImageKit Dev

Esteban Borai 4 Jul 31, 2022
A Rust library to interact with the MPesa API, simplifying B2C payment integrations and more.

MPesa SDK (Rust Library) A Rust library to interact with the MPesa API, simplifying B2C payment integrations and more. Features Configuration manageme

Ismael GraHms 8 Aug 23, 2023
A diffusers API in Burn (Rust)

diffusers-burn: A diffusers API in Rust/Burn ⚠️ This is still in development - contributors welcome! The diffusers-burn crate is a conversion of diffu

OxideAI 6 Nov 29, 2023
A Boring(SSL)-compatible API abstraction for Rust cryptographic implementations.

A Boring(SSL)-compatible API abstraction for Rust cryptographic implementations. What is Superboring? Superboring hides the complexity, diversity and

Frank Denis 7 Dec 29, 2023
A Simple Rust NFT API + Smart Contract

Rust NFT API Purpose Rust NFT API is a simple RESTful API developed in Rust that offers functionalities for creating, retrieving, and listing Non-Fung

Luis Soares 5 Feb 25, 2024
A Rust implementation of ECMAScript's Temporal API

Temporal in Rust ⚠️ This crate is highly experimental and NOT stable. We cannot make any guarantee that the API will be stable until 0.1.0. Do not use

Boa 8 Feb 29, 2024
A node API for the dprint TypeScript and JavaScript code formatter

dprint-node A node API for the dprint TypeScript and JavaScript code formatter. It's written in Rust for blazing fast speed. Usage Pass a file path an

Devon Govett 431 Dec 24, 2022
binance API client

bian-rs 币安API Rust async SDK 完成情况 接口 现货 U本位合约 币本位合约 欧式期权 http ?? 开发中 ?? ?? 开发中 未开始 websocket ?? 开发中 ?? ?? 开发中 未开始 使用 在 Cargo.toml 中添加依赖 [dependencies]

null 28 Nov 13, 2022
Rest API to check if a password is in a data breach

easypwned (haveibeenpwned / HIBP) Rest API to check if a password is in a data breach. Works offline - everything stays on your machine! Database is i

easybill GmbH 8 Mar 16, 2022
OGC API & STAC - Proof of Concept

OAPI - POC Proof of concept (POC) to ingest geospatial datasets from MeteoSuisse into a SpatioTemporal Asset Catalog (STAC), expose as OGC API Feature

Camptocamp 32 Dec 1, 2022
A demo of the Internet Computer's Bitcoin API

Bitcoin Integration Demo A demo of the bitcoin endpoints on the Internet Computer. This demo is already deployed to the IC, so you can already try it

Islam El-Ashi 8 Jul 2, 2022
An API and test-app that exposes zcash functionality for app consumption

Zingolib This repo provides both a library for zingoproxyclient and zingo-mobile, as well as an included cli application to interact with zcashd via l

ZingoLabs 5 Dec 15, 2022
API Utility for Hive Blockchain

Apiary - Hive API Utility WIP Todo Full API Coverage Follow Rust API Guidelines: https://rust-lang.github.io/api-guidelines/about.html Implement Displ

Bora 2 Oct 22, 2022
Gnosis Safe Tx Service API client & associated tooling

Safe Transaction Service API Client Using the SDK Instantiate an API client use safe_sdk::SafeClient; /// From a chain id, by looking up hardcoded en

Nomad 3 Dec 15, 2022
Bindings to MLIR using the full C++ API

Mithril Oxide Mithril MLIR is hard to rust but we did it anyway. Rust bindings to MLIR via the C++ API. Project structure mithril-oxide: Our Rusty bin

Lambdaclass 6 Jun 10, 2023
reth-indexer reads directly from the reth db and indexes the data into a postgres database all decoded with a simple config file and no extra setup alongside exposing a API ready to query the data.

reth-indexer reth-indexer reads directly from the reth db and indexes the data into a postgres database all decoded with a simple config file and no e

Josh Stevens 306 Jul 12, 2023
A smart-contract api and client for revm

revmup A smart contract and client API for revm. Features: Auto-generate contracts that interact directly with revm without needing ethers provider Co

Dave Bryson 17 Aug 6, 2023
Bindings for the etherscan API and other block explorers.

foundry-block-explorers Bindings for the etherscan.io web API and other block explorers. Examples use ethers_core::types::Chain; use foundry_block_exp

Foundry 7 Nov 3, 2023