I am using rust diesel to do a pagination query right now. I get the pagination information from request right now, I was wonder is it possible to get pagination information from Query result? This is my code:
pub fn fav_music_query<T>(request: Json<FavMusicRequest>) -> Paginated<Vec<Favorites>> {
use crate::model::diesel::rhythm::rhythm_schema::favorites::dsl::*;
let connection = config::establish_music_connection();
let query = favorites.filter(like_status.eq(1)).paginate(request.pageNum).per_page(request.pageSize);
let query_result = query.load_and_count_pages::<Favorites>(&connection).unwrap();
let page_result = Paginated{
query: query_result.0,
page: request.pageNum,
per_page: request.pageSize,
is_sub_query: false
};
return page_result;
}
from the request I could only get pageSize and pageNum, but I did not know the total size. what is the best way the get the pagination information? this is my pagination code:
use diesel::prelude::*;
use diesel::query_dsl::methods::LoadQuery;
use diesel::query_builder::{QueryFragment, Query, AstPass};
use diesel::pg::Pg;
use diesel::sql_types::BigInt;
use diesel::QueryId;
use serde::{Serialize, Deserialize};
pub trait PaginateForQueryFragment: Sized {
fn paginate(self, page: i64) -> Paginated<Self>;
}
impl<T> PaginateForQueryFragment for T
where T: QueryFragment<Pg>{
fn paginate(self, page: i64) -> Paginated<Self> {
Paginated {
query: self,
per_page: 10,
page,
is_sub_query: true,
}
}
}
#[derive(Debug, Clone, Copy, QueryId, Serialize, Deserialize, Default)]
pub struct Paginated<T> {
pub query: T,
pub page: i64,
pub per_page: i64,
pub is_sub_query: bool
}
impl<T> Paginated<T> {
pub fn per_page(self, per_page: i64) -> Self {
Paginated { per_page, ..self }
}
pub fn load_and_count_pages<U>(self, conn: &PgConnection) -> QueryResult<(Vec<U>, i64)>
where
Self: LoadQuery<PgConnection, (U, i64)>,
{
let per_page = self.per_page;
let results = self.load::<(U, i64)>(conn)?;
let total = results.get(0).map(|x| x.1).unwrap_or(0);
let records = results.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / per_page as f64).ceil() as i64;
Ok((records, total_pages))
}
}
impl<T: Query> Query for Paginated<T> {
type SqlType = (T::SqlType, BigInt);
}
impl<T> RunQueryDsl<PgConnection> for Paginated<T> {}
impl<T> QueryFragment<Pg> for Paginated<T>
where
T: QueryFragment<Pg>,
{
fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
out.push_sql("SELECT *, COUNT(*) OVER () FROM ");
if self.is_sub_query {
out.push_sql("(");
}
self.query.walk_ast(out.reborrow())?;
if self.is_sub_query {
out.push_sql(")");
}
out.push_sql(" t LIMIT ");
out.push_bind_param::<BigInt, _>(&self.per_page)?;
out.push_sql(" OFFSET ");
let offset = (self.page - 1) * self.per_page;
out.push_bind_param::<BigInt, _>(&offset)?;
Ok(())
}
}
#[derive(Debug, Clone, Copy, QueryId)]
pub struct QuerySourceToQueryFragment<T> {
query_source: T,
}
impl<FC, T> QueryFragment<Pg> for QuerySourceToQueryFragment<T>
where
FC: QueryFragment<Pg>,
T: QuerySource<FromClause=FC>,
{
fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
self.query_source.from_clause().walk_ast(out.reborrow())?;
Ok(())
}
}
pub trait PaginateForQuerySource: Sized {
fn paginate(self, page: i64) -> Paginated<QuerySourceToQueryFragment<Self>>;
}
impl<T> PaginateForQuerySource for T
where T: QuerySource {
fn paginate(self, page: i64) -> Paginated<QuerySourceToQueryFragment<Self>> {
Paginated {
query: QuerySourceToQueryFragment {query_source: self},
per_page: 10,
page,
is_sub_query: false,
}
}
}
and this is my FavMusicRequest that define the pagination query information:
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
#[allow(non_snake_case)]
pub struct FavMusicRequest {
pub userId: i64,
pub pageNum: i64,
pub pageSize: i64
}
and this is the query entity from database:
#[derive( Serialize, Queryable, Deserialize,Default)]
pub struct Favorites {
pub id: i64,
pub song_id: Option<i64>,
pub created_time: i64,
pub updated_time: i64,
pub user_id: i64,
pub source_id: String,
pub like_status: i32,
pub source: i32,
pub playlist_id: i64,
pub play_count: i32,
pub fetched_download_url: Option<i32>,
pub downloaded: Option<i32>
}
and this is the request defined with rocket:
#[post("/v1/page",data = "<request>")]
pub fn page(request: Json<FavMusicRequest>) -> content::Json<String> {
let fav_musics = fav_music_query::<Vec<Favorites>>(request);
let res = ApiResponse {
result: fav_musics,
..Default::default()
};
let response_json = serde_json::to_string(&res).unwrap();
return content::Json(response_json);
}
You can return the results in QueryResult<(....)> in the load_and_count_pages.
Here is a working example:
use diesel::pg::Pg;
use diesel::prelude::*;
use diesel::query_builder::*;
use diesel::query_dsl::methods::LoadQuery;
use diesel::sql_types::BigInt;
pub trait Paginate: Sized {
fn paginate(self, page: i64) -> Paginated<Self>;
}
impl<T> Paginate for T {
fn paginate(self, page: i64) -> Paginated<Self> {
Paginated {
query: self,
per_page: DEFAULT_PER_PAGE,
page,
}
}
}
const DEFAULT_PER_PAGE: i64 = 100;
#[derive(Debug, Clone, Copy, QueryId)]
pub struct Paginated<T> {
query: T,
page: i64,
per_page: i64,
}
impl<T> Paginated<T> {
pub fn per_page(self, per_page: i64) -> Self {
Paginated { per_page, ..self }
}
pub fn load_and_count_pages<U>(self, conn: &PgConnection) -> QueryResult<(Vec<U>, i64)>
where
Self: LoadQuery<PgConnection, (U, i64)>,
{
let _per_page = self.per_page;
let results = self.load::<(U, i64)>(conn)?;
let total = results.get(0).map(|x| x.1).unwrap_or(0);
let records = results.into_iter().map(|x| x.0).collect();
Ok((records, total))
}
}
impl<T: Query> Query for Paginated<T> {
type SqlType = (T::SqlType, BigInt);
}
impl<T> RunQueryDsl<PgConnection> for Paginated<T> {}
impl<T> QueryFragment<Pg> for Paginated<T>
where
T: QueryFragment<Pg>,
{
fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
out.push_sql("SELECT *, COUNT(*) OVER () FROM (");
self.query.walk_ast(out.reborrow())?;
out.push_sql(") t LIMIT ");
out.push_bind_param::<BigInt, _>(&self.per_page)?;
out.push_sql(" OFFSET ");
let offset = (self.page - 1) * self.per_page;
out.push_bind_param::<BigInt, _>(&offset)?;
Ok(())
}
}
Then you can define a pagination handler.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Cursor {
pub total_pages: i32,
pub filters: Vec<String>,
}
#[derive(Serialize)]
pub struct PaginationResult<T>
where
T: Serialize,
{
pub records: Vec<T>,
pub cursor: Cursor,
}
Then you can now do:
pub fn fav_music_query<T>(request: Json<FavMusicRequest>) -> PaginationResult<Vec<Favorites>> {
use crate::model::diesel::rhythm::rhythm_schema::favorites::dsl::*;
let connection = config::establish_music_connection();
let query = favorites
.filter(like_status.eq(1))
.paginate(request.pageNum)
.per_page(request.pageSize);
let (favorites, pages) = query
.load_and_count_pages::<Favorites>(&connection)
.unwrap();
return PaginationResult {
records: favorites,
cursor: Cursor {
total_pages: pages as i32,
filters: vec![],
},
};
}
My example just gets the total number of pages. You can add more all you need.
Related
I want to map entity from one Vec(this entity list search from database) into another Vec(this response entity list return to frontend) in rust, this is my code:
fn main() {
let musics:Vec<Music> = Vec::new();
for x in 0..10 {
let filtered_music:Vec<Music> = musics.into_iter()
.filter(|item| item.source_id == "1")
.collect();
let resp = MusicRes{
music: take(filtered_music, 0).unwrap()
};
}
}
fn take<T>(mut vec: Vec<T>, index: usize) -> Option<T> {
if index < vec.len() {
Some(vec.swap_remove(index))
} else {
None
}
}
pub struct Music {
pub id: i64,
pub name: String,
pub artists: String,
pub album_id: i64,
pub publishtime: i64,
pub status: i32,
pub duration: i32,
pub source_id: String,
pub source: i32,
pub created_time: i64,
pub updated_time:i64,
pub album: String,
pub fetched_download_url: i32
}
pub struct MusicRes {
pub music:Music
}
this code give me tips that musics was moved. I could change the musics to &musics, but the returned response need to Music. How to handle this situation properly?
I'm not exactly sure what your requirements are, ie. what's the point of the 0..10 then taking the 0th element, but you could do something like this:
let musics: Vec<_> = musics
.into_iter()
.take(10)
.filter(|m| m.source_id == "1")
.map(|m| MusicRes { music: m })
.collect();
I am trying to add the Deserialize attribute to struct A. Content's items contain Button like CallButton like below
let mut buttons: Vec<Box<dyn erased_serde::Serialize>> = Vec::new();
buttons.push(Box::new(
CallButton::new("LABEL".to_string())
.set_label("CALL LABEL".to_string())
.set_msg("MESSAGE".to_string()),
));
How can I make this also deserializable so I can deserialize it? Is there a better way? I think I'm using erased_serde wrong.
use serde::{Deserialize, Serialize};
#[allow(patterns_in_fns_without_body)]
pub trait Button: Serialize {
fn new(label: String) -> Self;
fn set_label(mut self, label: String) -> Self;
fn set_msg(mut self, msg: String) -> Self;
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
pub struct CallButton {
label: String,
action: String,
phone_number: String,
#[serde(skip_serializing_if = "Option::is_none")]
message_text: Option<String>,
}
impl Button for CallButton {
fn new(label: String) -> Self {
CallButton {
label: label,
action: "phone".to_string(),
phone_number: "0".to_string(),
message_text: None,
}
}
fn set_label(mut self, label: String) -> Self {
self.label = label;
self
}
fn set_msg(mut self, msg: String) -> Self {
self.message_text = Some(msg);
self
}
}
// other buttons implementing Button trait...
#[derive(Serialize, Deserialize)] // trying to add Deserialize
#[serde(deny_unknown_fields)]
pub struct A{
content: Content,
}
#[derive(Serialize, Deserialize)] // trying to add Deserialize
#[serde(deny_unknown_fields)]
pub struct Content{
#[serde(skip_serializing_if = "Vec::is_empty")]
items: Vec<Box<dyn erased_serde::Serialize>>, // ! HERE GOES ERROR
}
Error: the trait bound dyn erased_serde::Serialize: db::models::_::_serde::Deserialize<'_> is not satisfied
Maybe I'll have to implement Deserialize strictly
impl<'de> Deserialize<'de> for CarouselContent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let mut content = Content {
items: Vec::new(),
};
let s: Map<String, Value> = Map::deserialize(deserializer)?;
// dont know what to do
Ok(content)
}
}
Just changed everything into enums and it works, thanks for reading!
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Button {
Call(CallButton),
Share(ShareButton),
}
I have the following FlatBuffers schema (simplified):
table StringNode {
prefix: StringNode;
suffix: StringNode;
value: string (required);
}
table NodesData {
url1: StringNode (required);
url2: StringNode (required);
url3: StringNode (required);
}
root_type NodesData;
Is there a way to iterate all StringNodes without having separate urls: [StringNode] and adding them while encoding?
I don't see anything similar in generated Rust code.
PS. The Rust code can be generated using flatc --rust filename. here is what i have:
// automatically generated by the FlatBuffers compiler, do not modify
use std::mem;
use std::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::{EndianScalar, Follow};
#[allow(unused_imports, dead_code)]
pub mod com {
use std::mem;
use std::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::{EndianScalar, Follow};
#[allow(unused_imports, dead_code)]
pub mod company {
use std::mem;
use std::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::{EndianScalar, Follow};
#[allow(unused_imports, dead_code)]
pub mod project {
use std::mem;
use std::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::{EndianScalar, Follow};
#[allow(unused_imports, dead_code)]
pub mod fb {
use std::mem;
use std::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::{EndianScalar, Follow};
#[allow(unused_imports, dead_code)]
pub mod node {
use std::mem;
use std::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::{EndianScalar, Follow};
pub enum StringNodeOffset {}
#[derive(Copy, Clone, PartialEq)]
pub struct StringNode<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for StringNode<'a> {
type Inner = StringNode<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self { _tab: flatbuffers::Table { buf, loc } }
}
}
impl<'a> StringNode<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
StringNode { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args StringNodeArgs<'args>) -> flatbuffers::WIPOffset<StringNode<'bldr>> {
let mut builder = StringNodeBuilder::new(_fbb);
if let Some(x) = args.value { builder.add_value(x); }
if let Some(x) = args.suffix { builder.add_suffix(x); }
if let Some(x) = args.prefix { builder.add_prefix(x); }
builder.finish()
}
pub const VT_PREFIX: flatbuffers::VOffsetT = 4;
pub const VT_SUFFIX: flatbuffers::VOffsetT = 6;
pub const VT_VALUE: flatbuffers::VOffsetT = 8;
#[inline]
pub fn prefix(&self) -> Option<StringNode<'a>> {
self._tab.get::<flatbuffers::ForwardsUOffset<StringNode>>(StringNode::VT_PREFIX, None)
}
#[inline]
pub fn suffix(&self) -> Option<StringNode<'a>> {
self._tab.get::<flatbuffers::ForwardsUOffset<StringNode>>(StringNode::VT_SUFFIX, None)
}
#[inline]
pub fn value(&self) -> &'a str {
self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(StringNode::VT_VALUE, None).unwrap()
}
}
impl flatbuffers::Verifiable for StringNode<'_> {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
v.visit_table(pos)?
.visit_field::<flatbuffers::ForwardsUOffset<StringNode>>(&"prefix", Self::VT_PREFIX, false)?
.visit_field::<flatbuffers::ForwardsUOffset<StringNode>>(&"suffix", Self::VT_SUFFIX, false)?
.visit_field::<flatbuffers::ForwardsUOffset<&str>>(&"value", Self::VT_VALUE, true)?
.finish();
Ok(())
}
}
pub struct StringNodeArgs<'a> {
pub prefix: Option<flatbuffers::WIPOffset<StringNode<'a>>>,
pub suffix: Option<flatbuffers::WIPOffset<StringNode<'a>>>,
pub value: Option<flatbuffers::WIPOffset<&'a str>>,
}
impl<'a> Default for StringNodeArgs<'a> {
#[inline]
fn default() -> Self {
StringNodeArgs {
prefix: None,
suffix: None,
value: None, // required field
}
}
}
pub struct StringNodeBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> StringNodeBuilder<'a, 'b> {
#[inline]
pub fn add_prefix(&mut self, prefix: flatbuffers::WIPOffset<StringNode<'b >>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<StringNode>>(StringNode::VT_PREFIX, prefix);
}
#[inline]
pub fn add_suffix(&mut self, suffix: flatbuffers::WIPOffset<StringNode<'b >>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<StringNode>>(StringNode::VT_SUFFIX, suffix);
}
#[inline]
pub fn add_value(&mut self, value: flatbuffers::WIPOffset<&'b str>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(StringNode::VT_VALUE, value);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> StringNodeBuilder<'a, 'b> {
let start = _fbb.start_table();
StringNodeBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<StringNode<'a>> {
let o = self.fbb_.end_table(self.start_);
self.fbb_.required(o, StringNode::VT_VALUE,"value");
flatbuffers::WIPOffset::new(o.value())
}
}
impl std::fmt::Debug for StringNode<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut ds = f.debug_struct("StringNode");
ds.field("prefix", &self.prefix());
ds.field("suffix", &self.suffix());
ds.field("value", &self.value());
ds.finish()
}
}
pub enum NodesDataOffset {}
#[derive(Copy, Clone, PartialEq)]
pub struct NodesData<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for NodesData<'a> {
type Inner = NodesData<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self { _tab: flatbuffers::Table { buf, loc } }
}
}
impl<'a> NodesData<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
NodesData { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args NodesDataArgs<'args>) -> flatbuffers::WIPOffset<NodesData<'bldr>> {
let mut builder = NodesDataBuilder::new(_fbb);
if let Some(x) = args.url3 { builder.add_url3(x); }
if let Some(x) = args.url2 { builder.add_url2(x); }
if let Some(x) = args.url1 { builder.add_url1(x); }
builder.finish()
}
pub const VT_URL1: flatbuffers::VOffsetT = 4;
pub const VT_URL2: flatbuffers::VOffsetT = 6;
pub const VT_URL3: flatbuffers::VOffsetT = 8;
#[inline]
pub fn url1(&self) -> StringNode<'a> {
self._tab.get::<flatbuffers::ForwardsUOffset<StringNode>>(NodesData::VT_URL1, None).unwrap()
}
#[inline]
pub fn url2(&self) -> StringNode<'a> {
self._tab.get::<flatbuffers::ForwardsUOffset<StringNode>>(NodesData::VT_URL2, None).unwrap()
}
#[inline]
pub fn url3(&self) -> StringNode<'a> {
self._tab.get::<flatbuffers::ForwardsUOffset<StringNode>>(NodesData::VT_URL3, None).unwrap()
}
}
impl flatbuffers::Verifiable for NodesData<'_> {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
v.visit_table(pos)?
.visit_field::<flatbuffers::ForwardsUOffset<StringNode>>(&"url1", Self::VT_URL1, true)?
.visit_field::<flatbuffers::ForwardsUOffset<StringNode>>(&"url2", Self::VT_URL2, true)?
.visit_field::<flatbuffers::ForwardsUOffset<StringNode>>(&"url3", Self::VT_URL3, true)?
.finish();
Ok(())
}
}
pub struct NodesDataArgs<'a> {
pub url1: Option<flatbuffers::WIPOffset<StringNode<'a>>>,
pub url2: Option<flatbuffers::WIPOffset<StringNode<'a>>>,
pub url3: Option<flatbuffers::WIPOffset<StringNode<'a>>>,
}
impl<'a> Default for NodesDataArgs<'a> {
#[inline]
fn default() -> Self {
NodesDataArgs {
url1: None, // required field
url2: None, // required field
url3: None, // required field
}
}
}
pub struct NodesDataBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> NodesDataBuilder<'a, 'b> {
#[inline]
pub fn add_url1(&mut self, url1: flatbuffers::WIPOffset<StringNode<'b >>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<StringNode>>(NodesData::VT_URL1, url1);
}
#[inline]
pub fn add_url2(&mut self, url2: flatbuffers::WIPOffset<StringNode<'b >>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<StringNode>>(NodesData::VT_URL2, url2);
}
#[inline]
pub fn add_url3(&mut self, url3: flatbuffers::WIPOffset<StringNode<'b >>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<StringNode>>(NodesData::VT_URL3, url3);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> NodesDataBuilder<'a, 'b> {
let start = _fbb.start_table();
NodesDataBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<NodesData<'a>> {
let o = self.fbb_.end_table(self.start_);
self.fbb_.required(o, NodesData::VT_URL1,"url1");
self.fbb_.required(o, NodesData::VT_URL2,"url2");
self.fbb_.required(o, NodesData::VT_URL3,"url3");
flatbuffers::WIPOffset::new(o.value())
}
}
impl std::fmt::Debug for NodesData<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut ds = f.debug_struct("NodesData");
ds.field("url1", &self.url1());
ds.field("url2", &self.url2());
ds.field("url3", &self.url3());
ds.finish()
}
}
#[inline]
#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
pub fn get_root_as_nodes_data<'a>(buf: &'a [u8]) -> NodesData<'a> {
unsafe { flatbuffers::root_unchecked::<NodesData<'a>>(buf) }
}
#[inline]
#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
pub fn get_size_prefixed_root_as_nodes_data<'a>(buf: &'a [u8]) -> NodesData<'a> {
unsafe { flatbuffers::size_prefixed_root_unchecked::<NodesData<'a>>(buf) }
}
#[inline]
/// Verifies that a buffer of bytes contains a `NodesData`
/// and returns it.
/// Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `root_as_nodes_data_unchecked`.
pub fn root_as_nodes_data(buf: &[u8]) -> Result<NodesData, flatbuffers::InvalidFlatbuffer> {
flatbuffers::root::<NodesData>(buf)
}
#[inline]
/// Verifies that a buffer of bytes contains a size prefixed
/// `NodesData` and returns it.
/// Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `size_prefixed_root_as_nodes_data_unchecked`.
pub fn size_prefixed_root_as_nodes_data(buf: &[u8]) -> Result<NodesData, flatbuffers::InvalidFlatbuffer> {
flatbuffers::size_prefixed_root::<NodesData>(buf)
}
#[inline]
/// Verifies, with the given options, that a buffer of bytes
/// contains a `NodesData` and returns it.
/// Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `root_as_nodes_data_unchecked`.
pub fn root_as_nodes_data_with_opts<'b, 'o>(
opts: &'o flatbuffers::VerifierOptions,
buf: &'b [u8],
) -> Result<NodesData<'b>, flatbuffers::InvalidFlatbuffer> {
flatbuffers::root_with_opts::<NodesData<'b>>(opts, buf)
}
#[inline]
/// Verifies, with the given verifier options, that a buffer of
/// bytes contains a size prefixed `NodesData` and returns
/// it. Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `root_as_nodes_data_unchecked`.
pub fn size_prefixed_root_as_nodes_data_with_opts<'b, 'o>(
opts: &'o flatbuffers::VerifierOptions,
buf: &'b [u8],
) -> Result<NodesData<'b>, flatbuffers::InvalidFlatbuffer> {
flatbuffers::size_prefixed_root_with_opts::<NodesData<'b>>(opts, buf)
}
#[inline]
/// Assumes, without verification, that a buffer of bytes contains a NodesData and returns it.
/// # Safety
/// Callers must trust the given bytes do indeed contain a valid `NodesData`.
pub unsafe fn root_as_nodes_data_unchecked(buf: &[u8]) -> NodesData {
flatbuffers::root_unchecked::<NodesData>(buf)
}
#[inline]
/// Assumes, without verification, that a buffer of bytes contains a size prefixed NodesData and returns it.
/// # Safety
/// Callers must trust the given bytes do indeed contain a valid size prefixed `NodesData`.
pub unsafe fn size_prefixed_root_as_nodes_data_unchecked(buf: &[u8]) -> NodesData {
flatbuffers::size_prefixed_root_unchecked::<NodesData>(buf)
}
#[inline]
pub fn finish_nodes_data_buffer<'a, 'b>(
fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
root: flatbuffers::WIPOffset<NodesData<'a>>) {
fbb.finish(root, None);
}
#[inline]
pub fn finish_size_prefixed_nodes_data_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<NodesData<'a>>) {
fbb.finish_size_prefixed(root, None);
}
} // pub mod node
} // pub mod fb
} // pub mod project
} // pub mod company
} // pub mod com
But the questions is "even if the getter code is not generated by flatc Rust plugin, is it doable in general?". If following db concept that should be doable.
PPS. flatc "2.0.0" is used, flatbuffers "2.0.0" crate is used.
No, you can't. FlatBuffer fields are not necessarily contiguous in memory, and they potentially all have different types, so there is no way to iterate them.
While that potentially could be implemented with sufficient trickery (visitors?) there isn't a lot of point, especially in a system that is efficiency oriented.
Like you already say so yourself, you really want to be using a [StringNode] in cases like this.
I've recently got to grips with custom serialisation/deserialisation: https://stackoverflow.com/a/63846824/129805
I want to use this custom "stringy" serialisation (and des.) only for JSON and RON, while using the #[derive(Serialisation, ... for all the binary serialisations, such as bincode. (Inflating a two-byte (100, 200) to seven or more bytes of "100:200" is pointlessly wasteful.)
I need to do this within a single executable, as server/server comms will be bincode or protobufs, while client/server comms will be JSON.
Both server/server and client/server comms will use the same serialisable structs. i.e. I want a single set of structs for all comms, but they should use custom serialisation for JSON/RON but derived serialisation for bin/protobufs.
How can I do this?
Update:
Here is working code with tests which pass:
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use serde::de::{self, Visitor, Unexpected};
use std::fmt;
use std::str::FromStr;
use regex::Regex;
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct DerivedIncline {
rise: u8,
distance: u8,
}
impl DerivedIncline {
pub fn new(rise: u8, distance: u8) -> DerivedIncline {
DerivedIncline {rise, distance}
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct StringyIncline {
rise: u8,
distance: u8,
}
impl StringyIncline {
pub fn new(rise: u8, distance: u8) -> StringyIncline {
StringyIncline {rise, distance}
}
}
impl Serialize for StringyIncline {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{}:{}", self.rise, self.distance))
}
}
struct StringyInclineVisitor;
impl<'de> Visitor<'de> for StringyInclineVisitor {
type Value = StringyIncline;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a colon-separated pair of integers between 0 and 255")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
let re = Regex::new(r"(\d+):(\d+)").unwrap(); // PERF: move this into a lazy_static!
if let Some(nums) = re.captures_iter(s).next() {
if let Ok(rise) = u8::from_str(&nums[1]) { // nums[0] is the whole match, so we must skip that
if let Ok(distance) = u8::from_str(&nums[2]) {
Ok(StringyIncline::new(rise, distance))
} else {
Err(de::Error::invalid_value(Unexpected::Str(s), &self))
}
} else {
Err(de::Error::invalid_value(Unexpected::Str(s), &self))
}
} else {
Err(de::Error::invalid_value(Unexpected::Str(s), &self))
}
}
}
impl<'de> Deserialize<'de> for StringyIncline {
fn deserialize<D>(deserializer: D) -> Result<StringyIncline, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_string(StringyInclineVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialisation() {
let stringy_incline = StringyIncline::new(4, 3);
let derived_incline = DerivedIncline::new(4, 3);
let json = serde_json::to_string(&stringy_incline).unwrap();
assert_eq!(json, "\"4:3\"");
let bin = bincode::serialize(&derived_incline).unwrap();
assert_eq!(bin, [4u8, 3u8]);
}
#[test]
fn deserialisation() {
let json = "\"4:3\"";
let bin = [4u8, 3u8];
let deserialised_json: StringyIncline = serde_json::from_str(&json).unwrap();
let deserialised_bin: DerivedIncline = bincode::deserialize(&bin).unwrap();
assert_eq!(deserialised_json, StringyIncline::new(4, 3));
assert_eq!(deserialised_bin, DerivedIncline::new(4, 3));
}
}
I want to have a single Incline struct which acts like StringlyIncline when serialised to JSON or as DerivedIncline when serialised to bincode.
If you're using nightly and are willing to turn on the specialization feature you can write a function that will tell you if the generic parameter S is a serde_json::Serializer
trait IsJsonSerializer {
fn is_json_serializer() -> bool;
}
impl<T> IsJsonSerializer for T {
default fn is_json_serializer() -> bool {
false
}
}
impl<W,F> IsJsonSerializer for &mut serde_json::Serializer<W,F> {
fn is_json_serializer() -> bool {
true
}
}
Then you can write if S::is_json_serializer() {...}. Using this your serialization function can be written:
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
struct RawIncline {
rise: u8,
distance: u8,
}
impl Serialize for Incline {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if S::is_json_serializer() {
serializer.serialize_str(&format!("{}:{}", self.rise, self.distance))
} else {
RawIncline{rise:self.rise, distance:self.distance}.serialize(serializer)
}
}
}
You can then do something similar for deserialization.
I can't think of a way to get something like this to work without the specialization feature, so it limited to nightly for now - but I'd love to see if it is possible somehow.
use std::cell::RefCell;
use std::collections::VecDeque;
// minimum reproducible example for stack overflow question
// which is essentially the whole thing b/c all of these types
// depend on each other
// this is an implementation of Monopoly Deal (see http://monopolydealrules.com/)
// but the only relevant part to the question is in main(), around line 400
// card.rs
pub trait Card {
fn value(&self) -> i32;
fn kind(&self) -> CardKind;
}
pub enum CardKind {
Money,
Action,
Property,
Building,
}
// property.rs
pub struct PropertySet {
color: Color,
properties: Vec<Property>,
house: bool,
hotel: bool,
}
impl PropertySet {
pub fn rent(&self) -> i32 {
unimplemented!() // stub
}
pub fn color(&self) -> Color {
self.color
}
pub fn properties(&self) -> &Vec<Property> {
&self.properties
}
pub fn is_full(&self) -> bool {
self.properties().len() == self.color.set_size() as usize
}
pub fn is_empty(&self) -> bool {
self.properties().len() == 0
}
pub fn add(&mut self, property: Property) -> Result<(), PropertySetAddError> {
if !property.matches(self.color) {
return Err(PropertySetAddError {
property,
kind: PropertySetAddErrorKind::WrongColor,
});
}
if self.properties.len() + 1 < self.color.set_size() as usize {
self.properties.push(property);
Ok(())
} else {
Err(PropertySetAddError {
property,
kind: PropertySetAddErrorKind::SetFull,
})
}
}
fn remove(&mut self, index: usize) -> Property {
self.properties.remove(index)
}
}
pub struct PropertySetAddError {
property: Property,
kind: PropertySetAddErrorKind,
}
pub enum PropertySetAddErrorKind {
WrongColor,
SetFull,
}
pub enum Property {
Basic { name: String, color: Color },
Wild { colors: [Color; 2], value: i32 },
Any,
}
impl Card for Property {
fn value(&self) -> i32 {
unimplemented!() // stub
}
fn kind(&self) -> CardKind {
CardKind::Property
}
}
impl Property {
pub fn matches(&self, color: Color) -> bool {
unimplemented!() // stub
}
}
#[derive(Eq, PartialEq, Hash, Copy, Clone)]
pub enum Color {
Red,
Orange,
Yellow,
Green,
LightBlue,
DarkBlue,
Magenta,
Brown,
Utility,
Railroad,
}
impl Color {
pub fn set_size(&self) -> i32 {
unimplemented!() // stub
}
}
// money.rs
#[derive(PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Money(pub i32);
impl Card for Money {
fn value(&self) -> i32 {
self.0
}
fn kind(&self) -> CardKind {
CardKind::Money
}
}
#[derive(Copy, Clone, Hash, Eq, PartialEq)]
pub struct Id(pub usize);
pub struct Possessions {
bank: Vec<Money>,
hand: Vec<Box<dyn Card>>,
properties: Vec<PropertySet>,
}
// brain.rs
pub trait Brain {
fn act(&self, state: &GameState, possessions: &mut Possessions) -> Vec<Effect>;
fn react(
&self,
state: &GameState,
possessions: &mut Possessions,
effect: &Effect,
) -> Vec<Effect>;
}
pub struct Human {}
impl Human {
pub fn new() -> Human {
Human {}
}
}
impl Brain for Human {
fn act(&self, state: &GameState, possessions: &mut Possessions) -> Vec<Effect> {
unimplemented!()
}
fn react(
&self,
state: &GameState,
possessions: &mut Possessions,
effect: &Effect,
) -> Vec<Effect> {
unimplemented!()
}
}
// action.rs
pub enum Action {
Rent { colors: [Color; 2] },
AnyRent,
DoubleRent,
DealBreaker,
DebtCollector,
Birthday,
SayNo,
PassGo,
SlyDeal,
ForcedDeal,
}
impl Card for Action {
fn value(&self) -> i32 {
unimplemented!() // stub
}
fn kind(&self) -> CardKind {
CardKind::Action
}
}
impl Action {
pub fn effect<'a>(
&self,
source: Id,
target: ActionTarget<'a>,
) -> Result<Effect<'a>, EffectError> {
unimplemented!() // stub
}
}
pub enum ActionTarget<'a> {
None,
Player {
player: Id,
},
Set {
/// The player that this action is targeted against
player: Id,
/// Can be a set that player owns, such as in the case of Deal Breaker, or it
/// can be a set that the source owns, such as in the case of rent cards
set: &'a PropertySet,
},
Property {
player: Id,
property: (&'a PropertySet, usize),
},
Swap {
player: Id,
take: (&'a PropertySet, usize),
give: (&'a PropertySet, usize),
},
}
// effect.rs
#[derive(Clone)]
pub enum Effect<'a> {
// swaps properties with another player
Swap {
source: Id,
target: Id,
give: (&'a PropertySet, usize),
take: (&'a PropertySet, usize),
},
// steals properties from another player
Steal {
source: Id,
target: Id,
set: &'a PropertySet,
indices: Vec<usize>,
},
// charges another player
Charge {
source: Id,
target: Option<Id>,
amount: i32,
reason: ChargeReason,
},
// cancels prior effect
Cancel {
source: Id,
target: Id,
},
// pass Go, credit $2M
Go {
source: Id,
},
}
#[derive(Clone)]
pub enum ChargeReason {
Rent,
Birthday,
DebtCollector,
}
pub enum EffectError {
/// The target supplied was not valid for this action.
InvalidTarget,
/// You tried to charge rent for a color, but the specified set isn't that color
NoProperty,
}
// player.rs
pub struct Player {
pub id: Id,
pub name: String,
pub possessions: Possessions,
pub brain: Box<dyn Brain>,
}
impl Player {
pub fn new(id: Id, name: String, brain: Box<dyn Brain>) -> Player {
Player {
id,
possessions: Possessions {
bank: vec![],
hand: vec![],
properties: vec![],
},
name,
brain,
}
}
pub fn id(&self) -> Id {
self.id
}
pub fn bank(&self) -> &Vec<Money> {
&self.possessions.bank
}
pub fn properties(&self) -> &Vec<PropertySet> {
&self.possessions.properties
}
pub fn name(&self) -> &str {
&self.name
}
pub fn brain(&self) -> &Box<dyn Brain> {
&self.brain
}
pub fn act(&mut self, state: &GameState) -> Vec<Effect> {
self.brain.act(state, &mut self.possessions)
}
pub fn react(&mut self, state: &GameState, effect: &Effect) -> Vec<Effect> {
self.brain.react(state, &mut self.possessions, effect)
}
}
// state.rs
pub struct GameState {
pub players: Vec<RefCell<Player>>,
pub current: Id,
pub stack: Vec<Box<dyn Card>>,
}
impl GameState {
pub fn next(&mut self) {
self.current = Id((self.current.0 + 1) % self.players.len())
}
pub fn current_player(&self) -> &RefCell<Player> {
self.players.get(self.current.0).unwrap()
}
pub fn get_player(&self, id: Id) -> Option<&RefCell<Player>> {
self.players.get(id.0)
}
}
// deck.rs
pub fn create_deck() -> Vec<Box<dyn Card>> {
vec![
// ...
]
}
// main.rs
pub fn main() {
let brain = Human::new(); // Human implements Brain
let me = Player::new(Id(0), "Ibi".to_owned(), Box::new(brain));
let current = me.id();
let players = vec![RefCell::new(me)];
let stack = create_deck(); // returns Vec<Box<dyn Card>>
let mut state = GameState {
players,
stack,
current,
};
while !state.players.iter().any(|player| {
player
.borrow()
.properties()
.iter()
.filter(|&set| set.is_full())
.count()
>= 3
}) {
// ...
let mut effects = VecDeque::new();
{
let mut current_player = state.current_player().borrow_mut();
let action = current_player.act(&state);
effects.extend(action);
}
// let all other players react to effects until no more reactions are generated
while !effects.is_empty() {
let effect = effects.pop_front().unwrap();
// ...
}
}
}
I can't get this code to compile; it says that current_player does not live long enough and complains that it is dropped at the end of the block. Why does current_player need to survive beyond the end of the block? My understanding is that it returns a Vec<Effect> which my method now owns, and then that vector is consumed by extend() and the values it contained are now owned by effects, so why is current_player still necessary?