Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix build warnings and a few assorted tweaks #13

Merged
merged 2 commits into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions benchmark/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ version = "0.0.0"
publish = false

[features]
default = ["alkahest/default"]

nightly = ["criterion/real_blackbox"]

default = ["alkahest/default", "speedy", "rkyv", "serde", "bincode"]

[dependencies]
alkahest = { path = "..", features = ["derive"], default-features = false }
criterion = { version = "0.4", features = ["real_blackbox"] }
criterion = { version = "0.4" }
serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true }
bincode = { version = "1.3", optional = true }
Expand Down
119 changes: 110 additions & 9 deletions benchmark/benches/benchmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ extern crate rkyv;
#[cfg(feature = "speedy")]
extern crate speedy;

use alkahest::{alkahest, Deserialize, Formula, Lazy, Ref, SerIter, Serialize};
use alkahest::{alkahest, Deserialize, Formula, Lazy, SerIter, Serialize};
use criterion::{black_box, criterion_group, criterion_main, Criterion};

#[cfg(feature = "rkyv")]
use bytecheck::CheckBytes;
use rand::{
distributions::{Alphanumeric, DistString},
rngs::SmallRng,
thread_rng, Rng, SeedableRng,
Rng, SeedableRng,
};

#[derive(Debug, Clone, Formula, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize))]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv", archive_attr(derive(CheckBytes)))]
#[cfg_attr(feature = "speedy", derive(speedy::Writable, speedy::Readable))]
pub enum GameMessage {
Expand All @@ -42,7 +42,7 @@ pub enum GameMessageRead<'de> {

#[derive(Debug, Clone, Formula, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize))]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv", archive_attr(derive(CheckBytes)))]
#[cfg_attr(feature = "speedy", derive(speedy::Writable, speedy::Readable))]
pub enum ClientMessage {
Expand All @@ -60,7 +60,7 @@ pub enum ClientMessageRead<'de> {

#[derive(Debug, Clone, Formula, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize))]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv", archive_attr(derive(CheckBytes)))]
#[cfg_attr(feature = "speedy", derive(speedy::Writable, speedy::Readable))]
pub enum ServerMessage {
Expand All @@ -78,7 +78,7 @@ pub enum ServerMessageRead<'de> {

#[derive(Debug, Formula, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize))]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv", archive_attr(derive(CheckBytes)))]
#[cfg_attr(feature = "speedy", derive(speedy::Writable, speedy::Readable))]
pub struct NetPacket<G> {
Expand Down Expand Up @@ -123,9 +123,9 @@ fn messages<'a>(mut rng: impl Rng + 'a, len: usize) -> impl Iterator<Item = Game
pub fn criterion_benchmark(c: &mut Criterion) {
let mut buffer = Vec::with_capacity(1 << 14);
buffer.resize(buffer.capacity(), 0);
let mut rng = SmallRng::seed_from_u64(42);
let rng = SmallRng::seed_from_u64(42);

const LEN: usize = 200;
const LEN: usize = 2000;
let mut size = 0;

{
Expand Down Expand Up @@ -176,6 +176,41 @@ pub fn criterion_benchmark(c: &mut Criterion) {
}
})
});

group.bench_function("deserialize", |b| {
b.iter(|| {
let packet = alkahest::deserialize::<
NetPacket<GameMessage>,
NetPacket<GameMessage>,
>(&buffer[..size])
.unwrap();

for message in packet.game_messages.iter() {
match message {
GameMessage::Client(ClientMessage::ClientData {
nickname,
clan,
}) => {
black_box(nickname);
black_box(clan);
}
GameMessage::Client(ClientMessage::Chat(message)) => {
black_box(message);
}
GameMessage::Server(ServerMessage::ServerData(data)) => {
black_box(data);
}
GameMessage::Server(ServerMessage::ClientChat {
client_id,
message,
}) => {
black_box(client_id);
black_box(message);
}
}
}
})
});
}

#[cfg(feature = "bincode")]
Expand All @@ -194,7 +229,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
})
});

