]> git.lizzy.rs Git - rust.git/blob - src/librustrt/util.rs
c08652cc08c792feb14864b46660875ec289adc7
[rust.git] / src / librustrt / util.rs
1 // Copyright 2013 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 use core::prelude::*;
12
13 use core::cmp;
14 use core::fmt;
15 use core::intrinsics;
16 use core::slice;
17 use core::str;
18 use libc;
19
20 // Indicates whether we should perform expensive sanity checks, including rtassert!
21 //
22 // FIXME: Once the runtime matures remove the `true` below to turn off rtassert,
23 //        etc.
24 pub static ENFORCE_SANITY: bool = true || !cfg!(rtopt) || cfg!(rtdebug) ||
25                                   cfg!(rtassert);
26
27 pub struct Stdio(libc::c_int);
28
29 pub static Stdout: Stdio = Stdio(libc::STDOUT_FILENO);
30 pub static Stderr: Stdio = Stdio(libc::STDERR_FILENO);
31
32 impl fmt::FormatWriter for Stdio {
33     fn write(&mut self, data: &[u8]) -> fmt::Result {
34         #[cfg(unix)]
35         type WriteLen = libc::size_t;
36         #[cfg(windows)]
37         type WriteLen = libc::c_uint;
38         unsafe {
39             let Stdio(fd) = *self;
40             libc::write(fd,
41                         data.as_ptr() as *libc::c_void,
42                         data.len() as WriteLen);
43         }
44         Ok(()) // yes, we're lying
45     }
46 }
47
48 pub fn dumb_print(args: &fmt::Arguments) {
49     use core::fmt::FormatWriter;
50     let mut w = Stderr;
51     let _ = w.write_fmt(args);
52 }
53
54 pub fn abort(args: &fmt::Arguments) -> ! {
55     use core::fmt::FormatWriter;
56
57     struct BufWriter<'a> {
58         buf: &'a mut [u8],
59         pos: uint,
60     }
61     impl<'a> FormatWriter for BufWriter<'a> {
62         fn write(&mut self, bytes: &[u8]) -> fmt::Result {
63             let left = self.buf.mut_slice_from(self.pos);
64             let to_write = bytes.slice_to(cmp::min(bytes.len(), left.len()));
65             slice::bytes::copy_memory(left, to_write);
66             self.pos += to_write.len();
67             Ok(())
68         }
69     }
70
71     // Convert the arguments into a stack-allocated string
72     let mut msg = [0u8, ..512];
73     let mut w = BufWriter { buf: msg, pos: 0 };
74     let _ = write!(&mut w, "{}", args);
75     let msg = str::from_utf8(w.buf.slice_to(w.pos)).unwrap_or("aborted");
76     let msg = if msg.is_empty() {"aborted"} else {msg};
77
78     // Give some context to the message
79     let hash = msg.bytes().fold(0, |accum, val| accum + (val as uint) );
80     let quote = match hash % 10 {
81         0 => "
82 It was from the artists and poets that the pertinent answers came, and I
83 know that panic would have broken loose had they been able to compare notes.
84 As it was, lacking their original letters, I half suspected the compiler of
85 having asked leading questions, or of having edited the correspondence in
86 corroboration of what he had latently resolved to see.",
87         1 => "
88 There are not many persons who know what wonders are opened to them in the
89 stories and visions of their youth; for when as children we listen and dream,
90 we think but half-formed thoughts, and when as men we try to remember, we are
91 dulled and prosaic with the poison of life. But some of us awake in the night
92 with strange phantasms of enchanted hills and gardens, of fountains that sing
93 in the sun, of golden cliffs overhanging murmuring seas, of plains that stretch
94 down to sleeping cities of bronze and stone, and of shadowy companies of heroes
95 that ride caparisoned white horses along the edges of thick forests; and then
96 we know that we have looked back through the ivory gates into that world of
97 wonder which was ours before we were wise and unhappy.",
98         2 => "
99 Instead of the poems I had hoped for, there came only a shuddering blackness
100 and ineffable loneliness; and I saw at last a fearful truth which no one had
101 ever dared to breathe before — the unwhisperable secret of secrets — The fact
102 that this city of stone and stridor is not a sentient perpetuation of Old New
103 York as London is of Old London and Paris of Old Paris, but that it is in fact
104 quite dead, its sprawling body imperfectly embalmed and infested with queer
105 animate things which have nothing to do with it as it was in life.",
106         3 => "
107 The ocean ate the last of the land and poured into the smoking gulf, thereby
108 giving up all it had ever conquered. From the new-flooded lands it flowed
109 again, uncovering death and decay; and from its ancient and immemorial bed it
110 trickled loathsomely, uncovering nighted secrets of the years when Time was
111 young and the gods unborn. Above the waves rose weedy remembered spires. The
112 moon laid pale lilies of light on dead London, and Paris stood up from its damp
113 grave to be sanctified with star-dust. Then rose spires and monoliths that were
114 weedy but not remembered; terrible spires and monoliths of lands that men never
115 knew were lands...",
116         4 => "
117 There was a night when winds from unknown spaces whirled us irresistibly into
118 limitless vacuum beyond all thought and entity. Perceptions of the most
119 maddeningly untransmissible sort thronged upon us; perceptions of infinity
120 which at the time convulsed us with joy, yet which are now partly lost to my
121 memory and partly incapable of presentation to others.",
122         _ => "You've met with a terrible fate, haven't you?"
123     };
124     rterrln!("{}", "");
125     rterrln!("{}", quote);
126     rterrln!("{}", "");
127     rterrln!("fatal runtime error: {}", msg);
128     unsafe { intrinsics::abort(); }
129 }