fitzgen / inlinable_string

An owned, grow-able UTF-8 string that stores small strings inline and avoids heap-allocation.
http://fitzgen.github.io/inlinable_string/inlinable_string/index.html
Other
69 stars 11 forks source link

Format integer into an inlinable string #33

Closed hniksic closed 2 years ago

hniksic commented 3 years ago

Is there a way to format an integer into an inlinable string? E.g. create a function with this signature:

fn format_i32(n: i32) -> InlinableString;

n.into() doesn't work. I expected to be able to use write!() like this:

use inlinable_string::StringExt;

fn format_i32(n: i32) -> InlinableString {
    let mut out = InlinableString::new();
    write!(&mut out, "{}", n);
    out
}

But that complains that InlinableString doesn't implement std::io::Write.

ArtemGr commented 2 years ago

A macro I use often is

/// Fomat into InlinableString
macro_rules! ifomat {
  ($($args: tt)+) => ({
    let mut is = InlinableString::new();
    use std::fmt::Write;
    wite! (&mut is, $($args)+) .expect ("!wite");
    is})}

cf. https://crates.io/crates/fomat-macros

If std::fmt::Write clashes with std::io::Write then you can import it under a different name

use std::fmt::{Write as FmtWrite};

But that complains that InlinableString doesn't implement std::io::Write

For the record, the actual error message I'm seeing is

error[E0599]: no method named `write_fmt` found for mutable reference `&mut InlinableString` in the current scope
  --> src/....rs:17:5
   |
17 |     write!(&mut out, "{}", n);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^ method not found in `&mut InlinableString`
   |
   = help: items from traits can only be used if the trait is in scope
   = note: the following trait is implemented but not in scope; perhaps add a `use` for it:
           `use std::fmt::Write;`

Compiler hints the solution.