group.bench_function("read", |b| {
group.bench_function("deserialize", |b| {
b.iter(|| {
let packet = bincode::deserialize::<NetPacket<GameMessage>>(&buffer).unwrap();

Expand Down Expand Up @@ -268,6 +303,39 @@ pub fn criterion_benchmark(c: &mut Criterion) {
}
})
});

group.bench_function("deserialize", |b| {
b.iter(|| {
use rkyv::Deserialize;
let archive = rkyv::check_archived_root::<NetPacket<GameMessage>>(&vec[..]).unwrap();
let packet: NetPacket<GameMessage> = archive.deserialize(&mut rkyv::Infallible).unwrap();

for message in packet.game_messages.iter() {
match message {
GameMessage::Client(ClientMessage::ClientData {
nickname,
clan,
}) => {
black_box(nickname);
black_box(clan);
}
GameMessage::Client(ClientMessage::Chat(message)) => {
black_box(message);
}
GameMessage::Server(ServerMessage::ServerData(data)) => {
black_box(data);
}
GameMessage::Server(ServerMessage::ClientChat {
client_id,
message,
}) => {
black_box(client_id);
black_box(message);
}
}
}
})
});
}

#[cfg(feature = "speedy")]
Expand Down Expand Up @@ -321,6 +389,39 @@ pub fn criterion_benchmark(c: &mut Criterion) {
}
})
});

group.bench_function("deserialize", |b| {
b.iter(|| {
let packet =
<NetPacket<GameMessage> as speedy::Readable<_>>::read_from_buffer(&buffer)
.unwrap();

for message in packet.game_messages.iter() {
match message {
GameMessage::Client(ClientMessage::ClientData {
nickname,
clan,
}) => {
black_box(nickname);
black_box(clan);
}
GameMessage::Client(ClientMessage::Chat(message)) => {
black_box(message);
}
GameMessage::Server(ServerMessage::ServerData(data)) => {
black_box(data);
}
GameMessage::Server(ServerMessage::ClientChat {
client_id,
message,
}) => {
black_box(client_id);
black_box(message);
}
}
}
})
});
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/primitive.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::{borrow::Borrow, mem::size_of};
use core::mem::size_of;

