1.93K subscribers
3.74K photos
143 videos
15 files
3.94K links
Блог со звёздочкой.

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

Небольшое прикольное комьюнити: @decltype_chat_ptr_t
Автор: @insert_reference_here
Download Telegram
#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
🤯82😁2👎1
Блог*
#prog #rust #php #abnormalprogramming Experimentally compiling PHP code to Rust
#prog #rust #php #abnormalprogramming

rustc-php: A Rust compiler written in PHP

A Rust compiler written in PHP that emits x86-64 Linux ELF binaries directly (no LLVM, no assembler, no linker). Implements ownership checking, borrow checking, type checking, move semantics, generics, traits, closures, and iterators. Useful if you need to compile Rust on a shared hosting server from 2008 where the only installed runtime is PHP.
🤯15😁11😱1
#rust

docs.rs: building fewer targets by default

TL;DR: начиная с первого мая, если у пакета не указаны платформы, под которые он собирается, docs.rs будет собирать документацию только под x86_64-unknown-linux-gnu. Изменение касается только новых пакетов и пересборки старых.

Сейчас, если что, без метаданных документация собирается под пять платформ по умолчанию.
🔥14
#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 #python #article

How uv Works Under the Hood

Разбор архитектурных решений, позволяющих uv быть на пару порядков быстрее традиционного тулинга. Тот факт, что он написан на Rust, играет далеко не первую очередь
👍8🤮1🤡1
#prog #rust #rustreleasenotes

Вышла версия Rust 1.95.0! Как всегда, тут только выдержки, всё остальное в детальных заметках о релизе.

▪️if-гуарды на ветках match теперь могут использовать if let:

match value {
Some(x) if let Ok(y) = compute(x) => {
// Both `x` and `y` are available here
println!("{}, {}", x, y);
}
_ => {}
}


▪️Частично примыкающее изменение: компилятор больше не выдаёт предупреждение на безусловные паттерны в if let. Автор изменения мотивирует это распространением кода навроде такого:

fn main() {
if let x = funx() && x < usize::MAX {
// use x
}
}


Эта идиома позволяет привязать значение и что-то сделать/проверить с ним и при этом не пустить имя в окружающую область видимости.

▪️Добавили новый макрос cfg_select!, который позволяет сделать подобие match, но для cfg-предикатов:

cfg_select! {
unix => {
fn foo() { /* unix specific functionality */ }
}
target_pointer_width = "32" => {
fn foo() { /* non-unix, 32-bit functionality */ }
}
_ => {
fn foo() { /* fallback implementation */ }
}
}

let is_windows_str = cfg_select! {
windows => "windows",
_ => "not windows",
};


Технически этот макрос не даёт новых возможностей, но без него нужные атрибуты #[cfg] нужно выписывать самостоятельно, дублируя дословно все предикаты. Ровно по этой причине стал распространён и используется cfg-if — собственно, объявление в блоге напрямую на него и ссылается.

▪️Навряд ли кого-то коснётся, но: match по enum теперь всегда ведёт себя так, как будто он читает дискриминант. Это кажется странным, но объясняется #[non_exhaustive]. Без этого изменения то, есть ли в некотором unsafe-коде UB или нет, зависело от того, определён ли enum в текущем крейте или в другом. Также match теперь читает дискриминант, даже если только одна ветка населена — без этого изменения поведение различалось в обобщённом коде и в ручной мономорфизации.

▪️Поддержку части платформ подняли до Tier 2 — в основном встраиваемые ARM-платформы от Apple (и их симуляторные версии).

▪️Стабилизированы несколько API, в частности:

🔸Конверсии по ссылке из MaybeUninit-массивов в массивы и слайсы из MaybeUninit, а также конверсии по значению между ними
🔸Аналогичные конверсии по ссылке между массивами в Cell и массивами из Cell
🔸Модуль core::range, в котором собираются диапазоны, планируемые на замену текущим. Пока что стабилизированы только RangeInclusive и его итератор. В отличие от текущих диапазонов, новый тип не служит одновременно итератором и потому реализует Copy (при Copy-индексах, разумеется) и занимает меньше места: ему не нужно хранить состояние для отслеживания поведения на последней итерации, только два индекса.
🔸Функция core::hint::cold_path для пометки пути исполнения, который не предполагается, что будет часто исполняться. Этакая замена likely/unlikely.

