Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to return an owned diff with TextDiff::configure().diff_lines #65

Open
lbirkert opened this issue Jul 1, 2024 · 6 comments
Open

Comments

@lbirkert
Copy link

lbirkert commented Jul 1, 2024

TextDiff::configure().diff_lines does not want to accept owned Strings as arguments, only String references. Therefore I cannot return it, as the String I parse is owned by the current function. How can I transfer ownership to return this diff?

@lbirkert
Copy link
Author

lbirkert commented Jul 1, 2024

Am I forced to write a custom similar::Change type which allows owned Strings and then map every change to that custom struct or is there somehow a builtin method to do that?

@max-sixty
Copy link
Sponsor

Could you post a code example?

@lbirkert
Copy link
Author

lbirkert commented Jul 2, 2024

sure.

pub fn my_func() -> ... {
    // in reality these buffers are non trivial to fetch
    let old = fs::read(path_old).unwrap();
    let old = std::str::from_utf8(old).unwrap();
    let new = fs::read(path_old).unwrap();
    let new = std::str::from_utf8(new).unwrap();

    // I'd like to return this diff to process it further
    // but old and new are only refs to Strings which belong to the
    // current function, so they will be dropped once
    // we exit the function
    TextDiff::configure().diff_lines(old, new)
    

    // This is what I would like to do, to_string would turn
    // them owned and therefore ownership would get transfered 
    // to the TextDiff, allowing me to return it, as there is
    // no dependence on values owned by the current function
    //
    // This does not work though, diff_lines requires refs
    TextDiff::configure().diff_lines(old.to_string(), new.to_string())
}

I hope this makes it clear.

@mitsuhiko
Copy link
Owner

mitsuhiko commented Jul 2, 2024

Yes, this is not possible today. However this is not a lost cause as you can work around this with self_cell: https://docs.rs/self_cell/latest/self_cell/

This is related to #33.

@lbirkert
Copy link
Author

lbirkert commented Jul 2, 2024

Alright. Thanks for the tip

@lbirkert lbirkert closed this as completed Jul 2, 2024
@lbirkert
Copy link
Author

lbirkert commented Jul 7, 2024

I cannot get this to work. Self cell throws lifetime errors. Can you please post an example on how to do this?

@lbirkert lbirkert reopened this Jul 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants