Debian Codegraph @

src/fmtstr.rs

raw symbols SCIP
1 use std::fmt::Write;
2 use std::string::String;
3
4 use formatter::Formatter;
5 use types::*;
6
7 fn write_char(f: &mut Formatter, c: char, n: usize) {
8 for _ in 0..n {
9 f.write_char(c).unwrap();
10 }
11 }
12
13 #[test]
14 fn test_write_char() {
15 let mut s = String::new();
16 s.write_str("h ").unwrap();
17 {
18 let mut f = Formatter::from_str("{}", &mut s).unwrap();
19 write_char(&mut f, 'f', 3);
20 }
21 assert!(s == "h fff");
22 }
23
24 fn write_from<I>(fmt: &mut Formatter, f: I, n: usize) -> usize
25 where
26 I: Iterator<Item = char>,
27 {
28 // eexaust f or run out of n, return chars written
29 if n == 0 {
30 return 0;
31 }
32 let mut n_written: usize = 0;
33 for c in f {
34 fmt.write_char(c).unwrap();
35 n_written += 1;
36 if n_written == n {
37 return n_written;
38 }
39 }
40 n_written
41 }
42
43 #[test]
44 fn test_write_from() {
45 let mut s = String::new();
46 s.write_str("h ").unwrap();
47 {
48 let mut f = Formatter::from_str("{}", &mut s).unwrap();
49 write_from(&mut f, "fff".chars(), 5);
50 }
51 assert!(s == "h fff");
52 {
53 let mut f = Formatter::from_str("{}", &mut s).unwrap();
54 write_from(&mut f, "xxxx".chars(), 2);
55 }
56 assert!(s == "h fffxx");
57 {
58 let mut f = Formatter::from_str("{}", &mut s).unwrap();
59 write_from(&mut f, "333".chars(), 3);
60 }
61 assert!(s == "h fffxx333");
62 s.clear();
63 {
64 let mut f = Formatter::from_str("{}", &mut s).unwrap();
65 write!(f, "hello").unwrap();
66 }
67 assert!(s == "hello");
68 }
69
70 /// implement formatting of strings
71 impl<'a, 'b> Formatter<'a, 'b> {
72 /// format the given string onto the buffer
73 pub fn str(&mut self, s: &str) -> Result<()> {
74 self.set_default_align(Alignment::Left);
75 if !(self.ty() == None || self.ty() == Some('s')) {
76 let mut msg = String::new();
77 write!(
78 msg,
79 "Unknown format code {:?} for object of type 'str'",
80 self.ty()
81 )
82 .unwrap();
83 return Err(FmtError::TypeError(msg));
84 } else if self.alternate() {
85 return Err(FmtError::TypeError(
86 "Alternate form (#) not allowed in string \
87 format specifier"
88 .to_string(),
89 ));
90 } else if self.thousands() {
91 return Err(FmtError::TypeError(
92 "Cannot specify ',' with 's'".to_string(),
93 ));
94 } else if self.sign().is_unspecified() {
95 return Err(FmtError::TypeError(
96 "Sign not allowed in string format specifier".to_string(),
97 ));
98 }
99 self.str_unchecked(s)
100 }
101
102 /// UNSTABLE+UNTESTED: do not use in your own code (yet)
103 /// Do the same as `str` but do not check the format string for errors.
104 /// This gives a moderate performance boost.
105 /// This isn't exactly unsafe, it just ends up ignoring extranious format
106 /// specifiers
107 /// For example, {x:<-#10} should technically be formatting an int, but ignoring the
108 /// integer specific formatting is probably not the end of the world
109 /// This can also be used by the `u64` etc methods to finish their formatting while
110 /// still using the str formatter for width and alignment
111 pub fn str_unchecked(&mut self, s: &str) -> Result<()> {
112 let fill = self.fill();
113 let width = self.width();
114 let precision = self.precision();
115 let chars_count = s.chars().count();
116 // precision will limit length
117 let len = match precision {
118 Some(p) => {
119 if p < chars_count {
120 p
121 } else {
122 chars_count
123 }
124 }
125 None => chars_count,
126 };
127
128 let mut chars = s.chars();
129 let mut pad: usize = 0;
130 if let Some(mut width) = width {
131 if width > len {
132 let align = self.align();
133 match align {
134 Alignment::Left => pad = width - len,
135 Alignment::Center => {
136 width -= len;
137 pad = width / 2;
138 write_char(self, fill, pad);
139 pad += width % 2;
140 }
141 Alignment::Right => {
142 write_char(self, fill, width - len);
143 }
144 Alignment::Equal => {
145 return Err(FmtError::Invalid(
146 "sign aware zero padding and Align '=' not yet supported".to_string(),
147 ))
148 }
149 Alignment::Unspecified => unreachable!(),
150 }
151 }
152 }
153 write_from(self, &mut chars, len);
154 write_char(self, fill, pad);
155 Ok(())
156 }
157 }
158
159 /// UNSTABLE: the Formatter object is still considered unstable
160 /// Do not use this function if you aren't willing to have changes
161 /// forced on you!
162 ///
163 /// format a string given the string and a closure that uses
164 /// a Formatter
165 pub fn strfmt_map<F>(fmtstr: &str, f: F) -> Result<String>
166 where
167 F: FnMut(Formatter) -> Result<()>,
168 {
169 let mut f = f;
170 let mut out = String::with_capacity(fmtstr.len() * 2);
171 let mut bytes_read: usize = 0;
172 let mut opening_brace: usize = 0;
173 let mut closing_brace: bool = false;
174 let mut reading_fmt = false;
175 let mut remaining = fmtstr;
176 for c in fmtstr.chars() {
177 bytes_read += c.len_utf8();
178 if c == '{' {
179 if reading_fmt && opening_brace == bytes_read - 2 {
180 // found {{
181 out.push(c);
182 reading_fmt = false;
183 } else if !reading_fmt {
184 // found a first {
185 reading_fmt = true;
186 opening_brace = bytes_read - 1;
187 } else {
188 // found a { after finding an opening brace, error!
189 out.clear();
190 out.write_str("extra { found").unwrap();
191 return Err(FmtError::Invalid(out));
192 }
193 } else if c == '}' {
194 if !reading_fmt && !closing_brace {
195 // found a '}' that isn't after a '{'
196 closing_brace = true;
197 } else if closing_brace {
198 // found "}}"
199 out.push(c);
200 closing_brace = false;
201 } else {
202 // found a format string
203 // discard before opening brace
204 let (_, r) = remaining.split_at(opening_brace);
205
206 // get the fmt pattern and remaining
207 let (fmt_pattern, r) = r.split_at(bytes_read - opening_brace);
208 remaining = r;
209
210 // discard the braces
211 let (_, fmt_pattern) = fmt_pattern.split_at(1);
212 let (fmt_pattern, _) = fmt_pattern.split_at(fmt_pattern.len() - 1);
213 // use the closure to write the formatted string
214 let fmt = Formatter::from_str(fmt_pattern, &mut out)?;
215 f(fmt)?;
216 reading_fmt = false;
217 bytes_read = 0;
218 }
219 } else if closing_brace {
220 return Err(FmtError::Invalid(
221 "Single '}' encountered in format string".to_string(),
222 ));
223 } else if !reading_fmt {
224 out.push(c)
225 } // else we are currently reading a format string, so don't push
226 }
227 if closing_brace {
228 return Err(FmtError::Invalid(
229 "Single '}' encountered in format string".to_string(),
230 ));
231 } else if reading_fmt {
232 return Err(FmtError::Invalid(
233 "Expected '}' before end of string".to_string(),
234 ));
235 }
236 out.shrink_to_fit();
237 Ok(out)
238 }