1.98K subscribers
4.1K photos
167 videos
15 files
4.21K links
Блог со звёздочкой.

Много репостов, немножко программирования.

Небольшое прикольное комьюнити: @decltype_chat_ptr_t
Автор: @insert_reference_here
Download Telegram
#prog #rust #rustlib #article

🦀Building Rust Procedural Macros Without quote!: Introducing zyn

I've been writing proc macros for a while now. Derive macros for internal tools, attribute macros for instrumentation. And every time, the same two problems: quote! doesn't compose (you end up passing TokenStream fragments through five layers of helper functions and writing hundreds of let statements), and debugging generated code means cargo expand and then squinting at unformatted token output hoping something jumps out.

Because of this I ended up writing the same helper methods, composite AST parsing and tokenizing types, extractors etc. I would have to copy these from project to project as needed, and eventually just decided to publish a crate so I never have to do it again.

So I built zyn — a proc macro framework with a template language, composable components, and compile-time diagnostics.


I wrote the debug system after spending two days on a bug where a generated impl block was missing a lifetime bound. cargo expand spat out 400 lines of tokens and I couldn't find it, so I built a debug system.
🤔5❤1👍1🤡1
#prog #rust #rustlib

bnum — библиотека для работы с обобщёнными числами, для которых на уровне типов зафиксированы: знаковость, число байт под хранение, битовая ширина и поведение при переполнении.

use bnum::prelude::*;
// imports common use items
// including the `Integer` type and the `n!` macro

// say we want to write a polynomial function
// which takes any unsigned or signed integer
// of any bit width and with any overflow behaviour
// for example, the polynomial could be p(x) = 2x^3 + 3x^2 + 5x + 7

fn p<const S: bool, const N: usize, const B: usize, const OM: u8>(x: Integer<S, N, B, OM>) -> Integer<S, N, B, OM> {
n!(2)*x.pow(3) + n!(3)*x.pow(2) + n!(5)*x + n!(7)
// type inference means we don't need to specify the width of the integers in the n! macro
}

// 2*10^3 + 3*10^2 + 5*10 + 7 = 2357
assert_eq!(p(n!(10U256)), n!(2357));
// evaluates p(10) as a 256-bit unsigned integer

type U24w = t!(U24w);
// 24-bit unsigned integer with wrapping arithmetic
type I1044s = t!(I1044s);
// 1044-bit signed integer with saturating arithmetic
type U753p = t!(U753p);
// 753-bit unsigned integer that panics on arithmetic overflow

let a = p(U24w::MAX); // result wraps around and doesn't panic
let b = p(I1044s::MAX); // result is too large to be represented by the type, so saturates to I044s::MAX
// let c = p(U753p::MAX); // this would result in panic due to overflow
🫡10🤔2❤1
#prog #rust #rustlib #article #amazingopensource

jsongrep is faster than {jq, jmespath, jsonpath-rust, jql}

This article is both an introduction to a tool I have been working on called jsongrep, as well as a technical explanation of the internal search engine it uses. I also discuss the benchmarking strategy used to compare the performance of jsongrep against other JSON path-like query tools and implementations.

In this post I'll first show you the tool, then explain why it's fast (conceptually), then how it's fast (the automata theory), and finally prove it (benchmarks).
Язык запросов (именно запросов, не редактирования) намеренно ограничен, чтобы сделать его регулярным и позволить быструю реализацию поиска поверх стейт-машины.
👍7
#prog #rust #rustlib #article

Surelock

Deadlocks are a solved problem in theory — we’ve known how to prevent them since 1971. The challenge is making that prevention ergonomic enough that people actually use it. Surelock is my attempt at that: lean into Rust’s type system to make the correct thing the easy thing, and make the wrong thing a compiler error.


Работает и на no_std, полагается на lock_api для абстрагирования от реализации взаимной блокировки.
👍6
#prog #rust #rustlib #article

A faster bump allocator for rust

Новый bump-аллокатор, который на множестве бенчмарков быстрее альтернатив (blink-alloc и bumpalo), часто в 2-3 раза, а в остальных не уступает им. Поддерживает регионы (считай, суб-арены, которые автоматически очищаются на выходе из функции), которые могут быть вложенными.

Из недостатков, которые я заметил: в API есть функции, которые выделяют память под значение, возвращаемое переданной функцией, и они не очищают выделенную память, если функция паникует.
👍6
#prog #rust #rustlib #article

The Design Behind wincode, a Faster Rust Serializer

wincode is a fast, bincode-wire-compatible serializer and deserializer for Rust, built by Anza originally for the Agave validator. It is not a fork of bincode. It is a new implementation with its own traits and derive macros that produces the same bytes as bincode's default configuration


TL;DR: запись в предоставленный MaybeUninit буфер, батчинг валидаций для последовательностей "простых" значений, специализация по типам, использующая сгенерированную derive-макросами метаинформацию (facet на минималках)
🔥3🤔1
#prog #rust #rustlib

Fearless SIMD v1.0 is here

fearless_simd takes unsafe out of SIMD.
🤔4❤1👍1
#prog #rust #rustlib #article

Deser: Rethinking Rust Serialization

Статья про новую библиотеку (де)сериализации. Решает проблемы, которые есть в serde и которые очень сложно или почти невозможно решить из-за архитектуры.

Разумеется, это не строго лучше serde, и в статье подробно об этом рассказывается. В частности, в отличие от serde, deser поддерживает только self-describing форматы.
👍8❤1
#prog #rust #rustlib

hashify v0.3: compile-time perfect hashing, now 4 to 12 times faster than phf

hashify is a procedural macro crate that turns a fixed set of keys into a perfect hash lookup at compile time. The generated code has no runtime dependencies, never allocates and contains no unsafe.
🔥7
#prog #rust #rustlib

owo-colors — библиотека для вывода в терминал окрашенного и стилизованного текста. Без зависимостей (по умолчанию) и поддерживает #![no_std].

use owo_colors::OwoColorize;

fn main() {
// Foreground colors
println!("My number is {:#x}!", 10.green());
// Background colors
println!("My number is not {}!", 4.on_red());
}
❤9
Блог*
#prog #rust #rustlib Jiff — библиотека для работы с датой и временем от BurntSushi. Jiff is a datetime library for Rust that encourages you to jump into the pit of success. The focus of this library is providing high level datetime primitives that are difficult…
#prog #rust #rustlib #article

A datetime library for Rust

Unless some significant defect is found in Jiff’s API, my plan is to commit to Jiff 1.0 indefinitely. This is important because the intent is for Jiff to be an ecosystem building block that appears in the public API of other libraries. This makes Jiff an attractive public dependency, which means semver incompatible releases are likely to cause significant pain in the ecosystem. They will not be made lightly.
👍7