Skip to content

Generate safe bits writers when possible #554

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Bumped `xtensa-lx` and add `xtensa_lx::interrupt::InterruptNumber` implementation.
- Don't use a mask when the width of the mask is the same as the width of the parent register.
- Improved error handling
- Registers with single fields that span the entire register now generate safe `bits` writers.

## [v0.19.0] - 2021-05-26

Expand Down
40 changes: 33 additions & 7 deletions src/generate/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,40 @@ pub fn render(

mod_items.extend(w_impl_items);

mod_items.extend(quote! {
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: #rty) -> &mut Self {
self.0.bits(bits);
self
// the writer can be safe if:
// * there is a single field that covers the entire register
// * that field can represent all values
let can_write_safe = match register
.fields
.as_ref()
.and_then(|fields| fields.iter().next())
.and_then(|field| field.write_constraint)
{
Some(WriteConstraint::Range(range)) => {
range.min == 0 && range.max == u64::MAX >> (64 - rsize)
}
});
_ => false,
};

if can_write_safe {
mod_items.extend(quote! {
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub fn bits(&mut self, bits: #rty) -> &mut Self {
unsafe { self.0.bits(bits) };
self
}
});
} else {
mod_items.extend(quote! {
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: #rty) -> &mut Self {
self.0.bits(bits);
self
}
});
}

close.to_tokens(&mut mod_items);
}
Expand Down