]> git.proxmox.com Git - rustc.git/blob - vendor/derivative/tests/rustc-deriving-hash.rs
New upstream version 1.75.0+dfsg1
[rustc.git] / vendor / derivative / tests / rustc-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 #![allow(non_camel_case_types)]
12
13 #[cfg(feature = "use_core")]
14 extern crate core;
15
16 #[macro_use]
17 extern crate derivative;
18
19 use std::hash::{Hash, Hasher};
20 use std::collections::hash_map::DefaultHasher;
21
22 #[derive(Derivative)]
23 #[derivative(Hash)]
24 struct Person {
25 id: u16,
26 name: String,
27 phone: u64,
28 }
29
30 // test for hygiene name collisions
31 #[derive(Derivative)]
32 #[derivative(Hash)] struct __H__H;
33 #[derive(Derivative)]
34 #[allow(dead_code)] #[derivative(Hash)] struct Collision<__H> ( __H );
35 // TODO(rustc) #[derivative(Hash)] enum Collision<__H> { __H { __H__H: __H } }
36
37 #[derive(Derivative)]
38 #[derivative(Hash)]
39 enum E { A=1, B }
40
41 fn hash<T: Hash>(t: &T) -> u64 {
42 let mut s = DefaultHasher::new();
43 t.hash(&mut s);
44 s.finish()
45 }
46
47 struct FakeHasher<'a>(&'a mut Vec<u8>);
48 impl<'a> Hasher for FakeHasher<'a> {
49 fn finish(&self) -> u64 {
50 unimplemented!()
51 }
52
53 fn write(&mut self, bytes: &[u8]) {
54 self.0.extend(bytes);
55 }
56 }
57
58 fn fake_hash(v: &mut Vec<u8>, e: E) {
59 e.hash(&mut FakeHasher(v));
60 }
61
62 #[test]
63 fn main() {
64 let person1 = Person {
65 id: 5,
66 name: "Janet".to_string(),
67 phone: 555_666_777,
68 };
69 let person2 = Person {
70 id: 5,
71 name: "Bob".to_string(),
72 phone: 555_666_777,
73 };
74 assert_eq!(hash(&person1), hash(&person1));
75 assert!(hash(&person1) != hash(&person2));
76
77 // test #21714
78 let mut va = vec![];
79 let mut vb = vec![];
80 fake_hash(&mut va, E::A);
81 fake_hash(&mut vb, E::B);
82 assert!(va != vb);
83 }