#prog #rust #article
How we saved 100 terabytes of memory by optimizing 1.1.1.1’s DNS cache
Большая часть изменений довольно простая.
How we saved 100 terabytes of memory by optimizing 1.1.1.1’s DNS cache
Big Pineapple, the platform behind 1.1.1.1, Gateway DNS, DNS Firewall, AS112, and several other Cloudflare DNS services, stores over 250 billion DNS cache entries at any given time. At that scale, wasting a single byte per entry costs more than 250 gigabytes of memory across our fleet.
Five successive changes to how cache entries are stored in memory cut the per-entry footprint by over 50%. Across our fleet, these changes freed up roughly 100 terabytes of memory, equivalent to the amount of RAM in 130 of our Gen 13 servers. The cache also got faster. Insert throughput rose 43% and lookup latency dropped 19%, as fewer allocations and better memory locality meant we did not trade speed for space.
Большая часть изменений довольно простая.
🎉7🔥2🤔2
#prog #rust #article
How I made Rustdoc 33% faster in one week
How I made Rustdoc 33% faster in one week
More than any technical detail, the learnings I most want you to take away are to trust your instincts and to question assumptions. Just because a piece of code (or anything, not just code!) has been a certain way for a long time doesn’t mean that it’s optimal or even correct.
👍7❤1
#prog #js #abnormalprogramming #article
The Depths of JavaScript: Minesweeper in 247 Bytes
The Depths of JavaScript: Minesweeper in 247 Bytes
b=e=>document.body.innerHTML=m(73,e||[~9,..."1172711",~9].map(j=>m[i-=j]?++e:i).map(j=>b(b[i=j]^1|e),b[i]=!m[O--,i]*~e));b(m=t=>t--?`<a onmouseup=b(b[i=${t}]^=event.which)>${t%9?"*#F"[x=b[t]??=(O-=m[t]=Math.random()<.1,1)]??~x:"<p>"}`+m(t):O,O=64)🔥13😱1
#prog #rust #article
iddqd, or the hardest kind of unsafe Rust
iddqd, or the hardest kind of unsafe Rust
I’m the main author of iddqd, a Rust library for maps (named after the Doom cheat code) where keys are borrowed from values. <...>
iddqd consists of a fair amount of unsafe code underneath. There’s been some recent concern over the amount of unsafe code in Rust rewrites, so I thought I’d write about some of the unsafe code in iddqd and how we try to tame it.
🤔3
#prog #article
Implementing FMA and finding bugs in C and Rust standard libraries
Implementing FMA and finding bugs in C and Rust standard libraries
This is a story of how I tried to compute a * b + c, and found that Rust and musl libc get it subtly wrong.🤯8👍1
Блог*
#prog #rust #article Replacing a Rust Enum with a 64-bit Word Made My Interpreter 17% Faster <...> That being said, sha256_unfixed is still running 12% faster with the new value representation than with the old version, even though it's allocating a total…
#prog #rust #article
Plush's New Register-Based Interpreter Is Insanely Fast
Plush's New Register-Based Interpreter Is Insanely Fast
I'll go into some detail on how the interpreter was rewritten to switch from a stack-based design like CPython, to a register-based design like Lua, and optimized to deliver some surprising, and I think pretty impressive results. One thing I'll say right away is that if you care about interpreter performance, you probably should not be writing stack-based bytecode interpreters in 2026.
🤔7👍1🔥1
#prog #rust #article
Could Cargo's scheduler be better?
Автор поста собрала записи того, сколько времени уходит на компиляцию каждого крейта во время сборки разных проектов, и решила проверить, можно ли было ускорить сборку за счёт использования порядка сборки, отличного от того, что используется в cargo. В качестве приоритета она использовала т. н. b-level — фактически критический путь в графе зависимостей в терминах длительности компиляции.
TL;DR: этот гипотетический вариант эффективнее cargo и переживает добавление нормально распределённого шума (с разбросом ±60%) и схлопывание информации о длительности до одного бита (долго/недолго).
Could Cargo's scheduler be better?
Автор поста собрала записи того, сколько времени уходит на компиляцию каждого крейта во время сборки разных проектов, и решила проверить, можно ли было ускорить сборку за счёт использования порядка сборки, отличного от того, что используется в cargo. В качестве приоритета она использовала т. н. b-level — фактически критический путь в графе зависимостей в терминах длительности компиляции.
TL;DR: этот гипотетический вариант эффективнее cargo и переживает добавление нормально распределённого шума (с разбросом ±60%) и схлопывание информации о длительности до одного бита (долго/недолго).
❤5👍1
#prog #rust #rustlib #article
The Design Behind wincode, a Faster Rust Serializer
TL;DR: запись в предоставленный MaybeUninit буфер, батчинг валидаций для последовательностей "простых" значений, специализация по типам, использующая сгенерированную derive-макросами метаинформацию (facet на минималках)
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 #article
Proving my Rust NVR doesn't leak memory (it did)
К сожалению, описанные методы диагностирования специфичны для MacOS
Proving my Rust NVR doesn't leak memory (it did)
К сожалению, описанные методы диагностирования специфичны для MacOS
🤔2
#prog #article
Bespoke: A Programming Language for People Who Say Please
Bespoke: A Programming Language for People Who Say Please
I therefore propose Bespoke, a statically typed and uncompromisingly civilised programming language for developers who believe that machine execution should never come at the expense of good manners. Informally it is known as The Queen’s Code: Victoria’s, naturally; the etiquette committee has yet to approve the twentieth century. Source files use the .charming extension, and the compiler reserves the right to be disappointed in you.
❤9😁2
#prog #rust #article
Rust: When Empty Isn't Bottom
Или почему
Rust: When Empty Isn't Bottom
Или почему
! в Rust не является bottom типом. TL;DR: в Rust нет отношения подтипизации для типов, не включающих лайфтаймы.❤4🤔2
#prog #java #article
JVM Anatomy Quark #23: Compressed References
Спека Java ничего не говорит о том, как представляются ссылки. Как следствие, реализации могут использовать представление ссылок, которые меньше указателя на машине. Статья описывает эти трюки.
Несколько неожиданное следствие: эти трюки работают только на достаточно маленьких кучах, поэтому выделение JVM большего количества памяти может привести к тому, что куча выйдет за этот предел, ссылки перестанут использовать компактное представление и потребление памяти многократно вырастет.
JVM Anatomy Quark #23: Compressed References
Спека Java ничего не говорит о том, как представляются ссылки. Как следствие, реализации могут использовать представление ссылок, которые меньше указателя на машине. Статья описывает эти трюки.
Несколько неожиданное следствие: эти трюки работают только на достаточно маленьких кучах, поэтому выделение JVM большего количества памяти может привести к тому, что куча выйдет за этот предел, ссылки перестанут использовать компактное представление и потребление памяти многократно вырастет.
🥴4🤔3
Блог*
#prog #ml #menacingopensource gremllm — библиотека для Python, которая позволяет создавать по описанию объекты, для которых поля и методы создаются LLM по мере необходимости. from gremllm import Gremllm # Be sure to tell your gremllm what sort of thing…
#prog #ml #rust #abnormalprogramming
slopc
(thanks @saddevdiary)
slopc
A proc macro that uses an hallucination machine to write your function bodies at compile time. Throw a signature, slap #[slop] on it, and pray. If it doesn't compile, it feeds the errors back and retries until it does (or gives up).(thanks @saddevdiary)
🔥9
#prog #haskell #article
Type-level programming is still programming
TL;DR: вычисление типов, в отличие от вычисления термов, не является ленивым, и изменения в логике вычисления типов, не меняющее поведение, могут поменять асимптотику времени компиляции с экспоненциальной на линейную.
Type-level programming is still programming
TL;DR: вычисление типов, в отличие от вычисления термов, не является ленивым, и изменения в логике вычисления типов, не меняющее поведение, могут поменять асимптотику времени компиляции с экспоненциальной на линейную.
mchav.github.io
Type-level programming is still programming
I was showing a friend the typed dataframe API. The whole pitch was: look, you derive a schema from your data, and then the compiler catches column name typos, type mismatches, all the stuff that would otherwise blow up at runtime. I had a nice demo ready…
❤7👍2🔥1💩1
Блог*
#prog #rust В Google переписывают Android binder (компонент ядра для IPC) с C на Rust. Это компонент, который используется практически всем на Android, а потому для нормального функционирования он должен быть быстрым и корректным. Авторы ожидают, что переписывание…
#prog #rust
Версия binder на Rust вошла в состав ядра в версии 6.18, а в патче, который должен попасть в ядро версии 7.4, старую версию, на C, полностью удалили.
Версия binder на Rust вошла в состав ядра в версии 6.18, а в патче, который должен попасть в ядро версии 7.4, старую версию, на C, полностью удалили.
🎉14👍2
#prog #rust #article
Why building a Rust LSP is hard
Why building a Rust LSP is hard
This will be a (hopefully coherent) story about how Rust LSPs work, from the perspective of both rust-analyzer and Rust Glancer: how things that seem easy turn out to be hard, things that seem hard turn out to be even harder, and things I didn't expect to exist at all somehow do.
LSP is more of a guess game, where at each step all you are presented with is the potentially incorrect state, and your goal is to guess what would make sense for the user.
❤6💯2
#prog #article
Everyone Says Assembly Is Untyped—Everyone Is Wrong
Everyone Says Assembly Is Untyped—Everyone Is Wrong
TL;DR: I believe Odin’s inline assembly is currently the best out of any language.
The most important aspects are of this article listed below. I am not aware of any other assembly (GCC/Clang/Rust/Go…) that would combine all of these aspects:
* Inline assembly is organized into asm “templates”, similar to and callable as procedures.
* asm templates integrate with rest of the code, through bindings specifying clobbers, pinned, tied, and scratch registers.
* Assembly syntax is unified across ISAs and consistent with Odin syntax.
* Assembly is fully type checked, just like rest of Odin code.
* Understanding that assembly is actually typed.
* Real semantic diagnostics via core:rexcode encoding tables.
* It was built in ~7 days.
🤔6🥰3😱1
Ну #prog... Кусочек, это и статьёй-то не назвать, скорее, #tips
Printing Lists
Printing Lists
To print a comma-separated list, a concise idiom is to optionally print the comma first, before the element:
for (items, 0..) |item, item_index| {
if (item_index > 0) std.debug.print(", ");
std.debug.print("{}", .{item});
}matklad.github.io
Printing Lists
To print a comma-separated list, a concise idiom is to optionally print the comma first, before the element:
❤6🥴4
#prog #article
Steering Zig Fmt
TL;DR (но вообще заметка маленькая):
Steering Zig Fmt
TL;DR (но вообще заметка маленькая):
zig fmt не имеет the каноничного форматирования для кода, а опирается на указания в виде уже частично отформатированного кода и распространяет его на соседние семантически связанные строки.🤯16😁3🥴2🤔1