Skip to content

Suggestion: CStr literals #75401

Closed
Closed
@LunarLambda

Description

@LunarLambda

Why?

Currently, creating a CStr, even from a bytestring literal, is quite noisy.

// NOTE: Don't forget to add \0 at the end or this is unsound!
let cstr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello, World\0") };

Furthermore, there's no way to ensure the well formed-ness of that literal at compile time¹, despite hardcoded C-strings being fairly common when creating bindings for C libraries.

How?

To address this, I would like to propose a new string literal type:

let cstr = c"Hello, World!";

It would function nearly identical to byte-string literals, with the following key differences:

  1. Its type is &CStr, not &[u8]
  2. It may not contain any nul bytes (\0, \x00 as well as a 'physical' nul byte are forbidden)
  3. The compiler automatically adds a nul byte at the end of the string.

See also "Alternatives?" below.

Pros?

  • Fills a niche in the language people are forced to build around²
  • Allows creation of const CStr items (currently not possible on stable)

Cons?

  • Have to commit to adding a new literal (sub)type to the language, which may require small tweaks to the parser

Alternatives?

  1. Make associated functions on CStr const. This would still leave the burden of checking on the user.
  2. Add a cstr! macro taking a byte-string literal and applying the needed checks and transformations.

¹ It is possible using proc-macros, though this poses different issues regarding ergonomics and stability.
² GitHub code search for CStr::from_bytes_with_nul_unchecked

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-FFIArea: Foreign function interface (FFI)C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions