SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Bind me if you can
Răzvan Rotari
Cristian Neamțu
How will you transform JSON into
an object ?
C++
{
"a": "1",
"b": 2,
"c": 3.0
}
struct SimpleStruct {
std::string a;
int b;
double c;
};
auto j =
nlohmann::json::parse(jsonString);
SimpleStruct s;
s.a = j[“a”];
s.b = j[“b”];
s.c = j[“c”];
Rust
{
"a": "1",
"b": 2,
"c": 3.0
}
#[derive(Serialize, Deserialize)]
struct Example {
a: String,
b: i32,
c: f64
}
let e: Example = serde_json::from_str(data)?;
Can we reproduce this
in c++?
NO!
But how close can we get?
Idea 1- Pass object description as parameter
const auto description = std::make_tuple(
std::make_pair("a", &SimpleStruct::a),
std::make_pair("b", &SimpleStruct::b),
std::make_pair("c", &SimpleStruct::c));
const auto output = readJson<SimpleStruct>(jsonData, description);
template <typename ReturnType, typename... Tuple>
ReturnType readJson(std::string_view jsonString, const std::tuple&
description) {
ReturnType ret;
auto j = nlohmann::json::parse(jsonString);
auto readValue = [&](const auto& key) { return j[key]; };
auto populateObject = [&](const auto& elemDesc) {
auto ReturnType::*ptr = std::get<1>(elemDesc);
ret.*ptr = readValue(std::get<0>(elemDesc));
};
std::apply([&](auto&... x) { (..., populateObject(x)); }, description);
/* [&](std::pair<char*, int SimpleStruct::*>& x1,
std::pair<char*, std::string SimpleStruct::*>& x2, ...) {
(populateObject(x1), populateObject(x2), populateObject(x3));
} */
return ret;
}
Idea 1- Pass object description as parameter
- No direct link between object and description
- Boilerplate
- Does not exposes implementation details
Idea 2- Automatic description detection
template <>
struct Descriptor {
static auto getDescription() {
return std::make_tuple(
std::make_pair("a", &SimpleStruct::a),
std::make_pair("b", &SimpleStruct::b),
std::make_pair("c", &SimpleStruct::c));
}
};
const auto output = readJson<SimpleStruct>(jsonData);
template <typename ReturnType>
struct Descriptor {
static void getDescription() {}
};
template <typename ReturnType>
ReturnType readJson(std::string_view jsonString) {
ReturnType ret;
auto j = json::parse(jsonString);
auto populateObject = /*Same as above*/
const auto description = Descriptor<ReturnType>{}.getDescription();
std::apply([&](auto&... x) { (..., populateObject(x)); }, description);
return ret;
}
Idea 2- Automatic description detection
- Even more boilerplate
- Longer compilation times
- Simpler interface
- Does not exposes implementation details
Idea 3 - Embed description into a type
//Requires c++20
template <>
struct Descriptor {
using type = std::tuple<
SETTER("a", &SimpleStruct::a),
SETTER("b", &SimpleStruct::b),
SETTER("c", &SimpleStruct::c)>;
};
const auto output = readJson<SimpleStruct>(jsonData);
template <>
struct Descriptor {
using type =
std::tuple<std::pair<decltype([]() { return "a"; }),
decltype(setter<&SimpleStruct::a>())>,
std::pair<decltype([]() { return "b"; }),
decltype(setter<&SimpleStruct::b>())>,
std::pair<decltype([]() { return "c"; }),
decltype(setter<&SimpleStruct::c>())> >;
};
EXPANDED VERSION
setter() function
template<auto PtrToMember>
constexpr auto setter() {
using Def = PtrMemberExtractor<PtrToMember>;
constexpr auto setterf = [](Def::containing_type & obj,
const Def::result& value) constexpr {
obj.*(Def::value) = value;
};
return setterf;
}
template <typename Class, typename Result, Result Class::*Value>
struct PtrMemberExtractor {
using containing_type = Class;
using result = Result;
static const auto value = Value;
};
template <typename ReturnType>
ReturnType readJson(std::string_view jsonString) {
ReturnType ret;
const auto j = json::parse(jsonString);
auto populateObject = [&](const auto& elemDesc) {
auto setter = std::get<1>(elemDesc);
auto keyFunc = std::get<0>(elemDesc);
setter(ret, j[(keyFunc())]);
};
const typename Descriptor<ReturnType>::type desc;
std::apply([&](auto&... x) { (..., populateObject(x)); }, desc);
/*The above expands to this
[&](std::pair<decltype([]() { return "a"; }),
decltype(setter<&SimpleStruct::a>())> x1,...){
(populateObject(x1), populateObject(x2), populateObject(x3));
} */
return ret;
}
Idea 3 - Embed description into a type
- Uses macros
- Even longer compilation times
- Requires c++20
- Does not exposes implementation details
-
Performace
Baseline Parameter Automatic Compile
mean 2.631 us
Low mean 2.623 us
High mean 2.656 us
Conclusions
- Good to hide implementation
- In practice the keys need to be provided so the boilerplate is reduced
- Works better for complex data, like the output of a SQL JOIN
- Serialization can use the same description
- Flexible pattern
Rust
What  Why Rust?
● Focused on memory safety
● No classes, no inheritance
● Traits over Interfaces
● No variadics in general
● Types can be deduced implicitly
● macro_rules! and procedural macros
The Ownership system
1. Each value has an owner
2. There can be only one owner at a time
3. When the owner goes out of scope the value gets dropped
The compiler:
● checks if the rules are respected
● checks the lifetimes of the data
● inserts clean up code during compilation
Code Examples
Traits
● similar to the idea of interfaces with some differences
● define a contract that must be supported by the desired data type
● can define include both static and instance specific methods
● can provide default implementations
● can be attached to any datatype (owned code standard-library 3rd-party)
Code Examples
macro_rules!
macro_rules! map {
( $($key:expr => $value:expr),* ) => {{
let mut map = HashMap::new();
$(map.insert($key, $value); )*
map
}};
}
fn main() {
let person = map!(
"name" => "John",
"surname" => "Brown"
);
println!("{:?}", person);
}
● Pattern matched
● Token-type safe
○ ty - types
○ ident - identifiers
○ expr - expressions
○ etc.
● Steep learning curve
● Must produce syntactically correct code
● Rust Playground Link
Procedural macros
● a compiler plugin written in Rust that is loaded during compilation
○ it receives the (method, struct, etc.) AST as a parameter
○ produces another AST (rust syntax)
struct SimpleVisitor;
impl Visitor for SimpleVisitor {
type Value = Simple;
type Error = BindError;
fn visit_map(self, mut map: MapAccess) -> Result<Simple, BindError> {
Ok(Simple {
a: map.get_value("a")?.unwrap(),
b: map.get_value("b")?.unwrap(),
c: map.get_value("c")?.unwrap(),
})
}
}
How can I get from this?
To this?
#[derive(Deserializable,Debug)]
pub struct Simple {
pub a: i32,
pub b: String,
pub c: f64,
}
ProcMacro - TokenStream
pub[Ident] struct[Ident] Simple[Ident]
[Group]
pub[Ident] a[Ident] :[Punct] i32[Ident] ,[Punct]
pub[Ident] b[Ident] :[Punct] String[Ident] ,[Punct]
pub[Ident] c[Ident] :[Punct] f64[Ident] ,[Punct]
Implementation
Getting into Serde
● Main Traits
● Examples && Unit Tests
● Macros
Conclusions
● No boilerplate (due to the powerful macro system)
○ Serde: Extensive configurability (renaming, transforming or ignoring attributes, etc.)
○ Type safe conversions
● Serde efficiency due zero-copy deserialization
○ Benchmark - comparison
● Serde has been widely adopted as the “standard” for serialization and
deserialization in Rust:
○ https://serde.rs/#data-formats (json, yaml, csv, etc.)
Implementations available at:
● https://github.com/RazvanRotari/binding_experiment
Thank you!
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013aleks-f
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip CalçadoJustjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip CalçadoPaulo Silveira
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Alexander Granin
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012aleks-f
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th StudyChris Ohk
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Dimitrios Platis
 
