Shubham Ankit

Shubham Ankit

1568713521

What is Tokio-Trace Rust Library?

tokio-trace is a new set of Rust libraries that provide primitives for recording scoped, structured, and async-aware diagnostics. Unlike traditional logging, tokio-trace emits structured diagnostics that model the contextual and causal relationships between between events. tokio-trace was designed by the tokio project to solve problems with logging in asynchronous applications, but may be used in any Rust codebase. This talk presents the motivation and influences behind tokio-trace, introduces its core concepts, and demonstrates how it can be used.


Overview

tokio-trace is a framework for instrumenting Rust programs to collect structured, event-based diagnostic information.

In asynchronous systems like Tokio, interpreting traditional log messages can often be quite challenging. Since individual tasks are multiplexed on the same thread, associated events and log lines are intermixed making it difficult to trace the logic flow. tokio-trace expands upon logging-style diagnostics by allowing libraries and applications to record structured events with additional information about temporality and causality — unlike a log message, a span in tokio-trace has a beginning and end time, may be entered and exited by the flow of execution, and may exist within a nested tree of similar spans. In addition, tokio-trace spans are structured, with the ability to record typed data as well as textual messages.

The tokio-trace crate provides the APIs necessary for instrumenting libraries and applications to emit trace data.

Core Concepts

The core of tokio-trace's API is composed of Events, Spans, and Subscribers. We'll cover these in turn.

Spans

Span represents a period of time during which a program was executing in some context. A thread of execution is said to enter a span when it begins executing in that context, and to exit the span when switching to another context. The span in which a thread is currently executing is referred to as the current span.

For example:

#[macro_use]
extern crate tokio_trace;

use tokio_trace::Level;

span!(Level::TRACE, “my_span”).enter(|| {
// perform some work in the context of my_span
});

Spans form a tree structure — unless it is a root span, all spans have a parent, and may have one or more children. When a new span is created, the current span becomes the new span’s parent. The total execution time of a span consists of the time spent in that span and in the entire subtree represented by its children. Thus, a parent span always lasts for at least as long as the longest-executing span in its subtree.

// this span is considered the “root” of a new trace tree:
span!(Level::INFO, “root”).enter(|| {
// since we are now inside “root”, this span is considered a child
// of “root”:
span!(Level::DEBUG, “outer_child”).enter(|| {
// this span is a child of “outer_child”, which is in turn a
// child of “root”:
span!(Level::TRACE, “inner_child”).enter(|| {
// and so on…
});
});
});

In addition, data may be associated with spans. A span may have fields — a set of key-value pairs describing the state of the program during that span; an optional name, and metadata describing the source code location where the span was originally entered.

// construct a new span with three fields:
// - “foo”, with a value of 42,
// - “bar”, with the value “false”
// - “baz”, with no initial value
let my_span = span!(Level::INFO, “my_span”, foo = 42, bar = false, baz);

// record a value for the field “baz” declared above:
my_span.record(“baz”, &“hello world”);

When to use spans

As a rule of thumb, spans should be used to represent discrete units of work (e.g., a given request’s lifetime in a server) or periods of time spent in a given context (e.g., time spent interacting with an instance of an external system, such as a database).

Which scopes in a program correspond to new spans depend somewhat on user intent. For example, consider the case of a loop in a program. Should we construct one span and perform the entire loop inside of that span, like:

span!(Level::TRACE, “my loop”).enter(|| {
for i in 0…n {
// …
}
})

Or, should we create a new span for each iteration of the loop, as in:

for i in 0…n {
span!(Level::TRACE, “my loop”, iteration = i).enter(|| {
// …
})
}

Depending on the circumstances, we might want to do either, or both. For example, if we want to know how long was spent in the loop overall, we would create a single span around the entire loop; whereas if we wanted to know how much time was spent in each individual iteration, we would enter a new span on every iteration.

Events

An Event represents a point in time. It signifies something that happened while the trace was executing. Events are comparable to the log records emitted by unstructured logging code, but unlike a typical log line, an Event may occur within the context of a Span. Like a Span, it may have fields, and implicitly inherits any of the fields present on its parent span.

For example:

// records an event outside of any span context:
event!(Level::INFO, “something happened”);

span!(Level::INFO, “my_span”).enter(|| {
// records an event within “my_span”.
event!(Level::DEBUG, “something happened inside my_span”);
});