▪️rustdoc теперь предпочитает стабильные определения нестабильным при сортировке результатов поиска.
🎉92🔥1🥰1
😁25🔥4💯2🥰1🥴1
#prog #itsec #rust #article

Bugs Rust Won't Catch

In April 2026, Canonical disclosed 44 CVEs in uutils, the Rust reimplementation of GNU coreutils that ships by default since 25.10. Most of them came out of an external audit commissioned ahead of the 26.04 LTS.

I read through the list and thought there’s a lot to learn from it.

What’s notable is that all of these bugs landed in a production Rust codebase, written by people who knew what they were doing, and none of them were caught by the borrow checker, clippy lints, or cargo audit.

<...>

If you write systems code in Rust, this is the most concentrated look at where Rust’s safety ends that you’ll likely find anywhere right now.
4🥰2🍌1
🔥17👍7💯3🥰21
#prog #rust #cpp #article

How (and why) we rewrote our production C++ frontend infrastructure in Rust

"Фронтенд" в данном случае означает прокси-сервер, если что.

“Should we convert our _ code to Rust?” is a question that comes up a lot. And a lot of the time the right answer is a pretty firm, “No.” So I thought it might be beneficial (and hopefully interesting) to walk through a case where the code involved was incredibly you-cannot-fuck-this-up business-critical and when we asked that question about it, we came back with a yes. Here’s what it was, how we got to that answer, and what we did about it.


The bottom line is that C++ has caused more than a few situations where we wanted to do something or add a feature and it’s just like… that’s a cool idea, but it’s just not worth the uphill battle against the language. And it was to the point where any change carries the risk of unforeseen consequences.
👍1🥰1😁1
😭16😁10🤣3🥰1
#prog #rust #article

stable specialization in Rust

TL;DR: Iterator::fuse возвращает адаптер, который на вызовах .next() после возврата None продолжает возвращать None. Однако для типов, реализующих FusedIterator (то есть тех, кто уже обещает данное поведение), этот адаптер не отслеживает вызовы и просто вызывает .next() у нижележащего типа напрямую. Можно реализовать FusedIterator для своего типа, сделав её условной по предикату, который мы хотим проверить специализацией (например, реализует ли тип Send), и в реализации не соблюсти этот контракт. Тогда можно вызвать на этом типе, обёрнутом в Fuse, метод next() два раза, проверить, сколько раз next() был вызван реально, и тем самым получить ответ на предикат.
🤔6😭6👍3😁21
😁18
#prog #rust #article

Rust Debugging Progress Report May 2026

О том, как (постепенно) улучшается ситуация с использованием LLDB для Rust
👍51
#prog #rust #rustasync #article

Async Rust never left the MVP state

Заголовок кликбейтный, да. Рассказывается о недостатках текущей кодогенерации машин состояний для async-функций и async-блоков, причём недостатках вполне устранимых
👍5
#prog #rust #article

Why I built wrkflw

If you have spent enough time around CI, you probably know the loop. Change one line in a workflow. Push. Wait for the runner. Watch the job fail for a reason that has nothing to do with the line you changed. Push again. A few rounds later, the real feature is tiny and your git history is mostly you arguing with YAML in public. wrkflw started because I wanted that whole loop to happen on my laptop instead of on GitHub's servers, and preferably without leaving a trail of embarrassing commits behind.

Two years and more edge cases than I expected later, it has turned into a Cargo workspace with sixteen crates. It validates and runs GitHub Actions workflows locally, has a TUI, a proper expression evaluator, four runtime modes, watch mode, secrets, artifacts, cache, reusable workflows, and even a GitLab pipeline parser because apparently I don't know how to leave a side project alone. This post is mostly my attempt to answer the questions people keep asking me: why not just use act, why Rust, and what part was actually hard?
13😁1