Travel management
Travel managementTravel management
Travel management1Parimal2
 

Was ist angesagt? (20)

Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Arrays
ArraysArrays
Arrays
 
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip CalçadoJustjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
 
Day 1
Day 1Day 1
Day 1
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th Study
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Python GC
Python GCPython GC
Python GC
 
Lambda expressions in C++
Lambda expressions in C++Lambda expressions in C++
Lambda expressions in C++
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
Static and const members
Static and const membersStatic and const members
Static and const members
 
Function basics
Function basicsFunction basics
Function basics
 
Container adapters
Container adaptersContainer adapters
Container adapters
 
Travel management
Travel managementTravel management
Travel management
 
c programming
c programmingc programming
c programming
 

Ähnlich wie Bind me if you can

Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17LogeekNightUkraine
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! aleks-f
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersJen Yee Hong
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Yandex
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with PythonHan Lee
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsPVS-Studio
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersAppier
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumlercorehard_by
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxSirRafiLectures
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116Paulo Morgado
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaJevgeni Kabanov
 

Ähnlich wie Bind me if you can (20)

Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmers
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Lecture5
Lecture5Lecture5
Lecture5
 
Overloading
OverloadingOverloading
Overloading
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python Programmers
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 

Mehr von Ovidiu Farauanu

Back in Business with C++
Back in Business with C++Back in Business with C++
Back in Business with C++Ovidiu Farauanu
 
