#prog #cpp #article
Concept archetypes
Concepts in the form added in C++20 used to be called lite. This is because they do not provide one quite important functionality: having the compiler check if the author of a constrained template is only using operations and types allowed by the constraining concept. In other words, we can say that our template only requires operations A and B to be valid, but we can still use some other operations inside and this is fine with the compiler. In this post we will show how this is problematic, even for programmers aware of the issue, and how to address it with 'concept archetypes'.
Concept archetypes
Concepts in the form added in C++20 used to be called lite. This is because they do not provide one quite important functionality: having the compiler check if the author of a constrained template is only using operations and types allowed by the constraining concept. In other words, we can say that our template only requires operations A and B to be valid, but we can still use some other operations inside and this is fine with the compiler. In this post we will show how this is problematic, even for programmers aware of the issue, and how to address it with 'concept archetypes'.
#prog #rust #rustlib #article
Gaffer: A prioritised micro-batch scheduler in rust
...I looked at existing schedulers but didn't find any which had features which allowed us to take advantage of these optimisation opportunities, so I took this as an opportunity to build a new scheduler and publish my first rust crate, deciding that it needed this set of features:
* Job enqueuing: jobs can be enqueued from other threads using a
* Recurring jobs: in case a job is not enqueued by some maximum timeout, a job can be automatically enqueued.
* Futures: other threads which enqueue jobs should be able to await the results.
* Prioritisation: the job queue is executed in priority, followed by submission order
* Job merging: any jobs with the same effect should be merged in the queue to avoid unnecessary load. This is probably the most important feature and it brings with it some extra challenges for the other features:
* merged jobs with differing priority levels must be merged into the highest priority level
* merged jobs with futures awaiting them need to awaken both with the result of the combined job, so the result needs to implement
* Parallel execution: multiple worker threads are processing the jobs
* Concurrent exclusion: but some jobs need to acquire some lock and so can't run at the same time as each other
* Priority throttling: and to leave capacity ready for higher priority jobs we can limit the number of threads which run the lower priority jobs.
Gaffer: A prioritised micro-batch scheduler in rust
...I looked at existing schedulers but didn't find any which had features which allowed us to take advantage of these optimisation opportunities, so I took this as an opportunity to build a new scheduler and publish my first rust crate, deciding that it needed this set of features:
* Job enqueuing: jobs can be enqueued from other threads using a
Clone + Send
sender.* Recurring jobs: in case a job is not enqueued by some maximum timeout, a job can be automatically enqueued.
* Futures: other threads which enqueue jobs should be able to await the results.
* Prioritisation: the job queue is executed in priority, followed by submission order
* Job merging: any jobs with the same effect should be merged in the queue to avoid unnecessary load. This is probably the most important feature and it brings with it some extra challenges for the other features:
* merged jobs with differing priority levels must be merged into the highest priority level
* merged jobs with futures awaiting them need to awaken both with the result of the combined job, so the result needs to implement
Clone
so that it can be provided to both.* Parallel execution: multiple worker threads are processing the jobs
* Concurrent exclusion: but some jobs need to acquire some lock and so can't run at the same time as each other
* Priority throttling: and to leave capacity ready for higher priority jobs we can limit the number of threads which run the lower priority jobs.
#video
The Difference Between A Dork And A Nerd. Don McMillan, или как притащить PowerPoint на стендап (успешно)
The Difference Between A Dork And A Nerd. Don McMillan, или как притащить PowerPoint на стендап (успешно)
YouTube
The Difference Between A Dork And A Nerd. Don McMillan - Full Special
The difference between a dork and a nerd is harder to spot than you might think, but Don McMillan is here to clear up any misconceptions in his full Dry Bar Comedy special. Whether you're someone who is a geek, or you're someone who is a nerd, or maybe you're…
👍1
Forwarded from мне не нравится реальность
Похвастаюсь и здесь что-ли: я реализовал Rust RFC 3216. Вот прям PR уже смерджили.
TL;DR: фича позволяет явно писать лайфтайм параметры для замыканий:
TL;DR: фича позволяет явно писать лайфтайм параметры для замыканий:
let _f = for<'a, 'b> |a: &'a A, b: &'b B| -> &'b C { b.c(a) };https://github.com/rust-lang/rust/pull/98705
// ^^^^^^^^^^^--- new!
👍12
Forwarded from мне не нравится реальность
IF LET CHAINS ARE STABILIZED IN RUST 1.64
rust-lang/rust/pull/94927#event-7007028976
> 2 years, 4 months, 3 weeks and 1 day of long nights, obstacles and headaches.
> Hope stabilization won't be reverted but regardless, thanks to everyone who helped make this feature a reality.
Для тех кто не в теме, в расте можно делать паттерн матчинг в
rust-lang/rust/pull/94927#event-7007028976
> 2 years, 4 months, 3 weeks and 1 day of long nights, obstacles and headaches.
> Hope stabilization won't be reverted but regardless, thanks to everyone who helped make this feature a reality.
Для тех кто не в теме, в расте можно делать паттерн матчинг в
if
(и while
цикле). Называется эта конструкция "if-let" и выглядит примерно вот так:// выражение vvv
if let Some(x) = opt { ... }
// ^^^^^^^ паттерн
Синтаксис конфузный, но что имеем, то имеем, ладно. Проблемы (которые решает фича выше) начинается когда хочется сравнить сразу несколько выражений с паттернами. Можно использовать туплы:if let (Some(x), Ok(y)) = (opt, res) { ... }
Но мало того, что это абсолютно не читаемо, мало того что это вычисляет res
даже если паттерн и без него бы не сматчился, так ещё и в res
тут нельзя использовать x
. Поэтому это очень неудобно. Можно использовать вложенность:if let Some(x) = opt {
if let Ok(y) = res { ... }
}
Но это ломает else
(с таким вариантом его надо дублировать во все сложенные if
'ы). Это всё настолько печально, что есть даже крейт if_chain с макросом который разбирается со всеми этими проблемами. Ну и фича которую вот стабилизировали — if let chains, которая позволяет писать вот так:if let Some(x) = opt && let Ok(y) = res { ... }
😌GitHub
Stabilize `let_chains` in Rust 1.64 by c410-f3r · Pull Request #94927 · rust-lang/rust
Stabilization proposal
This PR proposes the stabilization of #![feature(let_chains)] in a future-compatibility way that will allow the possible addition of the EXPR is PAT syntax.
Tracking issue: #...
This PR proposes the stabilization of #![feature(let_chains)] in a future-compatibility way that will allow the possible addition of the EXPR is PAT syntax.
Tracking issue: #...
👍9🎉2
#prog #rust
В Rust стабилизировали core::ptr::slice_from_raw_parts в const-контексте, изменение войдёт в Rust 1.64.0. Что это значит? А это значит, что я наконец-то могу написать свой макрос по переводу числу в строку так, чтобы он работал без UB на стабильной версии!
В Rust стабилизировали core::ptr::slice_from_raw_parts в const-контексте, изменение войдёт в Rust 1.64.0. Что это значит? А это значит, что я наконец-то могу написать свой макрос по переводу числу в строку так, чтобы он работал без UB на стабильной версии!
GitHub
Partially stabilize const_slice_from_raw_parts by xfix · Pull Request #97522 · rust-lang/rust
This doesn't stabilize methods working on mutable pointers.
This pull request continues from #94946.
Pinging @rust-lang/wg-const-eval this because I use rustc_allow_const_fn_unstable. I believe...
This pull request continues from #94946.
Pinging @rust-lang/wg-const-eval this because I use rustc_allow_const_fn_unstable. I believe...
👍7👏1
#prog #rust #rustlib #article
Kani — bit-precise model checker for Rust. Верификатор, который исполняет код символически и потому эффективно проверяет код на всех возможных входах. Если код (без внесения ограничений на работу kani) проходит проверку, то его корректность можно считать доказанной.
А также статья, которая проверяет кусок логики из реального проекта:
Using the Kani Rust Verifier on a Firecracker Example
Kani — bit-precise model checker for Rust. Верификатор, который исполняет код символически и потому эффективно проверяет код на всех возможных входах. Если код (без внесения ограничений на работу kani) проходит проверку, то его корректность можно считать доказанной.
А также статья, которая проверяет кусок логики из реального проекта:
Using the Kani Rust Verifier on a Firecracker Example
GitHub
GitHub - model-checking/kani: Kani Rust Verifier
Kani Rust Verifier. Contribute to model-checking/kani development by creating an account on GitHub.
👍4
Forwarded from Generative Anton
Иногда я думаю, что идеи моего ресеча какая-то дичь и не стоит тратить на это время.
А потом вижу статью, в которой статистически подтверждается, что нападения волков в муниципалитетах Германии на уровне земель приводят к ультраправому голосованию, а зеленые на таких выборах голоса теряют 🤯
Популистское объединение против внешнего врага? Как вам объединение против волков 🐺🐺🐺!
Цитаты конечно платиновые (AfD -- ультраправая немецкая партия):
Second, we studied the AfD’s communication regarding the wolf, drawing on three data sources: 1) We obtained the entire universe of AfD Facebook ads between 2018 and 2022, amounting to 10,475 unique ads with 94,578,526 impressions. The data show that the AfD, indeed, uses the wolf as a way to garner votes and largely relies on a frame whereby the wolf hurts the economy…
А потом вижу статью, в которой статистически подтверждается, что нападения волков в муниципалитетах Германии на уровне земель приводят к ультраправому голосованию, а зеленые на таких выборах голоса теряют 🤯
Популистское объединение против внешнего врага? Как вам объединение против волков 🐺🐺🐺!
Цитаты конечно платиновые (AfD -- ультраправая немецкая партия):
Second, we studied the AfD’s communication regarding the wolf, drawing on three data sources: 1) We obtained the entire universe of AfD Facebook ads between 2018 and 2022, amounting to 10,475 unique ads with 94,578,526 impressions. The data show that the AfD, indeed, uses the wolf as a way to garner votes and largely relies on a frame whereby the wolf hurts the economy…
🤔1💩1
Блог*
#prog #julia #article Why I no longer recommend Julia (перевод) My conclusion after using Julia for many years is that there are too many correctness and composability bugs throughout the ecosystem to justify using it in just about any context where correctness…
Хабр
Десять предупреждений для желающих познакомиться поближе с Julia
Julia – мой любимый язык программирования и основной рабочий инструмент для проведения научных исследований и подготовки научной графики. Я восхищаюсь её простотой, изящностью и производительностью....