msp430g2553/
generic.rs

1use core::marker;
2
3/// Raw register type
4pub trait RegisterSpec {
5    /// Raw register type (`u8`, `u16`, `u32`, ...).
6    type Ux: Copy;
7}
8
9/// Trait implemented by readable registers to enable the `read` method.
10///
11/// Registers marked with `Writable` can be also `modify`'ed.
12pub trait Readable: RegisterSpec {
13    /// Result from a call to `read` and argument to `modify`.
14    type Reader: From<R<Self>> + core::ops::Deref<Target = R<Self>>;
15}
16
17/// Trait implemented by writeable registers.
18///
19/// This enables the  `write`, `write_with_zero` and `reset` methods.
20///
21/// Registers marked with `Readable` can be also `modify`'ed.
22pub trait Writable: RegisterSpec {
23    /// Writer type argument to `write`, et al.
24    type Writer: From<W<Self>> + core::ops::DerefMut<Target = W<Self>>;
25}
26
27/// Reset value of the register.
28///
29/// This value is the initial value for the `write` method. It can also be directly written to the
30/// register by using the `reset` method.
31pub trait Resettable: RegisterSpec {
32    /// Reset value of the register.
33    fn reset_value() -> Self::Ux;
34}
35
36/// This structure provides volatile access to registers.
37#[repr(transparent)]
38pub struct Reg<REG: RegisterSpec> {
39    register: vcell::VolatileCell<REG::Ux>,
40    _marker: marker::PhantomData<REG>,
41}
42
43unsafe impl<REG: RegisterSpec> Send for Reg<REG> where REG::Ux: Send {}
44
45impl<REG: RegisterSpec> Reg<REG> {
46    /// Returns the underlying memory address of register.
47    ///
48    /// ```ignore
49    /// let reg_ptr = periph.reg.as_ptr();
50    /// ```
51    #[inline(always)]
52    pub fn as_ptr(&self) -> *mut REG::Ux {
53        self.register.as_ptr()
54    }
55}
56
57impl<REG: Readable> Reg<REG> {
58    /// Reads the contents of a `Readable` register.
59    ///
60    /// You can read the raw contents of a register by using `bits`:
61    /// ```ignore
62    /// let bits = periph.reg.read().bits();
63    /// ```
64    /// or get the content of a particular field of a register:
65    /// ```ignore
66    /// let reader = periph.reg.read();
67    /// let bits = reader.field1().bits();
68    /// let flag = reader.field2().bit_is_set();
69    /// ```
70    #[inline(always)]
71    pub fn read(&self) -> REG::Reader {
72        REG::Reader::from(R {
73            bits: self.register.get(),
74            _reg: marker::PhantomData,
75        })
76    }
77}
78
79impl<REG: Resettable + Writable> Reg<REG> {
80    /// Writes the reset value to `Writable` register.
81    ///
82    /// Resets the register to its initial state.
83    #[inline(always)]
84    pub fn reset(&self) {
85        self.register.set(REG::reset_value())
86    }
87
88    /// Writes bits to a `Writable` register.
89    ///
90    /// You can write raw bits into a register:
91    /// ```ignore
92    /// periph.reg.write(|w| unsafe { w.bits(rawbits) });
93    /// ```
94    /// or write only the fields you need:
95    /// ```ignore
96    /// periph.reg.write(|w| w
97    ///     .field1().bits(newfield1bits)
98    ///     .field2().set_bit()
99    ///     .field3().variant(VARIANT)
100    /// );
101    /// ```
102    /// or an alternative way of saying the same:
103    /// ```ignore
104    /// periph.reg.write(|w| {
105    ///     w.field1().bits(newfield1bits);
106    ///     w.field2().set_bit();
107    ///     w.field3().variant(VARIANT)
108    /// });
109    /// ```
110    /// In the latter case, other fields will be set to their reset value.
111    #[inline(always)]
112    pub fn write<F>(&self, f: F)
113    where
114        F: FnOnce(&mut REG::Writer) -> &mut W<REG>,
115    {
116        self.register.set(
117            f(&mut REG::Writer::from(W {
118                bits: REG::reset_value(),
119                _reg: marker::PhantomData,
120            }))
121            .bits,
122        );
123    }
124}
125
126impl<REG: Writable> Reg<REG>
127where
128    REG::Ux: Default,
129{
130    /// Writes 0 to a `Writable` register.
131    ///
132    /// Similar to `write`, but unused bits will contain 0.
133    ///
134    /// # Safety
135    ///
136    /// Unsafe to use with registers which don't allow to write 0.
137    #[inline(always)]
138    pub unsafe fn write_with_zero<F>(&self, f: F)
139    where
140        F: FnOnce(&mut REG::Writer) -> &mut W<REG>,
141    {
142        self.register.set(
143            (*f(&mut REG::Writer::from(W {
144                bits: REG::Ux::default(),
145                _reg: marker::PhantomData,
146            })))
147            .bits,
148        );
149    }
150}
151
152impl<REG: Readable + Writable> Reg<REG> {
153    /// Modifies the contents of the register by reading and then writing it.
154    ///
155    /// E.g. to do a read-modify-write sequence to change parts of a register:
156    /// ```ignore
157    /// periph.reg.modify(|r, w| unsafe { w.bits(
158    ///    r.bits() | 3
159    /// ) });
160    /// ```
161    /// or
162    /// ```ignore
163    /// periph.reg.modify(|_, w| w
164    ///     .field1().bits(newfield1bits)
165    ///     .field2().set_bit()
166    ///     .field3().variant(VARIANT)
167    /// );
168    /// ```
169    /// or an alternative way of saying the same:
170    /// ```ignore
171    /// periph.reg.modify(|_, w| {
172    ///     w.field1().bits(newfield1bits);
173    ///     w.field2().set_bit();
174    ///     w.field3().variant(VARIANT)
175    /// });
176    /// ```
177    /// Other fields will have the value they had before the call to `modify`.
178    #[inline(always)]
179    pub fn modify<F>(&self, f: F)
180    where
181        for<'w> F: FnOnce(&REG::Reader, &'w mut REG::Writer) -> &'w mut W<REG>,
182    {
183        let bits = self.register.get();
184        self.register.set(
185            f(
186                &REG::Reader::from(R {
187                    bits,
188                    _reg: marker::PhantomData,
189                }),
190                &mut REG::Writer::from(W {
191                    bits,
192                    _reg: marker::PhantomData,
193                }),
194            )
195            .bits,
196        );
197    }
198}
199
200/// Register reader.
201///
202/// Result of the `read` methods of registers. Also used as a closure argument in the `modify`
203/// method.
204pub struct R<REG: RegisterSpec + ?Sized> {
205    pub(crate) bits: REG::Ux,
206    _reg: marker::PhantomData<REG>,
207}
208
209impl<REG: RegisterSpec> R<REG> {
210    /// Reads raw bits from register.
211    #[inline(always)]
212    pub fn bits(&self) -> REG::Ux {
213        self.bits
214    }
215}
216
217impl<REG: RegisterSpec, FI> PartialEq<FI> for R<REG>
218where
219    REG::Ux: PartialEq,
220    FI: Copy + Into<REG::Ux>,
221{
222    #[inline(always)]
223    fn eq(&self, other: &FI) -> bool {
224        self.bits.eq(&(*other).into())
225    }
226}
227
228/// Register writer.
229///
230/// Used as an argument to the closures in the `write` and `modify` methods of the register.
231pub struct W<REG: RegisterSpec + ?Sized> {
232    ///Writable bits
233    pub(crate) bits: REG::Ux,
234    _reg: marker::PhantomData<REG>,
235}
236
237impl<REG: RegisterSpec> W<REG> {
238    /// Writes raw bits to the register.
239    ///
240    /// # Safety
241    ///
242    /// Read datasheet or reference manual to find what values are allowed to pass.
243    #[inline(always)]
244    pub unsafe fn bits(&mut self, bits: REG::Ux) -> &mut Self {
245        self.bits = bits;
246        self
247    }
248}
249
250#[doc(hidden)]
251pub struct FieldReaderRaw<U, T> {
252    pub(crate) bits: U,
253    _reg: marker::PhantomData<T>,
254}
255
256impl<U, FI> FieldReaderRaw<U, FI>
257where
258    U: Copy,
259{
260    /// Creates a new instance of the reader.
261    #[allow(unused)]
262    #[inline(always)]
263    pub(crate) fn new(bits: U) -> Self {
264        Self {
265            bits,
266            _reg: marker::PhantomData,
267        }
268    }
269}
270
271#[doc(hidden)]
272pub struct BitReaderRaw<T> {
273    pub(crate) bits: bool,
274    _reg: marker::PhantomData<T>,
275}
276
277impl<FI> BitReaderRaw<FI> {
278    /// Creates a new instance of the reader.
279    #[allow(unused)]
280    #[inline(always)]
281    pub(crate) fn new(bits: bool) -> Self {
282        Self {
283            bits,
284            _reg: marker::PhantomData,
285        }
286    }
287}
288
289/// Field reader.
290///
291/// Result of the `read` methods of fields.
292pub type FieldReader<U, FI> = FieldReaderRaw<U, FI>;
293
294/// Bit-wise field reader
295pub type BitReader<FI> = BitReaderRaw<FI>;
296
297impl<U, FI> FieldReader<U, FI>
298where
299    U: Copy,
300{
301    /// Reads raw bits from field.
302    #[inline(always)]
303    pub fn bits(&self) -> U {
304        self.bits
305    }
306}
307
308impl<U, FI> PartialEq<FI> for FieldReader<U, FI>
309where
310    U: PartialEq,
311    FI: Copy + Into<U>,
312{
313    #[inline(always)]
314    fn eq(&self, other: &FI) -> bool {
315        self.bits.eq(&(*other).into())
316    }
317}
318
319impl<FI> PartialEq<FI> for BitReader<FI>
320where
321    FI: Copy + Into<bool>,
322{
323    #[inline(always)]
324    fn eq(&self, other: &FI) -> bool {
325        self.bits.eq(&(*other).into())
326    }
327}
328
329impl<FI> BitReader<FI> {
330    /// Value of the field as raw bits.
331    #[inline(always)]
332    pub fn bit(&self) -> bool {
333        self.bits
334    }
335    /// Returns `true` if the bit is clear (0).
336    #[inline(always)]
337    pub fn bit_is_clear(&self) -> bool {
338        !self.bit()
339    }
340    /// Returns `true` if the bit is set (1).
341    #[inline(always)]
342    pub fn bit_is_set(&self) -> bool {
343        self.bit()
344    }
345}
346
347#[doc(hidden)]
348pub struct Safe;
349#[doc(hidden)]
350pub struct Unsafe;
351
352#[doc(hidden)]
353pub struct FieldWriterRaw<'a, U, REG, N, FI, Safety, const WI: u8, const O: u8>
354where
355    REG: Writable + RegisterSpec<Ux = U>,
356    FI: Into<N>,
357{
358    pub(crate) w: &'a mut REG::Writer,
359    _field: marker::PhantomData<(N, FI, Safety)>,
360}
361
362impl<'a, U, REG, N, FI, Safety, const WI: u8, const O: u8>
363    FieldWriterRaw<'a, U, REG, N, FI, Safety, WI, O>
364where
365    REG: Writable + RegisterSpec<Ux = U>,
366    FI: Into<N>,
367{
368    /// Creates a new instance of the writer
369    #[allow(unused)]
370    #[inline(always)]
371    pub(crate) fn new(w: &'a mut REG::Writer) -> Self {
372        Self {
373            w,
374            _field: marker::PhantomData,
375        }
376    }
377}
378
379#[doc(hidden)]
380pub struct BitWriterRaw<'a, U, REG, FI, M, const O: u8>
381where
382    REG: Writable + RegisterSpec<Ux = U>,
383    FI: Into<bool>,
384{
385    pub(crate) w: &'a mut REG::Writer,
386    _field: marker::PhantomData<(FI, M)>,
387}
388
389impl<'a, U, REG, FI, M, const O: u8> BitWriterRaw<'a, U, REG, FI, M, O>
390where
391    REG: Writable + RegisterSpec<Ux = U>,
392    FI: Into<bool>,
393{
394    /// Creates a new instance of the writer
395    #[allow(unused)]
396    #[inline(always)]
397    pub(crate) fn new(w: &'a mut REG::Writer) -> Self {
398        Self {
399            w,
400            _field: marker::PhantomData,
401        }
402    }
403}
404
405/// Write field Proxy with unsafe `bits`
406pub type FieldWriter<'a, U, REG, N, FI, const WI: u8, const O: u8> =
407    FieldWriterRaw<'a, U, REG, N, FI, Unsafe, WI, O>;
408/// Write field Proxy with safe `bits`
409pub type FieldWriterSafe<'a, U, REG, N, FI, const WI: u8, const O: u8> =
410    FieldWriterRaw<'a, U, REG, N, FI, Safe, WI, O>;
411
412impl<'a, U, REG, N, FI, const WI: u8, const OF: u8>
413    FieldWriter<'a, U, REG, N, FI, WI, OF>
414where
415    REG: Writable + RegisterSpec<Ux = U>,
416    FI: Into<N>,
417{
418    /// Field width
419    pub const WIDTH: u8 = WI;
420    /// Field offset
421    pub const OFFSET: u8 = OF;
422}
423
424impl<'a, U, REG, N, FI, const WI: u8, const OF: u8>
425    FieldWriterSafe<'a, U, REG, N, FI, WI, OF>
426where
427    REG: Writable + RegisterSpec<Ux = U>,
428    FI: Into<N>,
429{
430    /// Field width
431    pub const WIDTH: u8 = WI;
432    /// Field offset
433    pub const OFFSET: u8 = OF;
434}
435
436macro_rules! bit_proxy {
437    ($writer:ident, $mwv:ident) => {
438        #[doc(hidden)]
439        pub struct $mwv;
440
441        /// Bit-wise write field proxy
442        pub type $writer<'a, U, REG, FI, const O: u8> =
443            BitWriterRaw<'a, U, REG, FI, $mwv, O>;
444
445        impl<'a, U, REG, FI, const OF: u8> $writer<'a, U, REG, FI, OF>
446        where
447            REG: Writable + RegisterSpec<Ux = U>,
448            FI: Into<bool>,
449        {
450            /// Field width
451            pub const WIDTH: u8 = 1;
452            /// Field offset
453            pub const OFFSET: u8 = OF;
454        }
455    };
456}
457
458macro_rules! impl_bit_proxy {
459    ($writer:ident, $U:ty) => {
460        impl<'a, REG, FI, const OF: u8> $writer<'a, $U, REG, FI, OF>
461        where
462            REG: Writable + RegisterSpec<Ux = $U>,
463            FI: Into<bool>,
464        {
465            /// Writes bit to the field
466            #[inline(always)]
467            pub fn bit(self, value: bool) -> &'a mut REG::Writer {
468                self.w.bits = (self.w.bits & !(1 << { OF }))
469                    | ((<$U>::from(value) & 1) << { OF });
470                self.w
471            }
472            /// Writes `variant` to the field
473            #[inline(always)]
474            pub fn variant(self, variant: FI) -> &'a mut REG::Writer {
475                self.bit(variant.into())
476            }
477        }
478    };
479}
480
481bit_proxy!(BitWriter, BitM);
482bit_proxy!(BitWriter1S, Bit1S);
483bit_proxy!(BitWriter0C, Bit0C);
484bit_proxy!(BitWriter1C, Bit1C);
485bit_proxy!(BitWriter0S, Bit0S);
486bit_proxy!(BitWriter1T, Bit1T);
487bit_proxy!(BitWriter0T, Bit0T);
488
489macro_rules! impl_proxy {
490    ($U:ty) => {
491        impl<'a, REG, N, FI, const WI: u8, const OF: u8>
492            FieldWriter<'a, $U, REG, N, FI, WI, OF>
493        where
494            REG: Writable + RegisterSpec<Ux = $U>,
495            N: Into<$U>,
496            FI: Into<N>,
497        {
498            const MASK: $U =
499                <$U>::MAX >> (<$U>::MAX.leading_ones() as u8 - { WI });
500            /// Writes raw bits to the field
501            ///
502            /// # Safety
503            ///
504            /// Passing incorrect value can cause undefined behaviour. See reference manual
505            #[inline(always)]
506            pub unsafe fn bits(self, value: N) -> &'a mut REG::Writer {
507                self.w.bits = (self.w.bits & !(Self::MASK << { OF }))
508                    | ((value.into() & Self::MASK) << { OF });
509                self.w
510            }
511            /// Writes `variant` to the field
512            #[inline(always)]
513            pub fn variant(self, variant: FI) -> &'a mut REG::Writer {
514                unsafe { self.bits(variant.into()) }
515            }
516        }
517        impl<'a, REG, N, FI, const WI: u8, const OF: u8>
518            FieldWriterSafe<'a, $U, REG, N, FI, WI, OF>
519        where
520            REG: Writable + RegisterSpec<Ux = $U>,
521            N: Into<$U>,
522            FI: Into<N>,
523        {
524            const MASK: $U =
525                <$U>::MAX >> (<$U>::MAX.leading_ones() as u8 - { WI });
526            /// Writes raw bits to the field
527            #[inline(always)]
528            pub fn bits(self, value: N) -> &'a mut REG::Writer {
529                self.w.bits = (self.w.bits & !(Self::MASK << { OF }))
530                    | ((value.into() & Self::MASK) << { OF });
531                self.w
532            }
533            /// Writes `variant` to the field
534            #[inline(always)]
535            pub fn variant(self, variant: FI) -> &'a mut REG::Writer {
536                self.bits(variant.into())
537            }
538        }
539        impl_bit_proxy!(BitWriter, $U);
540        impl_bit_proxy!(BitWriter1S, $U);
541        impl_bit_proxy!(BitWriter0C, $U);
542        impl_bit_proxy!(BitWriter1C, $U);
543        impl_bit_proxy!(BitWriter0S, $U);
544        impl_bit_proxy!(BitWriter1T, $U);
545        impl_bit_proxy!(BitWriter0T, $U);
546        impl<'a, REG, FI, const OF: u8> BitWriter<'a, $U, REG, FI, OF>
547        where
548            REG: Writable + RegisterSpec<Ux = $U>,
549            FI: Into<bool>,
550        {
551            /// Sets the field bit
552            #[inline(always)]
553            pub fn set_bit(self) -> &'a mut REG::Writer {
554                self.bit(true)
555            }
556            /// Clears the field bit
557            #[inline(always)]
558            pub fn clear_bit(self) -> &'a mut REG::Writer {
559                self.bit(false)
560            }
561        }
562        impl<'a, REG, FI, const OF: u8> BitWriter1S<'a, $U, REG, FI, OF>
563        where
564            REG: Writable + RegisterSpec<Ux = $U>,
565            FI: Into<bool>,
566        {
567            /// Sets the field bit
568            #[inline(always)]
569            pub fn set_bit(self) -> &'a mut REG::Writer {
570                self.bit(true)
571            }
572        }
573        impl<'a, REG, FI, const OF: u8> BitWriter0C<'a, $U, REG, FI, OF>
574        where
575            REG: Writable + RegisterSpec<Ux = $U>,
576            FI: Into<bool>,
577        {
578            /// Clears the field bit
579            #[inline(always)]
580            pub fn clear_bit(self) -> &'a mut REG::Writer {
581                self.bit(false)
582            }
583        }
584        impl<'a, REG, FI, const OF: u8> BitWriter1C<'a, $U, REG, FI, OF>
585        where
586            REG: Writable + RegisterSpec<Ux = $U>,
587            FI: Into<bool>,
588        {
589            ///Clears the field bit by passing one
590            #[inline(always)]
591            pub fn clear_bit_by_one(self) -> &'a mut REG::Writer {
592                self.bit(true)
593            }
594        }
595        impl<'a, REG, FI, const OF: u8> BitWriter0S<'a, $U, REG, FI, OF>
596        where
597            REG: Writable + RegisterSpec<Ux = $U>,
598            FI: Into<bool>,
599        {
600            ///Sets the field bit by passing zero
601            #[inline(always)]
602            pub fn set_bit_by_zero(self) -> &'a mut REG::Writer {
603                self.bit(false)
604            }
605        }
606        impl<'a, REG, FI, const OF: u8> BitWriter1T<'a, $U, REG, FI, OF>
607        where
608            REG: Writable + RegisterSpec<Ux = $U>,
609            FI: Into<bool>,
610        {
611            ///Toggle the field bit by passing one
612            #[inline(always)]
613            pub fn toggle_bit(self) -> &'a mut REG::Writer {
614                self.bit(true)
615            }
616        }
617        impl<'a, REG, FI, const OF: u8> BitWriter0T<'a, $U, REG, FI, OF>
618        where
619            REG: Writable + RegisterSpec<Ux = $U>,
620            FI: Into<bool>,
621        {
622            ///Toggle the field bit by passing zero
623            #[inline(always)]
624            pub fn toggle_bit(self) -> &'a mut REG::Writer {
625                self.bit(false)
626            }
627        }
628    };
629}
630
631impl_proxy!(u8);
632impl_proxy!(u16);