{"id":22286902,"url":"https://github.com/koraa/with_drop","last_synced_at":"2025-07-28T22:31:49.154Z","repository":{"id":47434480,"uuid":"281435758","full_name":"koraa/with_drop","owner":"koraa","description":"with_drop: Nostd wrapper for using a closure as a custom drop function","archived":false,"fork":false,"pushed_at":"2022-09-28T20:53:00.000Z","size":8,"stargazers_count":11,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-06-24T18:58:28.231Z","etag":null,"topics":["mem","nostd","rust","wrapper"],"latest_commit_sha":null,"homepage":"https://docs.rs/with_drop","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/koraa.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-07-21T15:30:01.000Z","updated_at":"2023-08-02T02:28:00.000Z","dependencies_parsed_at":"2022-08-23T15:11:03.988Z","dependency_job_id":null,"html_url":"https://github.com/koraa/with_drop","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/koraa/with_drop","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koraa%2Fwith_drop","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koraa%2Fwith_drop/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koraa%2Fwith_drop/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koraa%2Fwith_drop/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/koraa","download_url":"https://codeload.github.com/koraa/with_drop/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koraa%2Fwith_drop/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267421286,"owners_count":24084523,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-27T02:00:11.917Z","response_time":82,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mem","nostd","rust","wrapper"],"created_at":"2024-12-03T16:58:31.899Z","updated_at":"2025-07-28T22:31:48.843Z","avatar_url":"https://github.com/koraa.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# with_drop\n\nNostd wrapper that can be used to execute a custom destructor.\n\n## Usage\n\nCargo.toml\n\n```toml\n[dependencies]\nwith_drop = \"0.0.1\"\n```\n\nIn code:\n\n```rust\nuse std::{cell::RefCell};\nuse with_drop::with_drop;\n\nlet drop_sum = RefCell::new(0);\n\n{\n  let mut v = with_drop(32, |x| { *drop_sum.borrow_mut() += x });\n\n  // use value\n  assert!(*v == 32);\n\n  // Modify it\n  *v = 42;\n}\n\n// Drop function should have been executed\nassert!(*drop_sum.borrow() == 42);\n```\n\n## Motivation\n\nTake the following bit of code:\n\n```rust\nuse std::{io::Result, process::Command, process::Stdio};\n\nfn main() -\u003e Result\u003c()\u003e {\n  let child1 = Command::new(\"echo\").arg(\"42\").stdout(Stdio::piped()).spawn()?;\n  let child2 = Command::new(\"echo\").arg(\"23\").stdout(Stdio::piped()).spawn()?;\n  assert!(child1.wait_with_output()?.stdout == b\"42\\n\");\n  assert!(child2.wait_with_output()?.stdout == b\"23\\n\");\n  Ok(())\n}\n```\n\nSimple, right? We start two subprocesses, collect their results and compare them against a value.\nExcept, that this example is not entirely correct; it is not exception safe. The [std::process::Child](https://doc.rust-lang.org/std/process/struct.Child.html)\ndocumentation specifies that [wait()](https://doc.rust-lang.org/std/process/struct.Child.html#method.wait)\nmust be called *manually* (Child does not implement Drop) to properly clean up behind the processes\n(Failing to do so will result in [zombie processes](https://en.wikipedia.org/wiki/Zombie_process) under linux).\n\nNow, if you take a closer look at the above code example, you might spot that not every code path does\ncall wait; if everything goes as planned, wait will be called, however if we exit early due to a failed\nresult, wait will not be called on either child1 or child2.\n\nThis property is called exception safety (or result safety since rust does not have exceptions?); the code example\nabove is not exception safe. We could manually use if statements to catch all these cases, but that would grow\nvery unwieldy very quickly. Optimally, the Child type would implement Drop and automatically wait on the processes.\nbut it doesn't. Failing that, we can use `with_drop()` to create a wrapper:\n\n```rust\nuse std::{io::Result, process::Command, process::Stdio};\nuse with_drop::with_drop;\n\nfn main() -\u003e Result\u003c()\u003e {\n  let child1 = with_drop(Command::new(\"echo\").arg(\"42\").stdout(Stdio::piped()).spawn()?, |mut child| {\n    // Explicitly ignoring errors; the command might not have been started or might\n    // not have ended or might have yielded an error; in any case we don't mind because\n    // we just care about cleaning up zombies.\n    let _ = child.wait();\n  });\n  let child2 = with_drop(Command::new(\"echo\").arg(\"23\").stdout(Stdio::piped()).spawn()?, |mut child| {\n    let _ = child.wait();\n  });\n  assert!(child1.into_inner().wait_with_output()?.stdout == b\"42\\n\");\n  assert!(child2.into_inner().wait_with_output()?.stdout == b\"23\\n\");\n  Ok(())\n}\n```\n\n### How about `finally()`\n\nCouldn't a finally() like construction be used instead? No, it can not!\nOur finally() guard would have to store a mutable reference of our child\nvariables which would prevent us from calling wait_with_output (borrow checker\ncomplains).\n\n```rust\nuse std::{io::Result, process::Command, process::Stdio};\nuse with_drop::with_drop;\n\nstruct Finally\u003cF: FnMut()\u003e {\n  f: F\n}\n\nimpl\u003cF: FnMut()\u003e Drop for Finally\u003cF\u003e {\n    fn drop(\u0026mut self) {\n      (self.f)();\n    }\n}\n\nfn finally\u003cF: FnMut()\u003e(f: F) -\u003e Finally\u003cF\u003e {\n  Finally { f }\n}\n\nfn main() -\u003e Result\u003c()\u003e {\n  let mut child1 = Command::new(\"echo\").arg(\"42\").stdout(Stdio::piped()).spawn()?;\n  let finally_guard1 = finally(|| {\n    let _ = child1.wait();\n  });\n  let mut child2 = Command::new(\"echo\").arg(\"42\").stdout(Stdio::piped()).spawn()?;\n  let finally_guard2 = finally(|| {\n    let _ = child2.wait();\n  });\n\n  // error[E0505]: cannot move out of `child1` because it is borrowed\n\n  //assert!(child1.wait_with_output()?.stdout == b\"42\\n\");\n  //assert!(child2.wait_with_output()?.stdout == b\"23\\n\");\n\n  Ok(())\n}\n```\n\n## Testing\n\nInstall clippy, rustfmt and nono:\n\n```bash\n$ rustup component add rustfmt\n$ rustup component add clippy\n$ RUSTFLAGS=\"--cfg procmacro2_semver_exempt\" cargo install cargo-nono\n```\n\nAnd now use these to execute the tests.\n\n```bash\n$ cargo build\n$ cargo test\n$ cargo clippy --all-targets --all-features -- -D warnings\n$ cargo fmt -- --check\n$ cargo nono check\n```\n\n## License\n\nCopyright © (C) 2020, Karolin Varner. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\nNeither the name of the Karolin Varner nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Softwear, BV BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoraa%2Fwith_drop","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkoraa%2Fwith_drop","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoraa%2Fwith_drop/lists"}