Skip to content

Commit

Permalink
glib: Add optional support for serialization and deserialization with…
Browse files Browse the repository at this point in the history
… serde

This feature is gated as `serialize`

Supports both serialization and deserialization:
- glib::Bytes
- glib::GString

Supports serialization only:
- glib::ByteArray
- glib::GStr
- glib::StrV

Collection types are also supported as long as the type parameters implement the necessary traits:
- glib::PtrSlice<T: TransparentPtrType + _>
- glib::Slice<T: TransparentType + _>
- glib::List<T: TransparentPtrType + _>
- glib::SList<T: TransparentPtrType + _>
  • Loading branch information
rmnscnce committed Apr 5, 2023
1 parent 7f9a20b commit 5e2d762
Show file tree
Hide file tree
Showing 4 changed files with 263 additions and 0 deletions.
2 changes: 2 additions & 0 deletions glib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ smallvec = "1.0"
thiserror = "1"
gio_ffi = { package = "gio-sys", path = "../gio/sys", optional = true }
memchr = "2.5.0"
serde = { version = "1.0", optional = true }

[dev-dependencies]
tempfile = "3"
Expand All @@ -59,6 +60,7 @@ log_macros = ["log"]
dox = ["ffi/dox", "gobject_ffi/dox", "log_macros"]
compiletests = []
gio = ["gio_ffi"]
serialize = ["dep:serde"]

