Introduce distinct integer types

This PR does the following things:
- Give incompatible representations for integers with different semantics:
  - `usize` is used for natural numbers for the public API.
  - `Nat` is used internally for natural numbers (essentially a stable `usize`).
  - `Word` is used for sequences of bits representing words in flash.
  - `Position` is used for word positions in the virtual storage.
- Only use fixed size integers to preserve overflow behavior between targets.
- Use little-endian representation instead of native representation for `Word`.

Alternatives:
- Run tests and fuzzing on 32-bits architecture (or some compatibility mode).
  This approach would have better readability than the current solution (less
  conversions at public API). However it would require additional setup and
  might not be viable long-term by restricting machines on which fuzzing is
  possible.
- Accept the behavior difference for tests and fuzzing. This approach would also
  have better readability. However checking for arithmetic overflow (and other
  `usize` related concerns like memory size) is more important.
This commit is contained in:
Julien Cretin
2020-10-29 17:46:01 +01:00
parent dea28f622f
commit 9778ea7fd2
6 changed files with 254 additions and 159 deletions

View File

@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::StorageError;
use crate::{Nat, StorageError};
use alloc::vec::Vec;
/// Errors returned by store operations.
@@ -78,26 +78,26 @@ pub type StoreResult<T> = Result<T, StoreError>;
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct StoreRatio {
/// How much of the metric is used.
pub(crate) used: usize,
pub(crate) used: Nat,
/// How much of the metric can be used at most.
pub(crate) total: usize,
pub(crate) total: Nat,
}
impl StoreRatio {
/// How much of the metric is used.
pub fn used(self) -> usize {
self.used
self.used as usize
}
/// How much of the metric can be used at most.
pub fn total(self) -> usize {
self.total
self.total as usize
}
/// How much of the metric is remaining.
pub fn remaining(self) -> usize {
self.total - self.used
(self.total - self.used) as usize
}
}