Unit type aliases (Percentage, DegreesCelsius) provide no type safety

Open
#55 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
45/100
Issue type
Refactor
Clarity
Mostly clear
Activity status
Active
Tech stack
rust
Domain
embedded-iot

Research direction

Start with embedded-sensors/src/humidity.rs and embedded-sensors/src/temperature.rs, then trace usages of Percentage and DegreesCelsius across the crate. Define the newtype API and determine which conversions and arithmetic operations are required, while accounting for the stated breaking-change scope. Done means the two units are distinct types and incompatible values no longer compile where the wrong unit is used.

Written by the indexing model from the issue text.

Description

BREAKING CHANGE enhancement rust

Problem

Percentage (embedded-sensors/src/humidity.rs) and DegreesCelsius (embedded-sensors/src/temperature.rs) are both plain type aliases for f32. They are therefore the same type, and the compiler cannot distinguish them:

let rh: Percentage = sensor.relative_humidity()?;
temp_sensor.set_temperature_threshold_low(rh)?; // compiles fine

For a HAL whose purpose is unit-correct sensor abstraction, this is arguably the largest design gap in the crate.

Suggested fix

Introduce #[repr(transparent)] newtypes:

#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct DegreesCelsius(pub f32);

with From<f32> / Into<f32> (or an explicit constructor, see the validation issue) and the usual arithmetic impls where they make sense. Runtime cost is zero.

This is a breaking change and should be batched with any other breaking API work.

Related

Pairs naturally with the sample-domain validation issue - a newtype constructor is the obvious place to reject NaN / out-of-range values.

Dominant language
Rust
Stars
4
Forks
9
Avg merge
5d 13h
Merged PRs (30d)
3

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from OpenDevicePartnership/embedded-sensors

All issues in OpenDevicePartnership/embedded-sensors

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.