[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[PROPOSAL] with_cur_ios() function in the stdlib
From: |
apache2 |
Subject: |
[PROPOSAL] with_cur_ios() function in the stdlib |
Date: |
Sat, 9 Apr 2022 19:55:16 +0200 |
User-agent: |
Mutt/1.9.3 (2018-01-21) |
Hi list,
As per discussion with Mohammad-Reza and Jose, here is a function
proposed for inclusion in the stdlib:
//
// with_cur_ios(fn, cb) calls cb with fn opened as the current ios.
// if an exception is raised, fn will be closed before the exception
// is re-raised, allowing the enclosed code to fail without global
// side effects.
//
type void_lambda = ()void;
fun with_cur_ios = (string filename, void_lambda callback)void:
{
var old_ios = get_ios ?! E_no_ios ? get_ios : -1;
var new_ios = open(fn);
set_ios(new_ios);
try {
callback();
close(new_ios);
if (-1 != old_ios) set_ios(old_ios);
} catch (Exception exc) {
close(new_ios);
if (-1 != old_ios) set_ios(old_ios);
raise exc;
}
}
As an example of where this would be useful, consider:
fun cast_to_bytes = (uint32[] tmp)byte[]
{
var ret = byte[]();
with_cur_ios("*data*", lambda void:{
// if anything goes wrong here, we do not leak the *data* fd:
var tmp2 = uint32[tmp'length] @ 0#b;
for (var i = 0; i < tmp'length; i++) {
tmp2[i] = tmp[i];
}
for(var i = 0; i < 4*4; i++){
ret += byte[1] @ i#B;
}
});
}
- [PROPOSAL] with_cur_ios() function in the stdlib,
apache2 <=
- Re: [PROPOSAL] with_cur_ios() function in the stdlib, Jose E. Marchesi, 2022/04/10
- Re: [PROPOSAL] with_cur_ios() function in the stdlib, Mohammad-Reza Nabipoor, 2022/04/10
- Re: [PROPOSAL] with_cur_ios() function in the stdlib, Jose E. Marchesi, 2022/04/10
- Re: [PROPOSAL] with_cur_ios() function in the stdlib, Jose E. Marchesi, 2022/04/10
- Re: [PROPOSAL] with_cur_ios() function in the stdlib, Mohammad-Reza Nabipoor, 2022/04/10
- Re: [PROPOSAL] with_cur_ios() function in the stdlib, Jose E. Marchesi, 2022/04/10