Skip to content

Allow specifying custom from_bits/to_bits implementation for third-party types. #76

Description

@reitermarkus

I currently have this in one crate:

/// Clock selection.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ClkSel {
    /// Selects the internal clock.
    Internal,
    /// Selects the external SMA clock input.
    External,
}

impl ClkSel {
    /// Creates a new `ClkSel` variant from a bit representation.
    const fn from_bits(bits: u8) -> Self {
        if bits & 0b1 == 0 {
            Self::Internal
        } else {
            Self::External
        }
    }

    /// Returns the bit representation of the current variant.
    const fn into_bits(self) -> u8 {
        match self {
            Self::Internal => 0,
            Self::External => 1,
        }
    }
}

/// Configuration register.
#[bitfield(u8)]
#[derive(PartialEq, Eq)]
pub struct Cfg {
    #[bits(1)]
    clk_sel: ClkSel,
    dac_resetb: bool,
    dac_sleep: bool,
    dac_txena: bool,
    trf0_ps: bool,
    trf1_ps: bool,
    att0_rstn: bool,
    att1_rstn: bool,
}

Now, I want to move ClkSel into a separate crate, but not move from_bits/into_bits, so I'd need something like this:

const fn clk_sel_from_bits(bits: u8) -> Self {
    if bits & 0b1 == 0 {
        Self::Internal
    } else {
        Self::External
    }
}

const fn clk_sel_into_bits(self) -> u8 {
    match self {
        Self::Internal => 0,
        Self::External => 1,
    }
}

/// Configuration register.
#[bitfield(u8)]
#[derive(PartialEq, Eq)]
pub struct Cfg {
    #[bits(1, from = clk_sel_from_bits, into = clk_sel_into_bits)]
    clk_sel: ClkSel,
    dac_resetb: bool,
    dac_sleep: bool,
    dac_txena: bool,
    trf0_ps: bool,
    trf1_ps: bool,
    att0_rstn: bool,
    att1_rstn: bool,
}

Not sure if it's already possible somehow. I tried using access = na to see if it would be possible to have a different type internally, but this doesn't generate a private getter/setter.

Maybe alternatively, something like access = private would work, or simply not defaulting to pub visibility when no visibility is specified.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions