diff options
Diffstat (limited to 'docs/modules/ROOT/pages')
| -rw-r--r-- | docs/modules/ROOT/pages/best_practices.adoc | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/docs/modules/ROOT/pages/best_practices.adoc b/docs/modules/ROOT/pages/best_practices.adoc new file mode 100644 index 000000000..1e02f9ba9 --- /dev/null +++ b/docs/modules/ROOT/pages/best_practices.adoc | |||
| @@ -0,0 +1,53 @@ | |||
| 1 | = Best Practices | ||
| 2 | |||
| 3 | Over time, a couple of best practices have emerged. The following list should serve as a guideline for developers writing embedded software in _Rust_, especially in the context of the _Embassy_ framework. | ||
| 4 | |||
| 5 | == Passing Buffers by Reference | ||
| 6 | It may be tempting to pass arrays or wrappers, like link:https://docs.rs/heapless/latest/heapless/[`heapless::Vec`], to a function or return one just like you would with a `std::Vec`. However, in most embedded applications you don't want to spend ressources on an allocator and end up placing buffers on the stack. | ||
| 7 | This, however, can easily blow up your stack if you are not careful. | ||
| 8 | |||
| 9 | Consider the following example: | ||
| 10 | [,rust] | ||
| 11 | ---- | ||
| 12 | fn process_buffer(mut buf: [u8; 1024]) -> [u8; 1024] { | ||
| 13 | // do stuff and return new buffer | ||
| 14 | for elem in buf.iter_mut() { | ||
| 15 | *elem = 0; | ||
| 16 | } | ||
| 17 | buf | ||
| 18 | } | ||
| 19 | |||
| 20 | pub fn main() -> () { | ||
| 21 | let buf = [1u8; 1024]; | ||
| 22 | let buf_new = process_buffer(buf); | ||
| 23 | // do stuff with buf_new | ||
| 24 | () | ||
| 25 | } | ||
| 26 | ---- | ||
| 27 | When calling `process_buffer` in your program, a copy of the buffer you pass to the function will be created, | ||
| 28 | consuming another 1024 bytes. | ||
| 29 | After the processing, another 1024 byte buffer will be placed on the stack to be returned to the caller. | ||
| 30 | (You can check the assembly, there will be two memcopy operations, e.g., `bl __aeabi_memcpy` when compiling for a Cortex-M processor.) | ||
| 31 | |||
| 32 | *Possible Solution:* | ||
| 33 | |||
| 34 | Pass the data by reference and not by value on both, the way in and the way out. | ||
| 35 | For example, you could return a slice of the input buffer as the output. | ||
| 36 | Requiring the lifetime of the input slice and the output slice to be the same, the memory safetly of this procedure will be enforced by the compiler. | ||
| 37 | |||
| 38 | [,rust] | ||
| 39 | ---- | ||
| 40 | fn process_buffer<'a>(buf: &'a mut [u8]) -> &'a mut[u8] { | ||
| 41 | for elem in buf.iter_mut() { | ||
| 42 | *elem = 0; | ||
| 43 | } | ||
| 44 | buf | ||
| 45 | } | ||
| 46 | |||
| 47 | pub fn main() -> () { | ||
| 48 | let mut buf = [1u8; 1024]; | ||
| 49 | let buf_new = process_buffer(&mut buf); | ||
| 50 | // do stuff with buf_new | ||
| 51 | () | ||
| 52 | } | ||
| 53 | ---- | ||
