nix icon indicating copy to clipboard operation
nix copied to clipboard

Add a trait for non-path C string?

Open SteveLauC opened this issue 9 months ago • 1 comments
trafficstars

I am thinking about adding another trait to represent string, the definition will be same as our NixPath trait, and these 2 traits only differ in semantics, NixPath is for path, this new trait is for string.

By adding this trait, we split "C string" (C does not have a string type, it is only a sequence of chars followed by a NUL) into 2 categories by semantics:

  1. path
  2. string

Currently, it will be used in 2 interfaces if added:

  1. The ident argument of openlog() on non-Linux systems

    https://github.com/nix-rust/nix/blob/0c40b8d6e4ae7f9f55a9eec1f8b118dcd7db7ec1/src/syslog.rs#L45-L47

    From man page:

    The string pointed to by ident is prepended to every message, and is typically set to the program name.

  2. The path argument of posix_spawnp()

    https://github.com/nix-rust/nix/blob/0c40b8d6e4ae7f9f55a9eec1f8b118dcd7db7ec1/src/spawn.rs#L396-L397

    It is the name of the program that the spawned child process will execute

    This argument should not be called path, I will rename it to file


Alternative approaches

  1. Just use the NixPath trait

    It will definitely work, though it will feel weird semantically due to the Path in its name. Or maybe we can rename the trait to something like NixCString?

  2. Use S: AsRef<OsStr>

    openlog() currently uses this approach, after converting it to &OsStr we can use NixPath under the hood, so it is convenient:

    <OsStr as NixPath>::with_nix_path(os_str.as_ref(), |c_str| {
        // do something with c_str
    });
    

    The only flaw of this method IMHO is that users cannot use &CStr because CStr is not AsRef<OsStr>, but &CStr should be allowed.

SteveLauC avatar Feb 02 '25 14:02 SteveLauC