1 // Copyright 2012 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.
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.
17 enum cat_type { tuxedo, tabby, tortoiseshell }
19 impl cmp::Eq for cat_type {
20 fn eq(&self, other: &cat_type) -> bool {
21 ((*self) as uint) == ((*other) as uint)
23 fn ne(&self, other: &cat_type) -> bool { !(*self).eq(other) }
26 // Very silly -- this just returns the value of the name field
27 // for any int value that's less than the meows field
29 // ok: T should be in scope when resolving the trait ref for map
31 // Yes, you can have negative meows
39 pub fn speak(&mut self) { self.meow(); }
41 pub fn eat(&mut self) -> bool {
42 if self.how_hungry > 0 {
47 error!("Not hungry!");
53 impl<T> Container for cat<T> {
54 fn len(&const self) -> uint { self.meows as uint }
55 fn is_empty(&const self) -> bool { self.meows == 0 }
58 impl<T> Mutable for cat<T> {
59 fn clear(&mut self) {}
62 impl<T> Map<int, T> for cat<T> {
63 fn contains_key(&self, k: &int) -> bool { *k <= self.meows }
65 fn find<'a>(&'a self, k: &int) -> Option<&'a T> {
74 impl<T> MutableMap<int, T> for cat<T> {
75 fn insert(&mut self, k: int, _: T) -> bool {
80 fn find_mut<'a>(&'a mut self, _k: &int) -> Option<&'a mut T> { fail!() }
82 fn remove(&mut self, k: &int) -> bool {
83 if self.find(k).is_some() {
84 self.meows -= *k; true
90 fn pop(&mut self, _k: &int) -> Option<T> { fail!() }
92 fn swap(&mut self, _k: int, _v: T) -> Option<T> { fail!() }
96 pub fn get<'a>(&'a self, k: &int) -> &'a T {
99 None => { fail!("epic fail"); }
103 pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> {
104 cat{meows: in_x, how_hungry: in_y, name: in_name }
111 error!("Meow %d", self.meows);
112 if self.meows % 5 == 0 {
113 self.how_hungry += 1;
119 let mut nyan: cat<~str> = cat::new(0, 2, ~"nyan");
120 for _ in range(1u, 5) { nyan.speak(); }
121 assert!(*nyan.find(&1).unwrap() == ~"nyan");
122 assert_eq!(nyan.find(&10), None);
123 let mut spotty: cat<cat_type> = cat::new(2, 57, tuxedo);
124 for _ in range(0u, 6) { spotty.speak(); }
125 assert_eq!(spotty.len(), 8);
126 assert!((spotty.contains_key(&2)));
127 assert_eq!(spotty.get(&3), &tuxedo);