Essentially, Events exist to bridge the gap between traditional unstructured logging and span-based tracing. Similar to log records, they may be recorded at a number of levels, and can have unstructured, human-readable messages; however, they also carry key-value data and exist within the context of the tree of spans that comprise a trace. Thus, individual log record-like events can be pinpointed not only in time, but in the logical execution flow of the system.

Events are represented as a special case of spans — they are created, they may have fields added, and then they close immediately, without being entered.

In general, events should be used to represent points in time within a span — a request returned with a given status code, n new items were taken from a queue, and so on.

Subscribers

As Spans and Events occur, they are recorded or aggregated by implementations of the Subscriber trait. Subscribers are notified when an Event takes place and when a Span is entered or exited. These notifications are represented by the following Subscriber trait methods:

  • observe_event, called when an Event takes place,
  • enter, called when execution enters a Span,
  • exit, called when execution exits a Span

In addition, subscribers may implement the enabled function to filter the notifications they receive based on metadata describing each Span or Event. If a call to Subscriber::enabled returns false for a given set of metadata, that Subscriber will not be notified about the corresponding Span or Event. For performance reasons, if no currently active subscribers express interest in a given set of metadata by returning true, then the corresponding Span or Event will never be constructed.

Usage

First, add this to your Cargo.toml:

[dependencies]
tokio-trace = “0.1”

Next, add this to your crate:

#[macro_use]
extern crate tokio_trace;

Spans are constructed using the span! macro, and then entered to indicate that some code takes place within the context of that Span:

// Construct a new span named “my span” with trace log level.
let span = span!(Level::TRACE, “my span”);
span.enter(|| {
// Any trace events in this closure or code called by it will occur within
// the span.
});
// Dropping the span will close it, indicating that it has ended.

Events are created using the event! macro, and are recorded when the event is dropped:

use tokio_trace::Level;
event!(Level::INFO, “something has happened!”);

Users of the log crate should note that tokio-trace exposes a set of macros for creating Events (trace!debug!info!warn!, and error!) which may be invoked with the same syntax as the similarly-named macros from the log crate. Often, the process of converting a project to use tokio-trace can begin with a simple drop-in replacement.

Let’s consider the log crate’s yak-shaving example:

#[macro_use]
extern crate tokio_trace;
use tokio_trace::{field, Level};
pub fn shave_the_yak(yak: &mut Yak) {
// Create a new span for this invocation of shave_the_yak, annotated
// with the yak being shaved as a field on the span.
span!(Level::TRACE, “shave_the_yak”, yak = field::debug(&yak)).enter(|| {
// Since the span is annotated with the yak, it is part of the context
// for everything happening inside the span. Therefore, we don’t need
// to add it to the message for this event, as the log crate does.
info!(target: “yak_events”, “Commencing yak shaving”);

    loop {
        match find_a_razor() {
            Ok(razor) => {
                // We can add the razor as a field rather than formatting it
                // as part of the message, allowing subscribers to consume it
                // in a more structured manner:
                info!({ razor = field::display(razor) }, "Razor located");
                yak.shave(razor);
                break;
            }
            Err(err) => {
                // However, we can also create events with formatted messages,
                // just as we would for log records.
                warn!("Unable to locate a razor: {}, retrying", err);
            }
        }
    }
})

}

You can find examples showing how to use this crate in the examples directory.

In libraries

Libraries should link only to the tokio-trace crate, and use the provided macros to record whatever information will be useful to downstream consumers.

In executables

In order to record trace events, executables have to use a Subscriber implementation compatible with tokio-trace. A Subscriber implements a way of collecting trace data, such as by logging it to standard output.

Unlike the log crate, tokio-trace does not use a global Subscriber which is initialized once. Instead, it follows the tokio pattern of executing code in a context. For example:

#[macro_use]
extern crate tokio_trace;

let my_subscriber = FooSubscriber::new();

tokio_trace::subscriber::with_default(my_subscriber, || {
// Any trace events generated in this closure or by functions it calls
// will be collected by my_subscriber.
})

This approach allows trace data to be collected by multiple subscribers within different contexts in the program. Alternatively, a single subscriber may be constructed by the main function and all subsequent code executed with that subscriber as the default. Any trace events generated outside the context of a subscriber will not be collected.

The executable itself may use the tokio-trace crate to instrument itself as well.

The tokio-trace-nursery repository contains less stable crates designed to be used with the tokio-trace ecosystem. It includes a collection of Subscriber implementations, as well as utility and adapter crates.