Optimization of the build times using Conan
Optimization of the build times using ConanOptimization of the build times using Conan
Optimization of the build times using ConanOvidiu Farauanu
 
Distributed Cache, bridging C++ to new technologies (Hazelcast)
Distributed Cache, bridging C++ to new technologies (Hazelcast)Distributed Cache, bridging C++ to new technologies (Hazelcast)
Distributed Cache, bridging C++ to new technologies (Hazelcast)Ovidiu Farauanu
 
Monadic Computations in C++14
Monadic Computations in C++14Monadic Computations in C++14
Monadic Computations in C++14Ovidiu Farauanu
 
Domain Specific Languages and C++ Code Generation
Domain Specific Languages and C++ Code GenerationDomain Specific Languages and C++ Code Generation
Domain Specific Languages and C++ Code GenerationOvidiu Farauanu
 
Florentin Picioroaga - C++ by choice
Florentin Picioroaga - C++ by choiceFlorentin Picioroaga - C++ by choice
Florentin Picioroaga - C++ by choiceOvidiu Farauanu
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
Cap'n Proto (C++ Developer Meetup Iasi)
Cap'n Proto (C++ Developer Meetup Iasi)Cap'n Proto (C++ Developer Meetup Iasi)
Cap'n Proto (C++ Developer Meetup Iasi)Ovidiu Farauanu
 

Mehr von Ovidiu Farauanu (10)

Back in Business with C++
Back in Business with C++Back in Business with C++
Back in Business with C++
 
Interface Oxidation
Interface OxidationInterface Oxidation
Interface Oxidation
 
Optimization of the build times using Conan
Optimization of the build times using ConanOptimization of the build times using Conan
Optimization of the build times using Conan
 
Distributed Cache, bridging C++ to new technologies (Hazelcast)
Distributed Cache, bridging C++ to new technologies (Hazelcast)Distributed Cache, bridging C++ to new technologies (Hazelcast)
Distributed Cache, bridging C++ to new technologies (Hazelcast)
 
Monadic Computations in C++14
Monadic Computations in C++14Monadic Computations in C++14
Monadic Computations in C++14
 
Domain Specific Languages and C++ Code Generation
Domain Specific Languages and C++ Code GenerationDomain Specific Languages and C++ Code Generation
Domain Specific Languages and C++ Code Generation
 
Florentin Picioroaga - C++ by choice
Florentin Picioroaga - C++ by choiceFlorentin Picioroaga - C++ by choice
Florentin Picioroaga - C++ by choice
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
 
Cap'n Proto (C++ Developer Meetup Iasi)
Cap'n Proto (C++ Developer Meetup Iasi)Cap'n Proto (C++ Developer Meetup Iasi)
Cap'n Proto (C++ Developer Meetup Iasi)
 

