#prog #rust #rustreleasenotes
Вышла версия Rust 1.90.0!.. Больше недели назад. В свою защиту могу сказать, что в этой версии заметных для большинства пользователей изменений в языке и нету.
Как всегда, тут только избранные части, всё остальное в детальных заметках о релизе.
▪️Как и было обещано, для таргета
▪️В качестве расширения к методам, добавленным в Rust 1.66.0, добавили методы
▪️
▪️Старый PR докатился до стейбла: в const-контексте наконец можно вызывать
▪️Реализацию
▪️Реализации
▪️Компилятор теперь не даёт скомпилировать код, который упоминает ABI, неподдерживаемый на целевой платформе.
Вышла версия 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, неподдерживаемый на целевой платформе.
👍6❤1
#prog #web #article
You no longer need JavaScript
Демонстрация того, что можно сделать исключительно при помощи CSS. Включая виджет для выбора цвета (в статье). И включая целую игру-кликер.
You no longer need JavaScript
Демонстрация того, что можно сделать исключительно при помощи CSS. Включая виджет для выбора цвета (в статье). И включая целую игру-кликер.
🔥4🥴4
#prog #article
Towards Alias-Free Pointers (PDF)
Папир из 1995 года, про который я узнал из презентации Rust: Correctness at Large, Correctness in Motion. Уже тогда была база для основы Rust! Сама статья не столь ясна, как могла бы быть, поскольку демонстрирует примеры на основе модифицированной версии Eiffel.
И ещё, как отмечает автор:
И подобный подход действительно применяется в программах на Rust, самый наглядный пример — MutexGuard.
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
From Rust to Reality: The Hidden Journey of fetch_max
Why would Rust providefetch_maxas a built-in intrinsic? Intrinsics usually exist to leverage specific hardware instructions. But x86-64 doesn't have anatomic maxinstruction. 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
Итак, папищеки.
Я знаю, что среди вас есть те, кто сейчас живут в Армении.
И я знаю, что среди вас есть те, кому интересны настольные ролевые игры.
У меня есть подозрение, что пересечение этих двух подмножеств непустое, потому у меня вопрос:
Кто из вас заинтересован в том, чтобы сыграть в ваншот с системой Pathfinder 2e со мной в качестве мастера?
P. S.: если среди проживающих в Армении достаточно не найдётся, то попробую набрать на онлайн-игру.
UPD: игроки найдены
Я знаю, что среди вас есть те, кто сейчас живут в Армении.
И я знаю, что среди вас есть те, кому интересны настольные ролевые игры.
У меня есть подозрение, что пересечение этих двух подмножеств непустое, потому у меня вопрос:
Кто из вас заинтересован в том, чтобы сыграть в ваншот с системой Pathfinder 2e со мной в качестве мастера?
P. S.: если среди проживающих в Армении достаточно не найдётся, то попробую набрать на онлайн-игру.
UPD: игроки найдены
❤7😁4👍2🤯1💩1🤡1🖕1
#prog #math #article
Ideal divisors: when a division compiles down to just a multiplication
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.
Forwarded from Neural Machine
К сожалению, мы живем в мире, где необходимо встречаться с людьми.
😢18💯5🤡1
Cloning stamp — один из лучших инструментов, которых нам подарили цифровые редакторы
🤡2
Forwarded from Технологический Болт Генона
How Grab’s Migration from Go to Rust Cut Costs by 70%
https://blog.bytebytego.com/p/how-grabs-migration-from-go-to-rust
tl;dr Основным языком был Go, потом переписали один важный сервис на Rust и снизили затраты на 70%.
Теперь не очень кратко
Был выбран высоконагруженный, но достаточно простой по функциональности сервис
> To approach this decision carefully, the Grab Engineering Team set clear criteria for selecting a service to rewrite. The chosen system needed to be simple enough in its functionality to avoid unnecessary complexity. It also had to serve large amounts of traffic so that any efficiency gains would be meaningful. Finally, the team needed to be confident that engineers were willing and able to learn Rust to support the system for the long term.
Таким сервисом стал
- Фиксирует события, считает их и складывает в ScyllaDB
- Отвечает на GRPC запросы, которые собственно и касаются "циферок"
> While Counter Service handles very high traffic, reaching tens of thousands of requests every second at peak times, the work it performs is straightforward. It counts, stores, and returns numbers.
На первой картинке видно как этот сервис организован
Переписывали сервис "вслепую", как "чёрный ящик". Новая реализация должна была повторять полностью ответы старой системы на одинаковые запросы.
Далее смотрели какие библиотеки есть для Rust, что бы во-первых упростить перенос, во-вторых оценить некую "зрелость" зависимостей.
Here are the main dependencies:
- Datadog StatsD client: The Grab engineering team chose Cadence. It had fewer than 500 GitHub stars, which suggested a smaller user base, but the API was intuitive and covered all the required features.
- OpenTelemetry: They used opentelemetry-rust, which had more than 1,000 stars and solid community backing.
- GRPC: The tonic library was selected, a well-known Rust implementation of GRPC with active use and more than 500 stars.
- Web server: actix-web was picked. It is one of the most popular Rust frameworks, with more than 20,000 stars.
- Redis: Initially, the team tried redis-rs, the “official” Redis client with over 3,000 stars. However, it did not meet the needs of the project’s asynchronous design. They switched to fred.rs, which had over 5,000 stars and better async support.
- Scylla: They used the scylla-rust-driver. Although it had only around 500 stars, it was officially maintained by the Scylla project, giving confidence in its long-term support.
- Kafka: The kafka-rust client, with over 1,000 stars, was adopted to handle messaging needs.
Следующей проблемой было то, что их собственные компоненты и либы были написаны на Go. Одну из таких важных библиотек им пришлось переписать на Rust.
Пост большой и дальше там поднимаются проблемы Borrow Checker'а (а кто с ним не боролся на первых шагах 🌝) и Async Concurrency (тоже ловили проблемы на первых этапах разработки).
Итого
- Сервис перепилили
- latency обе реализации показали приблизительно одинаковую, иногда у Rust даже медленнее (вторая картинка)
- Но для реализации на Rust ресурсов надо меньше:
- The Go service needed about 20 CPU cores.
- The Rust service needed only about 4.5 cores.
- This translated into nearly five times better efficiency and about 70 percent lower infrastructure cost for the same workload.
Основных три общих вывода
- Rust is not always faster than Go. Go is already fast enough for most high-performance services, so Rust will not necessarily reduce latency
- Rust is more efficient. Thanks to its design, Rust uses less computing power to achieve the same results. This makes it especially valuable for services with heavy traffic where cost savings add up quickly
- Rust’s learning curve depends on context. Writing synchronous code in Rust is manageable for most experienced developers, especially with the help of the compiler and the Clippy linter. The real challenge comes with asynchronous code, which requires a deeper understanding of concurrency
https://blog.bytebytego.com/p/how-grabs-migration-from-go-to-rust
tl;dr Основным языком был Go, потом переписали один важный сервис на Rust и снизили затраты на 70%.
Теперь не очень кратко
Был выбран высоконагруженный, но достаточно простой по функциональности сервис
> To approach this decision carefully, the Grab Engineering Team set clear criteria for selecting a service to rewrite. The chosen system needed to be simple enough in its functionality to avoid unnecessary complexity. It also had to serve large amounts of traffic so that any efficiency gains would be meaningful. Finally, the team needed to be confident that engineers were willing and able to learn Rust to support the system for the long term.
Таким сервисом стал
Counter Service, который отслеживает происходящее и предоставляет различные счётчики- Фиксирует события, считает их и складывает в ScyllaDB
- Отвечает на GRPC запросы, которые собственно и касаются "циферок"
> While Counter Service handles very high traffic, reaching tens of thousands of requests every second at peak times, the work it performs is straightforward. It counts, stores, and returns numbers.
На первой картинке видно как этот сервис организован
Переписывали сервис "вслепую", как "чёрный ящик". Новая реализация должна была повторять полностью ответы старой системы на одинаковые запросы.
Далее смотрели какие библиотеки есть для Rust, что бы во-первых упростить перенос, во-вторых оценить некую "зрелость" зависимостей.
Here are the main dependencies:
- Datadog StatsD client: The Grab engineering team chose Cadence. It had fewer than 500 GitHub stars, which suggested a smaller user base, but the API was intuitive and covered all the required features.
- OpenTelemetry: They used opentelemetry-rust, which had more than 1,000 stars and solid community backing.
- GRPC: The tonic library was selected, a well-known Rust implementation of GRPC with active use and more than 500 stars.
- Web server: actix-web was picked. It is one of the most popular Rust frameworks, with more than 20,000 stars.
- Redis: Initially, the team tried redis-rs, the “official” Redis client with over 3,000 stars. However, it did not meet the needs of the project’s asynchronous design. They switched to fred.rs, which had over 5,000 stars and better async support.
- Scylla: They used the scylla-rust-driver. Although it had only around 500 stars, it was officially maintained by the Scylla project, giving confidence in its long-term support.
- Kafka: The kafka-rust client, with over 1,000 stars, was adopted to handle messaging needs.
Следующей проблемой было то, что их собственные компоненты и либы были написаны на Go. Одну из таких важных библиотек им пришлось переписать на Rust.
Пост большой и дальше там поднимаются проблемы Borrow Checker'а (а кто с ним не боролся на первых шагах 🌝) и Async Concurrency (тоже ловили проблемы на первых этапах разработки).
Итого
- Сервис перепилили
- latency обе реализации показали приблизительно одинаковую, иногда у Rust даже медленнее (вторая картинка)
- Но для реализации на Rust ресурсов надо меньше:
- The Go service needed about 20 CPU cores.
- The Rust service needed only about 4.5 cores.
- This translated into nearly five times better efficiency and about 70 percent lower infrastructure cost for the same workload.
Основных три общих вывода
- Rust is not always faster than Go. Go is already fast enough for most high-performance services, so Rust will not necessarily reduce latency
- Rust is more efficient. Thanks to its design, Rust uses less computing power to achieve the same results. This makes it especially valuable for services with heavy traffic where cost savings add up quickly
- Rust’s learning curve depends on context. Writing synchronous code in Rust is manageable for most experienced developers, especially with the help of the compiler and the Clippy linter. The real challenge comes with asynchronous code, which requires a deeper understanding of concurrency
🤡6🔥5😁2🤔1💩1🖕1