In particular, the following tokio-trace-nursery crates are likely to be of interest:

  • tokio-trace-futures provides a compatibility layer with the futures crate, allowing spans to be attached to Futures, Streams, and Executors.
  • tokio-trace-fmt provides a Subscriber implementation for logging formatted trace data to stdout, with similar filtering and formatting to the env-logger crate.
  • tokio-trace-log provides a compatibility layer with the log crate, allowing log Records to be recorded as tokio-trace Events within the trace tree. This is useful when a project using tokio-trace have dependencies which use log.


Crate Feature Flags

The following crate feature flags are available:

  • A set of features controlling the static verbosity level.
  • log causes trace instrumentation points to emit log records as well as trace events. This is inteded for use in libraries whose users may be using either tokio-trace or log.
[dependencies]
tokio-trace = { version = “0.1”, features = [“log”] }

Re-exports

pub use self::span::Span;

Modules

dispatcher Dispatches trace events to Subscribers.c

event Events represent single points in time during the execution of a program.

field Structured data associated with Spans and Events.

level_filters Trace verbosity level filtering.

span Spans represent periods of time in the execution of a program.

subscriber Collects and records trace data.

Macros

debug Constructs an event at the debug level.

debug_span Constructs a span at the debug level.

error Constructs an event at the error level.

error_span Constructs a span at the error level.

event Constructs a new Event.

info Constructs an event at the info level.

info_span Constructs a span at the info level.

span Constructs a new span.

trace Constructs an event at the trace level.

trace_span Constructs a span at the trace level.

warn Constructs an event at the warn level.

warn_span Constructs a span at the warn level.

Structs

Dispatch Dispatch trace data to a Subscriber.

Event Events represent single points in time where something occurred during the execution of a program.

Level Describes the level of verbosity of a span or event.

Metadata Metadata describing a span or [event].

Traits

Subscriber Trait representing the functions required to collect trace data.

Value A field value of an erased type.

Further Reading

Rust for Weld, a High Performance Parallell JIT Compiler

JavaScript to Rust, bringing it to Electron, adding WASM to an existing React

What is class fixes and class breaks in Rust Language?

Building a Retro Computer in Embedded Rust Language



#rust

What is GEEK

Buddha Community

What is Tokio-Trace Rust Library?

Serde Rust: Serialization Framework for Rust

Serde

*Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.*

You may be looking for:

Serde in action

Click to show Cargo.toml. Run this code in the playground.

[dependencies]

# The core APIs, including the Serialize and Deserialize traits. Always
# required when using Serde. The "derive" feature is only required when
# using #[derive(Serialize, Deserialize)] to make Serde work with structs
# and enums defined in your crate.
serde = { version = "1.0", features = ["derive"] }

# Each data format lives in its own crate; the sample code below uses JSON
# but you may be using a different one.
serde_json = "1.0"

 

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&point).unwrap();

    // Prints serialized = {"x":1,"y":2}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Point.
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Point { x: 1, y: 2 }
    println!("deserialized = {:?}", deserialized);
}

Getting help

Serde is one of the most widely used Rust libraries so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo but they tend not to get as many eyes as any of the above and may get closed without a response after some time.

Download Details:
Author: serde-rs
Source Code: https://github.com/serde-rs/serde
License: View license

#rust  #rustlang 

Carmen  Grimes

Carmen Grimes

1595498460

Contact Tracing App: The Technology, Approach to fight COVID-19/Corona

As COVID-19 staggeringly lands blows to nations across the world, governments are considering ways to see their citizens through this pandemic. At the moment, a WHO situation report clocks the number of confirmed cases above two million along with more than one hundred thousand deaths. With vaccines dubbed as the best possible chance to tackle COVID-19 having no precise time frame of being ready, the talk is quickly shifting away to Contact Tracing Applications.

Contact tracing apps are digital solutions that use mobile technology to power the process of manual contact tracing. The apps follow a user’s movement, either by the use of Bluetooth technology, QR codes, or geo-location data while also tracking and keeping data from other user phones nearby. If one user gets diagnosed, the apps alert other users that they may have been exposed to the virus. As such, Contact Tracing Applications are being welcomed and perceived as an important approach to stem the spread of COVID-19 by providing a more accurate platform with data and information about affected individuals.

How Contact Tracing App Works

contact-tracing-app-devathon-