use crate::{
buffer::Buffer,
Expand Down Expand Up @@ -157,7 +157,7 @@ impl Serialize<bool> for &bool {
where
B: Buffer,
{
<u8 as Serialize<u8>>::serialize(u8::from(*self.borrow()), sizes, buffer)
<u8 as Serialize<u8>>::serialize(u8::from(*self), sizes, buffer)
}

#[inline(always)]
Expand Down
1 change: 1 addition & 0 deletions src/serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,7 @@ where
let size = FixedUsize::truncate_unchecked(size);

if F::EXACT_SIZE {
debug_assert_eq!(size, FixedUsize::truncate_unchecked(F::MAX_STACK_SIZE.unwrap()));
buffer.write_stack(heap, stack, &address.to_le_bytes())?;
} else {
buffer.write_stack(heap, stack, &size.to_le_bytes())?;
Expand Down
68 changes: 46 additions & 22 deletions src/tests/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,68 +6,92 @@ use rand::{
};

use crate::{
alkahest, read_packet, write_packet_to_vec, Formula, Lazy, SerIter, Serialize, SerializeRef,
alkahest, read_packet, write_packet_to_vec, Deserialize, Formula, Lazy, SerIter, Serialize, SerializeRef, Ref,
};

#[alkahest(Formula)]
pub enum GameMessageFormula {
Client(Ref<ClientMessageFormula>),
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Ref looks unnecessary here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yeah, I was just experimenting with it -- this is actually the reason I initially wanted to separate the formula from the serialize and deserialize types, to insert a wrapping handler in the mix. Ultimately I'm trying to play with making a Ref-like wrapper that would help to do schema evolution (forward/backward compatibility). But it is of course unnecessary in this case.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What exactly are properties of Ref-like wrapper you have in mind?
Current Ref IMHO is enough to allow separate evolution of field's Formula.
Currently user may evolve schema and manually ensure desired compatibility.

I have the following plan to better support them:

  • Add validation to check compatibility between two Formulas.
  • Add attributes to mark new fields when deriving Formula. Then compatibility will be checked between versions. All in proc-macro execution time.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, not sure if I quite follow. If you serialize some data with Ref<SomeTV1>, add a field, then try to deserialize the old data with Ref<SomeTV2>, that will not work, right?

It would be nice to have the ability to provide default values for fields added and then based on size of serialized data detect which fields are missing and fill them in.

You could also put another wrapper that is like Lazy<Ref<T>> where instead of filling in with default values, you could "attempt to get" the type at different versions, i.e. with different numbers of fields. Similar to "probe" types I made in protoss experiment for rkyv: https://github.com/fu5ha/protoss/blob/master/protoss_test/src/derive.rs#L169-L173

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you would need to have defaults for new fields for backward compatibility.
For forward compatibility it would be enough to mark formula as non-exhaustive, so it would just skip fields added at the end.
How about Lazy<AnyRef> that can be viewed as Lazy<AnyRef<T>>.
Where the only difference between Ref<T> and AnyRef<T> is that binary format of AnyRef doesn't depend on T

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe Lazy layer is not needed.

struct AnyRef {...}

impl AnyRef {
  fn decode<F: Formula, T: Deserialize<F>>() -> Option<T> { ... }
}

This requires more work 🤣

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah exactly, I was thinking of making a single thing similar to what you propose that's like a hybrid.

Ideally it would still be typed based on the main type it represents "some version" of. Then decode would only let you ask for one of the known versions of that type

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

struct AnyVersionRef<T: Versioned> {...}

impl<T: Versioned> AnyVersionRef<T> {
  fn decode_version<V: VersionOf<T>>(&self) -> Option<V> { ... }
  fn latest_with_defaults(self) -> T { ... }
}

Needs more thinking about how exactly to integrate the deserialize and formula types/bounds but thats the basic vision I guess.

Server(Ref<ServerMessageFormula>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[alkahest(Formula, Serialize, Deserialize)]
#[alkahest(Serialize<GameMessageFormula>, Deserialize<'_, GameMessageFormula>)]
pub enum GameMessage {
Client(ClientMessage),
Server(ServerMessage),
}

#[derive(Debug)]
#[alkahest(Deserialize<'de, GameMessage>)]
#[alkahest(Deserialize<'de, GameMessageFormula>)]
pub enum GameMessageRead<'de> {
Client(ClientMessageRead<'de>),
Server(ServerMessageRead<'de>),
}

#[alkahest(Formula)]
pub enum ClientMessageFormula {
ClientData { nickname: Ref<str>, clan: Ref<str> },
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ref<str> and String are distinct but actually equivalent formulas.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right :D Which is cool

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So why making separate type? ClientMessage as Formula would be the same.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was not obvious to me from documentation what a formula actually is -- that it is a rust type that mirrors the type you want that contains types which have a direct exact representation. Making this split it becomes more obvious what's going on -- in my eyes at least. And it shows how you can create multiple formulas which the same type can serialize as / deserialize from, or customize the exact representation with wrappers like Ref. The point of all this change was to try what it would look like to 1. separate all the formulas 2. make tweaks like adding Ref to build my intuition on the versioned wrapper we talked about in the other thread.

Whether the proper place for that is in a test like here: perhaps not x) but I was just playing around with it to get a better idea of how things work.

Probably it should go in a separate test/example to show it better. I would be fine with reverting the formula changes in this file for sure.

Chat(Ref<str>),
}

#[derive(Debug, PartialEq, Eq, Clone)]
#[alkahest(Formula, Serialize, Deserialize)]
#[alkahest(Serialize<ClientMessageFormula>, Deserialize<'_, ClientMessageFormula>)]
pub enum ClientMessage {
ClientData { nickname: String, clan: String },
Chat(String),
}

#[derive(Debug)]
#[alkahest(Deserialize<'de, ClientMessage>)]
#[alkahest(Deserialize<'de, ClientMessageFormula>)]
pub enum ClientMessageRead<'de> {
ClientData { nickname: &'de str, clan: &'de str },
Chat(&'de str),
}

#[alkahest(Formula)]
pub enum ServerMessageFormula {
ServerData(u64),
ClientChat { client_id: u64, message: Ref<str> },
}

#[derive(Debug, PartialEq, Eq, Clone)]
#[alkahest(Formula, Serialize, Deserialize)]
#[alkahest(Serialize<ServerMessageFormula>, Deserialize<'_, ServerMessageFormula>)]
pub enum ServerMessage {
ServerData(u64),
ClientChat { client_id: u64, message: String },
}

#[derive(Debug)]
#[alkahest(Deserialize<'de, ServerMessage>)]
#[alkahest(Deserialize<'de, ServerMessageFormula>)]
pub enum ServerMessageRead<'de> {
ServerData(u64),
ClientChat { client_id: u64, message: &'de str },
}

#[alkahest(Formula)]
pub struct NetPacketFormula<F> {
pub game_messages: Vec<F>,
}

#[derive(Debug)]
#[alkahest(Formula, Serialize, Deserialize)]
#[alkahest(for<F: Formula> Serialize<NetPacketFormula<F>> where G: Serialize<F>)]
#[alkahest(for<'de, F: Formula> Deserialize<'de, NetPacketFormula<F>> where G: Deserialize<'de, F>)]
pub struct NetPacket<G> {
pub game_messages: Vec<G>,
}

#[derive(Debug)]
#[alkahest(for<X: Formula> Serialize<NetPacket<X>> where G: Serialize<[X]>)]
#[alkahest(for<X: Formula> SerializeRef<NetPacket<X>> where G: SerializeRef<[X]>)]
#[alkahest(for<F: Formula> Serialize<NetPacketFormula<F>> where G: Serialize<[F]>)]
#[alkahest(for<F: Formula> SerializeRef<NetPacketFormula<F>> where G: SerializeRef<[F]>)]
pub struct NetPacketWrite<G> {
pub game_messages: G,
}

#[derive(Debug)]
#[alkahest(Deserialize<'de, NetPacket::<G>> where G: Formula)]
pub struct NetPacketRead<'de, G> {
pub game_messages: Lazy<'de, [G]>,
#[alkahest(Deserialize<'de, NetPacketFormula<F>> where F: Formula)]
pub struct NetPacketRead<'de, F> {
pub game_messages: Lazy<'de, [F]>,
}

fn get_string(rng: &mut impl Rng) -> String {
Expand Down Expand Up @@ -103,15 +127,15 @@ fn test_net_packet() {
const LEN: usize = 1000;

let mut buffer = Vec::new();
let size = write_packet_to_vec::<NetPacket<GameMessage>, _>(
let size = write_packet_to_vec::<NetPacketFormula<GameMessageFormula>, _>(
NetPacketWrite {
game_messages: SerIter(messages(rng.clone(), LEN)),
},
&mut buffer,
);

let mut buffer2 = Vec::new();
let size2 = write_packet_to_vec::<NetPacket<GameMessage>, _>(
let size2 = write_packet_to_vec::<NetPacketFormula<GameMessageFormula>, _>(
NetPacket {
game_messages: messages(rng, LEN).collect::<Vec<_>>(),
},
Expand All @@ -122,23 +146,23 @@ fn test_net_packet() {
assert_eq!(buffer[..size], buffer2[..size]);

let (packet, _) =
read_packet::<NetPacket<GameMessage>, NetPacketRead<GameMessage>>(&buffer[..]).unwrap();
read_packet::<NetPacketFormula<GameMessageFormula>, NetPacketRead<GameMessageFormula>>(&buffer[..]).unwrap();

for message in packet.game_messages.iter::<GameMessageRead>() {
match message.unwrap() {
GameMessageRead::Client(ClientMessageRead::ClientData { nickname, clan }) => {
drop(nickname);
drop(clan);
let _ = nickname;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for this besides style?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clippy doesn't like dropping references and says to ignore it via _ instead. But yeah it's ultimately just style.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If default-configured clippy says so I have no objections.

let _ = clan;
}
GameMessageRead::Client(ClientMessageRead::Chat(message)) => {
drop(message);
let _ = message;
}
GameMessageRead::Server(ServerMessageRead::ServerData(data)) => {
drop(data);
let _ = data;
}
GameMessageRead::Server(ServerMessageRead::ClientChat { client_id, message }) => {
drop(client_id);
drop(message);
let _ = client_id;
let _ = message;
}
}
}
Expand Down