1.92K subscribers
3.78K photos
144 videos
15 files
3.97K links
Блог со звёздочкой.

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

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

Introducing facet: Reflection for Rust

Как сказано в facet.rs:

the last proc macro / the last derive you’ll ever need


Сердце библиотеки — трейт Facet и derive-макрос для него. В отличие от других крейтов, которые ползают по определениям типов, facet генерирует не код обхода значений, а константы, которые описывают формы значений и потому могут быть утилизированы разными библиотеками разными способами. Из примеров: (де)сериализация, отладочная печать, ассерты с диффами (которые не полагаются на пост-обработку Debug-выхлопа). В силу того, что код не генерируется, эти реализации могут использовать нерекурсивные алгоритмы и таким образом избежать переполнение стека и легко регулировать глубину вложенности.

В статье рассказывается, зачем это создано и какие ещё преимущества даёт.
👍125🔥2🤡1
#prog #rust #rustlib #article

I Wrote A String Type

Статья, рассказывающая о принципиальном устройстве byteyarn — оптимизированного типа для строк, который умещается в 16 байт, имеет small string optimisation и имеет нишу, позволяющую не увеличивать размер при оборачивании в Option
👍6🤔1
#prog #rust #rustlib #ml #abnormalprogramming

unwrap_or_ai

Tired of manually handling unwrap() results? Let AI do the heavy lifting!
🤩19🤡2
#prog #rust #rustlib

TIL что в bindgen есть возможность прицепить коллбеки, которые будут вызываться для определений, обрабатываемых во время генерации биндингов, и что есть уже готовый CargoCallbacks, который печатает

cargo:rerun-if-changed...

для каждого обрабатываемого файла и каждой явно заданной переменной окружения.
🤔2
#prog #rust #rustlib

brie-tree - SIMD-optimized B+ Tree implementation that uses integer keys

A fast B+ Tree implementation that uses integer keys.
The API is similar to the standard library's BTreeMap with some significant differences:

* Lookups and insertions are 2-4x faster than BTreeMap.
* BTree can optionally be used as a multi-map and hold duplicate keys.
* Keys must be integer types or convertible to integers via the BTreeKey trait.
* The maximum integer value is reserved for internal use and cannot be used by keys.
* Elements in the tree are ordered by the integer value of the key instead of the Ord implementation of the keys.
* Cursors can be used to seek back-and-forth in the tree while inserting or removing elements.
* Iterators only support forward iteration.
👍10
#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.
🤔51👍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🤔21
#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 есть функции, которые выделяют память под значение, возвращаемое переданной функцией, и они не очищают выделенную память, если функция паникует.
👍5