As mentioned above, contact tracing apps leverage mobile technology to trace cases of possible infection more accurately. But how exactly? Once installed and operative, the phone runs the app simultaneously with Bluetooth or location data to transmit signals with unique keys or IDs to phones in the designated range of connection. Similarly, the other phones with the app installed to detect and send back the signals.

For instance, if ‘Individual A’ has the app installed and goes outdoors to run some errands, they will interact with other individuals. In such a case, supposing all the other individuals had functional Contact Tracing Apps, each phone would exchange and store the contact data anonymously. It is important to note that the data collected only covers the app range distance to disregard irrelevant contacts and that their keys repeatedly change as individuals move. In any event that ‘Individual A’ tests positive for COVID-19 through confirmed tests, users who were previously within the proximity of ‘Individual A’ are alerted. Consequently, they are notified to check for symptoms, self-isolate, or get tested. Each time a person tests positive, the app notifies and advises the affected individuals.

In a nutshell, Contact Tracing Apps automate and supplement the traditional concept of tracing contacts to achieve extensive and realistic results in the least time possible.

What are the Benefits of Contact Tracing Apps?

Contract Tracing Apps are assets that offer indispensable solutions to health institutions and the public against COVID-19. There are several reasons why many governments are urging their citizens to use digital contact tracing apps to combat the spread of COVID-19. They include:

  1. The apps are more effective than manual tracing. While not perfect, their predictive algorithms frequently observe individuals detect new cases and analyze the probability one was infected. If one has contact with an asymptomatic individual, they are immediately notified and advised accordingly. Therefore, this saves time, energy, and resources that would have otherwise been overused.
  2. Contact tracing apps facilitate the relaxation of imposed restrictions or lockdowns. With a large number of infected people identified by the apps and put under surveillance, healthy citizens can be allowed to go about their duties. This may be a significant turning point to try and revive economies.
  3. Users’ private data is encrypted and secured. Even if you test positive, other users will only get notifications of possible infections. Your information is protected from both other users and developers of the app.
  4. They will increase the capacity to test and detect COVID-19 cases. With infected users alert, users who come in contact with affected persons come forward to be tested and treated with a higher recovery chance.

Future of Contact Tracing Apps?

Currently, the role of contact tracing apps is limited to accurately identifying infected individuals and their contacts as well as facilitating a quicker response to the Covid-19 threat.

Beyond that, the use of contact tracing apps is projected to take a different turn. One key area bound to change is how people’s privacy is handled. Tech institutions are under growing pressure to devise ways to develop privacy-preserving Contact Tracing Apps.

This will earn the users-trust, which is a pillar for these apps to help contain the disease. Technically, the technology will also have to improve drastically. The apps will have to seamlessly integrate with the user’s phone lifestyle causing minimal or no interference. With most applications having an open-source code, Artificial Intelligence, Beacon Technology, and Big Data solutions will be increasingly harnessed to power and improve them. The apps may also cut across various types of industries apart from health institutions.

How Can It Help to Trace COVID-19 and Reduce the Spread of the Virus?

contact-tracing-app-devathon-3

Contact Tracing Apps will effectively help stem lowering the cases of COVID-19. By using the apps, officials are able to monitor high-risk individuals easily. Also, should any new case arise, both users and health officials get notified they will swiftly act to trace, test, or isolate infected individuals.

Unlike traditional contact tracing, which may not get all contacts, these apps ensure that once Covid-19 cases are detected, they are all treated early, and those other individuals are not exposed to the infection. They also ward off users from high-risk areas. In the long run, they help break the COVID-19 chain by preventing further spread. Illustratively, an online publication by  CNBC states that more than 500,000 using a Singapore-registered mobile number downloaded the TraceTogether app within the first 24 hours of its launch. Subsequently, together with other government efforts, Singapore has since lowered the infection rate and eased restrictions.

If Contact Tracing Apps are implemented and used alongside other policies, we may as well be a few steps way to curbing this virus.

#android app #ios app #mobile app development #news #technology #contact tracing #contact tracing app #contact tracing app approach #contact tracing app technology #contact tracing coronavirus #contact tracing process #corona virus detecting app #corona virus tracing app #corona virus tracker #corona virus tracker live

Awesome  Rust

Awesome Rust

1654894080

Serde JSON: JSON Support for Serde Framework

Serde JSON

Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.

[dependencies]
serde_json = "1.0"

