]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass/deriving-hash.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / test / run-pass / deriving-hash.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 #![feature(hash_default)]
13
14 use std::hash::{Hash, SipHasher, Hasher};
15 use std::mem::size_of;
16
17 #[derive(Hash)]
18 struct Person {
19 id: usize,
20 name: String,
21 phone: usize,
22 }
23
24 // test for hygiene name collisions
25 #[derive(Hash)] struct __H__H;
26 #[derive(Hash)] enum Collision<__H> { __H { __H__H: __H } }
27
28 #[derive(Hash)]
29 enum E { A=1, B }
30
31 fn hash<T: Hash>(t: &T) -> u64 {
32 let mut s = SipHasher::new_with_keys(0, 0);
33 t.hash(&mut s);
34 s.finish()
35 }
36
37 struct FakeHasher<'a>(&'a mut Vec<u8>);
38 impl<'a> Hasher for FakeHasher<'a> {
39 fn finish(&self) -> u64 {
40 unimplemented!()
41 }
42
43 fn write(&mut self, bytes: &[u8]) {
44 self.0.extend(bytes);
45 }
46 }
47
48 fn fake_hash(v: &mut Vec<u8>, e: E) {
49 e.hash(&mut FakeHasher(v));
50 }
51
52 fn main() {
53 let person1 = Person {
54 id: 5,
55 name: "Janet".to_string(),
56 phone: 555_666_7777
57 };
58 let person2 = Person {
59 id: 5,
60 name: "Bob".to_string(),
61 phone: 555_666_7777
62 };
63 assert_eq!(hash(&person1), hash(&person1));
64 assert!(hash(&person1) != hash(&person2));
65
66 // test #21714
67 let mut va = vec![];
68 let mut vb = vec![];
69 fake_hash(&mut va, E::A);
70 fake_hash(&mut vb, E::B);
71 assert!(va != vb);
72 }