1.82K subscribers
3.31K photos
132 videos
15 files
3.58K links
Блог со звёздочкой.

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

Небольшое прикольное комьюнити: @decltype_chat_ptr_t
Автор: @insert_reference_here
Download Telegram
— У вас стандартная библиотека работает неправильно.
— Используйте железо, на котором работает правильно.

#prog #go #suckassstory

Source
🍌13🤡7
#prog #rust #article

Shortcomings of Procedural Macros

Или как в процедурный макрос, определённый на impl-блоке, прокинуть информацию о методах с реализацией по умолчанию из определения трейта.

Спойлер: всё в рамках языка, без IO между макросами, но выглядит всё равно как хак.
🤔61
#prog #rust

TIL что квалификатор видимости pub в Rust может иметь форму pub(self), что эквивалентно pub(in self) или отсутствию pub вообще.

Нет, я не знаю, зачем.
🤯10😁3
#prog #article

Writing Mac and iOS Apps Shouldn’t Be So Difficult

Вопреки названию, не специфично для эппловских платформ.

The app was implemented in two pieces:

The kernel, written in C, implemented the database, networking, inter-application communication, various built-in data types, script compiler and evaluator and debugger, and so on
The scripts used the kernel and implemented most of the actual app behavior

Since it was an app, it had plenty of UI — menus, contextual menus, buttons, larger UI components, and so on. What was brilliant was that you could, for instance, add and edit menus, and when you chose a menu command it would run your script. (Or when you clicked a toolbar button, etc.)

You could write an entire static blog publishing system and the UI to go with it without ever restarting the app. Click a thing, then see what happens in the app — and if it’s not right you’d edit the script, which would be automatically recompiled when called the next time.

In other words, there was absolutely no friction when it came to iteration. Write some code without restarting and see your changes immediately.

But I wanted to bring up a second aspect to this: it’s not just frictionless iteration that was so great, it was also the scripting language and environment.

One of the best parts of this was how easy persistence was. I mentioned the hash-table-based database. Hash tables could contain hash tables

<...>

In any script, at any time, without any ceremony, you could read and write from the database simply using dot notation: user.prefs.city = "Seattle" would set the value of city in the prefs table which was contained by the user table. This value would persist between runs of the app, because it was stored in the database.


I’ll remind you of the timing: this was the ’90s. We worked this way for real, and we were amazingly productive.

Автор также отмечает, что в силу того, что скрипты также хранились в базе данных, это позволяло применять обновления приложения без рестарта и без копирования большого количества нативного кода.
🤔41👍1
#prog #article

Faster Rust builds on Mac

Did you know that macOS has a secret setting that can make Rust builds faster? It can also make Rust tests faster (sometimes massively so). It probably even has similar effects for other compiled languages such as C, C++, Go, and Swift. It sounds crazy, but read on…


Nicholas Nethercote заметил, что на Mac компиляция одного Rust-проекта была подозрительно долгой. Замеры времени компиляции через cargo показали, что очень долго исполняются билд-скрипты, причём каждый следующий дольше предыдущего. Как оказалась, это антивирусная фича MacOS (называется XProtect), которая сканирует исполняемые файлы на признаки malware при первом запуске. Билд-скрипты компилируются и исполняются каждый раз заново при компиляции, поэтому постоянно страдают от этих задержек. Замедление же объясняется тем, что процесс, который сканирует исполняемые файлы, однопоточный.

You can avoid these scans by adding Terminal (or any alternative terminal app you are using, such as iTerm) as a “developer tool” in System Settings. See these docs for details.

<...>

Please note that if you do this you are disabling an OS security feature. You should not do it unless you are comfortable with the potential speed/security trade-off.


По очевидным причинам это ускоряет и cargo run, и cargo test (особенно для доктестов до edition 2024, каждый из которых компилируется в отдельный бинарник).

The status quo is that this behaviour is documented in a few obscure places and 99%+ of Mac users are unaware. Fortunately, Mads [Marquart] has a draft PR for Cargo that detects if XProtect is enabled and issues a warning to the user explaining its impact and how to disable it.

Из забавного: отключение XProtect снизило для Mads Marquart время для прогона всех UI-тестов rustc (около 4000 исполняемых файлов) с 9 мин 42 с до 3 мин 33 с.
🤯21👍7😁3🤣3
#prog #rust

Faster linking times with 1.90.0 stable on Linux using the LLD linker

TL;DR: rustc will start using the LLD linker by default on the x86_64-unknown-linux-gnu target starting with the next stable release (1.90.0, scheduled for 2025-09-18), which should significantly reduce linking times.

From our prior testing, we don't really expect issues to happen in practice. It is a drop-in replacement for the vast majority of cases, but lld is not bug-for-bug compatible with GNU ld.

In any case, using rust-lld can be disabled if any problem occurs: use the -C linker-features=-lld flag to revert to using the system's default linker.
❤‍🔥6🎉3🤩1
#prog #rust #serde #article

Be Careful Zero-Copying Strings with serde

TL;DR: из-за того, что строки во многих форматах передачи данных (JSON, например) требуют экранирования специальных символов, строки с подобными символами не могут быть десериализованы в &str (которые указывают на данные из входа). Для того, чтобы поддержать подобные строки, но по мере возможности все же не копировать данные, используйте Cow<str> с атрибутом #[serde(borrow)] на поле.
💯83👌2
#prog #rust