You may be looking for:

JSON is a ubiquitous open-standard format that uses human-readable text to transmit data objects consisting of key-value pairs.

{
    "name": "John Doe",
    "age": 43,
    "address": {
        "street": "10 Downing Street",
        "city": "London"
    },
    "phones": [
        "+44 1234567",
        "+44 2345678"
    ]
}

There are three common ways that you might find yourself needing to work with JSON data in Rust.

  • As text data. An unprocessed string of JSON data that you receive on an HTTP endpoint, read from a file, or prepare to send to a remote server.
  • As an untyped or loosely typed representation. Maybe you want to check that some JSON data is valid before passing it on, but without knowing the structure of what it contains. Or you want to do very basic manipulations like insert a key in a particular spot.
  • As a strongly typed Rust data structure. When you expect all or most of your data to conform to a particular structure and want to get real work done without JSON's loosey-goosey nature tripping you up.

Serde JSON provides efficient, flexible, safe ways of converting data between each of these representations.

Operating on untyped JSON values

Any valid JSON data can be manipulated in the following recursive enum representation. This data structure is serde_json::Value.

enum Value {
    Null,
    Bool(bool),
    Number(Number),
    String(String),
    Array(Vec<Value>),
    Object(Map<String, Value>),
}

A string of JSON data can be parsed into a serde_json::Value by the serde_json::from_str function. There is also from_slice for parsing from a byte slice &[u8] and from_reader for parsing from any io::Read like a File or a TCP stream.

use serde_json::{Result, Value};

fn untyped_example() -> Result<()> {
    // Some JSON input data as a &str. Maybe this comes from the user.
    let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

    // Parse the string of data into serde_json::Value.
    let v: Value = serde_json::from_str(data)?;

    // Access parts of the data by indexing with square brackets.
    println!("Please call {} at the number {}", v["name"], v["phones"][0]);

    Ok(())
}

The result of square bracket indexing like v["name"] is a borrow of the data at that index, so the type is &Value. A JSON map can be indexed with string keys, while a JSON array can be indexed with integer keys. If the type of the data is not right for the type with which it is being indexed, or if a map does not contain the key being indexed, or if the index into a vector is out of bounds, the returned element is Value::Null.

When a Value is printed, it is printed as a JSON string. So in the code above, the output looks like Please call "John Doe" at the number "+44 1234567". The quotation marks appear because v["name"] is a &Value containing a JSON string and its JSON representation is "John Doe". Printing as a plain string without quotation marks involves converting from a JSON string to a Rust string with as_str() or avoiding the use of Value as described in the following section.

The Value representation is sufficient for very basic tasks but can be tedious to work with for anything more significant. Error handling is verbose to implement correctly, for example imagine trying to detect the presence of unrecognized fields in the input data. The compiler is powerless to help you when you make a mistake, for example imagine typoing v["name"] as v["nmae"] in one of the dozens of places it is used in your code.

Parsing JSON as strongly typed data structures

Serde provides a powerful way of mapping JSON data into Rust data structures largely automatically.

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}

fn typed_example() -> Result<()> {
    // Some JSON input data as a &str. Maybe this comes from the user.
    let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

    // Parse the string of data into a Person object. This is exactly the
    // same function as the one that produced serde_json::Value above, but
    // now we are asking it for a Person as output.
    let p: Person = serde_json::from_str(data)?;

    // Do things just like with any other Rust data structure.
    println!("Please call {} at the number {}", p.name, p.phones[0]);

    Ok(())
}

This is the same serde_json::from_str function as before, but this time we assign the return value to a variable of type Person so Serde will automatically interpret the input data as a Person and produce informative error messages if the layout does not conform to what a Person is expected to look like.

Any type that implements Serde's Deserialize trait can be deserialized this way. This includes built-in Rust standard library types like Vec<T> and HashMap<K, V>, as well as any structs or enums annotated with #[derive(Deserialize)].

Once we have p of type Person, our IDE and the Rust compiler can help us use it correctly like they do for any other Rust code. The IDE can autocomplete field names to prevent typos, which was impossible in the serde_json::Value representation. And the Rust compiler can check that when we write p.phones[0], then p.phones is guaranteed to be a Vec<String> so indexing into it makes sense and produces a String.

The necessary setup for using Serde's derive macros is explained on the Using derive page of the Serde site.

Constructing JSON values

Serde JSON provides a json! macro to build serde_json::Value objects with very natural JSON syntax.

