Forwarded from Блог*
Forwarded from Блог*
#prog #rust
Пара советов по строкам в Rust:
1) Если вам нужно разбить строку по одному из нескольких возможных символов — не спешите расчехлять регулярки, для это задачи вполне хватит стандартной библиотеки. Множество строковых методов навроде {, r}split{, _terminator}, trim{, _start, _end}_matches, find и прочие принимают в качестве аргумента для поиска значение, тип которого реализует пока нестабильный трейт Pattern. В настоящий момент его реализуют
2) Если функция принимает на вход
Вызвать `next`?
Нет.
Также вызвать `next_back`?
Нет.
Это всё неполные ответы. Если мы получаем мутабельную ссылку на
Покажу на примере.
Вот первый способ вытащить строку из
Второй способ (побыстрее и не требующий аллокаций):
Пара советов по строкам в Rust:
1) Если вам нужно разбить строку по одному из нескольких возможных символов — не спешите расчехлять регулярки, для это задачи вполне хватит стандартной библиотеки. Множество строковых методов навроде {, r}split{, _terminator}, trim{, _start, _end}_matches, find и прочие принимают в качестве аргумента для поиска значение, тип которого реализует пока нестабильный трейт Pattern. В настоящий момент его реализуют
&str, &&str, &String, impl FnMut(char) -> bool и (почему-то малоизвестный) &[char]. Таким образом, разбить строку по нескольким символам легко:let result = "Hello, world!".split(&['o', 'l'][..]).collect::<Vec<_>>();
assert_eq!(result, vec!["He", "", "", ", w", "r", "d!"]);
2) Если функция принимает на вход
&mut std::str::Chars, что она может с ним сделать?Вызвать `next`?
Нет.
Также вызвать `next_back`?
Нет.
Это всё неполные ответы. Если мы получаем мутабельную ссылку на
Chars, мы можем редактировать произвольным образом, в том числе и поменять его целиком. Chars внутри себя содержит строки, символы которой он перебирает, и при помощи метода Chars::as_str эту строку можно достать. Таким образом, имея мутабельную ссылку на Chars, можно вытащить из него строку, вырезать из строки нужный кусок и переписать переданный итератор .chars() от этого кусочка.Покажу на примере.
Вот первый способ вытащить строку из
Chars (медленный, требующий аллокаций и не совсем корректный):fn extract_line2(chars: &mut Chars) -> String {
chars.take_while(|&ch| !matches!(ch, '\r' | '\n')).collect()
}Второй способ (побыстрее и не требующий аллокаций):
fn extract_line<'s>(chars: &mut Chars<'s>) -> Option<&'s str> {
let s = chars.as_str();
let line = s.lines().next()?;
*chars = s[line.len()..].chars();
Some(line)
}doc.rust-lang.org
Pattern in std::str::pattern - Rust
A string pattern.
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)
DEV Community
How to debug rust applications with VIM
This is a simple guide to configure the loved (and hated) VIM editor to develop and debug rust applications.
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 #rust #c #video
Unsafe Rust is not C
Или об отличиях в правилах, нарушение которых приводит в C и в Rust к UB, к чему UB может привести на практике и как эти правила выливаются в ограничения и возможности для оптимизации.
Unsafe Rust is not C
Или об отличиях в правилах, нарушение которых приводит в C и в Rust к UB, к чему UB может привести на практике и как эти правила выливаются в ограничения и возможности для оптимизации.
YouTube
Unsafe Rust is not C
Unsafe Rust is like C in some ways, but there are tricky rules that unsafe Rust has to follow that don't exist in C. C also has some tricky rules of its own. This is a talk about some of these differences, particularly when it comes to pointer aliasing. I've…
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…