Kürzlich hochgeladen

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Kürzlich hochgeladen (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Bind me if you can

  • 1. Bind me if you can Răzvan Rotari Cristian Neamțu
  • 2. How will you transform JSON into an object ?
  • 3. C++ { "a": "1", "b": 2, "c": 3.0 } struct SimpleStruct { std::string a; int b; double c; }; auto j = nlohmann::json::parse(jsonString); SimpleStruct s; s.a = j[“a”]; s.b = j[“b”]; s.c = j[“c”];
  • 4. Rust { "a": "1", "b": 2, "c": 3.0 } #[derive(Serialize, Deserialize)] struct Example { a: String, b: i32, c: f64 } let e: Example = serde_json::from_str(data)?;
  • 5. Can we reproduce this in c++?
  • 6. NO!
  • 7. But how close can we get?
  • 8. Idea 1- Pass object description as parameter const auto description = std::make_tuple( std::make_pair("a", &SimpleStruct::a), std::make_pair("b", &SimpleStruct::b), std::make_pair("c", &SimpleStruct::c)); const auto output = readJson<SimpleStruct>(jsonData, description);
  • 9. template <typename ReturnType, typename... Tuple> ReturnType readJson(std::string_view jsonString, const std::tuple& description) { ReturnType ret; auto j = nlohmann::json::parse(jsonString); auto readValue = [&](const auto& key) { return j[key]; }; auto populateObject = [&](const auto& elemDesc) { auto ReturnType::*ptr = std::get<1>(elemDesc); ret.*ptr = readValue(std::get<0>(elemDesc)); }; std::apply([&](auto&... x) { (..., populateObject(x)); }, description); /* [&](std::pair<char*, int SimpleStruct::*>& x1, std::pair<char*, std::string SimpleStruct::*>& x2, ...) { (populateObject(x1), populateObject(x2), populateObject(x3)); } */ return ret; }
  • 10. Idea 1- Pass object description as parameter - No direct link between object and description - Boilerplate - Does not exposes implementation details
  • 11. Idea 2- Automatic description detection template <> struct Descriptor { static auto getDescription() { return std::make_tuple( std::make_pair("a", &SimpleStruct::a), std::make_pair("b", &SimpleStruct::b), std::make_pair("c", &SimpleStruct::c)); } }; const auto output = readJson<SimpleStruct>(jsonData);
  • 12. template <typename ReturnType> struct Descriptor { static void getDescription() {} }; template <typename ReturnType> ReturnType readJson(std::string_view jsonString) { ReturnType ret; auto j = json::parse(jsonString); auto populateObject = /*Same as above*/ const auto description = Descriptor<ReturnType>{}.getDescription(); std::apply([&](auto&... x) { (..., populateObject(x)); }, description); return ret; }
  • 13. Idea 2- Automatic description detection - Even more boilerplate - Longer compilation times - Simpler interface - Does not exposes implementation details
  • 14. Idea 3 - Embed description into a type //Requires c++20 template <> struct Descriptor { using type = std::tuple< SETTER("a", &SimpleStruct::a), SETTER("b", &SimpleStruct::b), SETTER("c", &SimpleStruct::c)>; }; const auto output = readJson<SimpleStruct>(jsonData);
  • 15. template <> struct Descriptor { using type = std::tuple<std::pair<decltype([]() { return "a"; }), decltype(setter<&SimpleStruct::a>())>, std::pair<decltype([]() { return "b"; }), decltype(setter<&SimpleStruct::b>())>, std::pair<decltype([]() { return "c"; }), decltype(setter<&SimpleStruct::c>())> >; }; EXPANDED VERSION
  • 16. setter() function template<auto PtrToMember> constexpr auto setter() { using Def = PtrMemberExtractor<PtrToMember>; constexpr auto setterf = [](Def::containing_type & obj, const Def::result& value) constexpr { obj.*(Def::value) = value; }; return setterf; } template <typename Class, typename Result, Result Class::*Value> struct PtrMemberExtractor { using containing_type = Class; using result = Result; static const auto value = Value; };
  • 17. template <typename ReturnType> ReturnType readJson(std::string_view jsonString) { ReturnType ret; const auto j = json::parse(jsonString); auto populateObject = [&](const auto& elemDesc) { auto setter = std::get<1>(elemDesc); auto keyFunc = std::get<0>(elemDesc); setter(ret, j[(keyFunc())]); }; const typename Descriptor<ReturnType>::type desc; std::apply([&](auto&... x) { (..., populateObject(x)); }, desc); /*The above expands to this [&](std::pair<decltype([]() { return "a"; }), decltype(setter<&SimpleStruct::a>())> x1,...){ (populateObject(x1), populateObject(x2), populateObject(x3)); } */ return ret; }
  • 18. Idea 3 - Embed description into a type - Uses macros - Even longer compilation times - Requires c++20 - Does not exposes implementation details -
  • 19. Performace Baseline Parameter Automatic Compile mean 2.631 us Low mean 2.623 us High mean 2.656 us
  • 20. Conclusions - Good to hide implementation - In practice the keys need to be provided so the boilerplate is reduced - Works better for complex data, like the output of a SQL JOIN - Serialization can use the same description - Flexible pattern
  • 21. Rust
  • 22. What Why Rust? ● Focused on memory safety ● No classes, no inheritance ● Traits over Interfaces ● No variadics in general ● Types can be deduced implicitly ● macro_rules! and procedural macros
  • 23. The Ownership system 1. Each value has an owner 2. There can be only one owner at a time 3. When the owner goes out of scope the value gets dropped The compiler: ● checks if the rules are respected ● checks the lifetimes of the data ● inserts clean up code during compilation Code Examples
  • 24. Traits ● similar to the idea of interfaces with some differences ● define a contract that must be supported by the desired data type ● can define include both static and instance specific methods ● can provide default implementations ● can be attached to any datatype (owned code standard-library 3rd-party) Code Examples
  • 25. macro_rules! macro_rules! map { ( $($key:expr => $value:expr),* ) => {{ let mut map = HashMap::new(); $(map.insert($key, $value); )* map }}; } fn main() { let person = map!( "name" => "John", "surname" => "Brown" ); println!("{:?}", person); } ● Pattern matched ● Token-type safe ○ ty - types ○ ident - identifiers ○ expr - expressions ○ etc. ● Steep learning curve ● Must produce syntactically correct code ● Rust Playground Link
  • 26. Procedural macros ● a compiler plugin written in Rust that is loaded during compilation ○ it receives the (method, struct, etc.) AST as a parameter ○ produces another AST (rust syntax)
  • 27. struct SimpleVisitor; impl Visitor for SimpleVisitor { type Value = Simple; type Error = BindError; fn visit_map(self, mut map: MapAccess) -> Result<Simple, BindError> { Ok(Simple { a: map.get_value("a")?.unwrap(), b: map.get_value("b")?.unwrap(), c: map.get_value("c")?.unwrap(), }) } } How can I get from this?
  • 28. To this? #[derive(Deserializable,Debug)] pub struct Simple { pub a: i32, pub b: String, pub c: f64, }
  • 29. ProcMacro - TokenStream pub[Ident] struct[Ident] Simple[Ident] [Group] pub[Ident] a[Ident] :[Punct] i32[Ident] ,[Punct] pub[Ident] b[Ident] :[Punct] String[Ident] ,[Punct] pub[Ident] c[Ident] :[Punct] f64[Ident] ,[Punct] Implementation
  • 30. Getting into Serde ● Main Traits ● Examples && Unit Tests ● Macros
  • 31.
  • 32. Conclusions ● No boilerplate (due to the powerful macro system) ○ Serde: Extensive configurability (renaming, transforming or ignoring attributes, etc.) ○ Type safe conversions ● Serde efficiency due zero-copy deserialization ○ Benchmark - comparison ● Serde has been widely adopted as the “standard” for serialization and deserialization in Rust: ○ https://serde.rs/#data-formats (json, yaml, csv, etc.)
  • 33. Implementations available at: ● https://github.com/RazvanRotari/binding_experiment