Created
October 7, 2017 13:40
-
-
Save ubnt-intrepid/3a4cc14bab05ccf55033a81ff9e0f5fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(fmt_internals, rustc_private)] | |
extern crate fmt_macros; | |
use std::{fmt, io}; | |
#[derive(Default)] | |
struct ArgumentsBuilder<'a> { | |
pieces: Vec<&'a str>, | |
args: Vec<fmt::ArgumentV1<'a>>, | |
} | |
impl<'a> ArgumentsBuilder<'a> { | |
fn piece(mut self, piece: &'a str) -> Self { | |
self.pieces.push(piece); | |
self | |
} | |
fn arg<T>( | |
mut self, | |
value: &'a T, | |
formatter: fn(&T, &mut fmt::Formatter) -> fmt::Result, | |
) -> Self { | |
self.args.push(fmt::ArgumentV1::new(value, formatter)); | |
self | |
} | |
fn to_arguments(&'a self) -> fmt::Arguments<'a> { | |
fmt::Arguments::new_v1(&self.pieces, &self.args) | |
} | |
} | |
fn print(args: fmt::Arguments) { | |
let formatted = fmt::format(args); | |
io::Write::write_all(&mut io::stdout(), formatted.as_bytes()).unwrap(); | |
} | |
fn main() { | |
let name = String::from("Alice"); | |
let suffix = String::from("!\n"); | |
let my_format_string = |s: &String, f: &mut fmt::Formatter| f.write_str(s.as_str()); | |
let builder = ArgumentsBuilder::default() | |
.piece("Hello, ") | |
.arg(&name, my_format_string) | |
.piece(&suffix); | |
print(builder.to_arguments()); | |
let parser = fmt_macros::Parser::new("Hello, {}!\n"); | |
for (i, piece) in parser.into_iter().enumerate() { | |
println!( | |
"{}: {}", | |
i, | |
match piece { | |
fmt_macros::Piece::String(s) => s, | |
fmt_macros::Piece::NextArgument(_) => "Argument", | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment