From 045c7133dd22e4cc5fe62af136c15b04a8b8a485 Mon Sep 17 00:00:00 2001 From: Dylan Reid Date: Tue, 20 Jun 2017 13:44:40 -0700 Subject: Add data_model with DataInit trait The data_model crate is created to hold the DataInit trait. Types implementing this unsafe trait must guarantee that the type can be initialized with random data and the resulting object will be valid. Change-Id: Id6314d114805ec502adabe50a8bd6aa42fdb2c52 Signed-off-by: Dylan Reid Reviewed-on: https://chromium-review.googlesource.com/541681 Reviewed-by: Zach Reizner --- data_model/Cargo.toml | 6 ++++++ data_model/src/lib.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 data_model/Cargo.toml create mode 100644 data_model/src/lib.rs (limited to 'data_model') diff --git a/data_model/Cargo.toml b/data_model/Cargo.toml new file mode 100644 index 0000000..ca85b0b --- /dev/null +++ b/data_model/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "data_model" +version = "0.1.0" +authors = ["The Chromium OS Authors"] + +[dependencies] diff --git a/data_model/src/lib.rs b/data_model/src/lib.rs new file mode 100644 index 0000000..895f9ad --- /dev/null +++ b/data_model/src/lib.rs @@ -0,0 +1,43 @@ +// Copyright 2017 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/// Types for which it is safe to initialize from raw data. +/// +/// A type `T` is `DataInit` if and only if it can be initialized by reading its contents from a +/// byte array. This is generally true for all plain-old-data structs. It is notably not true for +/// any type that includes a reference. +/// +/// Implementing this trait guarantees that it is safe to instantiate the struct with random data. +pub unsafe trait DataInit: Copy + Send + Sync {} + +// All intrinsic types and arays of intrinsic types are DataInit. They are just numbers. +macro_rules! array_data_init { + ($T:ty, $($N:expr)+) => { + $( + unsafe impl DataInit for [$T; $N] {} + )+ + } +} +macro_rules! data_init_type { + ($T:ty) => { + unsafe impl DataInit for $T {} + array_data_init! { + $T, + 0 1 2 3 4 5 6 7 8 9 + 10 11 12 13 14 15 16 17 18 19 + 20 21 22 23 24 25 26 27 28 29 + 30 31 32 + } + } +} +data_init_type!(u8); +data_init_type!(u16); +data_init_type!(u32); +data_init_type!(u64); +data_init_type!(usize); +data_init_type!(i8); +data_init_type!(i16); +data_init_type!(i32); +data_init_type!(i64); +data_init_type!(isize); -- cgit 1.4.1