[package.metadata.docs.rs]
features = ["dox"]
Expand Down
10 changes: 10 additions & 0 deletions glib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,16 @@ glib = "0.13"
glib = { git = "https://github.com/gtk-rs/gtk-rs-core.git", package = "glib" }
```

### Serialization with Serde

If you want to serialize (and deserialize) some GLib types (e.g. `GString`) with Serde, you can enable the `serialize` feature:

```toml
glib = { version = "0.18", features = ["serialize"] }
```

This library implements serialization and deserialization as described in the `serde@^1.0` API.

## License

__glib__ is available under the MIT License, please refer to it.
3 changes: 3 additions & 0 deletions glib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,9 @@ pub use self::thread_pool::{ThreadHandle, ThreadPool};

pub mod thread_guard;

#[cfg(feature = "serialize")]
mod serde;

// rustdoc-stripper-ignore-next
/// This is the log domain used by the [`clone!`][crate::clone!] macro. If you want to use a custom
/// logger (it prints to stdout by default), you can set your own logger using the corresponding
Expand Down
248 changes: 248 additions & 0 deletions glib/src/serde.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
// Take a look at the license at the top of the repository in the LICENSE file.

macro_rules! serialize_impl {
($ty:ty, Bytes($bind:ident) => $expr:expr) => {
impl ::serde::Serialize for $ty {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ::serde::Serializer,
{
let $bind = self;

serializer.serialize_bytes($expr)
}
}
};
($ty:ty, Str($bind:ident) => $expr:expr) => {
impl ::serde::Serialize for $ty {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ::serde::Serializer,
{
let $bind = self;

serializer.serialize_str($expr)
}
}
};
($ty:ident$(<$($generic:ident $(: $bound:tt $(+ $bound2:tt)*)?),+>)?, Iterator($bind:ident) => $expr:expr) => {
impl$(<$($generic $(: ::serde::Serialize + $bound $(+ $bound2)*)?),+>)? ::serde::Serialize for $ty$(<$($generic),+>)? {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ::serde::Serializer
{
let $bind = self;
serializer.collect_seq($expr)
}
}
};
}

macro_rules! deserialize_impl {
($ty:ty, Bytes($arg:ident) => $body:block) => {
impl<'de> ::serde::Deserialize<'de> for $ty {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
struct Visitor;

impl<'a> ::serde::de::Visitor<'a> for Visitor {
type Value = $ty;

fn expecting(
&self,
formatter: &mut ::std::fmt::Formatter,
) -> ::std::fmt::Result {
formatter.write_str("an array of bytes")
}

fn visit_seq<A>(self, mut $arg: A) -> Result<Self::Value, A::Error>
where
A: ::serde::de::SeqAccess<'a>,
$body
}

deserializer.deserialize_seq(Visitor)
}
}
};
($ty:ty, String($arg:ident) => $body:block) => {
impl<'de> ::serde::Deserialize<'de> for $ty {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
struct Visitor;

impl<'a> ::serde::de::Visitor<'a> for Visitor {
type Value = $ty;

fn expecting(
&self,
formatter: &mut ::std::fmt::Formatter,
) -> ::std::fmt::Result {
formatter.write_str("a valid UTF-8 string")
}

fn visit_str<E>(self, _: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
todo!()
}

fn visit_string<E>(self, $arg: String) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
$body
}

deserializer.deserialize_string(Visitor)
}
}
};

($ty:ident$(<$($generic:ident$(: $bound:tt $(+ $bound2:tt)*)?),+>)?, $expect:literal, Collection($arg:ident) => $body:block) => {
impl<'de: 'a, 'a: 'de, $($($generic $(: ::serde::Deserialize<'de> + $bound $(+ $bound2)*)?),+)?> ::serde::Deserialize<'de> for $ty$(<$($generic),+>)? {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
struct Visitor<'v, $($($generic $(: ::serde::Deserialize<'v> + $bound $(+ $bound2)*)?),+)?>(::std::marker::PhantomData<&'v ()>, $($(::std::marker::PhantomData<fn() -> $generic>),+)?);

impl<'a, $($($generic $(: ::serde::Deserialize<'a> + $bound $(+ $bound2)*)?),+>)? ::serde::de::Visitor<'a> for Visitor<'a, $($($generic),+)?> {
type Value = $ty$(<$($generic),+>)?;

fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
formatter.write_str($expect)
}

fn visit_seq<A>(self, mut $arg: A) -> Result<Self::Value, A::Error>
where
A: ::serde::de::SeqAccess<'a>,
$body
}

deserializer.deserialize_seq(Visitor(::std::marker::PhantomData, $($(::std::marker::PhantomData::<fn() -> $generic>::default()),+)?))
}
}
};
}

mod byte_array {
use crate::ByteArray;

serialize_impl!(ByteArray, Bytes(b) => b);
}

mod bytes {
use crate::Bytes;

serialize_impl!(Bytes, Bytes(b) => b);

deserialize_impl!(
Bytes,
Bytes(seq) => {
let mut byte_vec = vec![];

while let Some(_size @ 1..) = seq.size_hint() {
match seq.next_element()? {
Some(byte) => byte_vec.push(byte),
None => break,
}
}

Ok(Bytes::from_owned(byte_vec))
}
);
}

mod gstring {
use crate::{GStr, GString, GStringPtr};
use serde::de;

serialize_impl!(GStr, Str(s) => s.as_str());

serialize_impl!(GString, Str(s) => s.as_str());

deserialize_impl!(
GString,
String(s) => {GString::from_string_checked(s).map_err(|e| de::Error::custom(e))}
);

serialize_impl!(GStringPtr, Str(s) => s.to_str());
}

mod collections {
use crate::{
translate::{TransparentPtrType, TransparentType},
List, PtrSlice, SList, Slice, StrV,
};

serialize_impl!(PtrSlice<T: TransparentPtrType>, Iterator(iter) => iter);

deserialize_impl!(PtrSlice<T: TransparentPtrType>, "a sequence of GLib transparent pointer values", Collection(seq) => {
let mut ret = PtrSlice::new();

while let Some(_size @ 1..) = seq.size_hint() {
ret.push(match seq.next_element()? {
Some(item) => item,
None => break,
})
}

Ok(ret)
});

serialize_impl!(Slice<T: TransparentType>, Iterator(iter) => iter);

deserialize_impl!(Slice<T: TransparentType>, "a sequence of GLib transparent values", Collection(seq) => {
let mut ret = Slice::new();

while let Some(_size @ 1..) = seq.size_hint() {
ret.push(match seq.next_element()? {
Some(item) => item,
None => break,
})
}

Ok(ret)
});

serialize_impl!(List<T: TransparentPtrType>, Iterator(iter) => iter.iter());

deserialize_impl!(List<T: TransparentPtrType>, "a sequence of GLib transparent pointer values", Collection(seq) => {
let mut ret = List::new();

while let Some(_size @ 1..) = seq.size_hint() {
ret.push_front(match seq.next_element()? {
Some(item) => item,
None => break,
})
}

ret.reverse();

Ok(ret)
});

serialize_impl!(SList<T: TransparentPtrType>, Iterator(iter) => iter.iter());

deserialize_impl!(SList<T: TransparentPtrType>, "a sequence of GLib transparent pointer values", Collection(seq) => {
let mut ret = SList::new();

while let Some(_size @ 1..) = seq.size_hint() {
ret.push_front(match seq.next_element()? {
Some(item) => item,
None => break,
})
}

ret.reverse();

Ok(ret)
});

serialize_impl!(StrV, Iterator(iter) => iter);
}

0 comments on commit 5e2d762

Please sign in to comment.