1
+ <!--
1
2
# Exception Safety
3
+ -->
2
4
5
+ # 例外安全性
6
+
7
+ <!--
3
8
Although programs should use unwinding sparingly, there's a lot of code that
4
9
*can* panic. If you unwrap a None, index out of bounds, or divide by 0, your
5
10
program will panic. On debug builds, every arithmetic operation can panic
6
11
if it overflows. Unless you are very careful and tightly control what code runs,
7
12
pretty much everything can unwind, and you need to be ready for it.
13
+ -->
14
+
15
+ プログラム内では巻き戻しを注意深く使用するべきですが、パニック*し得る*コードが
16
+ たくさんあります。もし None をアンラップしたり、境界外のインデックスを指定したり、
17
+ 0 で除算したりしたら、プログラムはパニックするでしょう。デバッグビルドでは、
18
+ 全ての算術演算は、オーバーフロー時にパニックします。非常に注意深く、
19
+ そしてどのコードを実行するかを厳しくコントロールしない限り、ほとんどすべての
20
+ コードが巻き戻しをする可能性があり、これに対して準備をする必要があります。
8
21
22
+ <!--
9
23
Being ready for unwinding is often referred to as *exception safety*
10
24
in the broader programming world. In Rust, there are two levels of exception
11
25
safety that one may concern themselves with:
26
+ -->
27
+
28
+ 巻き戻しに対して準備が出来ていることは、もっと広いプログラミングの世界において、
29
+ しばしば*例外安全*と呼ばれています。 Rust では、プログラムが関わる可能性のある、
30
+ 2 つの例外安全のレベルがあります。
12
31
32
+ <!--
13
33
* In unsafe code, we *must* be exception safe to the point of not violating
14
34
memory safety. We'll call this *minimal* exception safety.
15
35
16
36
* In safe code, it is *good* to be exception safe to the point of your program
17
37
doing the right thing. We'll call this *maximal* exception safety.
38
+ -->
39
+
40
+ * アンセーフなコードでは、メモリ安全性を侵害しないという点において、
41
+ 例外安全で*なければなりません*。これを、*最小限*の例外安全と呼びます。
42
+
43
+ * 安全なコードでは、プログラムが正しいことを行なうという点において、
44
+ 例外安全であると*良い*です。これを*最大限*の例外安全と呼びます。
18
45
46
+ <!--
19
47
As is the case in many places in Rust, Unsafe code must be ready to deal with
20
48
bad Safe code when it comes to unwinding. Code that transiently creates
21
49
unsound states must be careful that a panic does not cause that state to be
22
50
used. Generally this means ensuring that only non-panicking code is run while
23
51
these states exist, or making a guard that cleans up the state in the case of
24
52
a panic. This does not necessarily mean that the state a panic witnesses is a
25
53
fully coherent state. We need only guarantee that it's a *safe* state.
26
-
54
+ -->
55
+
56
+ Rust の多くの場において事実なのですが、巻き戻しとなると、アンセーフなコードは、
57
+ 悪い安全なコードに対処する準備をしなければなりません。一時的に健全ではない
58
+ 状態を生むコードは、パニックによってその状態が使用されないよう、注意深く
59
+ 扱わなければなりません。通常これは、このような健全でない状態が存在する間、
60
+ パニックを起こさないコードのみを確実に実行させることを意味するか、あるいは
61
+ パニックの際、その状態を片付けるガードを生成することを意味します。
62
+ これは必ずしも、パニックが起きているときの状態が、完全に一貫した状態であるということを
63
+ 意味しません。*安全な*状態であると保証されていることだけが必要なのです。
64
+
65
+ <!--
27
66
Most Unsafe code is leaf-like, and therefore fairly easy to make exception-safe.
28
67
It controls all the code that runs, and most of that code can't panic. However
29
68
it is not uncommon for Unsafe code to work with arrays of temporarily
30
69
uninitialized data while repeatedly invoking caller-provided code. Such code
31
70
needs to be careful and consider exception safety.
71
+ -->
72
+
73
+ ほとんどのアンセーフなコードは葉のようなもの (訳注: それ以上別の関数を呼ぶことが
74
+ ない) で、それ故に割と簡単に例外安全に出来ます。実行するコードは完全に制御されていて、
75
+ そしてほとんどのコードはパニックしません。しかし、アンセーフなコードが
76
+ 繰り返し呼び出し側のコードを実行している間に、部分的に初期化されていない配列を
77
+ 扱うことはよくあります。このようなコードは注意深く扱い、例外安全を考える必要があるのです。
32
78
33
79
34
80
35
81
36
82
37
83
## Vec::push_all
38
84
85
+ <!--
39
86
`Vec::push_all` is a temporary hack to get extending a Vec by a slice reliably
40
87
efficient without specialization. Here's a simple implementation:
88
+ -->
89
+
90
+ `Vec::push_all` は、特殊化なしに、スライスが確実に効率的であることを利用した、
91
+ Vec を伸ばす一時的なハックです。これは単純な実装です。
41
92
42
93
```rust,ignore
43
94
impl<T: Clone> Vec<T> {
44
95
fn push_all(&mut self, to_push: &[T]) {
45
96
self.reserve(to_push.len());
46
97
unsafe {
47
- // can't overflow because we just reserved this
98
+ // 今さっき reserve をしたので、オーバーフローするはずがありません
48
99
self.set_len(self.len() + to_push.len());
49
100
50
101
for (i, x) in to_push.iter().enumerate() {
@@ -55,28 +106,52 @@ impl<T: Clone> Vec<T> {
55
106
}
56
107
```
57
108
109
+ <!--
58
110
We bypass `push` in order to avoid redundant capacity and `len` checks on the
59
111
Vec that we definitely know has capacity. The logic is totally correct, except
60
112
there's a subtle problem with our code: it's not exception-safe! `set_len`,
61
113
`offset`, and `write` are all fine; `clone` is the panic bomb we over-looked.
114
+ -->
62
115
116
+ 絶対にキャパシティがあると分かっている Vec の capacity と `len` の余分なチェックを
117
+ 回避するため、 `push` を使用していません。論理は完全に正しいです。但し、
118
+ このコードに微妙な問題が含まれていることを除く。すなわち、このコードは例外安全
119
+ ではないのです! `set_len` と `offset` と `write` は全部問題ありません。 `clone` は、
120
+ 我々が見落としていたパニックの起爆装置です。
121
+
122
+ <!--
63
123
Clone is completely out of our control, and is totally free to panic. If it
64
124
does, our function will exit early with the length of the Vec set too large. If
65
125
the Vec is looked at or dropped, uninitialized memory will be read!
126
+ -->
127
+
128
+ Clone は全く制御不能で、全く自由にパニックしてしまいます。もしパニックしてしまえば、
129
+ この関数は、 Vec の長さが大きすぎる値に設定されたまま、早期に終了してしまいます。
130
+ もし Vec が読み出されたりドロップされたりすると、未初期化のメモリが読み出されて
131
+ しまいます!
66
132
133
+ <!--
67
134
The fix in this case is fairly simple. If we want to guarantee that the values
68
135
we *did* clone are dropped, we can set the `len` every loop iteration. If we
69
136
just want to guarantee that uninitialized memory can't be observed, we can set
70
137
the `len` after the loop.
138
+ -->
71
139
72
-
140
+ この場合、修正は割と簡単です。もし*本当に*、クローンした値がドロップされたと
141
+ いうことを保証したいのなら、全てのループのイテレーションにおいて、 `len` を
142
+ 設定することが出来ます。もし単に、未初期化のメモリが読まれないようにしたいのなら、
143
+ ループの後に `len` を設定することが出来ます。
73
144
74
145
75
146
76
147
## BinaryHeap::sift_up
77
148
149
+ <!--
78
150
Bubbling an element up a heap is a bit more complicated than extending a Vec.
79
151
The pseudocode is as follows:
152
+ -->
153
+
154
+ ヒープにおけるアップヒープは Vec を伸ばすことよりちょっと複雑です。擬似コードはこんな感じです。
80
155
81
156
```text
82
157
bubble_up(heap, index):
@@ -86,28 +161,48 @@ bubble_up(heap, index):
86
161
87
162
```
88
163
164
+ <!--
89
165
A literal transcription of this code to Rust is totally fine, but has an annoying
90
166
performance characteristic: the `self` element is swapped over and over again
91
167
uselessly. We would rather have the following:
168
+ -->
169
+
170
+ このコードを Rust に直訳するのは全く問題ありません。ですが、嫌になるようなパフォーマンス
171
+ です。すなわち、 `self` の要素が無駄に交換され続けます。それならむしろ、以下のコードの方が
172
+ 良いでしょう。
92
173
93
174
```text
94
175
bubble_up(heap, index):
95
176
let elem = heap[index]
96
- while index != 0 && element < heap[parent(index)]:
177
+ while index != 0 && elem < heap[parent(index)]:
97
178
heap[index] = heap[parent(index)]
98
179
index = parent(index)
99
180
heap[index] = elem
100
181
```
101
182
183
+ <!--
102
184
This code ensures that each element is copied as little as possible (it is in
103
185
fact necessary that elem be copied twice in general). However it now exposes
104
186
some exception safety trouble! At all times, there exists two copies of one
105
187
value. If we panic in this function something will be double-dropped.
106
188
Unfortunately, we also don't have full control of the code: that comparison is
107
189
user-defined!
190
+ -->
108
191
192
+ このコードでは確実に、それぞれの要素ができるだけ少ない回数でコピーされます
193
+ (実は一般的に、要素を 2 回コピーすることが必要なのです) 。しかし、これによって、
194
+ いくつか例外安全性の問題が露見しました! 毎回、ある値に対する 2 つのコピーが
195
+ 存在します。もしこの関数内でパニックしたら、何かが 2 回ドロップされてしまいます。
196
+ 残念ながら、このコードに関しても、完全にコントロールすることは出来ません。
197
+ 比較がユーザ定義されているのです!
198
+
199
+ <!--
109
200
Unlike Vec, the fix isn't as easy here. One option is to break the user-defined
110
201
code and the unsafe code into two separate phases:
202
+ -->
203
+
204
+ Vec とは違い、これを直すのは簡単ではありません。一つの選択肢として、ユーザ定義の
205
+ コードとアンセーフなコードを、 2 つの段階に分割することです。
111
206
112
207
```text
113
208
bubble_up(heap, index):
@@ -122,16 +217,34 @@ bubble_up(heap, index):
122
217
heap[index] = elem
123
218
```
124
219
220
+ <!--
125
221
If the user-defined code blows up, that's no problem anymore, because we haven't
126
222
actually touched the state of the heap yet. Once we do start messing with the
127
223
heap, we're working with only data and functions that we trust, so there's no
128
224
concern of panics.
225
+ -->
129
226
227
+ もしユーザ定義のコードでトラブっても、もう問題ありません。なぜなら、
228
+ ヒープの状態にはまだ触れていないからです。ヒープを実際に弄るとき、
229
+ 信用しているデータや関数のみを扱っています。ですからもうパニックの心配は
230
+ ありません。
231
+
232
+ <!--
130
233
Perhaps you're not happy with this design. Surely it's cheating! And we have
131
234
to do the complex heap traversal *twice*! Alright, let's bite the bullet. Let's
132
235
intermix untrusted and unsafe code *for reals*.
236
+ -->
237
+
238
+ 多分、この設計を嬉しく思わないでしょう。明らかに騙している! そして複雑な
239
+ ヒープのトラバーサルを *2 回* 行わなければならない! 分かった、我慢しよう。
240
+ 信用していないコードやアンセーフなコードを*本気で*混ぜてみよう。
133
241
242
+ <!--
134
243
If Rust had `try` and `finally` like in Java, we could do the following:
244
+ -->
245
+
246
+ もし Rust に Java のような `try` と `finally` があったら、コードは
247
+ こんな感じだったでしょう。
135
248
136
249
```text
137
250
bubble_up(heap, index):
@@ -144,21 +257,36 @@ bubble_up(heap, index):
144
257
heap[index] = elem
145
258
```
146
259
260
+ <!--
147
261
The basic idea is simple: if the comparison panics, we just toss the loose
148
262
element in the logically uninitialized index and bail out. Anyone who observes
149
263
the heap will see a potentially *inconsistent* heap, but at least it won't
150
264
cause any double-drops! If the algorithm terminates normally, then this
151
265
operation happens to coincide precisely with the how we finish up regardless.
266
+ -->
152
267
268
+ 基本的な考えは単純です。すなわち、もし比較においてパニックしたのなら、単に要素を
269
+ 論理的に未初期化のインデックスの位置に保存し、脱出します。このヒープを観察する誰もが、
270
+ 潜在的には*一貫性のない*ヒープを目にするでしょうが、少なくともこのコードは二重ドロップを
271
+ 起こしません! もしアルゴリズムが通常通り終了すれば、この操作はコードがどのように終了するかに
272
+ 関わらず、結果を正確に一致させるために実行されます。
273
+
274
+ <!--
153
275
Sadly, Rust has no such construct, so we're going to need to roll our own! The
154
276
way to do this is to store the algorithm's state in a separate struct with a
155
277
destructor for the "finally" logic. Whether we panic or not, that destructor
156
278
will run and clean up after us.
279
+ -->
280
+
281
+ 悲しいことに、 Rust にはそのような構造が存在しません。ですので、自分たちで退避させなければ
282
+ ならないようです! これを行なうには、 "finally" の論理を構成するため、デストラクタと共に
283
+ アルゴリズムの状態を、別の構造体に保存します。パニックしようがしまいが、デストラクタは
284
+ 実行され、状態を綺麗にします。
157
285
158
286
```rust,ignore
159
287
struct Hole<'a, T: 'a> {
160
288
data: &'a mut [T],
161
- /// `elt` is always `Some` from new until drop.
289
+ /// `elt` は new で生成されたときからドロップまで、常に Some です
162
290
elt: Option<T>,
163
291
pos: usize,
164
292
}
@@ -191,7 +319,7 @@ impl<'a, T> Hole<'a, T> {
191
319
192
320
impl<'a, T> Drop for Hole<'a, T> {
193
321
fn drop(&mut self) {
194
- // fill the hole again
322
+ // 穴を再び埋めます
195
323
unsafe {
196
324
let pos = self.pos;
197
325
ptr::write(&mut self.data[pos], self.elt.take().unwrap());
@@ -202,15 +330,15 @@ impl<'a, T> Drop for Hole<'a, T> {
202
330
impl<T: Ord> BinaryHeap<T> {
203
331
fn sift_up(&mut self, pos: usize) {
204
332
unsafe {
205
- // Take out the value at `pos` and create a hole.
333
+ // `pos` にある値を受け取り、穴を作ります。
206
334
let mut hole = Hole::new(&mut self.data, pos);
207
335
208
336
while hole.pos() != 0 {
209
337
let parent = parent(hole.pos());
210
338
if hole.removed() <= hole.get(parent) { break }
211
339
hole.move_to(parent);
212
340
}
213
- // Hole will be unconditionally filled here; panic or not !
341
+ // 状況に関わらず、穴はここで埋まります。パニックしてもしなくても !
214
342
}
215
343
}
216
344
}
0 commit comments