rust-rgb icon indicating copy to clipboard operation
rust-rgb copied to clipboard

Struct parameterized with colorspace newtype not accepted by compiler

Open mechazoidal opened this issue 7 years ago • 3 comments
trafficstars

Hi, I'm working with texture generation using this crate and would like to have the pixel operations use saturating_* math functions instead of the default.

Per the docs, I implemented a colorspace newtype and a different "add" implementation for it. However, the compiler insists I must provide Add for the parametrized type itself (rgb::RGBA<openktg::LinearLight, u16>): which I can't do as this is an external crate.

I am relatively new to Rust, so is this something I'm missing, or a legitimate bug with parameterized RGB structs?

Here's a minimal gist to illustrate: https://gist.github.com/rust-play/40a8fc9422f88c5af8bcd5900fe9230a

mechazoidal avatar May 11 '18 20:05 mechazoidal

Rust has "orphan rules" which guarantee that globally for every possible program, there can't be more than one implementation of any trait for any type.

Simplifying, you can implement a trait for a type only if either:

  • it's your type, or
  • it's your trait.

You can't implement someone else's trait (like std::ops::Add) for someone else's type (like openktg::LinearLight, since there's no guarantee that nobody else could create a conflicting implementation.

However, I may be able to add a more general Add implementation. I'll check that.

kornelski avatar May 11 '18 21:05 kornelski

I've released v0.8.9 which allows px+px for arbitrary newtypes.

Note that px.map(||) can't work if types of rgb and alpha are different, because Rust is statically typed, and the closure can't accept more than one type (it's still statically typed, even though it doesn't look like it). There's map_rgb and new_alpha for this reason.

kornelski avatar May 11 '18 21:05 kornelski

Thank you for the prompt turnaround! The rules make sense, I have no problem using map_rgb/new_alpha, and this should be what I need!

mechazoidal avatar May 11 '18 23:05 mechazoidal

This issue looks to have been resolved in v0.8.9, I'd recommend closing it.

ripytide avatar May 23 '24 12:05 ripytide