google / google/zerocopy

`#[derive(IntoBytes)]` should ignore unused `const` arguments

Open
#2,723 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
2.6k
Forks
179
Avg merge
1d 19h
Merged PRs (30d)
29

Description

When deriving `IntoBytes`, we check to see whether any generics are present:

https://github.com/google/zerocopy/blob/e5c4179158a161c70b94f08160e71031e187e323/zerocopy-derive/src/lib.rs#L1291

If they are, we require all fields to be `Unaligned`:

https://github.com/google/zerocopy/blob/e5c4179158a161c70b94f08160e71031e187e323/zerocopy-derive/src/lib.rs#L1312-L1321

This requirement could be lifted if the only generic parameters are `const` parameters which are not used in the body of the type. This should just be a matter of filtering `ast.generics.const_params()` and only retaining `const` params which appear in the type's body. There may be edge cases in which a `const` param is only used inside of another quantification (e.g. there's a nested `const` argument that shadows the outer one), but it's fine to conservatively treat these as being equal – it will just result in more types being rejected than should be.

## Original text

I have a const generic in a type, and no matter what types I set the inner fields (including a padding field), the derive macro insists that usize, u64, u32, etc. are unaligned. I tried setting a different type for the generic (u8, u16, u32), still the same problem.

```rust
use std::path::{Path, PathBuf};
use zerocopy::{FromBytes, Immutable, IntoBytes};

const MERC_SCALE: f64 = 123.456;
const TILE_SIZE: [f64; 20] = [1.; 20];

#[derive(Clone, IntoBytes, FromBytes, Immutable)]
#[repr(C)]
pub struct Tile(pub u32, pub u32);

impl Tile {
pub fn path>(&self, prefix: P, extension: &str) -> PathBuf {
prefix.as_ref().join(L.to_string()).join(self.0.to_string()).join(self.1.to_string()).with_extension(extension)
}
}

pub fn get_tile(x: f64, y: f64) -> Tile {
let tile_size = TILE_SIZE[L];
Tile(((MERC_SCALE + x) / tile_size) as u32, ((MERC_SCALE - y) / tile_size) as u32)
}
```

Error:
```
|
9 | #[derive(Clone, IntoBytes, FromBytes, Immutable)]
| ^^^^^^^^^ the trait `zerocopy::Unaligned` is not implemented for `u32`
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.