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.
15 enum cat_type { tuxedo, tabby, tortoiseshell }
17 impl cmp::Eq for cat_type {
18 fn eq(&self, other: &cat_type) -> bool {
19 ((*self) as uint) == ((*other) as uint)
21 fn ne(&self, other: &cat_type) -> bool { !(*self).eq(other) }
24 // Very silly -- this just returns the value of the name field
25 // for any int value that's less than the meows field
27 // ok: T should be in scope when resolving the trait ref for map
29 // Yes, you can have negative meows
37 pub fn speak(&mut self) { self.meow(); }
39 pub fn eat(&mut self) -> bool {
40 if self.how_hungry > 0 {
45 error!("Not hungry!");
51 impl<T> Container for cat<T> {
52 fn len(&self) -> uint { self.meows as uint }
53 fn is_empty(&self) -> bool { self.meows == 0 }
56 impl<T> Mutable for cat<T> {
57 fn clear(&mut self) {}
60 impl<T> Map<int, T> for cat<T> {
61 fn contains_key(&self, k: &int) -> bool { *k <= self.meows }
63 fn find<'a>(&'a self, k: &int) -> Option<&'a T> {
72 impl<T> MutableMap<int, T> for cat<T> {
73 fn insert(&mut self, k: int, _: T) -> bool {
78 fn find_mut<'a>(&'a mut self, _k: &int) -> Option<&'a mut T> { fail!() }
80 fn remove(&mut self, k: &int) -> bool {
81 if self.find(k).is_some() {
82 self.meows -= *k; true
88 fn pop(&mut self, _k: &int) -> Option<T> { fail!() }
90 fn swap(&mut self, _k: int, _v: T) -> Option<T> { fail!() }
94 pub fn get<'a>(&'a self, k: &int) -> &'a T {
97 None => { fail!("epic fail"); }
101 pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> {
102 cat{meows: in_x, how_hungry: in_y, name: in_name }
109 error!("Meow %d", self.meows);
110 if self.meows % 5 == 0 {
111 self.how_hungry += 1;
117 let mut nyan: cat<~str> = cat::new(0, 2, ~"nyan");
118 for _ in range(1u, 5) { nyan.speak(); }
119 assert!(*nyan.find(&1).unwrap() == ~"nyan");
120 assert_eq!(nyan.find(&10), None);
121 let mut spotty: cat<cat_type> = cat::new(2, 57, tuxedo);
122 for _ in range(0u, 6) { spotty.speak(); }
123 assert_eq!(spotty.len(), 8);
124 assert!((spotty.contains_key(&2)));
125 assert_eq!(spotty.get(&3), &tuxedo);