use serde_json::json;

fn main() {
    // The type of `john` is `serde_json::Value`
    let john = json!({
        "name": "John Doe",
        "age": 43,
        "phones": [
            "+44 1234567",
            "+44 2345678"
        ]
    });

    println!("first phone number: {}", john["phones"][0]);

    // Convert to a string of JSON and print it out
    println!("{}", john.to_string());
}

The Value::to_string() function converts a serde_json::Value into a String of JSON text.

One neat thing about the json! macro is that variables and expressions can be interpolated directly into the JSON value as you are building it. Serde will check at compile time that the value you are interpolating is able to be represented as JSON.

let full_name = "John Doe";
let age_last_year = 42;

// The type of `john` is `serde_json::Value`
let john = json!({
    "name": full_name,
    "age": age_last_year + 1,
    "phones": [
        format!("+44 {}", random_phone())
    ]
});

This is amazingly convenient, but we have the problem we had before with Value: the IDE and Rust compiler cannot help us if we get it wrong. Serde JSON provides a better way of serializing strongly-typed data structures into JSON text.

Creating JSON by serializing data structures

A data structure can be converted to a JSON string by serde_json::to_string. There is also serde_json::to_vec which serializes to a Vec<u8> and serde_json::to_writer which serializes to any io::Write such as a File or a TCP stream.

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Address {
    street: String,
    city: String,
}

fn print_an_address() -> Result<()> {
    // Some data structure.
    let address = Address {
        street: "10 Downing Street".to_owned(),
        city: "London".to_owned(),
    };

    // Serialize it to a JSON string.
    let j = serde_json::to_string(&address)?;

    // Print, write to a file, or send to an HTTP server.
    println!("{}", j);

    Ok(())
}

Any type that implements Serde's Serialize trait can be serialized this way. This includes built-in Rust standard library types like Vec<T> and HashMap<K, V>, as well as any structs or enums annotated with #[derive(Serialize)].

Performance

It is fast. You should expect in the ballpark of 500 to 1000 megabytes per second deserialization and 600 to 900 megabytes per second serialization, depending on the characteristics of your data. This is competitive with the fastest C and C++ JSON libraries or even 30% faster for many use cases. Benchmarks live in the serde-rs/json-benchmark repo.

Getting help

Serde is one of the most widely used Rust libraries, so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo, but they tend not to get as many eyes as any of the above and may get closed without a response after some time.

No-std support

As long as there is a memory allocator, it is possible to use serde_json without the rest of the Rust standard library. This is supported on Rust 1.36+. Disable the default "std" feature and enable the "alloc" feature:

[dependencies]
serde_json = { version = "1.0", default-features = false, features = ["alloc"] }

For JSON support in Serde without a memory allocator, please see the serde-json-core crate.

Link: https://crates.io/crates/serde_json

#rust  #rustlang  #encode   #json 

Odessa  Rice

Odessa Rice

1626208440

Rust Dublin Lightning Talks April 2021 - Rust crypto libraries

Evervault founder Shane Curran discusses his company’s mission to encrypt the web, with a brief survey of the landscape of Rust crypto libraries.

00:00:00 Intro
00:00:08 Background
00:02:08 evervault encryption engine
00:03:39 AWS Nitro Enclaves
00:05:55 E3 Architecture
00:06:47 Why Rust?
00:10:50 Rust Crypto Libraries
00:17:14 What crypto work is needed in Rust?

#rust #rust crypto libraries

Rust Lang Course For Beginner In 2021: Guessing Game

 What we learn in this chapter:
- Rust number types and their default
- First exposure to #Rust modules and the std::io module to read input from the terminal
- Rust Variable Shadowing
- Rust Loop keyword
- Rust if/else
- First exposure to #Rust match keyword

=== Content:
00:00 - Intro & Setup
02:11 - The Plan
03:04 - Variable Secret
04:03 - Number Types
05:45 - Mutability recap
06:22 - Ask the user
07:45 - First intro to module std::io
08:29 - Rust naming conventions
09:22 - Read user input io:stdin().read_line(&mut guess)
12:46 - Break & Understand
14:20 - Parse string to number
17:10 - Variable Shadowing
18:46 - If / Else - You Win, You Loose
19:28 - Loop
20:38 - Match
23:19 - Random with rand
26:35 - Run it all
27:09 - Conclusion and next episode

#rust