Programming News and Articles
8 subscribers
5 photos
3 files
241 links
Download Telegram
Forwarded from Блог*
#prog #article

Заметка о неожиданном взаимодействии fork и kill.
Forwarded from Блог*
#prog #rust

Пара советов по строкам в 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)
}
Forwarded from Блог*
#prog #python #article

Статья (в двух частях: первая, вторая), которая наглядно показывает слабость тайпчекера Mypy и проблемы с производительностью строк в Python. А, и ещё это статья о конструировании парсер-комбинаторов на Python, но это уже вторично.
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.
Forwarded from Так говорит Алиса (John Meow)
Начало цикла статей по процедурным макросам в Rust

#prog #rust #proc_macro #article
Forwarded from Блог*
#prog #rust #моё #article

Здрасьте. Сегодня поста не будет — но только потому, что я решил написать статью для Хабра. Собственно, вот она.

И напоминаю: если вам это понравилось — поддержите копеечкой автора, я вам благодарен буду: 4274 3200 5402 8520.
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."
Forwarded from Блог*
#prog #rust #article

Rust's Unsafe Pointer Types Need An Overhaul

Или что не так с сырыми указателями в Rust и что с этим стоило бы сделать
Forwarded from Блог*
#prog #rust #c #video

Unsafe Rust is not C

Или об отличиях в правилах, нарушение которых приводит в C и в Rust к UB, к чему UB может привести на практике и как эти правила выливаются в ограничения и возможности для оптимизации.
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.