Forwarded from Блог*
#prog #article
Продолжение темы от того же автора: Names are not type safety.
https://lexi-lambda.github.io/blog/2020/11/01/names-are-not-type-safety/
В рассуждениях автора легко провести параллели с тем, как использовать и ограничивать unsafe-код в Rust.
Продолжение темы от того же автора: Names are not type safety.
https://lexi-lambda.github.io/blog/2020/11/01/names-are-not-type-safety/
В рассуждениях автора легко провести параллели с тем, как использовать и ограничивать unsafe-код в Rust.
Forwarded from Блог*
#prog #rust #article
Статья про то, как писать код с инициализацией данных, сохранив сильную exception safety.
Статья про то, как писать код с инициализацией данных, сохранив сильную exception safety.
Arthur::Carcano
Exception safety in Rust: using transient droppers to prevent memory leaks
In this post, we dive into a common Rust pattern to prevent memory leaks in case of exceptions in unsafe code, as used in the `array-init` crate.
Forwarded from Так говорит Алиса (John Meow)
Forwarded from Блог*
#prog #rust #article
Обстоятельная статья о трейтах
Обстоятельная статья о трейтах
Send и Sync и о том, что они означают с точки зрения написания кода.nyanpasu64.github.io
An unsafe tour of Rust’s Send and Sync
Rust’s concurrency safety is based around the Send and Sync traits. For people writing safe code, you don’t really need to understand these traits on a deep level, only enough to satisfy the compiler when it spits errors at you (or switch from std threads…
Forwarded from Блог*
#prog #rust #моё #article
Здрасьте. Сегодня поста не будет — но только потому, что я решил написать статью для Хабра. Собственно, вот она.
И напоминаю: если вам это понравилось — поддержите копеечкой автора, я вам благодарен буду: 4274 3200 5402 8520.
Здрасьте. Сегодня поста не будет — но только потому, что я решил написать статью для Хабра. Собственно, вот она.
И напоминаю: если вам это понравилось — поддержите копеечкой автора, я вам благодарен буду: 4274 3200 5402 8520.
Хабр
Как написать FizzBuzz на собеседовании
Здравствуй, Хабр. Недавно я проходил собеседование в одну солидную айтишную контору. Когда мы разобрались с формальностями, начался технический этап, на котором мне поручили написать fizzbuzz. По не...
Forwarded from Блог*
Michael-F-Bryan
Common Newbie Mistakes and Bad Practices in Rust: Bad Habits
When you are coming to Rust from another language you bring all your previous experiences with you.
Often this is awesome because it means you aren’t learning programming from scratch! However, you can also bring along bad habits which can lead you down the…
Often this is awesome because it means you aren’t learning programming from scratch! However, you can also bring along bad habits which can lead you down the…
Forwarded from Блог*
#prog #article
Статья про паттерн для работы с IO.
"There’s a pattern that I keep recommending to teams over and over again, because it helps separate concerns around I/O; sending and receiving things over a network, interacting with AWS, saving and loading things from data stores. It’s an old idea; you’ll find it filed under “Decorator” in your Gang of Four book.
<...>
Decorators are a great compositional pattern allowing the different concerns that inevitably cluster around I/O boundaries to be neatly separated and recombined. This opportunity presents itself several times in every app we write, and does not require any fancy language, type system, or framework."
Статья про паттерн для работы с IO.
"There’s a pattern that I keep recommending to teams over and over again, because it helps separate concerns around I/O; sending and receiving things over a network, interacting with AWS, saving and loading things from data stores. It’s an old idea; you’ll find it filed under “Decorator” in your Gang of Four book.
<...>
Decorators are a great compositional pattern allowing the different concerns that inevitably cluster around I/O boundaries to be neatly separated and recombined. This opportunity presents itself several times in every app we write, and does not require any fancy language, type system, or framework."
REA Group Ltd
Use the decorator pattern for clean I/O boundaries | REA Group Ltd
Forwarded from Блог*
#prog #rust #article
Rust's Unsafe Pointer Types Need An Overhaul
Или что не так с сырыми указателями в Rust и что с этим стоило бы сделать
Rust's Unsafe Pointer Types Need An Overhaul
Или что не так с сырыми указателями в Rust и что с этим стоило бы сделать
Faultlore
Rust's Unsafe Pointer Types Need An Overhaul - Faultlore
Forwarded from Блог*
#prog #rust #article
How to speed up the Rust compiler in July 2022
Куча интересных усовершенствований!
How to speed up the Rust compiler in July 2022
Куча интересных усовершенствований!
Nicholas Nethercote
How to speed up the Rust compiler in July 2022
Let’s look at some of the progress on Rust compiler speed made since my last post. I will start with some important changes made by other people.
Forwarded from Блог*
#prog #math #article
Написано на удивление доходчиво.
High Performance Correctly Rounded Math Libraries for 32-bit Floating Point Representations
Everyone uses math libraries (i.e., libm), which provide approximations for elementary functions. Surprisingly (or not), mainstream math libraries (i.e., Intel’s and GCC’s libm) do not produce correct results for several thousands of inputs! Developers of modern software systems are seldom aware of them, which affects the reproducibility and portability of software systems. This blog post describes our new method for synthesizing elementary functions that produces correct results for all inputs but is also significantly faster than the state of the art libraries, which have been optimized for decades.
<...>
The overall goal of our RLIBM project is to make correctly rounded elementary functions mandatory rather than a recommendation by the standards (at least for 32 bits or lower). In our RLIBM project, we have been making a case for generating polynomials that approximate the correctly rounded result of f(x) rather than the real value of f(x) because our goal is to generate correct, yet efficient implementations. By approximating the correctly rounded result, we consider both approximation errors (i.e., polynomial approximation) and rounding errors (i.e., with polynomial evaluation with finite precision representations), which enables the generation of correct results. One can use existing high-precision libraries, which are slow, to generate oracle correctly rounded results. Now our goal is to generate efficient polynomials that produce these correctly rounded results for all inputs. Given a correctly rounded result, there is an interval of real values around the correct result that the polynomial can produce, which still rounds to the correct result. This interval is the amount of freedom available that our polynomial generator has for a given input. Using this interval, our idea is to structure the problem of polynomial generation that produces correct results for all inputs as a linear programming (LP) problem. To scale to representations with a large number of inputs, we propose counterexample guided polynomial generation, generate piecewise polynomials rather than a single polynomial, and develop techniques that support various complex range reductions.
Написано на удивление доходчиво.
High Performance Correctly Rounded Math Libraries for 32-bit Floating Point Representations
Everyone uses math libraries (i.e., libm), which provide approximations for elementary functions. Surprisingly (or not), mainstream math libraries (i.e., Intel’s and GCC’s libm) do not produce correct results for several thousands of inputs! Developers of modern software systems are seldom aware of them, which affects the reproducibility and portability of software systems. This blog post describes our new method for synthesizing elementary functions that produces correct results for all inputs but is also significantly faster than the state of the art libraries, which have been optimized for decades.
<...>
The overall goal of our RLIBM project is to make correctly rounded elementary functions mandatory rather than a recommendation by the standards (at least for 32 bits or lower). In our RLIBM project, we have been making a case for generating polynomials that approximate the correctly rounded result of f(x) rather than the real value of f(x) because our goal is to generate correct, yet efficient implementations. By approximating the correctly rounded result, we consider both approximation errors (i.e., polynomial approximation) and rounding errors (i.e., with polynomial evaluation with finite precision representations), which enables the generation of correct results. One can use existing high-precision libraries, which are slow, to generate oracle correctly rounded results. Now our goal is to generate efficient polynomials that produce these correctly rounded results for all inputs. Given a correctly rounded result, there is an interval of real values around the correct result that the polynomial can produce, which still rounds to the correct result. This interval is the amount of freedom available that our polynomial generator has for a given input. Using this interval, our idea is to structure the problem of polynomial generation that produces correct results for all inputs as a linear programming (LP) problem. To scale to representations with a large number of inputs, we propose counterexample guided polynomial generation, generate piecewise polynomials rather than a single polynomial, and develop techniques that support various complex range reductions.
SIGPLAN Blog
High Performance Correctly Rounded Math Libraries for 32-bit Floating Point Representations
Everyone uses math libraries. Surprisingly, mainstream math libraries do not produce correct results for several thousands of inputs. Developers are seldom aware of them, which affects reproducibil…
Forwarded from Блог*
#prog #rust #article
Набор из трёх статей Niko Matsakis про дизайн параллельных итераторов в rayon. Впрочем, первая статья посвящена обзору обычных, последовательных итераторов. Если у вас есть опыт работы с Rust — первую статью можно спокойно не читать.
Parallel Iterators Part 1: Foundations
Parallel Iterators Part 2: Producers
Parallel iterators, part 3: Consumers
И ещё небольшой документ в репе rayon о том, как реализовывать параллельные итераторы.
Набор из трёх статей Niko Matsakis про дизайн параллельных итераторов в rayon. Впрочем, первая статья посвящена обзору обычных, последовательных итераторов. Если у вас есть опыт работы с Rust — первую статью можно спокойно не читать.
Parallel Iterators Part 1: Foundations
Parallel Iterators Part 2: Producers
Parallel iterators, part 3: Consumers
И ещё небольшой документ в репе rayon о том, как реализовывать параллельные итераторы.
docs.rs
rayon - Rust
Rayon is a data-parallelism library that makes it easy to convert sequential computations into parallel.
Forwarded from Блог*
#prog #rust #article
The registers of Rust
Лодочник рассматривает существующие эффекты в Rust (асинхронность, итерирование, ошибочность) с точки зрения регистров (не процессорных, а в том смысле, в котором это слово используется в социолингвистике) и довольно аргументированно доказывает, что усилия по развитию асинхронности в Rust идут в не совсем нужном направлении. Даже если вы с ним не согласны, предложенный им способ рассмотрения фич языка программирования довольно полезен.
И продолжения:
Patterns & Abstractions
Const as an auto trait
The registers of Rust
Лодочник рассматривает существующие эффекты в Rust (асинхронность, итерирование, ошибочность) с точки зрения регистров (не процессорных, а в том смысле, в котором это слово используется в социолингвистике) и довольно аргументированно доказывает, что усилия по развитию асинхронности в Rust идут в не совсем нужном направлении. Даже если вы с ним не согласны, предложенный им способ рассмотрения фич языка программирования довольно полезен.
И продолжения:
Patterns & Abstractions
Const as an auto trait
Forwarded from Блог*
#prog #rust #rustasync #article
Efficient indexing with Quickwit Rust actor framework
Или немного о том, почему разработчики Quickwit решили реализовать свой акторный фреймворк. Также в тексте есть ссылка на статью Actors with Tokio, которая описывает, как создавать свои акторы, имея асинхронный рантайм, и показывает некоторые частые ошибки при подобном наивном подходе.
Efficient indexing with Quickwit Rust actor framework
Или немного о том, почему разработчики Quickwit решили реализовать свой акторный фреймворк. Также в тексте есть ссылка на статью Actors with Tokio, которая описывает, как создавать свои акторы, имея асинхронный рантайм, и показывает некоторые частые ошибки при подобном наивном подходе.
quickwit.io
Efficient indexing with Quickwit Rust actor framework
At Quickwit, we are building the most cost-efficient search engine for logs and traces. Such an engine typically ingests massive amounts of data while serving a comparatively low number of search queries. Under this workload, most of your CPU is spent on…
Forwarded from Блог*
#prog #rust #rustasync #article
Using Rustlang's Async Tokio Runtime for CPU-Bound Tasks
Да, это возможно и в этом есть смысл. Описываемый подход используется в InfluxDB, а InfluxDB используется в проде.
Using Rustlang's Async Tokio Runtime for CPU-Bound Tasks
Да, это возможно и в этом есть смысл. Описываемый подход используется в InfluxDB, а InfluxDB используется в проде.
InfluxData
%%title%% | InfluxData | InfluxData
This blog post argues that the Tokio runtime at the heart of the Rust async ecosystem is a good choice for CPU-heavy jobs.
Forwarded from Блог*
#prog #haskell #article
GADTs
Статья, которая показывает с опорой на лемму Йонеды, что GADT чисто технически не является чем-то, увеличивающим выразительность языка, и что GADT могут быть выражены на обычных ADT (не G) при наличии в языке полиморфизма второго ранга.
GADTs
Статья, которая показывает с опорой на лемму Йонеды, что GADT чисто технически не является чем-то, увеличивающим выразительность языка, и что GADT могут быть выражены на обычных ADT (не G) при наличии в языке полиморфизма второго ранга.
Haskellforall
GADTs
Prelude Some time ago I asked a question on /r/haskell about what unique purpose GADTs served that other language features could not prov...
Forwarded from Блог*
#prog #rust #article
Как известно, в Rust (почти) нет higher-ranked polymorphism. Тем не менее, иногда его можно эмулировать довольно простым образом.
leshow.github.io/post/cheat_rank_n
Как известно, в Rust (почти) нет higher-ranked polymorphism. Тем не менее, иногда его можно эмулировать довольно простым образом.
leshow.github.io/post/cheat_rank_n
Esoterically Typed
Cheating Higher Ranks with Traits
I ran into this a little while ago and thought it would be helpful to share a possible solution.
Imagine you have an enum that describes a set of possible branches, for each branch there is a type …
Imagine you have an enum that describes a set of possible branches, for each branch there is a type …
Forwarded from Блог*
#ml #article
Large Language Foobar
Суммировать всю статью до одного предложения можно цитатой из неё:
Stop treating GPT-4 as if it can understand things when it absolutely and fundamentally cannot and will not.
Разумеется, сам по себе этот призыв не особо убедителен, так что настоятельно рекомендую прочитать всю статью и ознакомиться с конкретными примерами, когда ChatGPT просто не может.
(алсо про частный случай того, что ChatGPT не могёт, я уже выкладывал статью)
Large Language Foobar
Суммировать всю статью до одного предложения можно цитатой из неё:
Stop treating GPT-4 as if it can understand things when it absolutely and fundamentally cannot and will not.
Разумеется, сам по себе этот призыв не особо убедителен, так что настоятельно рекомендую прочитать всю статью и ознакомиться с конкретными примерами, когда ChatGPT просто не может.
(алсо про частный случай того, что ChatGPT не могёт, я уже выкладывал статью)
overengineer.dev
Large Language Foobar - Dennis Schubert
Random thoughts, articles and projects by a chronic overengineer.