Skip to content

Commit 1fdb759

Browse files
committed
Make EnumSet not silently corrupt data.
Assert at run time instead. Fixes rust-lang#13756. I’d rather have this be detected at compile-time, but I don’t know how to do that.
1 parent 45cbdec commit 1fdb759

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

src/libcollections/enum_set.rs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ pub trait CLike {
5252
}
5353

5454
fn bit<E:CLike>(e: &E) -> uint {
55-
1 << e.to_uint()
55+
let value = e.to_uint();
56+
assert!(value < ::core::uint::BITS);
57+
1 << value
5658
}
5759

5860
impl<E:CLike> EnumSet<E> {
@@ -378,4 +380,31 @@ mod test {
378380
let elems = e_subtract.iter().collect();
379381
assert_eq!(vec![A], elems)
380382
}
383+
384+
#[test]
385+
#[should_fail]
386+
fn test_overflow() {
387+
#[allow(dead_code)]
388+
#[repr(uint)]
389+
enum Bar {
390+
V00, V01, V02, V03, V04, V05, V06, V07, V08, V09,
391+
V10, V11, V12, V13, V14, V15, V16, V17, V18, V19,
392+
V20, V21, V22, V23, V24, V25, V26, V27, V28, V29,
393+
V30, V31, V32, V33, V34, V35, V36, V37, V38, V39,
394+
V40, V41, V42, V43, V44, V45, V46, V47, V48, V49,
395+
V50, V51, V52, V53, V54, V55, V56, V57, V58, V59,
396+
V60, V61, V62, V63, V64, V65, V66, V67, V68, V69,
397+
}
398+
impl CLike for Bar {
399+
fn to_uint(&self) -> uint {
400+
*self as uint
401+
}
402+
403+
fn from_uint(v: uint) -> Bar {
404+
unsafe { mem::transmute(v) }
405+
}
406+
}
407+
let mut set = EnumSet::empty();
408+
set.add(V64);
409+
}
381410
}

0 commit comments

Comments
 (0)