Rust compiler performance survey 2025 results

Помимо того, что вынесено в заголовок — немного о конкретных усилиях для уменьшения времени компиляции.
👍1🤔1
#prog #article

Visitor as a sum type

In it, you'll see how the Visitor design pattern is equivalent to a sum type.


Примеры приведены на C#, но применимы к любому языку с рантайм-полиморфизмом
1👍1🤔1
#prog #abnormalprogramming

HTML, The Programming Language

Язык программирования (внезапно, стековый), программы на котором выглядят, как разметка HTML.
😐5👍4🤯2🍌1
#prog #meme про git и про дилемму вагонетки

(thanks @LoveDeathMath)
🔥18😁10🤣53
#prog #rust #itsec

crates.io: Malicious crates faster_log and async_println

The users in question were immediately disabled, and the crates in question were deleted from crates.io shortly after. We have retained copies of all logs associated with the users and the malicious crate files for further analysis.

The deletion was performed at 15:34 UTC on September 24, 2025.
#prog #rust #rustreleasenotes

Вышла версия Rust 1.90.0!.. Больше недели назад. В свою защиту могу сказать, что в этой версии заметных для большинства пользователей изменений в языке и нету.

Как всегда, тут только избранные части, всё остальное в детальных заметках о релизе.

▪️Как и было обещано, для таргета x86_64-unknown-linux-gnu теперь по умолчанию используется более быстрый линкер lld.

▪️В качестве расширения к методам, добавленным в Rust 1.66.0, добавили методы uX::*_sub_signed (wrapping, checked, overflowing и saturating варианты) для корректного вычитания чисел с разной знаковостью.

▪️CString, CStr и Cow<CStr> теперь можно сравнивать на равенство между собой. Нет, PartialOrd между ними не реализован. Нет, я не знаю, почему.

▪️Старый PR докатился до стейбла: в const-контексте наконец можно вызывать reverse на слайсах. Также теперь там можно вызывать на числах с плавающей точкой различные методы для округления и fract для извлечения дробной части.

▪️Реализацию Default для iter::Fuse привели в соответствие с документацией: теперь default создаёт Fuse, оборачивающий значение по умолчанию внутреннего итератора, вместо создания всегда пустого итератора.

▪️Реализации io::Write для TcpStream и UnixStream теперь на Linux пишут данные с флагом MSG_NOSIGNAL. Это означает, что запись в померший нижележащий сокет теперь возвращает EPIPE — или, в терминах Rust, io::Error, у которого kind() возвращает ErrorKind::BrokenPipe. Данное изменение делает поведение консистентным с тем, как сокеты ведут себя в других местах в std.

▪️Компилятор теперь не даёт скомпилировать код, который упоминает ABI, неподдерживаемый на целевой платформе.
👍41
#prog #web #article

You no longer need JavaScript

Демонстрация того, что можно сделать исключительно при помощи CSS. Включая виджет для выбора цвета (в статье). И включая целую игру-кликер.
🥴4🔥2
#prog #article

Towards Alias-Free Pointers (PDF)

Папир из 1995 года, про который я узнал из презентации Rust: Correctness at Large, Correctness in Motion. Уже тогда была база для основы Rust! Сама статья не столь ясна, как могла бы быть, поскольку демонстрирует примеры на основе модифицированной версии Eiffel.

In this paper we argue that pointer-induced aliasing is largely a self inflicted wound, caused by the almost universal practice in programming to transfer information by copy. As a remedy for this defect we intro duce a concept unshareable objects, and the companion concept of unique pointers, which can be moved from one place to another, but which cannot be copied. We argue that unshareable objects can be employed conveniently in many, if not most, situations where dynamic objects are being used, and without incurring their pitfalls. And we show that it takes no more than minor, and virtually costless, modifications to a typical imperative programming language to support such objects.

И ещё, как отмечает автор:
Another natural application of u-objects [unshareable objects — прим. моё] is discussed in [8], where we show how such objects can be used to implement tokens — objects that, like the capabilities of operating systems, represent certain authority. Such unshareable tokens can be utilized, in particular, for the control of sharing in software systems such as object-oriented databases.

И подобный подход действительно применяется в программах на Rust, самый наглядный пример — MutexGuard.
#prog #rust #article

From Rust to Reality: The Hidden Journey of fetch_max

Why would Rust provide fetch_max as a built-in intrinsic? Intrinsics usually exist to leverage specific hardware instructions. But x86-64 doesn't have an atomic max instruction. So there had to be a CAS loop somewhere in the pipeline.

<...>

So I started digging. What I found was a fascinating journey through five distinct layers of compiler transformations, each one peeling back another level of abstraction, until I found exactly where that loop materialized. Let me share what I discovered.
3
#prog #math #article

Ideal divisors: when a division compiles down to just a multiplication

The division instruction is one of the most expensive instruction in your CPU. Thus optimizing compilers often compile divisions by known constants down to a multiplication followed by a shift. However, in some lucky cases, the compiler does not even need a shift. I call the corresponding divisors ideal.
#prog #rust #rustlib #article

I Wrote A String Type

Статья, рассказывающая о принципиальном устройстве byteyarn — оптимизированного типа для строк, который умещается в 16 байт, имеет small string optimisation и имеет нишу, позволяющую не увеличивать размер при оборачивании в Option
👍4