Implementing rand::fill for half::f16

Hi,

I'm doing some experiments with the f16 type from the half crate, and I ended up needing to implement the Fill trait from the rand crate for [f16].

I'm aware that because of the orphan rule, I can't implement this on my own crate, so I was planning to open a PR with the code I needed. I soon ran into this error:

error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
  --> /home/andy/dev/projects/half-rs/src/rand_distr.rs:96:1
   |
96 | impl rand::Fill for [f16] {
   | ^^^^^^^^^^^^^^^^^^^^-----
   |                     |
   |                     this is not defined in the current crate because slices are always foreign
   |
   = note: impl doesn't have any local type before any uncovered type parameters
   = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
   = note: define and implement a trait or new type instead

This is in a local copy of the half crate.

Is there a way to implement what I need?

You need to contribute it to rand itself.

That doesn't feel very Rusty. So if I want to implement that trait for any arbitrary type I own, I have to go the provider of that trait and add my crate as a feature/dependency on the crate that defines that trait?

Unfortunately rand::Fill just doesn’t seem to be designed to be an extension point for third-party crates to impl it for [CustomType] – it’s only possible for CustomType (which would presumably be some collection-like type). A trait for filling [CustomType] would have to look like something like

trait Fill {
    fn fill(_: &mut [Self], _: &mut impl Rng);
}

That's unfortunate. I've opened an issue on the rand repo:

1 Like

I wonder if it would work to implement Fill for a new type wrapper around &mut [f16].

1 Like

What does it mean to generate a random f16? What probability distribution are you sampling from?

1 Like

The existing implementations for f32 and f64 use the StandardUniform distribution.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.