removed all of the git sources (#91)

This commit is contained in:
Miles Wirht
2026-07-13 21:25:00 -04:00
committed by GitHub
parent 5484fbaf88
commit 6c799b8e99
74 changed files with 20842 additions and 451 deletions
Generated
+584 -397
View File
File diff suppressed because it is too large Load Diff
+28 -23
View File
@@ -11,6 +11,14 @@ members = [
"./crates/gpui_platform/",
"./crates/gpui_shared_string/",
"./crates/gpui_elements/",
"./crates/gpui_collections/",
"./crates/gpui_refineable/",
"./crates/gpui_derive_refineable/",
"./crates/gpui_scheduler/",
"./crates/gpui_sum_tree/",
"./crates/gpui_media/",
"./crates/gpui_zed_util/",
"./crates/gpui_ce_util/",
"./tooling/perf/",
]
default-members = ["./crates/gpui/"]
@@ -33,7 +41,7 @@ accesskit_windows = "0.32.1"
anyhow = "1.0.86"
backtrace = "0.3"
bitflags = "2.6.0"
collections = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9", version = "0.1.0" }
collections = { path = "crates/gpui_collections", version = "0.2.2", package = "gpui_collections" }
ctor = "1.0.6"
derive_more = { version = "2.1.1", features = [
"add",
@@ -55,16 +63,13 @@ itertools = "0.14.0"
log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] }
parking_lot = "0.12.1"
postage = { version = "0.5", features = ["futures-traits"] }
proptest = { git = "https://github.com/proptest-rs/proptest", rev = "3dca198a8fef1b32e3a66f1e1897c955b4dc5b5b", features = [
"attr-macro",
] }
proptest = { version = "1.10", features = ["attr-macro"] }
chrono = { version = "0.4", features = ["serde"] }
profiling = "1"
rand = "0.9.4"
regex = "1.5"
refineable = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" }
scheduler = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" }
util_macros = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" }
refineable = { path = "crates/gpui_refineable", version = "0.2.2", package = "gpui_refineable" }
scheduler = { path = "crates/gpui_scheduler", version = "0.2.2", package = "gpui_scheduler" }
schemars = { version = "1.0", features = ["indexmap2"] }
serde = { version = "1.0.221", features = ["derive", "rc"] }
serde_json = { version = "1.0.144", features = ["preserve_order", "raw_value"] }
@@ -73,7 +78,7 @@ smallvec = { version = "1.6", features = ["union", "const_new"] }
async-channel = "2.5.0"
stacksafe = "1.0"
strum = { version = "0.27.2", features = ["derive"] }
sum_tree = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" }
sum_tree = { path = "crates/gpui_sum_tree", version = "0.2.2", package = "gpui_sum_tree" }
thiserror = "2.0.12"
hdrhistogram = "7"
pollster = "0.4.0"
@@ -85,11 +90,11 @@ cocoa-foundation = "=0.2.0"
core-foundation = "=0.10.0"
core-foundation-sys = "0.8.6"
core-video = { version = "0.5.2", features = ["metal"] }
media = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" }
media = { path = "crates/gpui_media", version = "0.2.2", package = "gpui_media" }
objc = "0.2"
mach2 = "0.5"
metal = "0.33"
scap = { git = "https://github.com/zed-industries/scap", rev = "4afea48c3b002197176fb19cd0f9b180dd36eaac", default-features = false, package = "zed-scap", version = "0.0.8-zed" }
scap = { version = "0.0.8-zed", package = "zed-scap", default-features = false }
env_logger = "0.11"
unicode-segmentation = "1.10"
@@ -108,8 +113,8 @@ ashpd = { version = "0.13", default-features = false, features = [
] }
libc = "0.2"
smol = "2.0"
util = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" }
wgpu = { git = "https://github.com/zed-industries/wgpu.git", rev = "357a0c56e0070480ad9daea5d2eaa83150b79e88" }
util = { path = "crates/gpui_zed_util", version = "0.2.2", package = "gpui_zed_util" }
wgpu = "29.0.3"
criterion = { version = "0.5", features = ["html_reports"] }
objc2-app-kit = { version = "0.3", default-features = false, features = [
"NSGraphics",
@@ -117,20 +122,20 @@ objc2-app-kit = { version = "0.3", default-features = false, features = [
semver = { version = "1.0", features = ["serde"] }
windows-core = "0.61"
tokio = { version = "1" }
gpui_util = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" }
gpui_util = { path = "crates/gpui_ce_util", version = "0.2.2", package = "gpui_ce_util" }
gpui = { path = "./crates/gpui/" }
gpui_platform = { path = "./crates/gpui_platform/" }
gpui_linux = { path = "./crates/gpui_linux/" }
gpui_macos = { path = "./crates/gpui_macos/" }
gpui_windows = { path = "./crates/gpui_windows/" }
gpui_web = { path = "./crates/gpui_web/" }
gpui = { path = "./crates/gpui/", version = "0.2.2" }
gpui_platform = { path = "./crates/gpui_platform/", version = "0.1.0" }
gpui_linux = { path = "./crates/gpui_linux/", version = "0.1.0" }
gpui_macos = { path = "./crates/gpui_macos/", version = "0.1.0" }
gpui_windows = { path = "./crates/gpui_windows/", version = "0.1.0" }
gpui_web = { path = "./crates/gpui_web/", version = "0.1.0" }
gpui_wgpu = { path = "./crates/gpui_wgpu/" }
gpui_wgpu = { path = "./crates/gpui_wgpu/", version = "0.1.0" }
gpui_macros = { path = "./crates/gpui_macros/" }
gpui_shared_string = { path = "./crates/gpui_shared_string/" }
gpui_tokio = { path = "./crates/gpui_tokio/" }
gpui_macros = { path = "./crates/gpui_macros/", version = "0.1.0" }
gpui_shared_string = { path = "./crates/gpui_shared_string/", version = "0.1.0" }
gpui_tokio = { path = "./crates/gpui_tokio/", version = "0.1.0" }
[workspace.dependencies.windows]
version = "0.61"
+1 -3
View File
@@ -77,7 +77,6 @@ resvg = { version = "0.45.0", default-features = false, features = [
] }
usvg = { version = "0.45.0", default-features = false }
ttf-parser = "0.25"
util_macros.workspace = true
schemars.workspace = true
seahash = "4.1"
serde.workspace = true
@@ -115,8 +114,7 @@ core-foundation-sys.workspace = true
core-graphics = "0.24"
core-video.workspace = true
core-text = "21"
# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", optional = true }
font-kit = { version = "0.14.1-zed", package = "zed-font-kit", optional = true }
foreign-types = "0.5"
log.workspace = true
media.workspace = true
+1 -1
View File
@@ -22,7 +22,7 @@ impl Render for HelloWorld {
.border_color(rgb(0x0000ff))
.text_xl()
.text_color(rgb(0xffffff))
.child(format!("Hello, {}!", &self.text))
.child(format!("Hello, {}!", self.text))
.child(
div()
.flex()
+3 -5
View File
@@ -1364,9 +1364,7 @@ mod tests {
use super::*;
use util_macros::perf;
#[perf]
#[test]
fn test_basic_highlight_style_combination() {
let style_a = HighlightStyle::default();
let style_b = HighlightStyle::default();
@@ -1451,7 +1449,7 @@ mod tests {
);
}
#[perf]
#[test]
fn test_combine_highlights() {
assert_eq!(
combine_highlights(
@@ -1540,7 +1538,7 @@ mod tests {
);
}
#[perf]
#[test]
fn test_text_style_refinement() {
let mut style = Style::default();
style.refine(&StyleRefinement::default().text_size(px(20.0)));
+1 -1
View File
@@ -1046,7 +1046,7 @@ mod tests {
..Default::default()
};
let text = "aa bbb cccc ddddd eeee".into();
let text = SharedString::from("aa bbb cccc ddddd eeee");
let lines = text_system
.shape_text(
text,
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "gpui_ce_util"
version = "0.2.2"
edition = "2024"
license = "Apache-2.0"
publish = true
description = "Utility structs and functions used by gpui-ce (vendored from Zed's gpui_util)."
repository = "https://github.com/gpui-ce/gpui-ce"
[lib]
name = "gpui_util"
path = "src/lib.rs"
[dependencies]
log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] }
anyhow = "1.0.86"
+222
View File
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+141
View File
@@ -0,0 +1,141 @@
use std::{
borrow::Cow,
cmp::Ordering,
fmt::{self, Debug},
hash::{Hash, Hasher},
sync::Arc,
};
pub enum ArcCow<'a, T: ?Sized> {
Borrowed(&'a T),
Owned(Arc<T>),
}
impl<T: ?Sized + PartialEq> PartialEq for ArcCow<'_, T> {
fn eq(&self, other: &Self) -> bool {
let a = self.as_ref();
let b = other.as_ref();
a == b
}
}
impl<T: ?Sized + PartialOrd> PartialOrd for ArcCow<'_, T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.as_ref().partial_cmp(other.as_ref())
}
}
impl<T: ?Sized + Ord> Ord for ArcCow<'_, T> {
fn cmp(&self, other: &Self) -> Ordering {
self.as_ref().cmp(other.as_ref())
}
}
impl<T: ?Sized + Eq> Eq for ArcCow<'_, T> {}
impl<T: ?Sized + Hash> Hash for ArcCow<'_, T> {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Self::Borrowed(borrowed) => Hash::hash(borrowed, state),
Self::Owned(owned) => Hash::hash(&**owned, state),
}
}
}
impl<T: ?Sized> Clone for ArcCow<'_, T> {
fn clone(&self) -> Self {
match self {
Self::Borrowed(borrowed) => Self::Borrowed(borrowed),
Self::Owned(owned) => Self::Owned(owned.clone()),
}
}
}
impl<'a, T: ?Sized> From<&'a T> for ArcCow<'a, T> {
fn from(s: &'a T) -> Self {
Self::Borrowed(s)
}
}
impl<T: ?Sized> From<Arc<T>> for ArcCow<'_, T> {
fn from(s: Arc<T>) -> Self {
Self::Owned(s)
}
}
impl<T: ?Sized> From<&'_ Arc<T>> for ArcCow<'_, T> {
fn from(s: &'_ Arc<T>) -> Self {
Self::Owned(s.clone())
}
}
impl From<String> for ArcCow<'_, str> {
fn from(value: String) -> Self {
Self::Owned(value.into())
}
}
impl From<&String> for ArcCow<'_, str> {
fn from(value: &String) -> Self {
Self::Owned(value.clone().into())
}
}
impl<'a> From<Cow<'a, str>> for ArcCow<'a, str> {
fn from(value: Cow<'a, str>) -> Self {
match value {
Cow::Borrowed(borrowed) => Self::Borrowed(borrowed),
Cow::Owned(owned) => Self::Owned(owned.into()),
}
}
}
impl<T> From<Vec<T>> for ArcCow<'_, [T]> {
fn from(vec: Vec<T>) -> Self {
ArcCow::Owned(Arc::from(vec))
}
}
impl<'a> From<&'a str> for ArcCow<'a, [u8]> {
fn from(s: &'a str) -> Self {
ArcCow::Borrowed(s.as_bytes())
}
}
impl<T: ?Sized + ToOwned> std::borrow::Borrow<T> for ArcCow<'_, T> {
fn borrow(&self) -> &T {
match self {
ArcCow::Borrowed(borrowed) => borrowed,
ArcCow::Owned(owned) => owned.as_ref(),
}
}
}
impl<T: ?Sized> std::ops::Deref for ArcCow<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match self {
ArcCow::Borrowed(s) => s,
ArcCow::Owned(s) => s.as_ref(),
}
}
}
impl<T: ?Sized> AsRef<T> for ArcCow<'_, T> {
fn as_ref(&self) -> &T {
match self {
ArcCow::Borrowed(borrowed) => borrowed,
ArcCow::Owned(owned) => owned.as_ref(),
}
}
}
impl<T: ?Sized + Debug> Debug for ArcCow<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ArcCow::Borrowed(borrowed) => Debug::fmt(borrowed, f),
ArcCow::Owned(owned) => Debug::fmt(&**owned, f),
}
}
}
+393
View File
@@ -0,0 +1,393 @@
// FluentBuilder
// pub use gpui_util::{FutureExt, Timeout, arc_cow::ArcCow};
use std::{
env,
ops::AddAssign,
panic::Location,
pin::Pin,
sync::OnceLock,
task::{Context, Poll},
time::Instant,
};
pub mod arc_cow;
pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
let prev = *value;
*value += T::from(1);
prev
}
pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
env::var("ZED_MEASUREMENTS")
.map(|measurements| measurements == "1" || measurements == "true")
.unwrap_or(false)
});
if *zed_measurements {
let start = Instant::now();
let result = f();
let elapsed = start.elapsed();
eprintln!("{}: {:?}", label, elapsed);
result
} else {
f()
}
}
#[macro_export]
macro_rules! debug_panic {
( $($fmt_arg:tt)* ) => {
if cfg!(debug_assertions) {
panic!( $($fmt_arg)* );
} else {
let backtrace = std::backtrace::Backtrace::capture();
log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
}
};
}
#[track_caller]
pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
#[cfg(debug_assertions)]
if option.is_none() {
panic!("Unexpected None");
}
option
}
/// Expands to an immediately-invoked function expression. Good for using the ? operator
/// in functions which do not return an Option or Result.
///
/// Accepts a normal block, an async block, or an async move block.
#[macro_export]
macro_rules! maybe {
($block:block) => {
(|| $block)()
};
(async $block:block) => {
(async || $block)()
};
(async move $block:block) => {
(async move || $block)()
};
}
pub trait ResultExt<E> {
type Ok;
fn log_err(self) -> Option<Self::Ok>;
/// Like [`ResultExt::log_err`], but uses `{:?}` formatting so `anyhow::Error` values emit their
/// full backtrace. Reach for this only when a backtrace is genuinely wanted — most call sites
/// should stick with `log_err` / `warn_on_err`, whose output is a single chained error message.
fn log_err_with_backtrace(self) -> Option<Self::Ok>
where
E: std::fmt::Debug;
/// Assert that this result should never be an error in development or tests.
fn debug_assert_ok(self, reason: &str) -> Self;
fn warn_on_err(self) -> Option<Self::Ok>;
fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
fn anyhow(self) -> anyhow::Result<Self::Ok>
where
E: Into<anyhow::Error>;
}
impl<T, E> ResultExt<E> for Result<T, E>
where
E: std::fmt::Display,
{
type Ok = T;
#[track_caller]
fn log_err(self) -> Option<T> {
self.log_with_level(log::Level::Error)
}
#[track_caller]
fn log_err_with_backtrace(self) -> Option<T>
where
E: std::fmt::Debug,
{
match self {
Ok(value) => Some(value),
Err(error) => {
log_error_with_caller(
*Location::caller(),
DebugAsDisplay(&error),
log::Level::Error,
);
None
}
}
}
#[track_caller]
fn debug_assert_ok(self, reason: &str) -> Self {
if let Err(error) = &self {
debug_panic!("{reason} - {error:#}");
}
self
}
#[track_caller]
fn warn_on_err(self) -> Option<T> {
self.log_with_level(log::Level::Warn)
}
#[track_caller]
fn log_with_level(self, level: log::Level) -> Option<T> {
match self {
Ok(value) => Some(value),
Err(error) => {
log_error_with_caller(*Location::caller(), error, level);
None
}
}
}
fn anyhow(self) -> anyhow::Result<T>
where
E: Into<anyhow::Error>,
{
self.map_err(Into::into)
}
}
fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
where
E: std::fmt::Display,
{
#[cfg(not(windows))]
let file = caller.file();
#[cfg(windows)]
let file = caller.file().replace('\\', "/");
// In this codebase all crates reside in a `crates` directory,
// so discard the prefix up to that segment to find the crate name
let file = file.split_once("crates/");
let target = file.as_ref().and_then(|(_, s)| s.split_once("/src/"));
let module_path = target.map(|(krate, module)| {
if module.starts_with(krate) {
module.trim_end_matches(".rs").replace('/', "::")
} else {
krate.to_owned() + "::" + &module.trim_end_matches(".rs").replace('/', "::")
}
});
let file = file.map(|(_, file)| format!("crates/{file}"));
log::logger().log(
&log::Record::builder()
.target(module_path.as_deref().unwrap_or(""))
.module_path(file.as_deref())
.args(format_args!("{:#}", error))
.file(Some(caller.file()))
.line(Some(caller.line()))
.level(level)
.build(),
);
}
pub fn log_err<E: std::fmt::Display>(error: &E) {
log_error_with_caller(*Location::caller(), error, log::Level::Error);
}
// Forces `{:?}` formatting through a `Display`-bounded logging helper so `anyhow::Error` emits a
// backtrace instead of the single-line chained message produced by its `Display`/`{:#}` forms.
struct DebugAsDisplay<'a, E>(&'a E);
impl<E: std::fmt::Debug> std::fmt::Display for DebugAsDisplay<'_, E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
pub trait TryFutureExt {
fn log_err(self) -> LogErrorFuture<Self>
where
Self: Sized;
fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
where
Self: Sized;
fn warn_on_err(self) -> LogErrorFuture<Self>
where
Self: Sized;
fn unwrap(self) -> UnwrapFuture<Self>
where
Self: Sized;
}
/// `{:?}`-formatting companion to [`TryFutureExt`]; emits a backtrace for `anyhow::Error`. Prefer
/// [`TryFutureExt`] unless a backtrace is genuinely wanted.
pub trait TryFutureExtBacktrace {
fn log_err_with_backtrace(self) -> LogErrorWithBacktraceFuture<Self>
where
Self: Sized;
fn log_tracked_err_with_backtrace(
self,
location: core::panic::Location<'static>,
) -> LogErrorWithBacktraceFuture<Self>
where
Self: Sized;
}
impl<F, T, E> TryFutureExt for F
where
F: Future<Output = Result<T, E>>,
E: std::fmt::Display,
{
#[track_caller]
fn log_err(self) -> LogErrorFuture<Self>
where
Self: Sized,
{
let location = Location::caller();
LogErrorFuture(self, log::Level::Error, *location)
}
fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
where
Self: Sized,
{
LogErrorFuture(self, log::Level::Error, location)
}
#[track_caller]
fn warn_on_err(self) -> LogErrorFuture<Self>
where
Self: Sized,
{
let location = Location::caller();
LogErrorFuture(self, log::Level::Warn, *location)
}
fn unwrap(self) -> UnwrapFuture<Self>
where
Self: Sized,
{
UnwrapFuture(self)
}
}
impl<F, T, E> TryFutureExtBacktrace for F
where
F: Future<Output = Result<T, E>>,
E: std::fmt::Debug,
{
#[track_caller]
fn log_err_with_backtrace(self) -> LogErrorWithBacktraceFuture<Self>
where
Self: Sized,
{
let location = Location::caller();
LogErrorWithBacktraceFuture(self, log::Level::Error, *location)
}
fn log_tracked_err_with_backtrace(
self,
location: core::panic::Location<'static>,
) -> LogErrorWithBacktraceFuture<Self>
where
Self: Sized,
{
LogErrorWithBacktraceFuture(self, log::Level::Error, location)
}
}
#[must_use]
pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
impl<F, T, E> Future for LogErrorFuture<F>
where
F: Future<Output = Result<T, E>>,
E: std::fmt::Display,
{
type Output = Option<T>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let level = self.1;
let location = self.2;
let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
match inner.poll(cx) {
Poll::Ready(output) => Poll::Ready(match output {
Ok(output) => Some(output),
Err(error) => {
log_error_with_caller(location, error, level);
None
}
}),
Poll::Pending => Poll::Pending,
}
}
}
#[must_use]
pub struct LogErrorWithBacktraceFuture<F>(F, log::Level, core::panic::Location<'static>);
impl<F, T, E> Future for LogErrorWithBacktraceFuture<F>
where
F: Future<Output = Result<T, E>>,
E: std::fmt::Debug,
{
type Output = Option<T>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let level = self.1;
let location = self.2;
let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
match inner.poll(cx) {
Poll::Ready(output) => Poll::Ready(match output {
Ok(output) => Some(output),
Err(error) => {
log_error_with_caller(location, DebugAsDisplay(&error), level);
None
}
}),
Poll::Pending => Poll::Pending,
}
}
}
pub struct UnwrapFuture<F>(F);
impl<F, T, E> Future for UnwrapFuture<F>
where
F: Future<Output = Result<T, E>>,
E: std::fmt::Debug,
{
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
match inner.poll(cx) {
Poll::Ready(result) => Poll::Ready(result.unwrap()),
Poll::Pending => Poll::Pending,
}
}
}
pub struct Deferred<F: FnOnce()>(Option<F>);
impl<F: FnOnce()> Deferred<F> {
/// Drop without running the deferred function.
pub fn abort(mut self) {
self.0.take();
}
}
impl<F: FnOnce()> Drop for Deferred<F> {
fn drop(&mut self) {
if let Some(f) = self.0.take() {
f()
}
}
}
/// Run the given function when the returned value is dropped (unless it's cancelled).
#[must_use]
pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
Deferred(Some(f))
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "gpui_collections"
version = "0.2.2"
edition = "2024"
license = "Apache-2.0"
publish = true
description = "Blessed hash collections used by gpui-ce (vendored from Zed)."
repository = "https://github.com/gpui-ce/gpui-ce"
[lib]
name = "collections"
path = "src/collections.rs"
doctest = false
[features]
test-support = []
[dependencies]
indexmap = { version = "2", features = ["serde"] }
rustc-hash = "2"
+222
View File
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
@@ -0,0 +1,13 @@
pub type HashMap<K, V> = FxHashMap<K, V>;
pub type HashSet<T> = FxHashSet<T>;
pub type IndexMap<K, V> = indexmap::IndexMap<K, V, rustc_hash::FxBuildHasher>;
pub type IndexSet<T> = indexmap::IndexSet<T, rustc_hash::FxBuildHasher>;
pub use indexmap::Equivalent;
pub use rustc_hash::FxHasher;
pub use rustc_hash::{FxHashMap, FxHashSet};
pub use std::collections::*;
pub mod vecmap;
#[cfg(test)]
mod vecmap_tests;
+192
View File
@@ -0,0 +1,192 @@
/// A collection that provides a map interface but is backed by vectors.
///
/// This is suitable for small key-value stores where the item count is not
/// large enough to overcome the overhead of a more complex algorithm.
///
/// If this meets your use cases, then [`VecMap`] should be a drop-in
/// replacement for [`std::collections::HashMap`] or [`crate::HashMap`]. Note
/// that we are adding APIs on an as-needed basis. If the API you need is not
/// present yet, please add it!
///
/// Because it uses vectors as a backing store, the map also iterates over items
/// in insertion order, like [`crate::IndexMap`].
///
/// This struct uses a struct-of-arrays (SoA) representation which tends to be
/// more cache efficient and promotes autovectorization when using simple key or
/// value types.
#[derive(Default)]
pub struct VecMap<K, V> {
keys: Vec<K>,
values: Vec<V>,
}
impl<K, V> VecMap<K, V> {
pub fn new() -> Self {
Self {
keys: Vec::new(),
values: Vec::new(),
}
}
pub fn iter(&self) -> Iter<'_, K, V> {
Iter {
iter: self.keys.iter().zip(self.values.iter()),
}
}
}
impl<K: Eq, V> VecMap<K, V> {
pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
match self.keys.iter().position(|k| k == &key) {
Some(index) => Entry::Occupied(OccupiedEntry {
key: &self.keys[index],
value: &mut self.values[index],
}),
None => Entry::Vacant(VacantEntry { map: self, key }),
}
}
/// Like [`Self::entry`] but takes its key by reference instead of by value.
///
/// This can be helpful if you have a key where cloning is expensive, as we
/// can avoid cloning the key until a value is inserted under that entry.
pub fn entry_ref<'a, 'k>(&'a mut self, key: &'k K) -> EntryRef<'k, 'a, K, V> {
match self.keys.iter().position(|k| k == key) {
Some(index) => EntryRef::Occupied(OccupiedEntry {
key: &self.keys[index],
value: &mut self.values[index],
}),
None => EntryRef::Vacant(VacantEntryRef { map: self, key }),
}
}
}
pub struct Iter<'a, K, V> {
iter: std::iter::Zip<std::slice::Iter<'a, K>, std::slice::Iter<'a, V>>,
}
impl<'a, K, V> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
}
pub enum Entry<'a, K, V> {
Occupied(OccupiedEntry<'a, K, V>),
Vacant(VacantEntry<'a, K, V>),
}
impl<'a, K, V> Entry<'a, K, V> {
pub fn key(&self) -> &K {
match self {
Entry::Occupied(entry) => entry.key,
Entry::Vacant(entry) => &entry.key,
}
}
pub fn or_insert_with_key<F>(self, default: F) -> &'a mut V
where
F: FnOnce(&K) -> V,
{
match self {
Entry::Occupied(entry) => entry.value,
Entry::Vacant(entry) => {
entry.map.values.push(default(&entry.key));
entry.map.keys.push(entry.key);
match entry.map.values.last_mut() {
Some(value) => value,
None => unreachable!("vec empty after pushing to it"),
}
}
}
}
pub fn or_insert_with<F>(self, default: F) -> &'a mut V
where
F: FnOnce() -> V,
{
self.or_insert_with_key(|_| default())
}
pub fn or_insert(self, value: V) -> &'a mut V {
self.or_insert_with_key(|_| value)
}
pub fn or_insert_default(self) -> &'a mut V
where
V: Default,
{
self.or_insert_with_key(|_| Default::default())
}
}
pub struct OccupiedEntry<'a, K, V> {
key: &'a K,
value: &'a mut V,
}
pub struct VacantEntry<'a, K, V> {
map: &'a mut VecMap<K, V>,
key: K,
}
pub enum EntryRef<'key, 'map, K, V> {
Occupied(OccupiedEntry<'map, K, V>),
Vacant(VacantEntryRef<'key, 'map, K, V>),
}
impl<'key, 'map, K, V> EntryRef<'key, 'map, K, V> {
pub fn key(&self) -> &K {
match self {
EntryRef::Occupied(entry) => entry.key,
EntryRef::Vacant(entry) => entry.key,
}
}
}
impl<'key, 'map, K, V> EntryRef<'key, 'map, K, V>
where
K: Clone,
{
pub fn or_insert_with_key<F>(self, default: F) -> &'map mut V
where
F: FnOnce(&K) -> V,
{
match self {
EntryRef::Occupied(entry) => entry.value,
EntryRef::Vacant(entry) => {
entry.map.values.push(default(entry.key));
entry.map.keys.push(entry.key.clone());
match entry.map.values.last_mut() {
Some(value) => value,
None => unreachable!("vec empty after pushing to it"),
}
}
}
}
pub fn or_insert_with<F>(self, default: F) -> &'map mut V
where
F: FnOnce() -> V,
{
self.or_insert_with_key(|_| default())
}
pub fn or_insert(self, value: V) -> &'map mut V {
self.or_insert_with_key(|_| value)
}
pub fn or_insert_default(self) -> &'map mut V
where
V: Default,
{
self.or_insert_with_key(|_| Default::default())
}
}
pub struct VacantEntryRef<'key, 'map, K, V> {
map: &'map mut VecMap<K, V>,
key: &'key K,
}
+211
View File
@@ -0,0 +1,211 @@
//! Tests for the VecMap collection.
//!
//! This is in a sibling module so that the tests are guaranteed to only cover
//! states that can be created by the public API.
use crate::vecmap::*;
#[test]
fn test_entry_vacant_or_insert() {
let mut map: VecMap<&str, i32> = VecMap::new();
let value = map.entry("a").or_insert(1);
assert_eq!(*value, 1);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&"a", &1)]);
}
#[test]
fn test_entry_occupied_or_insert_keeps_existing() {
let mut map: VecMap<&str, i32> = VecMap::new();
map.entry("a").or_insert(1);
let value = map.entry("a").or_insert(99);
assert_eq!(*value, 1);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&"a", &1)]);
}
#[test]
fn test_entry_or_insert_with() {
let mut map: VecMap<&str, i32> = VecMap::new();
map.entry("a").or_insert_with(|| 42);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&"a", &42)]);
}
#[test]
fn test_entry_or_insert_with_not_called_when_occupied() {
let mut map: VecMap<&str, i32> = VecMap::new();
map.entry("a").or_insert(1);
map.entry("a")
.or_insert_with(|| panic!("should not be called"));
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&"a", &1)]);
}
#[test]
fn test_entry_or_insert_with_key() {
let mut map: VecMap<&str, String> = VecMap::new();
map.entry("hello").or_insert_with_key(|k| k.to_uppercase());
assert_eq!(
map.iter().collect::<Vec<_>>(),
vec![(&"hello", &"HELLO".to_string())]
);
}
#[test]
fn test_entry_or_insert_default() {
let mut map: VecMap<&str, i32> = VecMap::new();
map.entry("a").or_insert_default();
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&"a", &0)]);
}
#[test]
fn test_entry_key() {
let mut map: VecMap<&str, i32> = VecMap::new();
assert_eq!(*map.entry("a").key(), "a");
map.entry("a").or_insert(1);
assert_eq!(*map.entry("a").key(), "a");
}
#[test]
fn test_entry_mut_ref_can_be_updated() {
let mut map: VecMap<&str, i32> = VecMap::new();
let value = map.entry("a").or_insert(0);
*value = 5;
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&"a", &5)]);
}
#[test]
fn test_insertion_order_preserved() {
let mut map: VecMap<&str, i32> = VecMap::new();
map.entry("b").or_insert(2);
map.entry("a").or_insert(1);
map.entry("c").or_insert(3);
assert_eq!(
map.iter().collect::<Vec<_>>(),
vec![(&"b", &2), (&"a", &1), (&"c", &3)]
);
}
#[test]
fn test_multiple_entries_independent() {
let mut map: VecMap<i32, i32> = VecMap::new();
map.entry(1).or_insert(10);
map.entry(2).or_insert(20);
map.entry(3).or_insert(30);
assert_eq!(map.iter().count(), 3);
// Re-inserting does not duplicate keys
map.entry(1).or_insert(99);
assert_eq!(map.iter().count(), 3);
}
// entry_ref tests
use std::cell::Cell;
use std::rc::Rc;
#[derive(PartialEq, Eq)]
struct CountedKey {
value: String,
clone_count: Rc<Cell<usize>>,
}
impl Clone for CountedKey {
fn clone(&self) -> Self {
self.clone_count.set(self.clone_count.get() + 1);
CountedKey {
value: self.value.clone(),
clone_count: self.clone_count.clone(),
}
}
}
#[test]
fn test_entry_ref_vacant_or_insert() {
let mut map: VecMap<String, i32> = VecMap::new();
let key = "a".to_string();
let value = map.entry_ref(&key).or_insert(1);
assert_eq!(*value, 1);
assert_eq!(map.iter().count(), 1);
}
#[test]
fn test_entry_ref_occupied_or_insert_keeps_existing() {
let mut map: VecMap<String, i32> = VecMap::new();
map.entry_ref(&"a".to_string()).or_insert(1);
let value = map.entry_ref(&"a".to_string()).or_insert(99);
assert_eq!(*value, 1);
assert_eq!(map.iter().count(), 1);
}
#[test]
fn test_entry_ref_key_not_cloned_when_occupied() {
let clone_count = Rc::new(Cell::new(0));
let key = CountedKey {
value: "a".to_string(),
clone_count: clone_count.clone(),
};
let mut map: VecMap<CountedKey, i32> = VecMap::new();
map.entry_ref(&key).or_insert(1);
let clones_after_insert = clone_count.get();
// Looking up an existing key must not clone it.
map.entry_ref(&key).or_insert(99);
assert_eq!(clone_count.get(), clones_after_insert);
}
#[test]
fn test_entry_ref_key_cloned_exactly_once_on_vacant_insert() {
let clone_count = Rc::new(Cell::new(0));
let key = CountedKey {
value: "a".to_string(),
clone_count: clone_count.clone(),
};
let mut map: VecMap<CountedKey, i32> = VecMap::new();
map.entry_ref(&key).or_insert(1);
assert_eq!(clone_count.get(), 1);
}
#[test]
fn test_entry_ref_or_insert_with_key() {
let mut map: VecMap<String, String> = VecMap::new();
let key = "hello".to_string();
map.entry_ref(&key).or_insert_with_key(|k| k.to_uppercase());
assert_eq!(
map.iter().collect::<Vec<_>>(),
vec![(&"hello".to_string(), &"HELLO".to_string())]
);
}
#[test]
fn test_entry_ref_or_insert_with_not_called_when_occupied() {
let mut map: VecMap<String, i32> = VecMap::new();
let key = "a".to_string();
map.entry_ref(&key).or_insert(1);
map.entry_ref(&key)
.or_insert_with(|| panic!("should not be called"));
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&key, &1)]);
}
#[test]
fn test_entry_ref_or_insert_default() {
let mut map: VecMap<String, i32> = VecMap::new();
map.entry_ref(&"a".to_string()).or_insert_default();
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&"a".to_string(), &0)]);
}
#[test]
fn test_entry_ref_key() {
let mut map: VecMap<String, i32> = VecMap::new();
let key = "a".to_string();
assert_eq!(*map.entry_ref(&key).key(), key);
map.entry_ref(&key).or_insert(1);
assert_eq!(*map.entry_ref(&key).key(), key);
}
#[test]
fn test_entry_ref_mut_ref_can_be_updated() {
let mut map: VecMap<String, i32> = VecMap::new();
let key = "a".to_string();
let value = map.entry_ref(&key).or_insert(0);
*value = 5;
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&key, &5)]);
}
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "gpui_derive_refineable"
version = "0.2.2"
edition = "2024"
license = "Apache-2.0"
publish = true
description = "Derive macro for gpui-ce's Refineable (vendored from Zed)."
[lib]
name = "derive_refineable"
path = "src/derive_refineable.rs"
proc-macro = true
doctest = false
[dependencies]
proc-macro2 = "1.0.101"
quote = "1.0.41"
syn = { version = "2.0.117", features = ["full", "extra-traits", "visit-mut"] }
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
@@ -0,0 +1,548 @@
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{
DeriveInput, Field, FieldsNamed, PredicateType, TraitBound, Type, TypeParamBound, WhereClause,
WherePredicate, parse_macro_input, parse_quote,
};
#[proc_macro_derive(Refineable, attributes(refineable))]
pub fn derive_refineable(input: TokenStream) -> TokenStream {
let DeriveInput {
ident,
data,
generics,
attrs,
..
} = parse_macro_input!(input);
let refineable_attr = attrs.iter().find(|attr| attr.path().is_ident("refineable"));
let mut impl_debug_on_refinement = false;
let mut derives_serialize = false;
let mut refinement_traits_to_derive = vec![];
if let Some(refineable_attr) = refineable_attr {
let _ = refineable_attr.parse_nested_meta(|meta| {
if meta.path.is_ident("Debug") {
impl_debug_on_refinement = true;
} else {
if meta.path.is_ident("Serialize") {
derives_serialize = true;
}
refinement_traits_to_derive.push(meta.path);
}
Ok(())
});
}
let refinement_ident = format_ident!("{}Refinement", ident);
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let fields = match data {
syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(FieldsNamed { named, .. }),
..
}) => named.into_iter().collect::<Vec<Field>>(),
_ => panic!("This derive macro only supports structs with named fields"),
};
let field_names: Vec<_> = fields.iter().map(|f| f.ident.as_ref().unwrap()).collect();
let field_visibilities: Vec<_> = fields.iter().map(|f| &f.vis).collect();
let wrapped_types: Vec<_> = fields.iter().map(|f| get_wrapper_type(f, &f.ty)).collect();
let field_attributes: Vec<TokenStream2> = fields
.iter()
.map(|f| {
if derives_serialize {
if is_refineable_field(f) {
quote! { #[serde(default, skip_serializing_if = "::refineable::IsEmpty::is_empty")] }
} else {
quote! { #[serde(skip_serializing_if = "::std::option::Option::is_none")] }
}
} else {
quote! {}
}
})
.collect();
// Create trait bound that each wrapped type must implement Clone
let type_param_bounds: Vec<_> = wrapped_types
.iter()
.map(|ty| {
WherePredicate::Type(PredicateType {
lifetimes: None,
bounded_ty: ty.clone(),
colon_token: Default::default(),
bounds: {
let mut punctuated = syn::punctuated::Punctuated::new();
punctuated.push_value(TypeParamBound::Trait(TraitBound {
paren_token: None,
modifier: syn::TraitBoundModifier::None,
lifetimes: None,
path: parse_quote!(Clone),
}));
punctuated
},
})
})
.collect();
// Append to where_clause or create a new one if it doesn't exist
let where_clause = match where_clause.cloned() {
Some(mut where_clause) => {
where_clause.predicates.extend(type_param_bounds);
where_clause.clone()
}
None => WhereClause {
where_token: Default::default(),
predicates: type_param_bounds.into_iter().collect(),
},
};
let refineable_refine_assignments: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
let is_optional = is_optional_field(field);
if is_refineable {
quote! {
self.#name.refine(&refinement.#name);
}
} else if is_optional {
quote! {
if let Some(value) = &refinement.#name {
self.#name = Some(value.clone());
}
}
} else {
quote! {
if let Some(value) = &refinement.#name {
self.#name = value.clone();
}
}
}
})
.collect();
let refineable_refined_assignments: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
let is_optional = is_optional_field(field);
if is_refineable {
quote! {
self.#name = self.#name.refined(refinement.#name);
}
} else if is_optional {
quote! {
if let Some(value) = refinement.#name {
self.#name = Some(value);
}
}
} else {
quote! {
if let Some(value) = refinement.#name {
self.#name = value;
}
}
}
})
.collect();
let refinement_refine_assignments: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
if is_refineable {
quote! {
self.#name.refine(&refinement.#name);
}
} else {
quote! {
if let Some(value) = &refinement.#name {
self.#name = Some(value.clone());
}
}
}
})
.collect();
let refinement_refined_assignments: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
if is_refineable {
quote! {
self.#name = self.#name.refined(refinement.#name);
}
} else {
quote! {
if let Some(value) = refinement.#name {
self.#name = Some(value);
}
}
}
})
.collect();
let from_refinement_assignments: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
let is_optional = is_optional_field(field);
if is_refineable {
quote! {
#name: value.#name.into(),
}
} else if is_optional {
quote! {
#name: value.#name.map(|v| v.into()),
}
} else {
quote! {
#name: value.#name.map(|v| v.into()).unwrap_or_default(),
}
}
})
.collect();
let debug_impl = if impl_debug_on_refinement {
let refinement_field_debugs: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
quote! {
if self.#name.is_some() {
debug_struct.field(stringify!(#name), &self.#name);
} else {
all_some = false;
}
}
})
.collect();
quote! {
impl #impl_generics std::fmt::Debug for #refinement_ident #ty_generics
#where_clause
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut debug_struct = f.debug_struct(stringify!(#refinement_ident));
let mut all_some = true;
#( #refinement_field_debugs )*
if all_some {
debug_struct.finish()
} else {
debug_struct.finish_non_exhaustive()
}
}
}
}
} else {
quote! {}
};
let refinement_is_empty_conditions: Vec<TokenStream2> = fields
.iter()
.enumerate()
.map(|(i, field)| {
let name = &field.ident;
let condition = if is_refineable_field(field) {
quote! { self.#name.is_empty() }
} else {
quote! { self.#name.is_none() }
};
if i < fields.len() - 1 {
quote! { #condition && }
} else {
condition
}
})
.collect();
let refineable_is_superset_conditions: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
let is_optional = is_optional_field(field);
if is_refineable {
quote! {
if !self.#name.is_superset_of(&refinement.#name) {
return false;
}
}
} else if is_optional {
quote! {
if refinement.#name.is_some() && &self.#name != &refinement.#name {
return false;
}
}
} else {
quote! {
if let Some(refinement_value) = &refinement.#name {
if &self.#name != refinement_value {
return false;
}
}
}
}
})
.collect();
let refinement_is_superset_conditions: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
if is_refineable {
quote! {
if !self.#name.is_superset_of(&refinement.#name) {
return false;
}
}
} else {
quote! {
if refinement.#name.is_some() && &self.#name != &refinement.#name {
return false;
}
}
}
})
.collect();
let refineable_subtract_assignments: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
let is_optional = is_optional_field(field);
if is_refineable {
quote! {
#name: self.#name.subtract(&refinement.#name),
}
} else if is_optional {
quote! {
#name: if &self.#name == &refinement.#name {
None
} else {
self.#name.clone()
},
}
} else {
quote! {
#name: if let Some(refinement_value) = &refinement.#name {
if &self.#name == refinement_value {
None
} else {
Some(self.#name.clone())
}
} else {
Some(self.#name.clone())
},
}
}
})
.collect();
let refinement_subtract_assignments: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
if is_refineable {
quote! {
#name: self.#name.subtract(&refinement.#name),
}
} else {
quote! {
#name: if &self.#name == &refinement.#name {
None
} else {
self.#name.clone()
},
}
}
})
.collect();
let mut derive_stream = quote! {};
for trait_to_derive in refinement_traits_to_derive {
derive_stream.extend(quote! { #[derive(#trait_to_derive)] })
}
let r#gen = quote! {
/// A refinable version of [`#ident`], see that documentation for details.
#[derive(Clone)]
#derive_stream
pub struct #refinement_ident #impl_generics {
#(
#[allow(missing_docs)]
#field_attributes
#field_visibilities #field_names: #wrapped_types
),*
}
impl #impl_generics Refineable for #ident #ty_generics
#where_clause
{
type Refinement = #refinement_ident #ty_generics;
fn refine(&mut self, refinement: &Self::Refinement) {
#( #refineable_refine_assignments )*
}
fn refined(mut self, refinement: Self::Refinement) -> Self {
#( #refineable_refined_assignments )*
self
}
fn is_superset_of(&self, refinement: &Self::Refinement) -> bool
{
#( #refineable_is_superset_conditions )*
true
}
fn subtract(&self, refinement: &Self::Refinement) -> Self::Refinement
{
#refinement_ident {
#( #refineable_subtract_assignments )*
}
}
}
impl #impl_generics Refineable for #refinement_ident #ty_generics
#where_clause
{
type Refinement = #refinement_ident #ty_generics;
fn refine(&mut self, refinement: &Self::Refinement) {
#( #refinement_refine_assignments )*
}
fn refined(mut self, refinement: Self::Refinement) -> Self {
#( #refinement_refined_assignments )*
self
}
fn is_superset_of(&self, refinement: &Self::Refinement) -> bool
{
#( #refinement_is_superset_conditions )*
true
}
fn subtract(&self, refinement: &Self::Refinement) -> Self::Refinement
{
#refinement_ident {
#( #refinement_subtract_assignments )*
}
}
}
impl #impl_generics ::refineable::IsEmpty for #refinement_ident #ty_generics
#where_clause
{
fn is_empty(&self) -> bool {
#( #refinement_is_empty_conditions )*
}
}
impl #impl_generics From<#refinement_ident #ty_generics> for #ident #ty_generics
#where_clause
{
fn from(value: #refinement_ident #ty_generics) -> Self {
Self {
#( #from_refinement_assignments )*
}
}
}
impl #impl_generics ::core::default::Default for #refinement_ident #ty_generics
#where_clause
{
fn default() -> Self {
#refinement_ident {
#( #field_names: Default::default() ),*
}
}
}
impl #impl_generics #refinement_ident #ty_generics
#where_clause
{
/// Returns `true` if all fields are `Some`
pub fn is_some(&self) -> bool {
#(
if self.#field_names.is_some() {
return true;
}
)*
false
}
}
#debug_impl
};
r#gen.into()
}
fn is_refineable_field(f: &Field) -> bool {
f.attrs
.iter()
.any(|attr| attr.path().is_ident("refineable"))
}
fn is_optional_field(f: &Field) -> bool {
if let Type::Path(typepath) = &f.ty
&& typepath.qself.is_none()
{
let segments = &typepath.path.segments;
if segments.len() == 1 && segments.iter().any(|s| s.ident == "Option") {
return true;
}
}
false
}
fn get_wrapper_type(field: &Field, ty: &Type) -> syn::Type {
if is_refineable_field(field) {
let struct_name = if let Type::Path(tp) = ty {
tp.path.segments.last().unwrap().ident.clone()
} else {
panic!("Expected struct type for a refineable field");
};
let refinement_struct_name = if struct_name.to_string().ends_with("Refinement") {
format_ident!("{}", struct_name)
} else {
format_ident!("{}Refinement", struct_name)
};
let generics = if let Type::Path(tp) = ty {
&tp.path.segments.last().unwrap().arguments
} else {
&syn::PathArguments::None
};
parse_quote!(#refinement_struct_name #generics)
} else if is_optional_field(field) {
ty.clone()
} else {
parse_quote!(Option<#ty>)
}
}
+2 -3
View File
@@ -125,9 +125,8 @@ x11rb = { version = "0.13.1", features = [
"sync",
"dri3",
], optional = true }
# WARNING: If you change this, you must also publish a new version of zed-xim to crates.io
xim = { git = "https://github.com/zed-industries/xim-rs.git", rev = "16f35a2c881b815a2b6cdfd6687988e84f8447d8", features = [
xim = { version = "0.4.0-zed", package = "zed-xim", features = [
"x11rb-xcb",
"x11rb-client",
], package = "zed-xim", version = "0.4.0-zed", optional = true }
], optional = true }
x11-clipboard = { version = "0.9.3", optional = true }
+1 -2
View File
@@ -38,8 +38,7 @@ ctor.workspace = true
derive_more.workspace = true
dispatch2 = "0.3.1"
etagere = "0.2"
# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", optional = true }
font-kit = { version = "0.14.1-zed", package = "zed-font-kit", optional = true }
foreign-types = "0.5"
futures.workspace = true
image.workspace = true
+1 -1
View File
@@ -2,7 +2,7 @@
name = "gpui_macros"
version = "0.1.0"
edition.workspace = true
publish = false
publish = true
license = "Apache-2.0"
description = "Macros used by gpui"
+2 -2
View File
@@ -193,7 +193,7 @@ pub fn test(args: TokenStream, function: TokenStream) -> TokenStream {
///
/// A property test, much like a standard GPUI randomized test, allows testing
/// claims of the form "for any possible X, Y should hold". For example:
/// ```
/// ```ignore
/// #[gpui::property_test]
/// fn test_arithmetic(x: i32, y: i32) {
/// assert!(x == y || x < y || x > y);
@@ -236,7 +236,7 @@ pub fn test(args: TokenStream, function: TokenStream) -> TokenStream {
/// `Arbitrary`. Parameters to a `#[gpui::property_test]`, by default, use a
/// type's `Arbitrary` implementation. If you'd like to provide a custom
/// strategy, you can use `#[strategy = ...]` on the argument:
/// ```
/// ```ignore
/// #[gpui::property_test]
/// fn int_test(#[strategy = 1..10] x: i32, #[strategy = "[a-zA-Z0-9]{20}"] s: String) {
/// assert!(s.len() > (x as usize));
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "gpui_media"
version = "0.2.2"
edition = "2024"
license = "Apache-2.0"
publish = true
description = "macOS CoreMedia/CoreVideo bindings for gpui-ce (vendored from Zed)."
[lib]
name = "media"
path = "src/media.rs"
doctest = false
[dependencies]
anyhow = "1.0.86"
[target.'cfg(target_os = "macos")'.dependencies]
core-foundation = "=0.10.0"
ctor = "1.0.6"
foreign-types = "0.5"
metal = "0.33"
core-video = { version = "0.5.2", features = ["metal"] }
objc = "0.2"
[build-dependencies]
bindgen = "0.71"
+222
View File
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+44
View File
@@ -0,0 +1,44 @@
#![allow(clippy::disallowed_methods, reason = "build scripts are exempt")]
#[cfg(target_os = "macos")]
fn main() {
use std::{env, path::PathBuf, process::Command};
let sdk_path = String::from_utf8(
Command::new("xcrun")
.args(["--sdk", "macosx", "--show-sdk-path"])
.output()
.unwrap()
.stdout,
)
.unwrap();
let sdk_path = sdk_path.trim_end();
println!("cargo:rerun-if-changed=src/bindings.h");
let bindings = bindgen::Builder::default()
.header("src/bindings.h")
.clang_arg(format!("-isysroot{}", sdk_path))
.clang_arg("-xobjective-c")
.allowlist_type("CMItemIndex")
.allowlist_type("CMSampleTimingInfo")
.allowlist_type("CMVideoCodecType")
.allowlist_type("VTEncodeInfoFlags")
.allowlist_function("CMTimeMake")
.allowlist_var("kCVPixelFormatType_.*")
.allowlist_var("kCVReturn.*")
.allowlist_var("VTEncodeInfoFlags_.*")
.allowlist_var("kCMVideoCodecType_.*")
.allowlist_var("kCMTime.*")
.allowlist_var("kCMSampleAttachmentKey_.*")
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.layout_tests(false)
.generate()
.expect("unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("couldn't write dispatch bindings");
}
#[cfg(not(target_os = "macos"))]
fn main() {}
+5
View File
@@ -0,0 +1,5 @@
#import <CoreMedia/CMFormatDescription.h>
#import <CoreMedia/CMSampleBuffer.h>
#import <CoreVideo/CVPixelFormatDescription.h>
#import <CoreVideo/CVReturn.h>
#import <VideoToolbox/VTCompressionSession.h>
+10
View File
@@ -0,0 +1,10 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(unused)]
#[cfg(target_os = "macos")]
use objc::*;
#[cfg(target_os = "macos")]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
+352
View File
@@ -0,0 +1,352 @@
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
mod bindings;
#[cfg(target_os = "macos")]
pub mod core_media {
#![allow(non_snake_case)]
pub use crate::bindings::{
CMItemIndex, CMSampleTimingInfo, CMTime, CMTimeMake, CMVideoCodecType,
kCMSampleAttachmentKey_NotSync, kCMTimeInvalid, kCMVideoCodecType_H264,
};
use anyhow::Result;
use core_foundation::{
array::{CFArray, CFArrayRef},
base::{CFTypeID, OSStatus, TCFType},
declare_TCFType,
dictionary::CFDictionary,
impl_CFTypeDescription, impl_TCFType,
string::CFString,
};
use core_video::image_buffer::{CVImageBuffer, CVImageBufferRef};
use std::{ffi::c_void, ptr};
#[repr(C)]
pub struct __CMSampleBuffer(c_void);
// The ref type must be a pointer to the underlying struct.
pub type CMSampleBufferRef = *const __CMSampleBuffer;
declare_TCFType!(CMSampleBuffer, CMSampleBufferRef);
impl_TCFType!(CMSampleBuffer, CMSampleBufferRef, CMSampleBufferGetTypeID);
impl_CFTypeDescription!(CMSampleBuffer);
impl CMSampleBuffer {
pub fn attachments(&self) -> Vec<CFDictionary<CFString>> {
unsafe {
let attachments =
CMSampleBufferGetSampleAttachmentsArray(self.as_concrete_TypeRef(), true);
CFArray::<CFDictionary>::wrap_under_get_rule(attachments)
.into_iter()
.map(|attachments| {
CFDictionary::wrap_under_get_rule(attachments.as_concrete_TypeRef())
})
.collect()
}
}
pub fn image_buffer(&self) -> Option<CVImageBuffer> {
unsafe {
let ptr = CMSampleBufferGetImageBuffer(self.as_concrete_TypeRef());
if ptr.is_null() {
None
} else {
Some(CVImageBuffer::wrap_under_get_rule(ptr))
}
}
}
pub fn sample_timing_info(&self, index: usize) -> Result<CMSampleTimingInfo> {
unsafe {
let mut timing_info = CMSampleTimingInfo {
duration: kCMTimeInvalid,
presentationTimeStamp: kCMTimeInvalid,
decodeTimeStamp: kCMTimeInvalid,
};
let result = CMSampleBufferGetSampleTimingInfo(
self.as_concrete_TypeRef(),
index as CMItemIndex,
&mut timing_info,
);
anyhow::ensure!(
result == 0,
"error getting sample timing info, code {result}"
);
Ok(timing_info)
}
}
pub fn format_description(&self) -> CMFormatDescription {
unsafe {
CMFormatDescription::wrap_under_get_rule(CMSampleBufferGetFormatDescription(
self.as_concrete_TypeRef(),
))
}
}
pub fn data(&self) -> CMBlockBuffer {
unsafe {
CMBlockBuffer::wrap_under_get_rule(CMSampleBufferGetDataBuffer(
self.as_concrete_TypeRef(),
))
}
}
}
#[link(name = "CoreMedia", kind = "framework")]
unsafe extern "C" {
fn CMSampleBufferGetTypeID() -> CFTypeID;
fn CMSampleBufferGetSampleAttachmentsArray(
buffer: CMSampleBufferRef,
create_if_necessary: bool,
) -> CFArrayRef;
fn CMSampleBufferGetImageBuffer(buffer: CMSampleBufferRef) -> CVImageBufferRef;
fn CMSampleBufferGetSampleTimingInfo(
buffer: CMSampleBufferRef,
index: CMItemIndex,
timing_info_out: *mut CMSampleTimingInfo,
) -> OSStatus;
fn CMSampleBufferGetFormatDescription(buffer: CMSampleBufferRef) -> CMFormatDescriptionRef;
fn CMSampleBufferGetDataBuffer(sample_buffer: CMSampleBufferRef) -> CMBlockBufferRef;
}
#[repr(C)]
pub struct __CMFormatDescription(c_void);
pub type CMFormatDescriptionRef = *const __CMFormatDescription;
declare_TCFType!(CMFormatDescription, CMFormatDescriptionRef);
impl_TCFType!(
CMFormatDescription,
CMFormatDescriptionRef,
CMFormatDescriptionGetTypeID
);
impl_CFTypeDescription!(CMFormatDescription);
impl CMFormatDescription {
pub fn h264_parameter_set_count(&self) -> usize {
unsafe {
let mut count = 0;
let result = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
self.as_concrete_TypeRef(),
0,
ptr::null_mut(),
ptr::null_mut(),
&mut count,
ptr::null_mut(),
);
assert_eq!(result, 0);
count
}
}
pub fn h264_parameter_set_at_index(&self, index: usize) -> Result<&[u8]> {
unsafe {
let mut bytes = ptr::null();
let mut len = 0;
let result = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
self.as_concrete_TypeRef(),
index,
&mut bytes,
&mut len,
ptr::null_mut(),
ptr::null_mut(),
);
anyhow::ensure!(result == 0, "error getting parameter set, code: {result}");
Ok(std::slice::from_raw_parts(bytes, len))
}
}
}
#[link(name = "CoreMedia", kind = "framework")]
unsafe extern "C" {
fn CMFormatDescriptionGetTypeID() -> CFTypeID;
fn CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
video_desc: CMFormatDescriptionRef,
parameter_set_index: usize,
parameter_set_pointer_out: *mut *const u8,
parameter_set_size_out: *mut usize,
parameter_set_count_out: *mut usize,
NALUnitHeaderLengthOut: *mut isize,
) -> OSStatus;
}
#[repr(C)]
pub struct __CMBlockBuffer(c_void);
pub type CMBlockBufferRef = *const __CMBlockBuffer;
declare_TCFType!(CMBlockBuffer, CMBlockBufferRef);
impl_TCFType!(CMBlockBuffer, CMBlockBufferRef, CMBlockBufferGetTypeID);
impl_CFTypeDescription!(CMBlockBuffer);
impl CMBlockBuffer {
pub fn bytes(&self) -> &[u8] {
unsafe {
let mut bytes = ptr::null();
let mut len = 0;
let result = CMBlockBufferGetDataPointer(
self.as_concrete_TypeRef(),
0,
&mut 0,
&mut len,
&mut bytes,
);
assert!(result == 0, "could not get block buffer data");
std::slice::from_raw_parts(bytes, len)
}
}
}
#[link(name = "CoreMedia", kind = "framework")]
unsafe extern "C" {
fn CMBlockBufferGetTypeID() -> CFTypeID;
fn CMBlockBufferGetDataPointer(
buffer: CMBlockBufferRef,
offset: usize,
length_at_offset_out: *mut usize,
total_length_out: *mut usize,
data_pointer_out: *mut *const u8,
) -> OSStatus;
}
}
#[cfg(target_os = "macos")]
pub mod core_video {
#![allow(non_snake_case)]
#[cfg(target_os = "macos")]
use core_foundation::{
base::{CFTypeID, TCFType},
declare_TCFType, impl_CFTypeDescription, impl_TCFType,
};
#[cfg(target_os = "macos")]
use std::ffi::c_void;
use crate::bindings::{CVReturn, kCVReturnSuccess};
pub use crate::bindings::{
kCVPixelFormatType_32BGRA, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr8Planar,
};
use anyhow::Result;
use core_foundation::{
base::kCFAllocatorDefault, dictionary::CFDictionaryRef, mach_port::CFAllocatorRef,
};
use foreign_types::ForeignTypeRef;
use metal::{MTLDevice, MTLPixelFormat};
use std::ptr;
#[repr(C)]
pub struct __CVMetalTextureCache(c_void);
pub type CVMetalTextureCacheRef = *const __CVMetalTextureCache;
declare_TCFType!(CVMetalTextureCache, CVMetalTextureCacheRef);
impl_TCFType!(
CVMetalTextureCache,
CVMetalTextureCacheRef,
CVMetalTextureCacheGetTypeID
);
impl_CFTypeDescription!(CVMetalTextureCache);
impl CVMetalTextureCache {
/// # Safety
///
/// metal_device must be valid according to CVMetalTextureCacheCreate
pub unsafe fn new(metal_device: *mut MTLDevice) -> Result<Self> {
let mut this = ptr::null();
let result = unsafe {
CVMetalTextureCacheCreate(
kCFAllocatorDefault,
ptr::null(),
metal_device,
ptr::null(),
&mut this,
)
};
anyhow::ensure!(
result == kCVReturnSuccess,
"could not create texture cache, code: {result}"
);
unsafe { Ok(CVMetalTextureCache::wrap_under_create_rule(this)) }
}
/// # Safety
///
/// The arguments to this function must be valid according to CVMetalTextureCacheCreateTextureFromImage
pub unsafe fn create_texture_from_image(
&self,
source: ::core_video::image_buffer::CVImageBufferRef,
texture_attributes: CFDictionaryRef,
pixel_format: MTLPixelFormat,
width: usize,
height: usize,
plane_index: usize,
) -> Result<CVMetalTexture> {
let mut this = ptr::null();
let result = unsafe {
CVMetalTextureCacheCreateTextureFromImage(
kCFAllocatorDefault,
self.as_concrete_TypeRef(),
source,
texture_attributes,
pixel_format,
width,
height,
plane_index,
&mut this,
)
};
anyhow::ensure!(
result == kCVReturnSuccess,
"could not create texture, code: {result}"
);
unsafe { Ok(CVMetalTexture::wrap_under_create_rule(this)) }
}
}
#[link(name = "CoreVideo", kind = "framework")]
unsafe extern "C" {
fn CVMetalTextureCacheGetTypeID() -> CFTypeID;
fn CVMetalTextureCacheCreate(
allocator: CFAllocatorRef,
cache_attributes: CFDictionaryRef,
metal_device: *const MTLDevice,
texture_attributes: CFDictionaryRef,
cache_out: *mut CVMetalTextureCacheRef,
) -> CVReturn;
fn CVMetalTextureCacheCreateTextureFromImage(
allocator: CFAllocatorRef,
texture_cache: CVMetalTextureCacheRef,
source_image: ::core_video::image_buffer::CVImageBufferRef,
texture_attributes: CFDictionaryRef,
pixel_format: MTLPixelFormat,
width: usize,
height: usize,
plane_index: usize,
texture_out: *mut CVMetalTextureRef,
) -> CVReturn;
}
#[repr(C)]
pub struct __CVMetalTexture(c_void);
pub type CVMetalTextureRef = *const __CVMetalTexture;
declare_TCFType!(CVMetalTexture, CVMetalTextureRef);
impl_TCFType!(CVMetalTexture, CVMetalTextureRef, CVMetalTextureGetTypeID);
impl_CFTypeDescription!(CVMetalTexture);
impl CVMetalTexture {
pub fn as_texture_ref(&self) -> &metal::TextureRef {
unsafe {
let texture = CVMetalTextureGetTexture(self.as_concrete_TypeRef());
metal::TextureRef::from_ptr(texture as *mut _)
}
}
}
#[link(name = "CoreVideo", kind = "framework")]
unsafe extern "C" {
fn CVMetalTextureGetTypeID() -> CFTypeID;
fn CVMetalTextureGetTexture(texture: CVMetalTextureRef) -> *mut c_void;
}
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "gpui_refineable"
version = "0.2.2"
edition = "2024"
license = "Apache-2.0"
publish = true
description = "Refineable trait + cascade for gpui-ce (vendored from Zed)."
[lib]
name = "refineable"
path = "src/refineable.rs"
doctest = false
[dependencies]
derive_refineable = { package = "gpui_derive_refineable", version = "0.2.2", path = "../gpui_derive_refineable" }
+222
View File
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+132
View File
@@ -0,0 +1,132 @@
pub use derive_refineable::Refineable;
/// A trait for types that can be refined with partial updates.
///
/// The `Refineable` trait enables hierarchical configuration patterns where a base configuration
/// can be selectively overridden by refinements. This is particularly useful for styling and
/// settings, and theme hierarchies.
///
/// # Derive Macro
///
/// The `#[derive(Refineable)]` macro automatically generates a companion refinement type and
/// implements this trait. For a struct `Style`, it creates `StyleRefinement` where each field is
/// wrapped appropriately:
///
/// - **Refineable fields** (marked with `#[refineable]`): Become the corresponding refinement type
/// (e.g., `Bar` becomes `BarRefinement`, or `BarRefinement` remains `BarRefinement`)
/// - **Optional fields** (`Option<T>`): Remain as `Option<T>`
/// - **Regular fields**: Become `Option<T>`
///
/// ## Attributes
///
/// The derive macro supports these attributes on the struct:
/// - `#[refineable(Debug)]`: Implements `Debug` for the refinement type
/// - `#[refineable(Serialize)]`: Derives `Serialize` which skips serializing `None`
/// - `#[refineable(OtherTrait)]`: Derives additional traits on the refinement type
///
/// Fields can be marked with:
/// - `#[refineable]`: Field is itself refineable (uses nested refinement type)
pub trait Refineable: Clone {
type Refinement: Refineable<Refinement = Self::Refinement> + IsEmpty + Default;
/// Applies the given refinement to this instance, modifying it in place.
///
/// Only non-empty values in the refinement are applied.
///
/// * For refineable fields, this recursively calls `refine`.
/// * For other fields, the value is replaced if present in the refinement.
fn refine(&mut self, refinement: &Self::Refinement);
/// Returns a new instance with the refinement applied, equivalent to cloning `self` and calling
/// `refine` on it.
fn refined(self, refinement: Self::Refinement) -> Self;
/// Creates an instance from a cascade by merging all refinements atop the default value.
fn from_cascade(cascade: &Cascade<Self>) -> Self
where
Self: Default + Sized,
{
Self::default().refined(cascade.merged())
}
/// Returns `true` if this instance would contain all values from the refinement.
///
/// For refineable fields, this recursively checks `is_superset_of`. For other fields, this
/// checks if the refinement's `Some` values match this instance's values.
fn is_superset_of(&self, refinement: &Self::Refinement) -> bool;
/// Returns a refinement that represents the difference between this instance and the given
/// refinement.
///
/// For refineable fields, this recursively calls `subtract`. For other fields, the field is
/// `None` if the field's value is equal to the refinement.
fn subtract(&self, refinement: &Self::Refinement) -> Self::Refinement;
}
pub trait IsEmpty {
/// Returns `true` if applying this refinement would have no effect.
fn is_empty(&self) -> bool;
}
/// A cascade of refinements that can be merged in priority order.
///
/// A cascade maintains a sequence of optional refinements where later entries
/// take precedence over earlier ones. The first slot (index 0) is always the
/// base refinement and is guaranteed to be present.
///
/// This is useful for implementing configuration hierarchies like CSS cascading,
/// where styles from different sources (user agent, user, author) are combined
/// with specific precedence rules.
pub struct Cascade<S: Refineable>(Vec<Option<S::Refinement>>);
impl<S: Refineable + Default> Default for Cascade<S> {
fn default() -> Self {
Self(vec![Some(Default::default())])
}
}
/// A handle to a specific slot in a cascade.
///
/// Slots are used to identify specific positions in the cascade where
/// refinements can be set or updated.
#[derive(Copy, Clone)]
pub struct CascadeSlot(usize);
impl<S: Refineable + Default> Cascade<S> {
/// Reserves a new slot in the cascade and returns a handle to it.
///
/// The new slot is initially empty (`None`) and can be populated later
/// using `set()`.
pub fn reserve(&mut self) -> CascadeSlot {
self.0.push(None);
CascadeSlot(self.0.len() - 1)
}
/// Returns a mutable reference to the base refinement (slot 0).
///
/// The base refinement is always present and serves as the foundation
/// for the cascade.
pub fn base(&mut self) -> &mut S::Refinement {
self.0[0].as_mut().unwrap()
}
/// Sets the refinement for a specific slot in the cascade.
///
/// Setting a slot to `None` effectively removes it from consideration
/// during merging.
pub fn set(&mut self, slot: CascadeSlot, refinement: Option<S::Refinement>) {
self.0[slot.0] = refinement
}
/// Merges all refinements in the cascade into a single refinement.
///
/// Refinements are applied in order, with later slots taking precedence.
/// Empty slots (`None`) are skipped during merging.
pub fn merged(&self) -> S::Refinement {
let mut merged = self.0[0].clone().unwrap();
for refinement in self.0.iter().skip(1).flatten() {
merged.refine(refinement);
}
merged
}
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "gpui_scheduler"
version = "0.2.2"
edition = "2024"
license = "Apache-2.0"
publish = true
description = "Async task scheduler/executor for gpui-ce (vendored from Zed)."
[lib]
name = "scheduler"
path = "src/scheduler.rs"
doctest = false
[features]
test-support = []
[dependencies]
async-task = "4.7"
backtrace = "0.3.76"
chrono = { version = "0.4.42", features = ["serde"] }
flume = "0.11"
futures = "0.3.32"
parking_lot = "0.12.5"
rand = "0.9.4"
web-time = "1.1.0"
+222
View File
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+55
View File
@@ -0,0 +1,55 @@
use chrono::{DateTime, Utc};
use parking_lot::Mutex;
use std::time::Duration;
pub use web_time::Instant;
pub trait Clock {
fn utc_now(&self) -> DateTime<Utc>;
fn now(&self) -> Instant;
}
pub struct TestClock(Mutex<TestClockState>);
struct TestClockState {
now: Instant,
utc_now: DateTime<Utc>,
}
impl TestClock {
pub fn new() -> Self {
const START_TIME: &str = "2025-07-01T23:59:58-00:00";
let utc_now = DateTime::parse_from_rfc3339(START_TIME).unwrap().to_utc();
Self(Mutex::new(TestClockState {
now: Instant::now(),
utc_now,
}))
}
pub fn set_utc_now(&self, now: DateTime<Utc>) {
let mut state = self.0.lock();
state.utc_now = now;
}
pub fn advance(&self, duration: Duration) {
let mut state = self.0.lock();
state.now += duration;
state.utc_now += duration;
}
}
impl Default for TestClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for TestClock {
fn utc_now(&self) -> DateTime<Utc> {
self.0.lock().utc_now
}
fn now(&self) -> Instant {
self.0.lock().now
}
}
+546
View File
@@ -0,0 +1,546 @@
use crate::{Instant, Priority, RunnableMeta, Scheduler, SessionId, Timer};
use async_task::Runnable;
use std::{
any::Any,
future::Future,
marker::PhantomData,
mem::ManuallyDrop,
panic::Location,
pin::Pin,
rc::Rc,
sync::Arc,
task::{Context, Poll},
thread::{self, ThreadId},
time::Duration,
};
/// Type-erased closure shape expected by [`Scheduler::spawn_dedicated`]:
/// runs on a [`LocalExecutor`], returns a boxed future whose output is itself
/// boxed as `Box<dyn Any + Send + Sync>`.
pub type DedicatedFn = Box<
dyn FnOnce(LocalExecutor) -> Pin<Box<dyn Future<Output = Box<dyn Any + Send + Sync>> + 'static>>
+ Send
+ 'static,
>;
/// A `!Send` executor pinned to a single session. Tasks spawned on it run in
/// order on whichever thread drains the dispatch destination supplied at
/// construction time — typically the main thread for the default session, or
/// a dedicated OS thread for sessions created by `spawn_dedicated_thread`.
#[derive(Clone)]
pub struct LocalExecutor {
session_id: SessionId,
scheduler: Arc<dyn Scheduler>,
// Spawned tasks' schedule callbacks each hold an `Arc` clone of this
// closure, so the destination it captures stays alive as long as work
// could still land on it.
dispatch: Arc<dyn Fn(Runnable<RunnableMeta>) + Send + Sync>,
not_send: PhantomData<Rc<()>>,
}
impl LocalExecutor {
/// Constructs a local executor that runs spawned tasks by sending their
/// runnables through `dispatch`. The `scheduler` is retained for access to
/// clocks, timers, and other scheduler-level services.
///
/// For the common case of routing runnables through
/// `Scheduler::schedule_local`, callers pass a closure that does exactly
/// that. `spawn_dedicated_thread` instead passes a closure that sends to
/// the dedicated thread's channel.
pub fn new(
session_id: SessionId,
scheduler: Arc<dyn Scheduler>,
dispatch: impl Fn(Runnable<RunnableMeta>) + Send + Sync + 'static,
) -> Self {
Self {
session_id,
scheduler,
dispatch: Arc::new(dispatch),
not_send: PhantomData,
}
}
pub fn session_id(&self) -> SessionId {
self.session_id
}
pub fn scheduler(&self) -> &Arc<dyn Scheduler> {
&self.scheduler
}
#[track_caller]
pub fn spawn<F>(&self, future: F) -> Task<F::Output>
where
F: Future + 'static,
F::Output: 'static,
{
let dispatch = self.dispatch.clone();
let location = Location::caller();
let (runnable, task) = spawn_local_with_source_location(
future,
move |runnable| dispatch(runnable),
RunnableMeta { location },
);
runnable.schedule();
Task(TaskState::Spawned(task))
}
pub fn block_on<Fut: Future>(&self, future: Fut) -> Fut::Output {
use std::cell::Cell;
let output = Cell::new(None);
let future = async {
output.set(Some(future.await));
};
let mut future = std::pin::pin!(future);
self.scheduler
.block(Some(self.session_id), future.as_mut(), None);
output.take().expect("block_on future did not complete")
}
/// Block until the future completes or timeout occurs.
/// Returns Ok(output) if completed, Err(future) if timed out.
pub fn block_with_timeout<Fut: Future>(
&self,
timeout: Duration,
future: Fut,
) -> Result<Fut::Output, impl Future<Output = Fut::Output> + use<Fut>> {
use std::cell::Cell;
let output = Cell::new(None);
let mut future = Box::pin(future);
{
let future_ref = &mut future;
let wrapper = async {
output.set(Some(future_ref.await));
};
let mut wrapper = std::pin::pin!(wrapper);
self.scheduler
.block(Some(self.session_id), wrapper.as_mut(), Some(timeout));
}
match output.take() {
Some(value) => Ok(value),
None => Err(future),
}
}
#[track_caller]
pub fn timer(&self, duration: Duration) -> Timer {
self.scheduler.timer(duration)
}
pub fn now(&self) -> Instant {
self.scheduler.clock().now()
}
/// Spawn a closure on a fresh session pinned to its own [`LocalExecutor`].
/// The closure runs on a new OS thread under `PlatformScheduler`, or on
/// the test scheduler's loop under `TestScheduler`.
///
/// The returned `Task` represents the dedicated work: dropping it cancels
/// the dedicated closure, `.await`ing it yields the closure's return
/// value, `.detach()`ing it lets the dedicated work run independently of
/// the caller.
#[track_caller]
pub fn spawn_dedicated<F, Fut>(&self, f: F) -> Task<Fut::Output>
where
F: FnOnce(LocalExecutor) -> Fut + Send + 'static,
Fut: Future + 'static,
Fut::Output: Send + Sync + 'static,
{
self.scheduler
.clone()
.spawn_dedicated(box_dedicated(f))
.downcast::<Fut::Output>()
}
}
/// Boxes the user-supplied dedicated closure into the type-erased shape
/// expected by [`Scheduler::spawn_dedicated`]. The user's `Fut::Output` is
/// boxed as `Box<dyn Any + Send + Sync>` on the dedicated side and downcast
/// back to `Fut::Output` by [`Task::downcast`] in the wrapper.
fn box_dedicated<F, Fut>(f: F) -> DedicatedFn
where
F: FnOnce(LocalExecutor) -> Fut + Send + 'static,
Fut: Future + 'static,
Fut::Output: Send + Sync + 'static,
{
Box::new(move |executor| {
Box::pin(async move { Box::new(f(executor).await) as Box<dyn Any + Send + Sync> })
})
}
#[derive(Clone)]
pub struct BackgroundExecutor {
scheduler: Arc<dyn Scheduler>,
}
impl BackgroundExecutor {
pub fn new(scheduler: Arc<dyn Scheduler>) -> Self {
Self { scheduler }
}
#[track_caller]
pub fn spawn<F>(&self, future: F) -> Task<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
self.spawn_with_priority(Priority::default(), future)
}
#[track_caller]
pub fn spawn_with_priority<F>(&self, priority: Priority, future: F) -> Task<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let scheduler = Arc::downgrade(&self.scheduler);
let location = Location::caller();
let (runnable, task) = async_task::Builder::new()
.metadata(RunnableMeta { location })
.spawn(
move |_| future,
move |runnable| {
if let Some(scheduler) = scheduler.upgrade() {
scheduler.schedule_background_with_priority(runnable, priority);
}
},
);
runnable.schedule();
Task(TaskState::Spawned(task))
}
/// Spawns a future on a dedicated realtime thread for audio processing.
#[track_caller]
pub fn spawn_realtime<F>(&self, future: F) -> Task<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let location = Location::caller();
let (tx, rx) = flume::bounded::<async_task::Runnable<RunnableMeta>>(1);
self.scheduler.spawn_realtime(Box::new(move || {
while let Ok(runnable) = rx.recv() {
runnable.run();
}
}));
let (runnable, task) = async_task::Builder::new()
.metadata(RunnableMeta { location })
.spawn(
move |_| future,
move |runnable| {
let _ = tx.send(runnable);
},
);
runnable.schedule();
Task(TaskState::Spawned(task))
}
#[track_caller]
pub fn timer(&self, duration: Duration) -> Timer {
self.scheduler.timer(duration)
}
pub fn now(&self) -> Instant {
self.scheduler.clock().now()
}
pub fn scheduler(&self) -> &Arc<dyn Scheduler> {
&self.scheduler
}
/// Spawn a closure on a fresh session pinned to its own [`LocalExecutor`].
/// The closure runs on a new OS thread under `PlatformScheduler`, or on
/// the test scheduler's loop under `TestScheduler`.
///
/// The returned `Task` represents the dedicated work: dropping it cancels
/// the dedicated closure, `.await`ing it yields the closure's return
/// value, `.detach()`ing it lets the dedicated work run independently of
/// the caller.
#[track_caller]
pub fn spawn_dedicated<F, Fut>(&self, f: F) -> Task<Fut::Output>
where
F: FnOnce(LocalExecutor) -> Fut + Send + 'static,
Fut: Future + 'static,
Fut::Output: Send + Sync + 'static,
{
self.scheduler
.clone()
.spawn_dedicated(box_dedicated(f))
.downcast::<Fut::Output>()
}
}
/// Task is a primitive that allows work to happen in the background.
///
/// It implements [`Future`] so you can `.await` on it.
///
/// If you drop a task it will be cancelled immediately. Calling [`Task::detach`] allows
/// the task to continue running, but with no way to return a value.
#[must_use]
pub struct Task<T>(TaskState<T>);
enum TaskState<T> {
/// A task that is ready to return a value
Ready(Option<T>),
/// A task that is currently running.
Spawned(async_task::Task<T, RunnableMeta>),
/// A typed view of a [`Task<Box<dyn Any + Send + Sync>>`] obtained via
/// [`Task::downcast`]. The inner task drives the actual work; the
/// downcast layer just unwraps the `Box<dyn Any + Send + Sync>` on poll.
Downcast {
inner: Box<Task<Box<dyn Any + Send + Sync>>>,
marker: PhantomData<fn() -> T>,
},
}
impl<T> Task<T> {
/// Creates a new task that will resolve with the value
pub fn ready(val: T) -> Self {
Task(TaskState::Ready(Some(val)))
}
/// Creates a Task from an async_task::Task
pub fn from_async_task(task: async_task::Task<T, RunnableMeta>) -> Self {
Task(TaskState::Spawned(task))
}
pub fn is_ready(&self) -> bool {
match &self.0 {
TaskState::Ready(_) => true,
TaskState::Spawned(task) => task.is_finished(),
TaskState::Downcast { inner, .. } => inner.is_ready(),
}
}
/// Detaching a task runs it to completion in the background
pub fn detach(self) {
match self {
Task(TaskState::Ready(_)) => {}
Task(TaskState::Spawned(task)) => task.detach(),
Task(TaskState::Downcast { inner, .. }) => inner.detach(),
}
}
/// Converts this task into a fallible task that returns `Option<T>`.
pub fn fallible(self) -> FallibleTask<T> {
FallibleTask(match self.0 {
TaskState::Ready(val) => FallibleTaskState::Ready(val),
TaskState::Spawned(task) => FallibleTaskState::Spawned(task.fallible()),
TaskState::Downcast { inner, .. } => FallibleTaskState::Downcast {
inner: Box::new(inner.fallible()),
marker: PhantomData,
},
})
}
}
impl Task<Box<dyn Any + Send + Sync>> {
/// Reinterprets the boxed output as a concrete `T` via downcast on
/// completion. Used by [`LocalExecutor::spawn_dedicated`] and
/// [`BackgroundExecutor::spawn_dedicated`] to recover the user closure's
/// `Fut::Output` from the dyn-safe [`Scheduler::spawn_dedicated`].
///
/// Panics on poll if the inner output is not in fact a `T` -- a logic
/// error in whatever produced the inner task, since the downcast type is
/// chosen by the caller of `downcast`.
pub fn downcast<T: Send + Sync + 'static>(self) -> Task<T> {
Task(TaskState::Downcast {
inner: Box::new(self),
marker: PhantomData,
})
}
}
impl<T> std::fmt::Debug for Task<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
TaskState::Ready(_) => f.debug_tuple("Task::Ready").finish(),
TaskState::Spawned(task) => f.debug_tuple("Task::Spawned").field(task).finish(),
TaskState::Downcast { inner, .. } => {
f.debug_tuple("Task::Downcast").field(inner).finish()
}
}
}
}
/// A task that returns `Option<T>` instead of panicking when cancelled.
#[must_use]
pub struct FallibleTask<T>(FallibleTaskState<T>);
enum FallibleTaskState<T> {
/// A task that is ready to return a value
Ready(Option<T>),
/// A task that is currently running (wraps async_task::FallibleTask).
Spawned(async_task::FallibleTask<T, RunnableMeta>),
/// Mirror of [`TaskState::Downcast`] for fallible tasks.
Downcast {
inner: Box<FallibleTask<Box<dyn Any + Send + Sync>>>,
marker: PhantomData<fn() -> T>,
},
}
impl<T> FallibleTask<T> {
/// Creates a new fallible task that will resolve with the value.
pub fn ready(val: T) -> Self {
FallibleTask(FallibleTaskState::Ready(Some(val)))
}
/// Detaching a task runs it to completion in the background.
pub fn detach(self) {
match self.0 {
FallibleTaskState::Ready(_) => {}
FallibleTaskState::Spawned(task) => task.detach(),
FallibleTaskState::Downcast { inner, .. } => inner.detach(),
}
}
}
impl<T: 'static> Future for FallibleTask<T> {
type Output = Option<T>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
match unsafe { self.get_unchecked_mut() } {
FallibleTask(FallibleTaskState::Ready(val)) => Poll::Ready(val.take()),
FallibleTask(FallibleTaskState::Spawned(task)) => Pin::new(task).poll(cx),
FallibleTask(FallibleTaskState::Downcast { inner, .. }) => {
match Pin::new(inner.as_mut()).poll(cx) {
Poll::Ready(Some(boxed_any)) => Poll::Ready(Some(
*boxed_any
.downcast::<T>()
.expect("FallibleTask::poll: downcast type mismatch"),
)),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
}
}
impl<T> std::fmt::Debug for FallibleTask<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
FallibleTaskState::Ready(_) => f.debug_tuple("FallibleTask::Ready").finish(),
FallibleTaskState::Spawned(task) => {
f.debug_tuple("FallibleTask::Spawned").field(task).finish()
}
FallibleTaskState::Downcast { inner, .. } => f
.debug_tuple("FallibleTask::Downcast")
.field(inner)
.finish(),
}
}
}
impl<T: 'static> Future for Task<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
match unsafe { self.get_unchecked_mut() } {
Task(TaskState::Ready(val)) => Poll::Ready(val.take().unwrap()),
Task(TaskState::Spawned(task)) => Pin::new(task).poll(cx),
Task(TaskState::Downcast { inner, .. }) => match Pin::new(inner.as_mut()).poll(cx) {
Poll::Ready(boxed_any) => Poll::Ready(
*boxed_any
.downcast::<T>()
.expect("Task::poll: downcast type mismatch"),
),
Poll::Pending => Poll::Pending,
},
}
}
}
/// Variant of `async_task::spawn_local` that includes the source location of the spawn in panics.
#[track_caller]
fn spawn_local_with_source_location<Fut, S>(
future: Fut,
schedule: S,
metadata: RunnableMeta,
) -> (
async_task::Runnable<RunnableMeta>,
async_task::Task<Fut::Output, RunnableMeta>,
)
where
Fut: Future + 'static,
Fut::Output: 'static,
S: async_task::Schedule<RunnableMeta> + Send + Sync + 'static,
{
#[inline]
fn thread_id() -> ThreadId {
std::thread_local! {
static ID: ThreadId = thread::current().id();
}
ID.try_with(|id| *id)
.unwrap_or_else(|_| thread::current().id())
}
struct Checked<F> {
id: ThreadId,
inner: ManuallyDrop<F>,
location: &'static Location<'static>,
}
impl<F> Drop for Checked<F> {
fn drop(&mut self) {
assert_eq!(
self.id,
thread_id(),
"local task dropped by a thread that didn't spawn it. Task spawned at {}",
self.location
);
// SAFETY: `inner` is wrapped in `ManuallyDrop`, so this is the only
// place it is dropped. The thread check above ensures local futures
// are dropped on the thread that created them.
unsafe { ManuallyDrop::drop(&mut self.inner) };
}
}
impl<F: Future> Future for Checked<F> {
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
// SAFETY: We don't move any fields out of `self`; this mutable
// reference is only used to check metadata and to project the pin to
// `inner` below.
let this = unsafe { self.get_unchecked_mut() };
assert!(
this.id == thread_id(),
"local task polled by a thread that didn't spawn it. Task spawned at {}",
this.location
);
// SAFETY: `inner` is structurally pinned by `Checked`; after
// `Checked` is pinned, `inner` is never moved. The thread check
// above ensures the local future is only polled by its spawning
// thread.
unsafe { Pin::new_unchecked(&mut *this.inner).poll(cx) }
}
}
let location = metadata.location;
let future = move |_| Checked {
id: thread_id(),
inner: ManuallyDrop::new(future),
location,
};
let builder = async_task::Builder::new().metadata(metadata);
// SAFETY: `Checked` enforces the invariants required by `spawn_unchecked`:
// the non-`Send` future is only polled and dropped on the thread that
// spawned it.
unsafe { builder.spawn_unchecked(future, schedule) }
}
+209
View File
@@ -0,0 +1,209 @@
mod clock;
mod executor;
mod test_scheduler;
#[cfg(test)]
mod tests;
pub use clock::*;
pub use executor::*;
pub use test_scheduler::*;
use async_task::Runnable;
use futures::channel::oneshot;
use std::{
any::Any,
future::Future,
panic::Location,
pin::Pin,
sync::Arc,
task::{Context, Poll},
thread,
time::Duration,
};
/// Task priority for background tasks.
///
/// Higher priority tasks are more likely to be scheduled before lower priority tasks,
/// but this is not a strict guarantee - the scheduler may interleave tasks of different
/// priorities to prevent starvation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Priority {
/// Realtime priority
///
/// Spawning a task with this priority will spin it off on a separate thread dedicated just to that task. Only use for audio.
RealtimeAudio,
/// High priority - use for tasks critical to user experience/responsiveness.
High,
/// Medium priority - suitable for most use cases.
#[default]
Medium,
/// Low priority - use for background work that can be deprioritized.
Low,
}
impl Priority {
/// Returns the relative probability weight for this priority level.
/// Used by schedulers to determine task selection probability.
pub const fn weight(self) -> u32 {
match self {
Priority::High => 60,
Priority::Medium => 30,
Priority::Low => 10,
// realtime priorities are not considered for probability scheduling
Priority::RealtimeAudio => 0,
}
}
}
/// Metadata attached to runnables for debugging and profiling.
#[derive(Clone)]
pub struct RunnableMeta {
/// The source location where the task was spawned.
pub location: &'static Location<'static>,
}
impl std::fmt::Debug for RunnableMeta {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RunnableMeta")
.field("location", &self.location)
.finish()
}
}
pub trait Scheduler: Send + Sync {
/// Block until the given future completes or timeout occurs.
///
/// Returns `true` if the future completed, `false` if it timed out.
/// The future is passed as a pinned mutable reference so the caller
/// retains ownership and can continue polling or return it on timeout.
fn block(
&self,
session_id: Option<SessionId>,
future: Pin<&mut dyn Future<Output = ()>>,
timeout: Option<Duration>,
) -> bool;
/// Schedule a runnable on the local (session-pinned) queue for `session_id`.
/// Runnables scheduled here run in order on whichever thread drains the
/// session — the main thread for ordinary sessions, or a dedicated OS
/// thread for sessions created via `spawn_dedicated_thread`.
fn schedule_local(&self, session_id: SessionId, runnable: Runnable<RunnableMeta>);
/// Schedule a background task with the given priority.
fn schedule_background_with_priority(
&self,
runnable: Runnable<RunnableMeta>,
priority: Priority,
);
/// Spawn a closure on a dedicated realtime thread for audio processing.
fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
/// Schedule a background task with default (medium) priority.
fn schedule_background(&self, runnable: Runnable<RunnableMeta>) {
self.schedule_background_with_priority(runnable, Priority::default());
}
#[track_caller]
fn timer(&self, timeout: Duration) -> Timer;
fn clock(&self) -> Arc<dyn Clock>;
/// Spawn a closure on a fresh session pinned to its own [`LocalExecutor`].
///
/// `PlatformScheduler` runs the closure on a new OS thread (see
/// [`spawn_dedicated_thread`]). `TestScheduler` runs it on the test
/// scheduler's loop alongside everything else so determinism under
/// `TestScheduler::many` is preserved.
///
/// This is the dyn-safe entry point: the closure's output is type-erased
/// as `Box<dyn Any + Send + Sync>` so the trait stays object-safe.
/// Callers typically reach for the type-safe wrappers on
/// [`LocalExecutor::spawn_dedicated`] and
/// [`BackgroundExecutor::spawn_dedicated`], which compose this method
/// with [`Task::downcast`] to recover the closure's concrete return type.
fn spawn_dedicated(self: Arc<Self>, f: DedicatedFn) -> Task<Box<dyn Any + Send + Sync>>;
fn as_test(&self) -> Option<&TestScheduler> {
None
}
}
/// Spawn work on a fresh OS thread that's exclusive to the returned task and
/// anything spawned on the executor it provides. Blocking syscalls inside that
/// work don't disturb any other executor in the process.
///
/// `f` is called on the dedicated thread with a [`LocalExecutor`] pinned
/// to it. The future `f` returns may freely be `!Send`. The returned `Task` is
/// that future's task: dropping it cancels the root, but detached children
/// keep running until they finish. The thread shuts down once the executor and
/// every task on it are gone.
///
/// The caller is responsible for supplying a `session_id` that's distinct from
/// every other live session on `scheduler`. Concrete schedulers typically wrap
/// this in an inherent method that allocates the id from their own counter.
pub fn spawn_dedicated_thread<F, Fut>(
session_id: SessionId,
scheduler: Arc<dyn Scheduler>,
f: F,
) -> Task<Fut::Output>
where
F: FnOnce(LocalExecutor) -> Fut + Send + 'static,
Fut: Future + 'static,
Fut::Output: Send + 'static,
{
let (runnable_sender, runnable_receiver) = flume::unbounded::<Runnable<RunnableMeta>>();
let (task_sender, task_receiver) = flume::bounded::<Task<Fut::Output>>(1);
thread::Builder::new()
.name(format!("spawn_dedicated session {:?}", session_id))
.spawn(move || {
let dispatch = move |runnable: Runnable<RunnableMeta>| {
let _ = runnable_sender.send(runnable);
};
let executor = LocalExecutor::new(session_id, scheduler, dispatch);
let root_task = executor.spawn(f(executor.clone()));
let _ = task_sender.send(root_task);
// After this drop, every strong reference to the runnable sender
// lives inside a spawned task or a user-held executor clone. The
// recv loop exits once all of those are gone.
drop(executor);
while let Ok(runnable) = runnable_receiver.recv() {
runnable.run();
}
})
.expect("failed to spawn dedicated thread");
task_receiver
.recv()
.expect("dedicated thread failed to produce root task")
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SessionId(u16);
impl SessionId {
pub fn new(id: u16) -> Self {
SessionId(id)
}
}
pub struct Timer(oneshot::Receiver<()>);
impl Timer {
pub fn new(rx: oneshot::Receiver<()>) -> Self {
Timer(rx)
}
}
impl Future for Timer {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
match Pin::new(&mut self.0).poll(cx) {
Poll::Ready(_) => Poll::Ready(()),
Poll::Pending => Poll::Pending,
}
}
}
+926
View File
@@ -0,0 +1,926 @@
use crate::{
BackgroundExecutor, Clock, Instant, LocalExecutor, Priority, RunnableMeta, Scheduler,
SessionId, Task, TestClock, Timer,
};
use async_task::Runnable;
use backtrace::{Backtrace, BacktraceFrame};
use futures::channel::oneshot;
use parking_lot::{Mutex, MutexGuard};
use rand::{
distr::{StandardUniform, uniform::SampleRange, uniform::SampleUniform},
prelude::*,
};
use std::any::Any;
use std::{
any::type_name_of_val,
collections::{BTreeMap, HashSet, VecDeque},
env,
fmt::Write,
future::Future,
mem,
ops::RangeInclusive,
panic::{self, AssertUnwindSafe},
pin::Pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering::SeqCst},
},
task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
thread::{self, Thread},
time::Duration,
};
const PENDING_TRACES_VAR_NAME: &str = "PENDING_TRACES";
pub struct TestScheduler {
clock: Arc<TestClock>,
rng: Arc<Mutex<StdRng>>,
state: Arc<Mutex<SchedulerState>>,
thread: Thread,
}
impl TestScheduler {
/// Run a test once with default configuration (seed 0)
pub fn once<R>(f: impl AsyncFnOnce(Arc<TestScheduler>) -> R) -> R {
Self::with_seed(0, f)
}
/// Run a test multiple times with sequential seeds (0, 1, 2, ...)
pub fn many<R>(
default_iterations: usize,
mut f: impl AsyncFnMut(Arc<TestScheduler>) -> R,
) -> Vec<R> {
let num_iterations = std::env::var("ITERATIONS")
.map(|iterations| iterations.parse().unwrap())
.unwrap_or(default_iterations);
let seed = std::env::var("SEED")
.map(|seed| seed.parse().unwrap())
.unwrap_or(0);
let interactive = !std::env::var("SCHEDULER_NONINTERACTIVE").is_ok();
(seed..seed + num_iterations as u64)
.map(|seed| {
let mut unwind_safe_f = AssertUnwindSafe(&mut f);
if interactive {
eprintln!("Running seed: {seed}");
}
match panic::catch_unwind(move || Self::with_seed(seed, &mut *unwind_safe_f)) {
Ok(result) => result,
Err(error) => {
eprintln!("\x1b[31mFailing Seed: {seed}\x1b[0m");
panic::resume_unwind(error);
}
}
})
.collect()
}
fn with_seed<R>(seed: u64, f: impl AsyncFnOnce(Arc<TestScheduler>) -> R) -> R {
let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::with_seed(seed)));
let future = f(scheduler.clone());
let result = scheduler.foreground().block_on(future);
scheduler.run(); // Ensure spawned tasks finish up before returning in tests
result
}
pub fn new(config: TestSchedulerConfig) -> Self {
Self {
rng: Arc::new(Mutex::new(StdRng::seed_from_u64(config.seed))),
state: Arc::new(Mutex::new(SchedulerState {
runnables: VecDeque::new(),
timers: Vec::new(),
blocked_sessions: Vec::new(),
randomize_order: config.randomize_order,
allow_parking: config.allow_parking,
timeout_ticks: config.timeout_ticks,
next_session_id: SessionId(0),
capture_pending_traces: config.capture_pending_traces,
pending_traces: BTreeMap::new(),
next_trace_id: TraceId(0),
is_main_thread: true,
non_determinism_error: None,
finished: false,
parking_allowed_once: false,
unparked: false,
})),
clock: Arc::new(TestClock::new()),
thread: thread::current(),
}
}
pub fn end_test(&self) {
let mut state = self.state.lock();
if let Some((message, backtrace)) = &state.non_determinism_error {
if cfg!(miri) {
// miri cannot debug print backtraces with `miri-disable-isolation` enabled
panic!("{}", message)
} else {
panic!("{}\n{:?}", message, backtrace)
}
}
state.finished = true;
}
pub fn clock(&self) -> Arc<TestClock> {
self.clock.clone()
}
pub fn rng(&self) -> SharedRng {
SharedRng(self.rng.clone())
}
pub fn set_timeout_ticks(&self, timeout_ticks: RangeInclusive<usize>) {
self.state.lock().timeout_ticks = timeout_ticks;
}
pub fn allow_parking(&self) {
let mut state = self.state.lock();
state.allow_parking = true;
state.parking_allowed_once = true;
}
pub fn forbid_parking(&self) {
self.state.lock().allow_parking = false;
}
pub fn parking_allowed(&self) -> bool {
self.state.lock().allow_parking
}
pub fn is_main_thread(&self) -> bool {
self.state.lock().is_main_thread
}
pub fn allocate_session_id(&self) -> SessionId {
let mut state = self.state.lock();
state.next_session_id.0 += 1;
state.next_session_id
}
/// Create a local executor for this scheduler.
pub fn foreground(self: &Arc<Self>) -> LocalExecutor {
let session_id = self.allocate_session_id();
let scheduler = Arc::downgrade(self);
LocalExecutor::new(session_id, self.clone(), move |runnable| {
if let Some(scheduler) = scheduler.upgrade() {
scheduler.schedule_local(session_id, runnable);
}
})
}
/// Create a background executor for this scheduler
pub fn background(self: &Arc<Self>) -> BackgroundExecutor {
BackgroundExecutor::new(self.clone())
}
pub fn yield_random(&self) -> Yield {
let rng = &mut *self.rng.lock();
if rng.random_bool(0.1) {
Yield(rng.random_range(10..20))
} else {
Yield(rng.random_range(0..2))
}
}
pub fn run(&self) {
while self.step() {
// Continue until no work remains
}
}
pub fn run_with_clock_advancement(&self) {
while self.step() || self.advance_clock_to_next_timer() {
// Continue until no work remains
}
}
/// Execute one tick of the scheduler, processing expired timers and running
/// at most one task. Returns true if any work was done.
///
/// This is the public interface for GPUI's TestDispatcher to drive task execution.
pub fn tick(&self) -> bool {
self.step_filtered(false)
}
/// Execute one tick, but only run background tasks (no foreground/session tasks).
/// Returns true if any work was done.
pub fn tick_background_only(&self) -> bool {
self.step_filtered(true)
}
/// Check if there are any pending tasks or timers that could run.
pub fn has_pending_tasks(&self) -> bool {
let state = self.state.lock();
!state.runnables.is_empty() || !state.timers.is_empty()
}
/// Returns counts of (foreground_tasks, background_tasks) currently queued.
/// Foreground tasks are those with a session_id, background tasks have none.
pub fn pending_task_counts(&self) -> (usize, usize) {
let state = self.state.lock();
let foreground = state
.runnables
.iter()
.filter(|r| r.session_id.is_some())
.count();
let background = state
.runnables
.iter()
.filter(|r| r.session_id.is_none())
.count();
(foreground, background)
}
fn step(&self) -> bool {
self.step_filtered(false)
}
fn step_filtered(&self, background_only: bool) -> bool {
let (elapsed_count, runnables_before) = {
let mut state = self.state.lock();
let end_ix = state
.timers
.partition_point(|timer| timer.expiration <= self.clock.now());
let elapsed: Vec<_> = state.timers.drain(..end_ix).collect();
let count = elapsed.len();
let runnables = state.runnables.len();
drop(state);
// Dropping elapsed timers here wakes the waiting futures
drop(elapsed);
(count, runnables)
};
if elapsed_count > 0 {
let runnables_after = self.state.lock().runnables.len();
if std::env::var("DEBUG_SCHEDULER").is_ok() {
eprintln!(
"[scheduler] Expired {} timers at {:?}, runnables: {} -> {}",
elapsed_count,
self.clock.now(),
runnables_before,
runnables_after
);
}
return true;
}
let runnable = {
let state = &mut *self.state.lock();
// Find candidate tasks:
// - For foreground tasks (with session_id), only the first task from each session
// is a candidate (to preserve intra-session ordering)
// - For background tasks (no session_id), all are candidates
// - Tasks from blocked sessions are excluded
// - If background_only is true, skip foreground tasks entirely
let mut seen_sessions = HashSet::new();
let candidate_indices: Vec<usize> = state
.runnables
.iter()
.enumerate()
.filter(|(_, runnable)| {
if let Some(session_id) = runnable.session_id {
// Skip foreground tasks if background_only mode
if background_only {
return false;
}
// Exclude tasks from blocked sessions
if state.blocked_sessions.contains(&session_id) {
return false;
}
// Only include first task from each session (insert returns true if new)
seen_sessions.insert(session_id)
} else {
// Background tasks are always candidates
true
}
})
.map(|(ix, _)| ix)
.collect();
if candidate_indices.is_empty() {
None
} else if state.randomize_order {
// Use priority-weighted random selection
let weights: Vec<u32> = candidate_indices
.iter()
.map(|&ix| state.runnables[ix].priority.weight())
.collect();
let total_weight: u32 = weights.iter().sum();
if total_weight == 0 {
// Fallback to uniform random if all weights are zero
let choice = self.rng.lock().random_range(0..candidate_indices.len());
state.runnables.remove(candidate_indices[choice])
} else {
let mut target = self.rng.lock().random_range(0..total_weight);
let mut selected_idx = 0;
for (i, &weight) in weights.iter().enumerate() {
if target < weight {
selected_idx = i;
break;
}
target -= weight;
}
state.runnables.remove(candidate_indices[selected_idx])
}
} else {
// Non-randomized: just take the first candidate task
state.runnables.remove(candidate_indices[0])
}
};
if let Some(runnable) = runnable {
let is_foreground = runnable.session_id.is_some();
let was_main_thread = self.state.lock().is_main_thread;
self.state.lock().is_main_thread = is_foreground;
runnable.run();
self.state.lock().is_main_thread = was_main_thread;
return true;
}
false
}
/// Drops all runnable tasks from the scheduler.
///
/// This is used by the leak detector to ensure that all tasks have been dropped as tasks may keep entities alive otherwise.
/// Why do we even have tasks left when tests finish you may ask. The reason for that is simple, the scheduler itself is the executor and it retains the scheduled runnables.
/// A lot of tasks, including every foreground task contain an executor handle that keeps the test scheduler alive, causing a reference cycle, thus the need for this function right now.
pub fn drain_tasks(&self) {
// dropping runnables may reschedule tasks
// due to drop impls with executors in them
// so drop until we reach a fixpoint
loop {
let mut state = self.state.lock();
if state.runnables.is_empty() && state.timers.is_empty() {
break;
}
let runnables = std::mem::take(&mut state.runnables);
let timers = std::mem::take(&mut state.timers);
drop(state);
drop(timers);
drop(runnables);
}
}
pub fn advance_clock_to_next_timer(&self) -> bool {
if let Some(timer) = self.state.lock().timers.first() {
self.clock.advance(timer.expiration - self.clock.now());
true
} else {
false
}
}
pub fn advance_clock(&self, duration: Duration) {
let debug = std::env::var("DEBUG_SCHEDULER").is_ok();
let start = self.clock.now();
let next_now = start + duration;
if debug {
let timer_count = self.state.lock().timers.len();
eprintln!(
"[scheduler] advance_clock({:?}) from {:?}, {} pending timers",
duration, start, timer_count
);
}
loop {
self.run();
if let Some(timer) = self.state.lock().timers.first()
&& timer.expiration <= next_now
{
let advance_to = timer.expiration;
if debug {
eprintln!(
"[scheduler] Advancing clock {:?} -> {:?} for timer",
self.clock.now(),
advance_to
);
}
self.clock.advance(advance_to - self.clock.now());
} else {
break;
}
}
self.clock.advance(next_now - self.clock.now());
if debug {
eprintln!(
"[scheduler] advance_clock done, now at {:?}",
self.clock.now()
);
}
}
fn park(&self, deadline: Option<Instant>) -> bool {
if self.state.lock().allow_parking {
let start = Instant::now();
// Enforce a hard timeout to prevent tests from hanging indefinitely
let hard_deadline = start + Duration::from_secs(15);
// Use the earlier of the provided deadline or the hard timeout deadline
let effective_deadline = deadline
.map(|d| d.min(hard_deadline))
.unwrap_or(hard_deadline);
// Park in small intervals to allow checking both deadlines
const PARK_INTERVAL: Duration = Duration::from_millis(100);
loop {
let now = Instant::now();
if now >= effective_deadline {
// Check if we hit the hard timeout
if now >= hard_deadline {
panic!(
"Test timed out after 15 seconds while parking. \
This may indicate a deadlock or missing waker.",
);
}
// Hit the provided deadline
return false;
}
let remaining = effective_deadline.saturating_duration_since(now);
let park_duration = remaining.min(PARK_INTERVAL);
let before_park = Instant::now();
thread::park_timeout(park_duration);
let elapsed = before_park.elapsed();
// Advance the test clock by the real elapsed time while parking
self.clock.advance(elapsed);
// Check if any timers have expired after advancing the clock.
// If so, return so the caller can process them.
if self
.state
.lock()
.timers
.first()
.is_some_and(|t| t.expiration <= self.clock.now())
{
return true;
}
// Check if we were woken up by a different thread.
// We use a flag because timing-based detection is unreliable:
// OS scheduling delays can cause elapsed >= park_duration even when
// we were woken early by unpark().
if std::mem::take(&mut self.state.lock().unparked) {
return true;
}
}
} else if deadline.is_some() {
false
} else if cfg!(miri) {
// miri cannot debug print backtraces with `miri-disable-isolation` enabled
panic!("Parking forbidden.");
} else if self.state.lock().capture_pending_traces {
let mut pending_traces = String::new();
for (_, trace) in mem::take(&mut self.state.lock().pending_traces) {
writeln!(pending_traces, "{:?}", exclude_wakers_from_trace(trace)).unwrap();
}
panic!("Parking forbidden. Pending traces:\n{}", pending_traces);
} else {
panic!(
"Parking forbidden. Re-run with {PENDING_TRACES_VAR_NAME}=1 to show pending traces"
);
}
}
}
fn assert_correct_thread(expected: &Thread, state: &Arc<Mutex<SchedulerState>>) {
let current_thread = thread::current();
let mut state = state.lock();
if state.parking_allowed_once {
return;
}
if current_thread.id() == expected.id() {
return;
}
let message = format!(
"Detected activity on thread {:?} {:?}, but test scheduler is running on {:?} {:?}. Your test is not deterministic.",
current_thread.name(),
current_thread.id(),
expected.name(),
expected.id(),
);
let backtrace = Backtrace::new();
if state.finished {
panic!("{}", message);
} else {
state.non_determinism_error = Some((message, backtrace))
}
}
impl Scheduler for TestScheduler {
/// Block until the given future completes, with an optional timeout. If the
/// future is unable to make progress at any moment before the timeout and
/// no other tasks or timers remain, we panic unless parking is allowed. If
/// parking is allowed, we block up to the timeout or indefinitely if none
/// is provided. This is to allow testing a mix of deterministic and
/// non-deterministic async behavior, such as when interacting with I/O in
/// an otherwise deterministic test.
fn block(
&self,
session_id: Option<SessionId>,
mut future: Pin<&mut dyn Future<Output = ()>>,
timeout: Option<Duration>,
) -> bool {
if let Some(session_id) = session_id {
self.state.lock().blocked_sessions.push(session_id);
}
let deadline = timeout.map(|timeout| Instant::now() + timeout);
let awoken = Arc::new(AtomicBool::new(false));
let waker = Box::new(TracingWaker {
id: None,
awoken: awoken.clone(),
thread: self.thread.clone(),
state: self.state.clone(),
});
let waker = unsafe { Waker::new(Box::into_raw(waker) as *const (), &WAKER_VTABLE) };
let max_ticks = if timeout.is_some() {
self.rng
.lock()
.random_range(self.state.lock().timeout_ticks.clone())
} else {
usize::MAX
};
let mut cx = Context::from_waker(&waker);
let mut completed = false;
for _ in 0..max_ticks {
match future.as_mut().poll(&mut cx) {
Poll::Ready(()) => {
completed = true;
break;
}
Poll::Pending => {}
}
let mut stepped = None;
while self.rng.lock().random() {
let stepped = stepped.get_or_insert(false);
if self.step() {
*stepped = true;
} else {
break;
}
}
let stepped = stepped.unwrap_or(true);
let awoken = awoken.swap(false, SeqCst);
if !stepped && !awoken {
let parking_allowed = self.state.lock().allow_parking;
// In deterministic mode (parking forbidden), instantly jump to the next timer.
// In non-deterministic mode (parking allowed), let real time pass instead.
let advanced_to_timer = !parking_allowed && self.advance_clock_to_next_timer();
if !advanced_to_timer && !self.park(deadline) {
break;
}
}
}
if session_id.is_some() {
self.state.lock().blocked_sessions.pop();
}
completed
}
fn schedule_local(&self, session_id: SessionId, runnable: Runnable<RunnableMeta>) {
assert_correct_thread(&self.thread, &self.state);
let mut state = self.state.lock();
let ix = if state.randomize_order {
let start_ix = state
.runnables
.iter()
.rposition(|task| task.session_id == Some(session_id))
.map_or(0, |ix| ix + 1);
self.rng
.lock()
.random_range(start_ix..=state.runnables.len())
} else {
state.runnables.len()
};
state.runnables.insert(
ix,
ScheduledRunnable {
session_id: Some(session_id),
priority: Priority::default(),
runnable,
},
);
state.unparked = true;
drop(state);
self.thread.unpark();
}
fn schedule_background_with_priority(
&self,
runnable: Runnable<RunnableMeta>,
priority: Priority,
) {
assert_correct_thread(&self.thread, &self.state);
let mut state = self.state.lock();
let ix = if state.randomize_order {
self.rng.lock().random_range(0..=state.runnables.len())
} else {
state.runnables.len()
};
state.runnables.insert(
ix,
ScheduledRunnable {
session_id: None,
priority,
runnable,
},
);
state.unparked = true;
drop(state);
self.thread.unpark();
}
fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>) {
std::thread::spawn(move || {
f();
});
}
#[track_caller]
fn timer(&self, duration: Duration) -> Timer {
let (tx, rx) = oneshot::channel();
let state = &mut *self.state.lock();
state.timers.push(ScheduledTimer {
expiration: self.clock.now() + duration,
_notify: tx,
});
state.timers.sort_by_key(|timer| timer.expiration);
Timer(rx)
}
fn clock(&self) -> Arc<dyn Clock> {
self.clock.clone()
}
/// In the test world, dedicated work is just a fresh local session driven
/// by the test scheduler's run loop alongside everything else. No real
/// thread is spawned, so determinism under `TestScheduler::many` is
/// preserved.
fn spawn_dedicated(
self: Arc<Self>,
f: Box<
dyn FnOnce(
LocalExecutor,
)
-> Pin<Box<dyn Future<Output = Box<dyn Any + Send + Sync>> + 'static>>
+ Send
+ 'static,
>,
) -> Task<Box<dyn Any + Send + Sync>> {
let session_id = self.allocate_session_id();
let scheduler = Arc::downgrade(&self);
let executor = LocalExecutor::new(session_id, self, move |runnable| {
if let Some(scheduler) = scheduler.upgrade() {
scheduler.schedule_local(session_id, runnable);
}
});
executor.spawn(f(executor.clone()))
}
fn as_test(&self) -> Option<&TestScheduler> {
Some(self)
}
}
#[derive(Clone, Debug)]
pub struct TestSchedulerConfig {
pub seed: u64,
pub randomize_order: bool,
pub allow_parking: bool,
pub capture_pending_traces: bool,
pub timeout_ticks: RangeInclusive<usize>,
}
impl TestSchedulerConfig {
pub fn with_seed(seed: u64) -> Self {
Self {
seed,
..Default::default()
}
}
}
impl Default for TestSchedulerConfig {
fn default() -> Self {
Self {
seed: 0,
randomize_order: true,
allow_parking: false,
capture_pending_traces: env::var(PENDING_TRACES_VAR_NAME)
.is_ok_and(|var| var == "1" || var == "true"),
timeout_ticks: 1..=1000,
}
}
}
struct ScheduledRunnable {
session_id: Option<SessionId>,
priority: Priority,
runnable: Runnable<RunnableMeta>,
}
impl ScheduledRunnable {
fn run(self) {
self.runnable.run();
}
}
struct ScheduledTimer {
expiration: Instant,
_notify: oneshot::Sender<()>,
}
struct SchedulerState {
runnables: VecDeque<ScheduledRunnable>,
timers: Vec<ScheduledTimer>,
blocked_sessions: Vec<SessionId>,
randomize_order: bool,
allow_parking: bool,
timeout_ticks: RangeInclusive<usize>,
next_session_id: SessionId,
capture_pending_traces: bool,
next_trace_id: TraceId,
pending_traces: BTreeMap<TraceId, Backtrace>,
is_main_thread: bool,
non_determinism_error: Option<(String, Backtrace)>,
parking_allowed_once: bool,
finished: bool,
unparked: bool,
}
const WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
TracingWaker::clone_raw,
TracingWaker::wake_raw,
TracingWaker::wake_by_ref_raw,
TracingWaker::drop_raw,
);
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
struct TraceId(usize);
struct TracingWaker {
id: Option<TraceId>,
awoken: Arc<AtomicBool>,
thread: Thread,
state: Arc<Mutex<SchedulerState>>,
}
impl Clone for TracingWaker {
fn clone(&self) -> Self {
let mut state = self.state.lock();
let id = if state.capture_pending_traces {
let id = state.next_trace_id;
state.next_trace_id.0 += 1;
state.pending_traces.insert(id, Backtrace::new_unresolved());
Some(id)
} else {
None
};
Self {
id,
awoken: self.awoken.clone(),
thread: self.thread.clone(),
state: self.state.clone(),
}
}
}
impl Drop for TracingWaker {
fn drop(&mut self) {
assert_correct_thread(&self.thread, &self.state);
if let Some(id) = self.id {
self.state.lock().pending_traces.remove(&id);
}
}
}
impl TracingWaker {
fn wake(self) {
self.wake_by_ref();
}
fn wake_by_ref(&self) {
assert_correct_thread(&self.thread, &self.state);
let mut state = self.state.lock();
if let Some(id) = self.id {
state.pending_traces.remove(&id);
}
state.unparked = true;
drop(state);
self.awoken.store(true, SeqCst);
self.thread.unpark();
}
fn clone_raw(waker: *const ()) -> RawWaker {
let waker = waker as *const TracingWaker;
let waker = unsafe { &*waker };
RawWaker::new(
Box::into_raw(Box::new(waker.clone())) as *const (),
&WAKER_VTABLE,
)
}
fn wake_raw(waker: *const ()) {
let waker = unsafe { Box::from_raw(waker as *mut TracingWaker) };
waker.wake();
}
fn wake_by_ref_raw(waker: *const ()) {
let waker = waker as *const TracingWaker;
let waker = unsafe { &*waker };
waker.wake_by_ref();
}
fn drop_raw(waker: *const ()) {
let waker = unsafe { Box::from_raw(waker as *mut TracingWaker) };
drop(waker);
}
}
pub struct Yield(usize);
/// A wrapper around `Arc<Mutex<StdRng>>` that provides convenient methods
/// for random number generation without requiring explicit locking.
#[derive(Clone)]
pub struct SharedRng(Arc<Mutex<StdRng>>);
impl SharedRng {
/// Lock the inner RNG for direct access. Use this when you need multiple
/// random operations without re-locking between each one.
pub fn lock(&self) -> MutexGuard<'_, StdRng> {
self.0.lock()
}
/// Generate a random value in the given range.
pub fn random_range<T, R>(&self, range: R) -> T
where
T: SampleUniform,
R: SampleRange<T>,
{
self.0.lock().random_range(range)
}
/// Generate a random boolean with the given probability of being true.
pub fn random_bool(&self, p: f64) -> bool {
self.0.lock().random_bool(p)
}
/// Generate a random value of the given type.
pub fn random<T>(&self) -> T
where
StandardUniform: Distribution<T>,
{
self.0.lock().random()
}
/// Generate a random ratio - true with probability `numerator/denominator`.
pub fn random_ratio(&self, numerator: u32, denominator: u32) -> bool {
self.0.lock().random_ratio(numerator, denominator)
}
}
impl Future for Yield {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
if self.0 == 0 {
Poll::Ready(())
} else {
self.0 -= 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
fn exclude_wakers_from_trace(mut trace: Backtrace) -> Backtrace {
trace.resolve();
let mut frames: Vec<BacktraceFrame> = trace.into();
let waker_clone_frame_ix = frames.iter().position(|frame| {
frame.symbols().iter().any(|symbol| {
symbol
.name()
.is_some_and(|name| format!("{name:#?}") == type_name_of_val(&Waker::clone))
})
});
if let Some(waker_clone_frame_ix) = waker_clone_frame_ix {
frames.drain(..waker_clone_frame_ix + 1);
}
Backtrace::from(frames)
}
+961
View File
@@ -0,0 +1,961 @@
use super::*;
use futures::{
FutureExt,
channel::{mpsc, oneshot},
executor::block_on,
future,
sink::SinkExt,
stream::{FuturesUnordered, StreamExt},
};
use std::{
cell::RefCell,
collections::{BTreeSet, HashSet},
pin::Pin,
rc::Rc,
sync::Arc,
task::{Context, Poll, Waker},
};
#[test]
fn test_foreground_executor_spawn() {
let result = TestScheduler::once(async |scheduler| {
let task = scheduler.foreground().spawn(async move { 42 });
task.await
});
assert_eq!(result, 42);
}
#[test]
fn test_background_executor_spawn() {
TestScheduler::once(async |scheduler| {
let task = scheduler.background().spawn(async move { 42 });
let result = task.await;
assert_eq!(result, 42);
});
}
#[test]
fn test_scheduler_drops_with_stalled_detached_foreground_task() {
let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::default()));
let weak_scheduler = Arc::downgrade(&scheduler);
let (sender, receiver) = oneshot::channel::<()>();
scheduler
.foreground()
.spawn(async move {
receiver.await.ok();
})
.detach();
scheduler.run();
drop(scheduler);
assert!(weak_scheduler.upgrade().is_none());
drop(sender);
}
#[test]
fn test_scheduler_drops_with_stalled_detached_background_task() {
let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::default()));
let weak_scheduler = Arc::downgrade(&scheduler);
let (sender, receiver) = oneshot::channel::<()>();
scheduler
.background()
.spawn(async move {
receiver.await.ok();
})
.detach();
scheduler.run();
drop(scheduler);
assert!(weak_scheduler.upgrade().is_none());
drop(sender);
}
#[test]
fn test_foreground_ordering() {
let mut traces = HashSet::new();
TestScheduler::many(if cfg!(miri) { 5 } else { 100 }, async |scheduler| {
#[derive(Hash, PartialEq, Eq)]
struct TraceEntry {
session: usize,
task: usize,
}
let trace = Rc::new(RefCell::new(Vec::new()));
let foreground_1 = scheduler.foreground();
for task in 0..10 {
foreground_1
.spawn({
let trace = trace.clone();
async move {
trace.borrow_mut().push(TraceEntry { session: 0, task });
}
})
.detach();
}
let foreground_2 = scheduler.foreground();
for task in 0..10 {
foreground_2
.spawn({
let trace = trace.clone();
async move {
trace.borrow_mut().push(TraceEntry { session: 1, task });
}
})
.detach();
}
scheduler.run();
assert_eq!(
trace
.borrow()
.iter()
.filter(|entry| entry.session == 0)
.map(|entry| entry.task)
.collect::<Vec<_>>(),
(0..10).collect::<Vec<_>>()
);
assert_eq!(
trace
.borrow()
.iter()
.filter(|entry| entry.session == 1)
.map(|entry| entry.task)
.collect::<Vec<_>>(),
(0..10).collect::<Vec<_>>()
);
traces.insert(trace.take());
});
assert!(traces.len() > 1, "Expected at least two traces");
}
#[test]
fn test_timer_ordering() {
TestScheduler::many(1, async |scheduler| {
let background = scheduler.background();
let futures = FuturesUnordered::new();
futures.push(
async {
background.timer(Duration::from_millis(100)).await;
2
}
.boxed(),
);
futures.push(
async {
background.timer(Duration::from_millis(50)).await;
1
}
.boxed(),
);
futures.push(
async {
background.timer(Duration::from_millis(150)).await;
3
}
.boxed(),
);
assert_eq!(futures.collect::<Vec<_>>().await, vec![1, 2, 3]);
});
}
#[test]
fn test_foreground_task_can_hold_mut_borrow_across_await() {
TestScheduler::once(async |scheduler| {
let foreground = scheduler.foreground();
let (sender, mut receiver) = mpsc::unbounded::<()>();
foreground
.spawn(async move {
receiver.next().await;
})
.detach();
scheduler.run();
sender.unbounded_send(()).unwrap();
scheduler.run();
});
}
#[test]
fn test_send_from_bg_to_fg() {
TestScheduler::once(async |scheduler| {
let foreground = scheduler.foreground();
let background = scheduler.background();
let (sender, receiver) = oneshot::channel::<i32>();
background
.spawn(async move {
sender.send(42).unwrap();
})
.detach();
let task = foreground.spawn(async move { receiver.await.unwrap() });
let result = task.await;
assert_eq!(result, 42);
});
}
#[test]
fn test_randomize_order() {
// Test deterministic mode: different seeds should produce same execution order
let mut deterministic_results = HashSet::new();
for seed in 0..10 {
let config = TestSchedulerConfig {
seed,
randomize_order: false,
..Default::default()
};
let order = block_on(capture_execution_order(config));
assert_eq!(order.len(), 6);
deterministic_results.insert(order);
}
// All deterministic runs should produce the same result
assert_eq!(
deterministic_results.len(),
1,
"Deterministic mode should always produce same execution order"
);
// Test randomized mode: different seeds can produce different execution orders
let mut randomized_results = HashSet::new();
for seed in 0..20 {
let config = TestSchedulerConfig::with_seed(seed);
let order = block_on(capture_execution_order(config));
assert_eq!(order.len(), 6);
randomized_results.insert(order);
}
// Randomized mode should produce multiple different execution orders
assert!(
randomized_results.len() > 1,
"Randomized mode should produce multiple different orders"
);
}
async fn capture_execution_order(config: TestSchedulerConfig) -> Vec<String> {
let scheduler = Arc::new(TestScheduler::new(config));
let foreground = scheduler.foreground();
let background = scheduler.background();
let (sender, receiver) = mpsc::unbounded::<String>();
// Spawn foreground tasks
for i in 0..3 {
let mut sender = sender.clone();
foreground
.spawn(async move {
sender.send(format!("fg-{}", i)).await.ok();
})
.detach();
}
// Spawn background tasks
for i in 0..3 {
let mut sender = sender.clone();
background
.spawn(async move {
sender.send(format!("bg-{}", i)).await.ok();
})
.detach();
}
drop(sender); // Close sender to signal no more messages
scheduler.run();
receiver.collect().await
}
#[test]
fn test_block() {
let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::default()));
let (tx, rx) = oneshot::channel();
// Spawn background task to send value
scheduler
.background()
.spawn(async move {
tx.send(42).unwrap();
})
.detach();
// Block on receiving the value
let result = scheduler.foreground().block_on(async { rx.await.unwrap() });
assert_eq!(result, 42);
}
#[test]
#[should_panic(expected = "Parking forbidden.")]
fn test_parking_panics() {
let config = TestSchedulerConfig {
capture_pending_traces: true,
..Default::default()
};
let scheduler = Arc::new(TestScheduler::new(config));
scheduler.foreground().block_on(async {
let (_tx, rx) = oneshot::channel::<()>();
rx.await.unwrap(); // This will never complete
});
}
#[test]
fn test_block_with_parking() {
let config = TestSchedulerConfig {
allow_parking: true,
..Default::default()
};
let scheduler = Arc::new(TestScheduler::new(config));
let (tx, rx) = oneshot::channel();
// Spawn background task to send value
scheduler
.background()
.spawn(async move {
tx.send(42).unwrap();
})
.detach();
// Block on receiving the value (will park if needed)
let result = scheduler.foreground().block_on(async { rx.await.unwrap() });
assert_eq!(result, 42);
}
#[test]
fn test_helper_methods() {
// Test the once method
let result = TestScheduler::once(async |scheduler: Arc<TestScheduler>| {
let background = scheduler.background();
background.spawn(async { 42 }).await
});
assert_eq!(result, 42);
// Test the many method
let results = TestScheduler::many(3, async |scheduler: Arc<TestScheduler>| {
let background = scheduler.background();
background.spawn(async { 10 }).await
});
assert_eq!(results, vec![10, 10, 10]);
}
#[test]
fn test_many_with_arbitrary_seed() {
for seed in [0u64, 1, 5, 42] {
let mut seeds_seen = Vec::new();
let iterations = 3usize;
for current_seed in seed..seed + iterations as u64 {
let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::with_seed(
current_seed,
)));
let captured_seed = current_seed;
scheduler
.foreground()
.block_on(async { seeds_seen.push(captured_seed) });
scheduler.run();
}
assert_eq!(
seeds_seen,
(seed..seed + iterations as u64).collect::<Vec<_>>(),
"Expected {iterations} iterations starting at seed {seed}"
);
}
}
#[test]
fn test_block_with_timeout() {
// Test case: future completes within timeout
TestScheduler::once(async |scheduler| {
let foreground = scheduler.foreground();
let future = future::ready(42);
let output = foreground.block_with_timeout(Duration::from_millis(100), future);
assert_eq!(output.ok(), Some(42));
});
// Test case: future times out
TestScheduler::once(async |scheduler| {
// Make timeout behavior deterministic by forcing the timeout tick budget to be exactly 0.
// This prevents `block_with_timeout` from making progress via extra scheduler stepping and
// accidentally completing work that we expect to time out.
scheduler.set_timeout_ticks(0..=0);
let foreground = scheduler.foreground();
let future = future::pending::<()>();
let output = foreground.block_with_timeout(Duration::from_millis(50), future);
assert!(output.is_err(), "future should not have finished");
});
// Test case: future makes progress via timer but still times out
let mut results = BTreeSet::new();
TestScheduler::many(if cfg!(miri) { 5 } else { 100 }, async |scheduler| {
// Keep the existing probabilistic behavior here (do not force 0 ticks), since this subtest
// is explicitly checking that some seeds/timeouts can complete while others can time out.
let task = scheduler.background().spawn(async move {
Yield { polls: 10 }.await;
42
});
let output = scheduler
.foreground()
.block_with_timeout(Duration::from_millis(50), task);
results.insert(output.ok());
});
assert_eq!(
results.into_iter().collect::<Vec<_>>(),
if cfg!(miri) {
vec![Some(42)]
} else {
vec![None, Some(42)]
}
);
// Regression test:
// A timed-out future must not be cancelled. The returned future should still be
// pollable to completion later. We also want to ensure time only advances when we
// explicitly advance it (not by yielding).
TestScheduler::once(async |scheduler| {
// Force immediate timeout: the timeout tick budget is 0 so we will not step or
// advance timers inside `block_with_timeout`.
scheduler.set_timeout_ticks(0..=0);
let background = scheduler.background();
// This task should only complete once time is explicitly advanced.
let task = background.spawn({
let scheduler = scheduler.clone();
async move {
scheduler.timer(Duration::from_millis(100)).await;
123
}
});
// This should time out before we advance time enough for the timer to fire.
let timed_out = scheduler
.foreground()
.block_with_timeout(Duration::from_millis(50), task);
assert!(
timed_out.is_err(),
"expected timeout before advancing the clock enough for the timer"
);
// Now explicitly advance time and ensure the returned future can complete.
let mut task = timed_out.err().unwrap();
scheduler.advance_clock(Duration::from_millis(100));
scheduler.run();
let output = scheduler.foreground().block_on(&mut task);
assert_eq!(output, 123);
});
}
// When calling block, we shouldn't make progress on foreground-spawned futures with the same session id.
#[test]
fn test_block_does_not_progress_same_session_foreground() {
let mut task2_made_progress_once = false;
TestScheduler::many(if cfg!(miri) { 5 } else { 1000 }, async |scheduler| {
let foreground1 = scheduler.foreground();
let foreground2 = scheduler.foreground();
let task1 = foreground1.spawn(async move {});
let task2 = foreground2.spawn(async move {});
foreground1.block_on(async {
scheduler.yield_random().await;
assert!(!task1.is_ready());
task2_made_progress_once |= task2.is_ready();
});
task1.await;
task2.await;
});
assert!(
task2_made_progress_once,
"Expected task from different foreground executor to make progress (at least once)"
);
}
struct Yield {
polls: usize,
}
impl Future for Yield {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.polls -= 1;
if self.polls == 0 {
Poll::Ready(())
} else {
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
#[test]
fn test_nondeterministic_wake_detection() {
let config = TestSchedulerConfig {
allow_parking: false,
..Default::default()
};
let scheduler = Arc::new(TestScheduler::new(config));
// A future that captures its waker and sends it to an external thread
struct SendWakerToThread {
waker_tx: Option<std::sync::mpsc::Sender<Waker>>,
}
impl Future for SendWakerToThread {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(tx) = self.waker_tx.take() {
tx.send(cx.waker().clone()).ok();
}
Poll::Ready(())
}
}
let (waker_tx, waker_rx) = std::sync::mpsc::channel::<Waker>();
// Get a waker by running a future that sends it
scheduler.foreground().block_on(SendWakerToThread {
waker_tx: Some(waker_tx),
});
// Spawn a real OS thread that will call wake() on the waker
let handle = std::thread::spawn(move || {
if let Ok(waker) = waker_rx.recv() {
// This should trigger the non-determinism detection
waker.wake();
}
});
// Wait for the spawned thread to complete
handle.join().ok();
// The non-determinism error should be detected when end_test is called
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
scheduler.end_test();
}));
assert!(result.is_err(), "Expected end_test to panic");
let panic_payload = result.unwrap_err();
let panic_message = panic_payload
.downcast_ref::<String>()
.map(|s| s.as_str())
.or_else(|| panic_payload.downcast_ref::<&str>().copied())
.unwrap_or("<unknown panic>");
assert!(
panic_message.contains("Your test is not deterministic"),
"Expected panic message to contain non-determinism error, got: {}",
panic_message
);
}
#[test]
fn test_nondeterministic_wake_allowed_with_parking() {
let config = TestSchedulerConfig {
allow_parking: true,
..Default::default()
};
let scheduler = Arc::new(TestScheduler::new(config));
// A future that captures its waker and sends it to an external thread
struct WakeFromExternalThread {
waker_sent: bool,
waker_tx: Option<std::sync::mpsc::Sender<Waker>>,
}
impl Future for WakeFromExternalThread {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if !self.waker_sent {
self.waker_sent = true;
if let Some(tx) = self.waker_tx.take() {
tx.send(cx.waker().clone()).ok();
}
Poll::Pending
} else {
Poll::Ready(())
}
}
}
let (waker_tx, waker_rx) = std::sync::mpsc::channel::<Waker>();
// Spawn a real OS thread that will call wake() on the waker
std::thread::spawn(move || {
if let Ok(waker) = waker_rx.recv() {
// With allow_parking, this should NOT panic
waker.wake();
}
});
// This should complete without panicking
scheduler.foreground().block_on(WakeFromExternalThread {
waker_sent: false,
waker_tx: Some(waker_tx),
});
}
#[test]
fn test_nondeterministic_waker_drop_detection() {
let config = TestSchedulerConfig {
allow_parking: false,
..Default::default()
};
let scheduler = Arc::new(TestScheduler::new(config));
// A future that captures its waker and sends it to an external thread
struct SendWakerToThread {
waker_tx: Option<std::sync::mpsc::Sender<Waker>>,
}
impl Future for SendWakerToThread {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(tx) = self.waker_tx.take() {
tx.send(cx.waker().clone()).ok();
}
Poll::Ready(())
}
}
let (waker_tx, waker_rx) = std::sync::mpsc::channel::<Waker>();
// Get a waker by running a future that sends it
scheduler.foreground().block_on(SendWakerToThread {
waker_tx: Some(waker_tx),
});
// Spawn a real OS thread that will drop the waker without calling wake
let handle = std::thread::spawn(move || {
if let Ok(waker) = waker_rx.recv() {
// This should trigger the non-determinism detection on drop
drop(waker);
}
});
// Wait for the spawned thread to complete
handle.join().ok();
// The non-determinism error should be detected when end_test is called
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
scheduler.end_test();
}));
assert!(result.is_err(), "Expected end_test to panic");
let panic_payload = result.unwrap_err();
let panic_message = panic_payload
.downcast_ref::<String>()
.map(|s| s.as_str())
.or_else(|| panic_payload.downcast_ref::<&str>().copied())
.unwrap_or("<unknown panic>");
assert!(
panic_message.contains("Your test is not deterministic"),
"Expected panic message to contain non-determinism error, got: {}",
panic_message
);
}
#[test]
fn test_background_priority_scheduling() {
use parking_lot::Mutex;
// Run many iterations to get statistical significance
let mut high_before_low_count = 0;
let iterations = if cfg!(miri) { 5 } else { 100 };
for seed in 0..iterations {
let config = TestSchedulerConfig::with_seed(seed);
let scheduler = Arc::new(TestScheduler::new(config));
let background = scheduler.background();
let execution_order = Arc::new(Mutex::new(Vec::new()));
// Spawn low priority tasks first
for i in 0..3 {
let order = execution_order.clone();
background
.spawn_with_priority(Priority::Low, async move {
order.lock().push(format!("low-{}", i));
})
.detach();
}
// Spawn high priority tasks second
for i in 0..3 {
let order = execution_order.clone();
background
.spawn_with_priority(Priority::High, async move {
order.lock().push(format!("high-{}", i));
})
.detach();
}
scheduler.run();
// Count how many high priority tasks ran in the first half
let order = execution_order.lock();
let high_in_first_half = order
.iter()
.take(3)
.filter(|s| s.starts_with("high"))
.count();
if high_in_first_half >= 2 {
high_before_low_count += 1;
}
}
// High priority tasks should tend to run before low priority tasks
// With weights of 60 vs 10, high priority should dominate early execution
assert!(
high_before_low_count > iterations / 2,
"Expected high priority tasks to run before low priority tasks more often. \
Got {} out of {} iterations",
high_before_low_count,
iterations
);
}
#[test]
fn test_spawn_dedicated_basic_round_trip() {
let result = TestScheduler::once(async |scheduler| {
scheduler
.background()
.spawn_dedicated(|_executor| async { 42 })
.await
});
assert_eq!(result, 42);
}
#[test]
fn test_spawn_dedicated_not_send_future() {
let result = TestScheduler::once(async |scheduler| {
scheduler
.background()
.spawn_dedicated(|_executor| async move {
// `Rc<RefCell<_>>` is `!Send`. If `spawn_dedicated` required
// the returned future to be `Send`, this wouldn't compile.
let state = Rc::new(RefCell::new(0_i32));
for _ in 0..5 {
*state.borrow_mut() += 1;
}
*state.borrow()
})
.await
});
assert_eq!(result, 5);
}
#[test]
fn test_spawn_dedicated_send_closure_captures() {
use parking_lot::Mutex;
let observed = TestScheduler::once(async |scheduler| {
let shared = Arc::new(Mutex::new(0_i32));
let shared_for_closure = shared.clone();
let returned = scheduler
.background()
.spawn_dedicated(move |_executor| {
// `shared_for_closure` crossed the `Send` boundary of the
// closure; we then mutate it from inside the !Send future.
let local = shared_for_closure;
async move {
*local.lock() = 7;
}
})
.await;
let _: () = returned;
*shared.lock()
});
assert_eq!(observed, 7);
}
#[test]
fn test_spawn_dedicated_inner_spawn_local() {
let result = TestScheduler::once(async |scheduler| {
scheduler
.background()
.spawn_dedicated(|executor| async move {
// The provided executor can spawn additional `!Send` work
// onto the same dedicated session.
let inner = Rc::new(RefCell::new(0_i32));
let inner_for_child = inner.clone();
let child = executor.spawn(async move {
*inner_for_child.borrow_mut() = 99;
*inner_for_child.borrow()
});
child.await
})
.await
});
assert_eq!(result, 99);
}
#[test]
fn test_spawn_dedicated_determinism_under_many() {
use parking_lot::Mutex;
let outcomes = TestScheduler::many(if cfg!(miri) { 4 } else { 20 }, async |scheduler| {
let trace = Arc::new(Mutex::new(Vec::<u32>::new()));
let background = scheduler.background();
let mut tasks = Vec::new();
for id in 0..4_u32 {
let trace = trace.clone();
let task = background.spawn_dedicated(move |executor| async move {
for step in 0..3 {
trace.lock().push(id * 100 + step);
executor.spawn(async {}).await;
}
id
});
tasks.push(task);
}
let mut outputs = Vec::new();
for task in tasks {
outputs.push(task.await);
}
(trace.lock().clone(), outputs)
});
// Re-running with the same seed should produce the same trace. Run a
// second pass with identical seeds and compare to the first.
let outcomes_replay = TestScheduler::many(if cfg!(miri) { 4 } else { 20 }, async |scheduler| {
let trace = Arc::new(Mutex::new(Vec::<u32>::new()));
let background = scheduler.background();
let mut tasks = Vec::new();
for id in 0..4_u32 {
let trace = trace.clone();
let task = background.spawn_dedicated(move |executor| async move {
for step in 0..3 {
trace.lock().push(id * 100 + step);
executor.spawn(async {}).await;
}
id
});
tasks.push(task);
}
let mut outputs = Vec::new();
for task in tasks {
outputs.push(task.await);
}
(trace.lock().clone(), outputs)
});
assert_eq!(
outcomes, outcomes_replay,
"per-seed outcomes should be reproducible"
);
// Sanity: at least one seed produced a non-monotonic trace,
// demonstrating that dedicated tasks really do interleave under the
// scheduler's randomization.
let any_interleaved = outcomes.iter().any(|(trace, _)| {
trace
.windows(2)
.any(|window| window[0] / 100 != window[1] / 100)
});
assert!(
any_interleaved,
"expected at least one seed to interleave dedicated tasks"
);
}
#[test]
fn test_spawn_dedicated_dropping_task_cancels_future() {
use parking_lot::Mutex;
let counter_after = TestScheduler::once(async |scheduler| {
let counter = Arc::new(Mutex::new(0_u32));
let (resume_tx, resume_rx) = oneshot::channel::<()>();
let task = {
let counter = counter.clone();
scheduler
.background()
.spawn_dedicated(move |_executor| async move {
*counter.lock() = 1;
// Park here until the test resumes us. If the task is
// dropped before this resolves, the second assignment
// below must never happen.
let _ = resume_rx.await;
*counter.lock() = 2;
})
};
// Let the dedicated future make its first observable step.
scheduler.run();
assert_eq!(*counter.lock(), 1);
// Cancel by dropping the root task, then unblock the parked oneshot.
// The future must not advance past the await: counter stays at 1.
drop(task);
let _ = resume_tx.send(());
scheduler.run();
*counter.lock()
});
assert_eq!(
counter_after, 1,
"dropping the dedicated task must cancel the root future before its second write"
);
}
#[test]
fn test_spawn_dedicated_detached_child_runs_after_root_completes() {
use parking_lot::Mutex;
let child_ran = TestScheduler::once(async |scheduler| {
let child_ran = Arc::new(Mutex::new(false));
let task = {
let child_ran = child_ran.clone();
scheduler
.background()
.spawn_dedicated(move |executor| async move {
executor
.spawn(async move {
*child_ran.lock() = true;
})
.detach();
// Root returns immediately, before the child has had a
// chance to run.
})
};
task.await;
// Drain the dedicated session. The detached child must run.
scheduler.run();
*child_ran.lock()
});
assert!(
child_ran,
"detached child must complete after the root, not be cancelled with it"
);
}
// The production smoke test for `spawn_dedicated` lives in the `gpui` crate
// alongside `PlatformScheduler`, which is the real production implementation
// of the `Scheduler` trait. See `crates/gpui/src/platform_scheduler.rs`.
+29
View File
@@ -0,0 +1,29 @@
[package]
name = "gpui_sum_tree"
version = "0.2.2"
edition = "2024"
license = "Apache-2.0"
description = "Copy-on-write B+ tree with monoidal summaries for gpui-ce (vendored from Zed)."
publish = true
[lib]
name = "sum_tree"
path = "src/sum_tree.rs"
doctest = false
[dependencies]
heapless = "0.9.2"
rayon = "1.11.0"
log = "0.4.29"
tracing = { version = "0.1.43", features = ["attributes"] }
proptest = { version = "1.0", features = ["attr-macro"], optional = true }
[dev-dependencies]
rand = "0.9"
proptest = { version = "1.0", features = ["attr-macro"] }
[features]
test-support = ["proptest"]
[package.metadata.cargo-machete]
ignored = ["tracing"]
+222
View File
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+861
View File
@@ -0,0 +1,861 @@
use super::*;
use heapless::Vec as ArrayVec;
use std::{cmp::Ordering, mem, sync::Arc};
use tracing::instrument;
#[derive(Clone)]
struct StackEntry<'a, T: Item, D> {
tree: &'a SumTree<T>,
index: u32,
position: D,
}
impl<'a, T: Item, D> StackEntry<'a, T, D> {
#[inline]
fn index(&self) -> usize {
self.index as usize
}
}
impl<T: Item + fmt::Debug, D: fmt::Debug> fmt::Debug for StackEntry<'_, T, D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StackEntry")
.field("index", &self.index)
.field("position", &self.position)
.finish()
}
}
#[derive(Clone)]
pub struct Cursor<'a, 'b, T: Item, D> {
tree: &'a SumTree<T>,
stack: ArrayVec<StackEntry<'a, T, D>, 16, u8>,
pub position: D,
did_seek: bool,
at_end: bool,
cx: <T::Summary as Summary>::Context<'b>,
}
impl<T: Item + fmt::Debug, D: fmt::Debug> fmt::Debug for Cursor<'_, '_, T, D>
where
T::Summary: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Cursor")
.field("tree", &self.tree)
.field("stack", &self.stack)
.field("position", &self.position)
.field("did_seek", &self.did_seek)
.field("at_end", &self.at_end)
.finish()
}
}
pub struct Iter<'a, T: Item> {
tree: &'a SumTree<T>,
stack: ArrayVec<StackEntry<'a, T, ()>, 16, u8>,
}
impl<'a, 'b, T, D> Cursor<'a, 'b, T, D>
where
T: Item,
D: Dimension<'a, T::Summary>,
{
pub fn new(tree: &'a SumTree<T>, cx: <T::Summary as Summary>::Context<'b>) -> Self {
Self {
tree,
stack: ArrayVec::new(),
position: D::zero(cx),
did_seek: false,
at_end: tree.is_empty(),
cx,
}
}
pub fn reset(&mut self) {
self.did_seek = false;
self.at_end = self.tree.is_empty();
self.stack.truncate(0);
self.position = D::zero(self.cx);
}
pub fn start(&self) -> &D {
&self.position
}
#[track_caller]
pub fn end(&self) -> D {
if let Some(item_summary) = self.item_summary() {
let mut end = self.start().clone();
end.add_summary(item_summary, self.cx);
end
} else {
self.start().clone()
}
}
/// Item is None, when the list is empty, or this cursor is at the end of the list.
#[track_caller]
pub fn item(&self) -> Option<&'a T> {
self.assert_did_seek();
if let Some(entry) = self.stack.last() {
match *entry.tree.0 {
Node::Leaf { ref items, .. } => {
if entry.index() == items.len() {
None
} else {
Some(&items[entry.index()])
}
}
_ => unreachable!(),
}
} else {
None
}
}
#[track_caller]
pub fn item_summary(&self) -> Option<&'a T::Summary> {
self.assert_did_seek();
if let Some(entry) = self.stack.last() {
match *entry.tree.0 {
Node::Leaf {
ref item_summaries, ..
} => {
if entry.index() == item_summaries.len() {
None
} else {
Some(&item_summaries[entry.index()])
}
}
_ => unreachable!(),
}
} else {
None
}
}
#[track_caller]
pub fn next_item(&self) -> Option<&'a T> {
self.assert_did_seek();
if let Some(entry) = self.stack.last() {
if entry.index() == entry.tree.0.items().len() - 1 {
if let Some(next_leaf) = self.next_leaf() {
Some(next_leaf.0.items().first().unwrap())
} else {
None
}
} else {
match *entry.tree.0 {
Node::Leaf { ref items, .. } => Some(&items[entry.index() + 1]),
_ => unreachable!(),
}
}
} else if self.at_end {
None
} else {
self.tree.first()
}
}
#[track_caller]
fn next_leaf(&self) -> Option<&'a SumTree<T>> {
for entry in self.stack.iter().rev().skip(1) {
if entry.index() < entry.tree.0.child_trees().len() - 1 {
match *entry.tree.0 {
Node::Internal {
ref child_trees, ..
} => return Some(child_trees[entry.index() + 1].leftmost_leaf()),
Node::Leaf { .. } => unreachable!(),
};
}
}
None
}
#[track_caller]
pub fn prev_item(&self) -> Option<&'a T> {
self.assert_did_seek();
if let Some(entry) = self.stack.last() {
if entry.index() == 0 {
if let Some(prev_leaf) = self.prev_leaf() {
Some(prev_leaf.0.items().last().unwrap())
} else {
None
}
} else {
match *entry.tree.0 {
Node::Leaf { ref items, .. } => Some(&items[entry.index() - 1]),
_ => unreachable!(),
}
}
} else if self.at_end {
self.tree.last()
} else {
None
}
}
#[track_caller]
fn prev_leaf(&self) -> Option<&'a SumTree<T>> {
for entry in self.stack.iter().rev().skip(1) {
if entry.index() != 0 {
match *entry.tree.0 {
Node::Internal {
ref child_trees, ..
} => return Some(child_trees[entry.index() - 1].rightmost_leaf()),
Node::Leaf { .. } => unreachable!(),
};
}
}
None
}
#[track_caller]
#[instrument(skip_all)]
pub fn prev(&mut self) {
self.search_backward(|_| true)
}
#[track_caller]
pub fn search_backward<F>(&mut self, mut filter_node: F)
where
F: FnMut(&T::Summary) -> bool,
{
if !self.did_seek {
self.did_seek = true;
self.at_end = true;
}
if self.at_end {
self.position = D::zero(self.cx);
self.at_end = self.tree.is_empty();
if !self.tree.is_empty() {
self.stack
.push(StackEntry {
tree: self.tree,
index: self.tree.0.child_summaries().len() as u32,
position: D::from_summary(self.tree.summary(), self.cx),
})
.unwrap_oob();
}
}
let mut descending = false;
while !self.stack.is_empty() {
if let Some(StackEntry { position, .. }) = self.stack.iter().rev().nth(1) {
self.position = position.clone();
} else {
self.position = D::zero(self.cx);
}
let entry = self.stack.last_mut().unwrap();
if !descending {
if entry.index() == 0 {
self.stack.pop();
continue;
} else {
entry.index -= 1;
}
}
for summary in &entry.tree.0.child_summaries()[..entry.index()] {
self.position.add_summary(summary, self.cx);
}
entry.position = self.position.clone();
descending = filter_node(&entry.tree.0.child_summaries()[entry.index()]);
match entry.tree.0.as_ref() {
Node::Internal { child_trees, .. } => {
if descending {
let tree = &child_trees[entry.index()];
self.stack
.push(StackEntry {
position: D::zero(self.cx),
tree,
index: tree.0.child_summaries().len() as u32 - 1,
})
.unwrap_oob();
}
}
Node::Leaf { .. } => {
if descending {
break;
}
}
}
}
}
#[track_caller]
pub fn next(&mut self) {
self.search_forward(|_| true)
}
#[track_caller]
pub fn search_forward<F>(&mut self, mut filter_node: F)
where
F: FnMut(&T::Summary) -> bool,
{
let mut descend = false;
if self.stack.is_empty() {
if !self.at_end {
self.stack
.push(StackEntry {
tree: self.tree,
index: 0,
position: D::zero(self.cx),
})
.unwrap_oob();
descend = true;
}
self.did_seek = true;
}
while !self.stack.is_empty() {
let new_subtree = {
let entry = self.stack.last_mut().unwrap();
match entry.tree.0.as_ref() {
Node::Internal {
child_trees,
child_summaries,
..
} => {
if !descend {
entry.index += 1;
entry.position = self.position.clone();
}
while entry.index() < child_summaries.len() {
let next_summary = &child_summaries[entry.index()];
if filter_node(next_summary) {
break;
} else {
entry.index += 1;
entry.position.add_summary(next_summary, self.cx);
self.position.add_summary(next_summary, self.cx);
}
}
child_trees.get(entry.index())
}
Node::Leaf { item_summaries, .. } => {
if !descend {
let item_summary = &item_summaries[entry.index()];
entry.index += 1;
entry.position.add_summary(item_summary, self.cx);
self.position.add_summary(item_summary, self.cx);
}
loop {
if let Some(next_item_summary) = item_summaries.get(entry.index()) {
if filter_node(next_item_summary) {
return;
} else {
entry.index += 1;
entry.position.add_summary(next_item_summary, self.cx);
self.position.add_summary(next_item_summary, self.cx);
}
} else {
break None;
}
}
}
}
};
if let Some(subtree) = new_subtree {
descend = true;
self.stack
.push(StackEntry {
tree: subtree,
index: 0,
position: self.position.clone(),
})
.unwrap_oob();
} else {
descend = false;
self.stack.pop();
}
}
self.at_end = self.stack.is_empty();
debug_assert!(self.stack.is_empty() || self.stack.last().unwrap().tree.0.is_leaf());
}
#[track_caller]
fn assert_did_seek(&self) {
assert!(
self.did_seek,
"Must call `seek`, `next` or `prev` before calling this method"
);
}
pub fn did_seek(&self) -> bool {
self.did_seek
}
}
impl<'a, 'b, T, D> Cursor<'a, 'b, T, D>
where
T: Item,
D: Dimension<'a, T::Summary>,
{
/// Returns whether we found the item you were seeking for.
#[track_caller]
#[instrument(skip_all)]
pub fn seek<Target>(&mut self, pos: &Target, bias: Bias) -> bool
where
Target: SeekTarget<'a, T::Summary, D>,
{
self.reset();
self.seek_internal(pos, bias, &mut ())
}
/// Returns whether we found the item you were seeking for.
///
/// # Panics
///
/// If we did not seek before, use seek instead in that case.
#[track_caller]
#[instrument(skip_all)]
pub fn seek_forward<Target>(&mut self, pos: &Target, bias: Bias) -> bool
where
Target: SeekTarget<'a, T::Summary, D>,
{
self.seek_internal(pos, bias, &mut ())
}
/// Advances the cursor and returns traversed items as a tree.
#[track_caller]
pub fn slice<Target>(&mut self, end: &Target, bias: Bias) -> SumTree<T>
where
Target: SeekTarget<'a, T::Summary, D>,
{
let mut slice = SliceSeekAggregate {
tree: SumTree::new(self.cx),
leaf_items: ArrayVec::new(),
leaf_item_summaries: ArrayVec::new(),
leaf_summary: <T::Summary as Summary>::zero(self.cx),
};
self.seek_internal(end, bias, &mut slice);
slice.tree
}
#[track_caller]
pub fn suffix(&mut self) -> SumTree<T> {
self.slice(&End::new(), Bias::Right)
}
#[track_caller]
pub fn summary<Target, Output>(&mut self, end: &Target, bias: Bias) -> Output
where
Target: SeekTarget<'a, T::Summary, D>,
Output: Dimension<'a, T::Summary>,
{
let mut summary = SummarySeekAggregate(Output::zero(self.cx));
self.seek_internal(end, bias, &mut summary);
summary.0
}
/// Returns whether we found the item you were seeking for.
#[track_caller]
#[instrument(skip_all)]
fn seek_internal(
&mut self,
target: &dyn SeekTarget<'a, T::Summary, D>,
bias: Bias,
aggregate: &mut dyn SeekAggregate<'a, T>,
) -> bool {
assert!(
target.cmp(&self.position, self.cx).is_ge(),
"cannot seek backward",
);
if !self.did_seek {
self.did_seek = true;
self.stack
.push(StackEntry {
tree: self.tree,
index: 0,
position: D::zero(self.cx),
})
.unwrap_oob();
}
let mut ascending = false;
'outer: while let Some(entry) = self.stack.last_mut() {
match *entry.tree.0 {
Node::Internal {
ref child_summaries,
ref child_trees,
..
} => {
if ascending {
entry.index += 1;
entry.position = self.position.clone();
}
for (child_tree, child_summary) in child_trees[entry.index()..]
.iter()
.zip(&child_summaries[entry.index()..])
{
let mut child_end = self.position.clone();
child_end.add_summary(child_summary, self.cx);
let comparison = target.cmp(&child_end, self.cx);
if comparison == Ordering::Greater
|| (comparison == Ordering::Equal && bias == Bias::Right)
{
self.position = child_end;
aggregate.push_tree(child_tree, child_summary, self.cx);
entry.index += 1;
entry.position = self.position.clone();
} else {
self.stack
.push(StackEntry {
tree: child_tree,
index: 0,
position: self.position.clone(),
})
.unwrap_oob();
ascending = false;
continue 'outer;
}
}
}
Node::Leaf {
ref items,
ref item_summaries,
..
} => {
aggregate.begin_leaf();
for (item, item_summary) in items[entry.index()..]
.iter()
.zip(&item_summaries[entry.index()..])
{
let mut child_end = self.position.clone();
child_end.add_summary(item_summary, self.cx);
let comparison = target.cmp(&child_end, self.cx);
if comparison == Ordering::Greater
|| (comparison == Ordering::Equal && bias == Bias::Right)
{
self.position = child_end;
aggregate.push_item(item, item_summary, self.cx);
entry.index += 1;
} else {
aggregate.end_leaf(self.cx);
break 'outer;
}
}
aggregate.end_leaf(self.cx);
}
}
self.stack.pop();
ascending = true;
}
self.at_end = self.stack.is_empty();
debug_assert!(self.stack.is_empty() || self.stack.last().unwrap().tree.0.is_leaf());
let mut end = self.position.clone();
if bias == Bias::Left
&& let Some(summary) = self.item_summary()
{
end.add_summary(summary, self.cx);
}
target.cmp(&end, self.cx) == Ordering::Equal
}
}
impl<'a, T: Item> Iter<'a, T> {
pub(crate) fn new(tree: &'a SumTree<T>) -> Self {
Self {
tree,
stack: Default::default(),
}
}
}
impl<'a, T: Item> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let mut descend = false;
if self.stack.is_empty() {
self.stack
.push(StackEntry {
tree: self.tree,
index: 0,
position: (),
})
.unwrap_oob();
descend = true;
}
while let Some(entry) = self.stack.last_mut() {
let new_subtree = {
match entry.tree.0.as_ref() {
Node::Internal { child_trees, .. } => {
if !descend {
entry.index += 1;
}
child_trees.get(entry.index())
}
Node::Leaf { items, .. } => {
if !descend {
entry.index += 1;
}
if let Some(next_item) = items.get(entry.index()) {
return Some(next_item);
} else {
None
}
}
}
};
if let Some(subtree) = new_subtree {
descend = true;
self.stack
.push(StackEntry {
tree: subtree,
index: 0,
position: (),
})
.unwrap_oob();
} else {
descend = false;
self.stack.pop();
}
}
None
}
fn last(mut self) -> Option<Self::Item> {
self.stack.clear();
self.tree.rightmost_leaf().last()
}
fn size_hint(&self) -> (usize, Option<usize>) {
let lower_bound = match self.stack.last() {
Some(top) => top.tree.0.child_summaries().len() - top.index as usize,
None => self.tree.0.child_summaries().len(),
};
(lower_bound, None)
}
}
impl<'a, 'b, T: Item, D> Iterator for Cursor<'a, 'b, T, D>
where
D: Dimension<'a, T::Summary>,
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if !self.did_seek {
self.next();
}
if let Some(item) = self.item() {
self.next();
Some(item)
} else {
None
}
}
}
pub struct FilterCursor<'a, 'b, F, T: Item, D> {
cursor: Cursor<'a, 'b, T, D>,
filter_node: F,
}
impl<'a, 'b, F, T: Item, D> FilterCursor<'a, 'b, F, T, D>
where
F: FnMut(&T::Summary) -> bool,
T: Item,
D: Dimension<'a, T::Summary>,
{
pub fn new(
tree: &'a SumTree<T>,
cx: <T::Summary as Summary>::Context<'b>,
filter_node: F,
) -> Self {
let cursor = tree.cursor::<D>(cx);
Self {
cursor,
filter_node,
}
}
pub fn start(&self) -> &D {
self.cursor.start()
}
pub fn end(&self) -> D {
self.cursor.end()
}
pub fn item(&self) -> Option<&'a T> {
self.cursor.item()
}
pub fn item_summary(&self) -> Option<&'a T::Summary> {
self.cursor.item_summary()
}
pub fn next(&mut self) {
self.cursor.search_forward(&mut self.filter_node);
}
pub fn prev(&mut self) {
self.cursor.search_backward(&mut self.filter_node);
}
}
impl<'a, 'b, F, T: Item, U> Iterator for FilterCursor<'a, 'b, F, T, U>
where
F: FnMut(&T::Summary) -> bool,
U: Dimension<'a, T::Summary>,
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if !self.cursor.did_seek {
self.next();
}
if let Some(item) = self.item() {
self.cursor.search_forward(&mut self.filter_node);
Some(item)
} else {
None
}
}
}
trait SeekAggregate<'a, T: Item> {
fn begin_leaf(&mut self);
fn end_leaf(&mut self, cx: <T::Summary as Summary>::Context<'_>);
fn push_item(
&mut self,
item: &'a T,
summary: &'a T::Summary,
cx: <T::Summary as Summary>::Context<'_>,
);
fn push_tree(
&mut self,
tree: &'a SumTree<T>,
summary: &'a T::Summary,
cx: <T::Summary as Summary>::Context<'_>,
);
}
struct SliceSeekAggregate<T: Item> {
tree: SumTree<T>,
leaf_items: ArrayVec<T, { 2 * TREE_BASE }, u8>,
leaf_item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }, u8>,
leaf_summary: T::Summary,
}
struct SummarySeekAggregate<D>(D);
impl<T: Item> SeekAggregate<'_, T> for () {
fn begin_leaf(&mut self) {}
fn end_leaf(&mut self, _: <T::Summary as Summary>::Context<'_>) {}
fn push_item(&mut self, _: &T, _: &T::Summary, _: <T::Summary as Summary>::Context<'_>) {}
fn push_tree(
&mut self,
_: &SumTree<T>,
_: &T::Summary,
_: <T::Summary as Summary>::Context<'_>,
) {
}
}
impl<T: Item> SeekAggregate<'_, T> for SliceSeekAggregate<T> {
fn begin_leaf(&mut self) {}
fn end_leaf(&mut self, cx: <T::Summary as Summary>::Context<'_>) {
self.tree.append(
SumTree(Arc::new(Node::Leaf {
summary: mem::replace(&mut self.leaf_summary, <T::Summary as Summary>::zero(cx)),
items: mem::take(&mut self.leaf_items),
item_summaries: mem::take(&mut self.leaf_item_summaries),
})),
cx,
);
}
fn push_item(
&mut self,
item: &T,
summary: &T::Summary,
cx: <T::Summary as Summary>::Context<'_>,
) {
self.leaf_items.push(item.clone()).unwrap_oob();
self.leaf_item_summaries.push(summary.clone()).unwrap_oob();
Summary::add_summary(&mut self.leaf_summary, summary, cx);
}
fn push_tree(
&mut self,
tree: &SumTree<T>,
_: &T::Summary,
cx: <T::Summary as Summary>::Context<'_>,
) {
self.tree.append(tree.clone(), cx);
}
}
impl<'a, T: Item, D> SeekAggregate<'a, T> for SummarySeekAggregate<D>
where
D: Dimension<'a, T::Summary>,
{
fn begin_leaf(&mut self) {}
fn end_leaf(&mut self, _: <T::Summary as Summary>::Context<'_>) {}
fn push_item(
&mut self,
_: &T,
summary: &'a T::Summary,
cx: <T::Summary as Summary>::Context<'_>,
) {
self.0.add_summary(summary, cx);
}
fn push_tree(
&mut self,
_: &SumTree<T>,
summary: &'a T::Summary,
cx: <T::Summary as Summary>::Context<'_>,
) {
self.0.add_summary(summary, cx);
}
}
struct End<D>(PhantomData<D>);
impl<D> End<D> {
fn new() -> Self {
Self(PhantomData)
}
}
impl<'a, S: Summary, D: Dimension<'a, S>> SeekTarget<'a, S, D> for End<D> {
fn cmp(&self, _: &D, _: S::Context<'_>) -> Ordering {
Ordering::Greater
}
}
impl<D> fmt::Debug for End<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("End").finish()
}
}
+32
View File
@@ -0,0 +1,32 @@
use core::fmt::Debug;
use proptest::{prelude::*, sample::SizeRange};
use crate::{Item, SumTree, Summary};
impl<T> Arbitrary for SumTree<T>
where
T: Debug + Arbitrary + Item + 'static,
T::Summary: Debug + Summary<Context<'static> = ()>,
{
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with((): Self::Parameters) -> Self::Strategy {
any::<Vec<T>>()
.prop_map(|vec| SumTree::from_iter(vec, ()))
.boxed()
}
}
/// A strategy for producing a [`SumTree`] with a given size.
///
/// Equivalent to [`proptest::collection::vec`].
pub fn sum_tree<S, T>(values: S, size: impl Into<SizeRange>) -> impl Strategy<Value = SumTree<T>>
where
T: Debug + Arbitrary + Item + 'static,
T::Summary: Debug + Summary<Context<'static> = ()>,
S: Strategy<Value = T>,
{
proptest::collection::vec(values, size).prop_map(|vec| SumTree::from_iter(vec, ()))
}
File diff suppressed because it is too large Load Diff
+531
View File
@@ -0,0 +1,531 @@
use std::{cmp::Ordering, fmt::Debug};
use crate::{Bias, ContextLessSummary, Dimension, Edit, Item, KeyedItem, SeekTarget, SumTree};
/// A cheaply-cloneable ordered map based on a [SumTree](crate::SumTree).
#[derive(Clone, PartialEq, Eq)]
pub struct TreeMap<K, V>(SumTree<MapEntry<K, V>>)
where
K: Clone + Ord,
V: Clone;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MapEntry<K, V> {
key: K,
value: V,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct MapKey<K>(Option<K>);
impl<K> Default for MapKey<K> {
fn default() -> Self {
Self(None)
}
}
#[derive(Clone, Debug)]
pub struct MapKeyRef<'a, K>(Option<&'a K>);
impl<K> Default for MapKeyRef<'_, K> {
fn default() -> Self {
Self(None)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeSet<K>(TreeMap<K, ()>)
where
K: Clone + Ord;
impl<K: Clone + Ord, V: Clone> TreeMap<K, V> {
pub fn from_ordered_entries(entries: impl IntoIterator<Item = (K, V)>) -> Self {
let tree = SumTree::from_iter(
entries
.into_iter()
.map(|(key, value)| MapEntry { key, value }),
(),
);
Self(tree)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn contains_key(&self, key: &K) -> bool {
self.get(key).is_some()
}
pub fn get(&self, key: &K) -> Option<&V> {
let (.., item) = self
.0
.find::<MapKeyRef<'_, K>, _>((), &MapKeyRef(Some(key)), Bias::Left);
if let Some(item) = item {
if Some(key) == item.key().0.as_ref() {
Some(&item.value)
} else {
None
}
} else {
None
}
}
pub fn insert(&mut self, key: K, value: V) {
self.0.insert_or_replace(MapEntry { key, value }, ());
}
pub fn insert_or_replace(&mut self, key: K, value: V) -> Option<V> {
self.0
.insert_or_replace(MapEntry { key, value }, ())
.map(|it| it.value)
}
pub fn extend(&mut self, iter: impl IntoIterator<Item = (K, V)>) {
let edits: Vec<_> = iter
.into_iter()
.map(|(key, value)| Edit::Insert(MapEntry { key, value }))
.collect();
self.0.edit(edits, ());
}
pub fn clear(&mut self) {
self.0 = SumTree::default();
}
pub fn remove(&mut self, key: &K) -> Option<V> {
let mut removed = None;
let mut cursor = self.0.cursor::<MapKeyRef<'_, K>>(());
let key = MapKeyRef(Some(key));
let mut new_tree = cursor.slice(&key, Bias::Left);
if key.cmp(&cursor.end(), ()) == Ordering::Equal {
removed = Some(cursor.item().unwrap().value.clone());
cursor.next();
}
new_tree.append(cursor.suffix(), ());
drop(cursor);
self.0 = new_tree;
removed
}
pub fn remove_range(&mut self, start: &impl MapSeekTarget<K>, end: &impl MapSeekTarget<K>) {
let start = MapSeekTargetAdaptor(start);
let end = MapSeekTargetAdaptor(end);
let mut cursor = self.0.cursor::<MapKeyRef<'_, K>>(());
let mut new_tree = cursor.slice(&start, Bias::Left);
cursor.seek(&end, Bias::Left);
new_tree.append(cursor.suffix(), ());
drop(cursor);
self.0 = new_tree;
}
/// Returns the key-value pair with the greatest key less than or equal to the given key.
pub fn closest(&self, key: &K) -> Option<(&K, &V)> {
let mut cursor = self.0.cursor::<MapKeyRef<'_, K>>(());
let key = MapKeyRef(Some(key));
cursor.seek(&key, Bias::Right);
cursor.prev();
cursor.item().map(|item| (&item.key, &item.value))
}
pub fn iter_from<'a>(&'a self, from: &K) -> impl Iterator<Item = (&'a K, &'a V)> + 'a {
let mut cursor = self.0.cursor::<MapKeyRef<'_, K>>(());
let from_key = MapKeyRef(Some(from));
cursor.seek(&from_key, Bias::Left);
cursor.map(|map_entry| (&map_entry.key, &map_entry.value))
}
pub fn update<F, T>(&mut self, key: &K, f: F) -> Option<T>
where
F: FnOnce(&mut V) -> T,
{
let mut cursor = self.0.cursor::<MapKeyRef<'_, K>>(());
let key = MapKeyRef(Some(key));
let mut new_tree = cursor.slice(&key, Bias::Left);
let mut result = None;
if key.cmp(&cursor.end(), ()) == Ordering::Equal {
let mut updated = cursor.item().unwrap().clone();
result = Some(f(&mut updated.value));
new_tree.push(updated, ());
cursor.next();
}
new_tree.append(cursor.suffix(), ());
drop(cursor);
self.0 = new_tree;
result
}
pub fn retain<F: FnMut(&K, &V) -> bool>(&mut self, mut predicate: F) {
let mut new_map = SumTree::<MapEntry<K, V>>::default();
let mut cursor = self.0.cursor::<MapKeyRef<'_, K>>(());
cursor.next();
while let Some(item) = cursor.item() {
if predicate(&item.key, &item.value) {
new_map.push(item.clone(), ());
}
cursor.next();
}
drop(cursor);
self.0 = new_map;
}
pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> + '_ {
self.0.iter().map(|entry| (&entry.key, &entry.value))
}
pub fn values(&self) -> impl Iterator<Item = &V> + '_ {
self.0.iter().map(|entry| &entry.value)
}
pub fn first(&self) -> Option<(&K, &V)> {
self.0.first().map(|entry| (&entry.key, &entry.value))
}
pub fn last(&self) -> Option<(&K, &V)> {
self.0.last().map(|entry| (&entry.key, &entry.value))
}
pub fn insert_tree(&mut self, other: TreeMap<K, V>) {
let edits = other
.iter()
.map(|(key, value)| {
Edit::Insert(MapEntry {
key: key.to_owned(),
value: value.to_owned(),
})
})
.collect();
self.0.edit(edits, ());
}
}
impl<K, V> Debug for TreeMap<K, V>
where
K: Clone + Debug + Ord,
V: Clone + Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
#[derive(Debug)]
struct MapSeekTargetAdaptor<'a, T>(&'a T);
impl<'a, K: Clone + Ord, T: MapSeekTarget<K>> SeekTarget<'a, MapKey<K>, MapKeyRef<'a, K>>
for MapSeekTargetAdaptor<'_, T>
{
fn cmp(&self, cursor_location: &MapKeyRef<K>, _: ()) -> Ordering {
if let Some(key) = &cursor_location.0 {
MapSeekTarget::cmp_cursor(self.0, key)
} else {
Ordering::Greater
}
}
}
pub trait MapSeekTarget<K> {
fn cmp_cursor(&self, cursor_location: &K) -> Ordering;
}
impl<K: Ord> MapSeekTarget<K> for K {
fn cmp_cursor(&self, cursor_location: &K) -> Ordering {
self.cmp(cursor_location)
}
}
impl<K, V> Default for TreeMap<K, V>
where
K: Clone + Ord,
V: Clone,
{
fn default() -> Self {
Self(Default::default())
}
}
impl<K, V> Item for MapEntry<K, V>
where
K: Clone + Ord,
V: Clone,
{
type Summary = MapKey<K>;
fn summary(&self, _cx: ()) -> Self::Summary {
self.key()
}
}
impl<K, V> KeyedItem for MapEntry<K, V>
where
K: Clone + Ord,
V: Clone,
{
type Key = MapKey<K>;
fn key(&self) -> Self::Key {
MapKey(Some(self.key.clone()))
}
}
impl<K> ContextLessSummary for MapKey<K>
where
K: Clone,
{
fn zero() -> Self {
Default::default()
}
fn add_summary(&mut self, summary: &Self) {
*self = summary.clone()
}
}
impl<'a, K> Dimension<'a, MapKey<K>> for MapKeyRef<'a, K>
where
K: Clone + Ord,
{
fn zero(_cx: ()) -> Self {
Default::default()
}
fn add_summary(&mut self, summary: &'a MapKey<K>, _: ()) {
self.0 = summary.0.as_ref();
}
}
impl<'a, K> SeekTarget<'a, MapKey<K>, MapKeyRef<'a, K>> for MapKeyRef<'_, K>
where
K: Clone + Ord,
{
fn cmp(&self, cursor_location: &MapKeyRef<K>, _: ()) -> Ordering {
Ord::cmp(&self.0, &cursor_location.0)
}
}
impl<K> Default for TreeSet<K>
where
K: Clone + Ord,
{
fn default() -> Self {
Self(Default::default())
}
}
impl<K> TreeSet<K>
where
K: Clone + Ord,
{
pub fn from_ordered_entries(entries: impl IntoIterator<Item = K>) -> Self {
Self(TreeMap::from_ordered_entries(
entries.into_iter().map(|key| (key, ())),
))
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn insert(&mut self, key: K) {
self.0.insert(key, ());
}
pub fn remove(&mut self, key: &K) -> bool {
self.0.remove(key).is_some()
}
pub fn extend(&mut self, iter: impl IntoIterator<Item = K>) {
self.0.extend(iter.into_iter().map(|key| (key, ())));
}
pub fn contains(&self, key: &K) -> bool {
self.0.get(key).is_some()
}
pub fn iter(&self) -> impl Iterator<Item = &K> + '_ {
self.0.iter().map(|(k, _)| k)
}
pub fn iter_from<'a>(&'a self, key: &K) -> impl Iterator<Item = &'a K> + 'a {
self.0.iter_from(key).map(move |(k, _)| k)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic() {
let mut map = TreeMap::default();
assert_eq!(map.iter().collect::<Vec<_>>(), vec![]);
map.insert(3, "c");
assert_eq!(map.get(&3), Some(&"c"));
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&3, &"c")]);
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&1, &"a"), (&3, &"c")]);
map.insert(2, "b");
assert_eq!(map.get(&2), Some(&"b"));
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&3), Some(&"c"));
assert_eq!(
map.iter().collect::<Vec<_>>(),
vec![(&1, &"a"), (&2, &"b"), (&3, &"c")]
);
assert_eq!(map.closest(&0), None);
assert_eq!(map.closest(&1), Some((&1, &"a")));
assert_eq!(map.closest(&10), Some((&3, &"c")));
map.remove(&2);
assert_eq!(map.get(&2), None);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&1, &"a"), (&3, &"c")]);
assert_eq!(map.closest(&2), Some((&1, &"a")));
map.remove(&3);
assert_eq!(map.get(&3), None);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&1, &"a")]);
map.remove(&1);
assert_eq!(map.get(&1), None);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![]);
map.insert(4, "d");
map.insert(5, "e");
map.insert(6, "f");
map.retain(|key, _| *key % 2 == 0);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&4, &"d"), (&6, &"f")]);
}
#[test]
fn test_iter_from() {
let mut map = TreeMap::default();
map.insert("a", 1);
map.insert("b", 2);
map.insert("baa", 3);
map.insert("baaab", 4);
map.insert("c", 5);
let result = map
.iter_from(&"ba")
.take_while(|(key, _)| key.starts_with("ba"))
.collect::<Vec<_>>();
assert_eq!(result.len(), 2);
assert!(result.iter().any(|(k, _)| k == &&"baa"));
assert!(result.iter().any(|(k, _)| k == &&"baaab"));
let result = map
.iter_from(&"c")
.take_while(|(key, _)| key.starts_with("c"))
.collect::<Vec<_>>();
assert_eq!(result.len(), 1);
assert!(result.iter().any(|(k, _)| k == &&"c"));
}
#[test]
fn test_insert_tree() {
let mut map = TreeMap::default();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let mut other = TreeMap::default();
other.insert("a", 2);
other.insert("b", 2);
other.insert("d", 4);
map.insert_tree(other);
assert_eq!(map.iter().count(), 4);
assert_eq!(map.get(&"a"), Some(&2));
assert_eq!(map.get(&"b"), Some(&2));
assert_eq!(map.get(&"c"), Some(&3));
assert_eq!(map.get(&"d"), Some(&4));
}
#[test]
fn test_extend() {
let mut map = TreeMap::default();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
map.extend([("a", 2), ("b", 2), ("d", 4)]);
assert_eq!(map.iter().count(), 4);
assert_eq!(map.get(&"a"), Some(&2));
assert_eq!(map.get(&"b"), Some(&2));
assert_eq!(map.get(&"c"), Some(&3));
assert_eq!(map.get(&"d"), Some(&4));
}
#[test]
fn test_remove_between_and_path_successor() {
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct PathDescendants<'a>(&'a Path);
impl MapSeekTarget<PathBuf> for PathDescendants<'_> {
fn cmp_cursor(&self, key: &PathBuf) -> Ordering {
if key.starts_with(self.0) {
Ordering::Greater
} else {
self.0.cmp(key)
}
}
}
let mut map = TreeMap::default();
map.insert(PathBuf::from("a"), 1);
map.insert(PathBuf::from("a/a"), 1);
map.insert(PathBuf::from("b"), 2);
map.insert(PathBuf::from("b/a/a"), 3);
map.insert(PathBuf::from("b/a/a/a/b"), 4);
map.insert(PathBuf::from("c"), 5);
map.insert(PathBuf::from("c/a"), 6);
map.remove_range(
&PathBuf::from("b/a"),
&PathDescendants(&PathBuf::from("b/a")),
);
assert_eq!(map.get(&PathBuf::from("a")), Some(&1));
assert_eq!(map.get(&PathBuf::from("a/a")), Some(&1));
assert_eq!(map.get(&PathBuf::from("b")), Some(&2));
assert_eq!(map.get(&PathBuf::from("b/a/a")), None);
assert_eq!(map.get(&PathBuf::from("b/a/a/a/b")), None);
assert_eq!(map.get(&PathBuf::from("c")), Some(&5));
assert_eq!(map.get(&PathBuf::from("c/a")), Some(&6));
map.remove_range(&PathBuf::from("c"), &PathDescendants(&PathBuf::from("c")));
assert_eq!(map.get(&PathBuf::from("a")), Some(&1));
assert_eq!(map.get(&PathBuf::from("a/a")), Some(&1));
assert_eq!(map.get(&PathBuf::from("b")), Some(&2));
assert_eq!(map.get(&PathBuf::from("c")), None);
assert_eq!(map.get(&PathBuf::from("c/a")), None);
map.remove_range(&PathBuf::from("a"), &PathDescendants(&PathBuf::from("a")));
assert_eq!(map.get(&PathBuf::from("a")), None);
assert_eq!(map.get(&PathBuf::from("a/a")), None);
assert_eq!(map.get(&PathBuf::from("b")), Some(&2));
map.remove_range(&PathBuf::from("b"), &PathDescendants(&PathBuf::from("b")));
assert_eq!(map.get(&PathBuf::from("b")), None);
}
}
+1 -2
View File
@@ -34,8 +34,7 @@ gpui_util.workspace = true
wgpu.workspace = true
# Optional: only needed on platforms with multiple font sources (e.g. Linux)
# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", optional = true }
font-kit = { version = "0.14.1-zed", package = "zed-font-kit", optional = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
pollster.workspace = true
+68
View File
@@ -0,0 +1,68 @@
[package]
name = "gpui_zed_util"
version = "0.2.2"
edition = "2024"
license = "Apache-2.0"
publish = true
description = "OS/utility helpers used by gpui-ce platform backends (vendored from Zed's util)."
repository = "https://github.com/gpui-ce/gpui-ce"
[lib]
name = "util"
path = "src/util.rs"
doctest = true
[dependencies]
anyhow = "1.0.86"
async_zip = { version = "0.0.18", features = ["deflate", "deflate64"] }
collections = { package = "gpui_collections", version = "0.2.2", path = "../gpui_collections" }
dunce = "1.0"
futures-lite = "1.13"
futures = "0.3.32"
globset = "0.4"
itertools = "0.14.0"
log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] }
regex = "1.5"
rust-embed = { version = "8.11", features = ["include-exclude"] }
schemars = { version = "1.0", features = ["indexmap2"] }
serde = { version = "1.0.221", features = ["derive", "rc"] }
serde_json = { version = "1.0.144", features = ["preserve_order", "raw_value"] }
serde_json_lenient = { version = "0.2", features = [
"preserve_order",
"raw_value",
] }
shlex = "1.3.0"
take-until = "0.2.0"
tempfile = "3.20.0"
unicase = "2.6"
url = "2.2"
percent-encoding = "2.3.2"
gpui_util = { package = "gpui_ce_util", version = "0.2.2", path = "../gpui_ce_util" }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
smol = "2.0"
which = "6.0.0"
async-fs = "2.1"
walkdir = "2.5"
dirs = "6.0"
[target.'cfg(unix)'.dependencies]
command-fds = "0.3.1"
libc = "0.2"
nix = { version = "0.29", features = ["user"] }
[target.'cfg(target_os = "macos")'.dependencies]
mach2 = "0.5"
[target.'cfg(windows)'.dependencies]
tendril = "0.4.3"
[dev-dependencies]
pretty_assertions = { version = "1.3.0", features = ["unstable"] }
git2 = { version = "0.21", default-features = false, features = [
"vendored-libgit2",
] }
rand = "0.9"
[features]
test-support = []
+222
View File
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+383
View File
@@ -0,0 +1,383 @@
use std::path::Path;
use anyhow::{Context as _, Result};
use async_zip::base::read;
#[cfg(not(windows))]
use futures::AsyncSeek;
use futures::{AsyncRead, io::BufReader};
#[cfg(any(unix, windows))]
fn archive_path_is_normal(filename: &str) -> bool {
Path::new(filename).components().all(|c| {
matches!(
c,
std::path::Component::Normal(_) | std::path::Component::CurDir
)
})
}
#[cfg(windows)]
pub async fn extract_zip<R: AsyncRead + Unpin>(destination: &Path, reader: R) -> Result<()> {
let mut reader = read::stream::ZipFileReader::new(BufReader::new(reader));
let destination = &destination
.canonicalize()
.unwrap_or_else(|_| destination.to_path_buf());
while let Some(mut item) = reader.next_with_entry().await? {
let entry_reader = item.reader_mut();
let entry = entry_reader.entry();
let filename = entry
.filename()
.as_str()
.context("reading zip entry file name")?;
if !archive_path_is_normal(filename) {
reader = item.skip().await.context("reading next zip entry")?;
continue;
}
let path = destination.join(filename);
if entry
.dir()
.with_context(|| format!("reading zip entry metadata for path {path:?}"))?
{
std::fs::create_dir_all(&path)
.with_context(|| format!("creating directory {path:?}"))?;
} else {
let parent_dir = path
.parent()
.with_context(|| format!("no parent directory for {path:?}"))?;
std::fs::create_dir_all(parent_dir)
.with_context(|| format!("creating parent directory {parent_dir:?}"))?;
let mut file = smol::fs::File::create(&path)
.await
.with_context(|| format!("creating file {path:?}"))?;
futures::io::copy(entry_reader, &mut file)
.await
.with_context(|| format!("extracting into file {path:?}"))?;
}
reader = item.skip().await.context("reading next zip entry")?;
}
Ok(())
}
#[cfg(unix)]
pub async fn extract_zip<R: AsyncRead + Unpin>(destination: &Path, reader: R) -> Result<()> {
// Unix needs file permissions copied when extracting.
// This is only possible to do when a reader impls `AsyncSeek` and `seek::ZipFileReader` is used.
// `stream::ZipFileReader` also has the `unix_permissions` method, but it will always return `Some(0)`.
//
// A typical `reader` comes from a streaming network response, so cannot be sought right away,
// and reading the entire archive into the memory seems wasteful.
//
// So, save the stream into a temporary file first and then get it read with a seeking reader.
let mut file = async_fs::File::from(tempfile::tempfile().context("creating a temporary file")?);
futures::io::copy(&mut BufReader::new(reader), &mut file)
.await
.context("saving archive contents into the temporary file")?;
extract_seekable_zip(destination, file).await
}
#[cfg(unix)]
pub async fn extract_seekable_zip<R: AsyncRead + AsyncSeek + Unpin>(
destination: &Path,
reader: R,
) -> Result<()> {
let mut reader = read::seek::ZipFileReader::new(BufReader::new(reader))
.await
.context("reading the zip archive")?;
let destination = &destination
.canonicalize()
.unwrap_or_else(|_| destination.to_path_buf());
for (i, entry) in reader.file().entries().to_vec().into_iter().enumerate() {
let filename = entry
.filename()
.as_str()
.context("reading zip entry file name")?;
if !archive_path_is_normal(filename) {
continue;
}
let path = destination.join(filename);
if entry
.dir()
.with_context(|| format!("reading zip entry metadata for path {path:?}"))?
{
std::fs::create_dir_all(&path)
.with_context(|| format!("creating directory {path:?}"))?;
} else {
let parent_dir = path
.parent()
.with_context(|| format!("no parent directory for {path:?}"))?;
std::fs::create_dir_all(parent_dir)
.with_context(|| format!("creating parent directory {parent_dir:?}"))?;
let mut file = smol::fs::File::create(&path)
.await
.with_context(|| format!("creating file {path:?}"))?;
let mut entry_reader = reader
.reader_with_entry(i)
.await
.with_context(|| format!("reading entry for path {path:?}"))?;
futures::io::copy(&mut entry_reader, &mut file)
.await
.with_context(|| format!("extracting into file {path:?}"))?;
if let Some(perms) = entry.unix_permissions()
&& perms != 0o000
{
use std::os::unix::fs::PermissionsExt;
let permissions = std::fs::Permissions::from_mode(u32::from(perms));
file.set_permissions(permissions)
.await
.with_context(|| format!("setting permissions for file {path:?}"))?;
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use async_zip::ZipEntryBuilder;
use async_zip::base::write::ZipFileWriter;
use futures::{AsyncSeek, AsyncWriteExt};
use smol::io::Cursor;
use tempfile::TempDir;
use super::*;
#[allow(unused_variables)]
async fn compress_zip(src_dir: &Path, dst: &Path, keep_file_permissions: bool) -> Result<()> {
let mut out = smol::fs::File::create(dst).await?;
let mut writer = ZipFileWriter::new(&mut out);
for entry in walkdir::WalkDir::new(src_dir) {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
continue;
}
let relative_path = path.strip_prefix(src_dir)?;
let data = smol::fs::read(&path).await?;
let filename = relative_path.display().to_string();
#[cfg(unix)]
{
let mut builder =
ZipEntryBuilder::new(filename.into(), async_zip::Compression::Deflate);
use std::os::unix::fs::PermissionsExt;
let metadata = std::fs::metadata(path)?;
let perms = keep_file_permissions.then(|| metadata.permissions().mode() as u16);
builder = builder.unix_permissions(perms.unwrap_or_default());
writer.write_entry_whole(builder, &data).await?;
}
#[cfg(not(unix))]
{
let builder =
ZipEntryBuilder::new(filename.into(), async_zip::Compression::Deflate);
writer.write_entry_whole(builder, &data).await?;
}
}
writer.close().await?;
out.flush().await?;
out.sync_all().await?;
Ok(())
}
#[track_caller]
fn assert_file_content(path: &Path, content: &str) {
assert!(path.exists(), "file not found: {:?}", path);
let actual = std::fs::read_to_string(path).unwrap();
assert_eq!(actual, content);
}
#[track_caller]
fn make_test_data() -> TempDir {
let dir = tempfile::tempdir().unwrap();
let dst = dir.path();
std::fs::write(dst.join("test"), "Hello world.").unwrap();
std::fs::create_dir_all(dst.join("foo/bar")).unwrap();
std::fs::write(dst.join("foo/bar.txt"), "Foo bar.").unwrap();
std::fs::write(dst.join("foo/dar.md"), "Bar dar.").unwrap();
std::fs::write(dst.join("foo/bar/dar你好.txt"), "你好世界").unwrap();
dir
}
async fn read_archive(path: &Path) -> impl AsyncRead + AsyncSeek + Unpin {
let data = smol::fs::read(&path).await.unwrap();
Cursor::new(data)
}
#[test]
fn test_extract_zip() {
let test_dir = make_test_data();
let zip_file = test_dir.path().join("test.zip");
smol::block_on(async {
compress_zip(test_dir.path(), &zip_file, true)
.await
.unwrap();
let reader = read_archive(&zip_file).await;
let dir = tempfile::tempdir().unwrap();
let dst = dir.path();
extract_zip(dst, reader).await.unwrap();
assert_file_content(&dst.join("test"), "Hello world.");
assert_file_content(&dst.join("foo/bar.txt"), "Foo bar.");
assert_file_content(&dst.join("foo/dar.md"), "Bar dar.");
assert_file_content(&dst.join("foo/bar/dar你好.txt"), "你好世界");
});
}
#[cfg(unix)]
#[test]
fn test_extract_zip_preserves_executable_permissions() {
use std::os::unix::fs::PermissionsExt;
smol::block_on(async {
let test_dir = tempfile::tempdir().unwrap();
let executable_path = test_dir.path().join("my_script");
// Create an executable file
std::fs::write(&executable_path, "#!/bin/bash\necho 'Hello'").unwrap();
let mut perms = std::fs::metadata(&executable_path).unwrap().permissions();
perms.set_mode(0o755); // rwxr-xr-x
std::fs::set_permissions(&executable_path, perms).unwrap();
// Create zip
let zip_file = test_dir.path().join("test.zip");
compress_zip(test_dir.path(), &zip_file, true)
.await
.unwrap();
// Extract to new location
let extract_dir = tempfile::tempdir().unwrap();
let reader = read_archive(&zip_file).await;
extract_zip(extract_dir.path(), reader).await.unwrap();
// Check permissions are preserved
let extracted_path = extract_dir.path().join("my_script");
assert!(extracted_path.exists());
let extracted_perms = std::fs::metadata(&extracted_path).unwrap().permissions();
assert_eq!(extracted_perms.mode() & 0o777, 0o755);
});
}
#[cfg(unix)]
#[test]
fn test_extract_zip_sets_default_permissions() {
use std::os::unix::fs::PermissionsExt;
smol::block_on(async {
let test_dir = tempfile::tempdir().unwrap();
let file_path = test_dir.path().join("my_script");
std::fs::write(&file_path, "#!/bin/bash\necho 'Hello'").unwrap();
// The permissions will be shaped by the umask in the test environment
let original_perms = std::fs::metadata(&file_path).unwrap().permissions();
// Create zip
let zip_file = test_dir.path().join("test.zip");
compress_zip(test_dir.path(), &zip_file, false)
.await
.unwrap();
// Extract to new location
let extract_dir = tempfile::tempdir().unwrap();
let reader = read_archive(&zip_file).await;
extract_zip(extract_dir.path(), reader).await.unwrap();
// Permissions were not stored, so will be whatever the umask generates
// by default for new files. This should match what we saw when we previously wrote
// the file.
let extracted_path = extract_dir.path().join("my_script");
assert!(extracted_path.exists());
let extracted_perms = std::fs::metadata(&extracted_path).unwrap().permissions();
assert_eq!(
extracted_perms.mode(),
original_perms.mode(),
"Expected matching Unix file mode for unzipped file without keep_file_permissions"
);
assert_eq!(
extracted_perms, original_perms,
"Expected default set of permissions for unzipped file without keep_file_permissions"
);
});
}
#[test]
fn test_archive_path_is_normal_rejects_traversal() {
assert!(!archive_path_is_normal("../parent.txt"));
assert!(!archive_path_is_normal("foo/../../grandparent.txt"));
assert!(!archive_path_is_normal("/tmp/absolute.txt"));
assert!(archive_path_is_normal("foo/bar.txt"));
assert!(archive_path_is_normal("foo/bar/baz.txt"));
assert!(archive_path_is_normal("./foo/bar.txt"));
assert!(archive_path_is_normal("normal.txt"));
}
async fn build_zip_with_entries(entries: &[(&str, &[u8])]) -> Cursor<Vec<u8>> {
let mut buf = Cursor::new(Vec::new());
let mut writer = ZipFileWriter::new(&mut buf);
for (name, data) in entries {
let builder = ZipEntryBuilder::new((*name).into(), async_zip::Compression::Stored);
writer.write_entry_whole(builder, data).await.unwrap();
}
writer.close().await.unwrap();
buf.set_position(0);
buf
}
#[test]
fn test_extract_zip_skips_path_traversal_entries() {
smol::block_on(async {
let base_dir = tempfile::tempdir().unwrap();
let extract_dir = base_dir.path().join("subdir");
std::fs::create_dir_all(&extract_dir).unwrap();
let absolute_target = base_dir.path().join("absolute.txt");
let reader = build_zip_with_entries(&[
("normal.txt", b"normal file"),
("subdir/nested.txt", b"nested file"),
("../parent.txt", b"parent file"),
("foo/../../grandparent.txt", b"grandparent file"),
(absolute_target.to_str().unwrap(), b"absolute file"),
])
.await;
extract_zip(&extract_dir, reader).await.unwrap();
assert_file_content(&extract_dir.join("normal.txt"), "normal file");
assert_file_content(&extract_dir.join("subdir/nested.txt"), "nested file");
assert!(
!base_dir.path().join("parent.txt").exists(),
"parent traversal entry should have been skipped"
);
assert!(
!base_dir.path().join("grandparent.txt").exists(),
"nested traversal entry should have been skipped"
);
assert!(
!absolute_target.exists(),
"absolute path entry should have been skipped"
);
});
}
}
+140
View File
@@ -0,0 +1,140 @@
use std::ffi::OsStr;
#[cfg(not(target_os = "macos"))]
use std::path::Path;
#[cfg(target_os = "macos")]
mod darwin;
#[cfg(target_os = "macos")]
pub use darwin::{Child, Command, Stdio};
#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x0800_0000_u32;
pub fn new_command(program: impl AsRef<OsStr>) -> Command {
Command::new(program)
}
#[cfg(target_os = "windows")]
pub fn new_std_command(program: impl AsRef<OsStr>) -> std::process::Command {
use std::os::windows::process::CommandExt;
let mut command = std::process::Command::new(program);
command.creation_flags(CREATE_NO_WINDOW);
command
}
#[cfg(not(target_os = "windows"))]
pub fn new_std_command(program: impl AsRef<OsStr>) -> std::process::Command {
std::process::Command::new(program)
}
#[cfg(not(target_os = "macos"))]
pub type Child = smol::process::Child;
#[cfg(not(target_os = "macos"))]
pub use std::process::Stdio;
#[cfg(not(target_os = "macos"))]
#[derive(Debug)]
pub struct Command(smol::process::Command);
#[cfg(not(target_os = "macos"))]
impl Command {
#[inline]
pub fn new(program: impl AsRef<OsStr>) -> Self {
#[cfg(target_os = "windows")]
{
use smol::process::windows::CommandExt;
let mut cmd = smol::process::Command::new(program);
cmd.creation_flags(CREATE_NO_WINDOW);
Self(cmd)
}
#[cfg(not(target_os = "windows"))]
Self(smol::process::Command::new(program))
}
pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
self.0.arg(arg);
self
}
pub fn args<I, S>(&mut self, args: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.0.args(args);
self
}
pub fn get_args(&self) -> impl Iterator<Item = &OsStr> {
self.0.get_args()
}
pub fn env(&mut self, key: impl AsRef<OsStr>, val: impl AsRef<OsStr>) -> &mut Self {
self.0.env(key, val);
self
}
pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.0.envs(vars);
self
}
pub fn env_remove(&mut self, key: impl AsRef<OsStr>) -> &mut Self {
self.0.env_remove(key);
self
}
pub fn env_clear(&mut self) -> &mut Self {
self.0.env_clear();
self
}
pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Self {
self.0.current_dir(dir);
self
}
pub fn stdin(&mut self, cfg: impl Into<Stdio>) -> &mut Self {
self.0.stdin(cfg.into());
self
}
pub fn stdout(&mut self, cfg: impl Into<Stdio>) -> &mut Self {
self.0.stdout(cfg.into());
self
}
pub fn stderr(&mut self, cfg: impl Into<Stdio>) -> &mut Self {
self.0.stderr(cfg.into());
self
}
pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Self {
self.0.kill_on_drop(kill_on_drop);
self
}
pub fn spawn(&mut self) -> std::io::Result<Child> {
self.0.spawn()
}
pub async fn output(&mut self) -> std::io::Result<std::process::Output> {
self.0.output().await
}
pub async fn status(&mut self) -> std::io::Result<std::process::ExitStatus> {
self.0.status().await
}
pub fn get_program(&self) -> &OsStr {
self.0.get_program()
}
}
+915
View File
@@ -0,0 +1,915 @@
use mach2::exception_types::{
EXC_MASK_ALL, EXCEPTION_DEFAULT, exception_behavior_t, exception_mask_t,
};
use mach2::port::{MACH_PORT_NULL, mach_port_t};
use mach2::thread_status::{THREAD_STATE_NONE, thread_state_flavor_t};
use smol::Unblock;
use std::collections::BTreeMap;
use std::ffi::{CString, OsStr, OsString};
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::FromRawFd;
use std::os::unix::process::ExitStatusExt;
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Output};
use std::ptr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Stdio {
/// A new pipe should be arranged to connect the parent and child processes.
#[default]
Piped,
/// The child inherits from the corresponding parent descriptor.
Inherit,
/// This stream will be ignored (redirected to `/dev/null`).
Null,
}
impl Stdio {
pub fn piped() -> Self {
Self::Piped
}
pub fn inherit() -> Self {
Self::Inherit
}
pub fn null() -> Self {
Self::Null
}
}
unsafe extern "C" {
fn posix_spawnattr_setexceptionports_np(
attr: *mut libc::posix_spawnattr_t,
mask: exception_mask_t,
new_port: mach_port_t,
behavior: exception_behavior_t,
new_flavor: thread_state_flavor_t,
) -> libc::c_int;
fn posix_spawn_file_actions_addchdir_np(
file_actions: *mut libc::posix_spawn_file_actions_t,
path: *const libc::c_char,
) -> libc::c_int;
fn posix_spawn_file_actions_addinherit_np(
file_actions: *mut libc::posix_spawn_file_actions_t,
filedes: libc::c_int,
) -> libc::c_int;
static environ: *const *mut libc::c_char;
}
#[derive(Debug)]
pub struct Command {
program: OsString,
args: Vec<OsString>,
envs: BTreeMap<OsString, Option<OsString>>,
env_clear: bool,
current_dir: Option<PathBuf>,
stdin_cfg: Option<Stdio>,
stdout_cfg: Option<Stdio>,
stderr_cfg: Option<Stdio>,
kill_on_drop: bool,
}
impl Command {
pub fn new(program: impl AsRef<OsStr>) -> Self {
Self {
program: program.as_ref().to_owned(),
args: Vec::new(),
envs: BTreeMap::new(),
env_clear: false,
current_dir: None,
stdin_cfg: None,
stdout_cfg: None,
stderr_cfg: None,
kill_on_drop: false,
}
}
pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
self.args.push(arg.as_ref().to_owned());
self
}
pub fn args<I, S>(&mut self, args: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.args
.extend(args.into_iter().map(|a| a.as_ref().to_owned()));
self
}
pub fn get_args(&self) -> impl Iterator<Item = &OsStr> {
self.args.iter().map(|s| s.as_os_str())
}
pub fn env(&mut self, key: impl AsRef<OsStr>, val: impl AsRef<OsStr>) -> &mut Self {
self.envs
.insert(key.as_ref().to_owned(), Some(val.as_ref().to_owned()));
self
}
pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
for (key, val) in vars {
self.envs
.insert(key.as_ref().to_owned(), Some(val.as_ref().to_owned()));
}
self
}
pub fn env_remove(&mut self, key: impl AsRef<OsStr>) -> &mut Self {
let key = key.as_ref().to_owned();
if self.env_clear {
self.envs.remove(&key);
} else {
self.envs.insert(key, None);
}
self
}
pub fn env_clear(&mut self) -> &mut Self {
self.env_clear = true;
self.envs.clear();
self
}
pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Self {
self.current_dir = Some(dir.as_ref().to_owned());
self
}
pub fn stdin(&mut self, cfg: Stdio) -> &mut Self {
self.stdin_cfg = Some(cfg);
self
}
pub fn stdout(&mut self, cfg: Stdio) -> &mut Self {
self.stdout_cfg = Some(cfg);
self
}
pub fn stderr(&mut self, cfg: Stdio) -> &mut Self {
self.stderr_cfg = Some(cfg);
self
}
pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Self {
self.kill_on_drop = kill_on_drop;
self
}
pub fn spawn(&mut self) -> io::Result<Child> {
let current_dir = self
.current_dir
.as_deref()
.unwrap_or_else(|| Path::new("."));
// Optimization: if no environment modifications were requested, pass None
// to spawn_posix so it uses the `environ` global directly, avoiding a
// full copy of the environment. This matches std::process::Command behavior.
let envs = if self.env_clear || !self.envs.is_empty() {
let mut result = BTreeMap::<OsString, OsString>::new();
if !self.env_clear {
for (key, val) in std::env::vars_os() {
result.insert(key, val);
}
}
for (key, maybe_val) in &self.envs {
if let Some(val) = maybe_val {
result.insert(key.clone(), val.clone());
} else {
result.remove(key);
}
}
Some(result.into_iter().collect::<Vec<_>>())
} else {
None
};
spawn_posix_spawn(SpawnOptions {
program: &self.program,
args: &self.args,
current_dir,
envs: envs.as_deref(),
stdin_cfg: self.stdin_cfg.unwrap_or_default(),
stdout_cfg: self.stdout_cfg.unwrap_or_default(),
stderr_cfg: self.stderr_cfg.unwrap_or_default(),
kill_on_drop: self.kill_on_drop,
})
}
pub async fn output(&mut self) -> io::Result<Output> {
self.stdin_cfg.get_or_insert(Stdio::null());
self.stdout_cfg.get_or_insert(Stdio::piped());
self.stderr_cfg.get_or_insert(Stdio::piped());
let child = self.spawn()?;
child.output().await
}
pub async fn status(&mut self) -> io::Result<ExitStatus> {
let mut child = self.spawn()?;
child.status().await
}
pub fn get_program(&self) -> &OsStr {
self.program.as_os_str()
}
}
#[derive(Debug)]
pub struct Child {
pid: libc::pid_t,
pub stdin: Option<Unblock<std::fs::File>>,
pub stdout: Option<Unblock<std::fs::File>>,
pub stderr: Option<Unblock<std::fs::File>>,
kill_on_drop: bool,
status: Option<ExitStatus>,
}
impl Drop for Child {
fn drop(&mut self) {
if self.kill_on_drop && self.status.is_none() {
let _ = self.kill();
}
}
}
impl Child {
pub fn id(&self) -> u32 {
self.pid as u32
}
pub fn kill(&mut self) -> io::Result<()> {
let result = unsafe { libc::kill(self.pid, libc::SIGKILL) };
if result == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn try_status(&mut self) -> io::Result<Option<ExitStatus>> {
if let Some(status) = self.status {
return Ok(Some(status));
}
let mut status: libc::c_int = 0;
let result = unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) };
if result == -1 {
Err(io::Error::last_os_error())
} else if result == 0 {
Ok(None)
} else {
let exit_status = ExitStatus::from_raw(status);
self.status = Some(exit_status);
Ok(Some(exit_status))
}
}
pub fn status(
&mut self,
) -> impl std::future::Future<Output = io::Result<ExitStatus>> + Send + 'static {
self.stdin.take();
let pid = self.pid;
let cached_status = self.status;
async move {
if let Some(status) = cached_status {
return Ok(status);
}
smol::unblock(move || {
let mut status: libc::c_int = 0;
let result = unsafe { libc::waitpid(pid, &mut status, 0) };
if result == -1 {
Err(io::Error::last_os_error())
} else {
Ok(ExitStatus::from_raw(status))
}
})
.await
}
}
pub async fn output(mut self) -> io::Result<Output> {
use futures_lite::AsyncReadExt;
let status = self.status();
let stdout = self.stdout.take();
let stdout_future = async move {
let mut data = Vec::new();
if let Some(mut stdout) = stdout {
stdout.read_to_end(&mut data).await?;
}
io::Result::Ok(data)
};
let stderr = self.stderr.take();
let stderr_future = async move {
let mut data = Vec::new();
if let Some(mut stderr) = stderr {
stderr.read_to_end(&mut data).await?;
}
io::Result::Ok(data)
};
let (stdout_data, stderr_data) =
futures_lite::future::try_zip(stdout_future, stderr_future).await?;
let status = status.await?;
Ok(Output {
status,
stdout: stdout_data,
stderr: stderr_data,
})
}
}
struct SpawnOptions<'a> {
program: &'a OsStr,
args: &'a [OsString],
current_dir: &'a Path,
envs: Option<&'a [(OsString, OsString)]>,
stdin_cfg: Stdio,
stdout_cfg: Stdio,
stderr_cfg: Stdio,
kill_on_drop: bool,
}
fn spawn_posix_spawn(options: SpawnOptions<'_>) -> io::Result<Child> {
let SpawnOptions {
program,
args,
current_dir,
envs,
stdin_cfg,
stdout_cfg,
stderr_cfg,
kill_on_drop,
} = options;
let program_cstr = CString::new(program.as_bytes()).map_err(|_| invalid_input_error())?;
let current_dir_cstr =
CString::new(current_dir.as_os_str().as_bytes()).map_err(|_| invalid_input_error())?;
let mut argv_cstrs = vec![program_cstr.clone()];
for arg in args {
let cstr = CString::new(arg.as_bytes()).map_err(|_| invalid_input_error())?;
argv_cstrs.push(cstr);
}
let mut argv_ptrs: Vec<*mut libc::c_char> = argv_cstrs
.iter()
.map(|s| s.as_ptr() as *mut libc::c_char)
.collect();
argv_ptrs.push(ptr::null_mut());
let envp: Vec<CString> = if let Some(envs) = envs {
envs.iter()
.map(|(key, value)| {
let mut env_str = key.as_bytes().to_vec();
env_str.push(b'=');
env_str.extend_from_slice(value.as_bytes());
CString::new(env_str)
})
.collect::<Result<Vec<_>, _>>()
.map_err(|_| invalid_input_error())?
} else {
Vec::new()
};
let mut envp_ptrs: Vec<*mut libc::c_char> = envp
.iter()
.map(|s| s.as_ptr() as *mut libc::c_char)
.collect();
envp_ptrs.push(ptr::null_mut());
let (stdin_read, stdin_write) = match stdin_cfg {
Stdio::Piped => {
let (r, w) = create_pipe()?;
(Some(r), Some(w))
}
Stdio::Null => {
let fd = open_dev_null(libc::O_RDONLY)?;
(Some(fd), None)
}
Stdio::Inherit => (None, None),
};
let (stdout_read, stdout_write) = match stdout_cfg {
Stdio::Piped => {
let (r, w) = create_pipe()?;
(Some(r), Some(w))
}
Stdio::Null => {
let fd = open_dev_null(libc::O_WRONLY)?;
(None, Some(fd))
}
Stdio::Inherit => (None, None),
};
let (stderr_read, stderr_write) = match stderr_cfg {
Stdio::Piped => {
let (r, w) = create_pipe()?;
(Some(r), Some(w))
}
Stdio::Null => {
let fd = open_dev_null(libc::O_WRONLY)?;
(None, Some(fd))
}
Stdio::Inherit => (None, None),
};
let mut attr: libc::posix_spawnattr_t = ptr::null_mut();
let mut file_actions: libc::posix_spawn_file_actions_t = ptr::null_mut();
unsafe {
cvt_nz(libc::posix_spawnattr_init(&mut attr))?;
cvt_nz(libc::posix_spawn_file_actions_init(&mut file_actions))?;
cvt_nz(libc::posix_spawnattr_setflags(
&mut attr,
libc::POSIX_SPAWN_CLOEXEC_DEFAULT as libc::c_short,
))?;
cvt_nz(posix_spawnattr_setexceptionports_np(
&mut attr,
EXC_MASK_ALL,
MACH_PORT_NULL,
EXCEPTION_DEFAULT as exception_behavior_t,
THREAD_STATE_NONE,
))?;
cvt_nz(posix_spawn_file_actions_addchdir_np(
&mut file_actions,
current_dir_cstr.as_ptr(),
))?;
if let Some(fd) = stdin_read {
cvt_nz(libc::posix_spawn_file_actions_adddup2(
&mut file_actions,
fd,
libc::STDIN_FILENO,
))?;
cvt_nz(posix_spawn_file_actions_addinherit_np(
&mut file_actions,
libc::STDIN_FILENO,
))?;
}
if let Some(fd) = stdout_write {
cvt_nz(libc::posix_spawn_file_actions_adddup2(
&mut file_actions,
fd,
libc::STDOUT_FILENO,
))?;
cvt_nz(posix_spawn_file_actions_addinherit_np(
&mut file_actions,
libc::STDOUT_FILENO,
))?;
}
if let Some(fd) = stderr_write {
cvt_nz(libc::posix_spawn_file_actions_adddup2(
&mut file_actions,
fd,
libc::STDERR_FILENO,
))?;
cvt_nz(posix_spawn_file_actions_addinherit_np(
&mut file_actions,
libc::STDERR_FILENO,
))?;
}
let mut pid: libc::pid_t = 0;
let spawn_result = libc::posix_spawnp(
&mut pid,
program_cstr.as_ptr(),
&file_actions,
&attr,
argv_ptrs.as_ptr(),
if envs.is_some() {
envp_ptrs.as_ptr()
} else {
environ
},
);
libc::posix_spawnattr_destroy(&mut attr);
libc::posix_spawn_file_actions_destroy(&mut file_actions);
if let Some(fd) = stdin_read {
libc::close(fd);
}
if let Some(fd) = stdout_write {
libc::close(fd);
}
if let Some(fd) = stderr_write {
libc::close(fd);
}
cvt_nz(spawn_result)?;
Ok(Child {
pid,
stdin: stdin_write.map(|fd| Unblock::new(std::fs::File::from_raw_fd(fd))),
stdout: stdout_read.map(|fd| Unblock::new(std::fs::File::from_raw_fd(fd))),
stderr: stderr_read.map(|fd| Unblock::new(std::fs::File::from_raw_fd(fd))),
kill_on_drop,
status: None,
})
}
}
fn create_pipe() -> io::Result<(libc::c_int, libc::c_int)> {
let mut fds: [libc::c_int; 2] = [0; 2];
unsafe {
let result = libc::pipe(fds.as_mut_ptr());
if result == -1 {
let error = io::Error::last_os_error();
return Err(error);
}
// Set close-on-exec on both ends of the pipe.
//
// Without this, unrelated spawns elsewhere in the process (e.g.
// `smol::process` or `async_process`, which on Apple platforms use
// `posix_spawn` *without* `POSIX_SPAWN_CLOEXEC_DEFAULT`) would inherit
// these file descriptors and keep the pipes open even after we drop our
// side.
for &fd in &fds {
let result = libc::ioctl(fd, libc::FIOCLEX);
if result == -1 {
let error = io::Error::last_os_error();
libc::close(fds[0]);
libc::close(fds[1]);
return Err(error);
}
}
Ok((fds[0], fds[1]))
}
}
fn open_dev_null(flags: libc::c_int) -> io::Result<libc::c_int> {
// Set close-on-exec for this pipe, for the same reason as in `create_pipe`.
let fd = unsafe {
libc::open(
c"/dev/null".as_ptr() as *const libc::c_char,
flags | libc::O_CLOEXEC,
)
};
if fd == -1 {
return Err(io::Error::last_os_error());
}
Ok(fd)
}
/// Zero means `Ok()`, all other values are treated as raw OS errors. Does not look at `errno`.
/// Mirrored after Rust's std `cvt_nz` function.
fn cvt_nz(error: libc::c_int) -> io::Result<()> {
if error == 0 {
Ok(())
} else {
Err(io::Error::from_raw_os_error(error))
}
}
fn invalid_input_error() -> io::Error {
io::Error::new(
io::ErrorKind::InvalidInput,
"invalid argument: path or argument contains null byte",
)
}
#[cfg(test)]
mod tests {
use super::*;
use futures_lite::AsyncWriteExt;
// Verifies that pipes returned by `create_pipe` aren't visible to unrelated
// child processes spawned via `std::process::Command`. On macOS, `std`
// uses `posix_spawn` without `POSIX_SPAWN_CLOEXEC_DEFAULT`, so any
// non-CLOEXEC fd in the parent leaks into the child. Without
// `FD_CLOEXEC` on our pipe fds, an unrelated spawn (a terminal, the crash
// handler, etc.) running concurrently with a piped git child would hold
// git's stdin write end open and deadlock the git child on `read()`.
#[test]
fn test_create_pipe_not_inherited_by_unrelated_spawn() {
let (read_fd, write_fd) = create_pipe().expect("create_pipe failed");
// Probe with the exact fds returned by `create_pipe` (no dup), since
// duping with `F_DUPFD` would lose CLOEXEC and `F_DUPFD_CLOEXEC` would
// unconditionally set it, either of which would defeat the test.
#[allow(clippy::disallowed_methods)]
let output = std::process::Command::new("/bin/sh")
.arg("-c")
.arg(format!(
"for fd in {read_fd} {write_fd}; do \
if [ -e /dev/fd/$fd ]; then \
echo $fd WAS INHERITED; \
else \
echo $fd WAS NOT INHERITED; \
fi; \
done; \
echo DONE"
))
.output()
.expect("failed to spawn sh");
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
unsafe {
libc::close(read_fd);
libc::close(write_fd);
}
assert_eq!(
stdout,
format!("{read_fd} WAS NOT INHERITED\n{write_fd} WAS NOT INHERITED\nDONE\n")
);
}
#[test]
fn test_spawn_echo() {
smol::block_on(async {
let output = Command::new("/bin/echo")
.args(["-n", "hello world"])
.output()
.await
.expect("failed to run command");
assert!(output.status.success());
assert_eq!(output.stdout, b"hello world");
});
}
#[test]
fn test_spawn_cat_stdin() {
smol::block_on(async {
let mut child = Command::new("/bin/cat")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("failed to spawn");
if let Some(ref mut stdin) = child.stdin {
stdin
.write_all(b"hello from stdin")
.await
.expect("failed to write");
stdin.close().await.expect("failed to close");
}
drop(child.stdin.take());
let output = child.output().await.expect("failed to get output");
assert!(output.status.success());
assert_eq!(output.stdout, b"hello from stdin");
});
}
#[test]
fn test_spawn_stderr() {
smol::block_on(async {
let output = Command::new("/bin/sh")
.args(["-c", "echo error >&2"])
.output()
.await
.expect("failed to run command");
assert!(output.status.success());
assert_eq!(output.stderr, b"error\n");
});
}
#[test]
fn test_spawn_exit_code() {
smol::block_on(async {
let output = Command::new("/bin/sh")
.args(["-c", "exit 42"])
.output()
.await
.expect("failed to run command");
assert!(!output.status.success());
assert_eq!(output.status.code(), Some(42));
});
}
#[test]
fn test_spawn_current_dir() {
smol::block_on(async {
let output = Command::new("/bin/pwd")
.current_dir("/tmp")
.output()
.await
.expect("failed to run command");
assert!(output.status.success());
let pwd = String::from_utf8_lossy(&output.stdout);
assert!(pwd.trim() == "/tmp" || pwd.trim() == "/private/tmp");
});
}
#[test]
fn test_spawn_env() {
smol::block_on(async {
let output = Command::new("/bin/sh")
.args(["-c", "echo $MY_TEST_VAR"])
.env("MY_TEST_VAR", "test_value")
.output()
.await
.expect("failed to run command");
assert!(output.status.success());
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "test_value");
});
}
#[test]
fn test_spawn_status() {
smol::block_on(async {
let status = Command::new("/usr/bin/true")
.status()
.await
.expect("failed to run command");
assert!(status.success());
let status = Command::new("/usr/bin/false")
.status()
.await
.expect("failed to run command");
assert!(!status.success());
});
}
#[test]
fn test_env_remove_removes_set_env() {
smol::block_on(async {
let output = Command::new("/bin/sh")
.args(["-c", "echo ${MY_VAR:-unset}"])
.env("MY_VAR", "set_value")
.env_remove("MY_VAR")
.output()
.await
.expect("failed to run command");
assert!(output.status.success());
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "unset");
});
}
#[test]
fn test_env_remove_removes_inherited_env() {
smol::block_on(async {
// SAFETY: This test is single-threaded and we clean up the var at the end
unsafe { std::env::set_var("TEST_INHERITED_VAR", "inherited_value") };
let output = Command::new("/bin/sh")
.args(["-c", "echo ${TEST_INHERITED_VAR:-unset}"])
.env_remove("TEST_INHERITED_VAR")
.output()
.await
.expect("failed to run command");
assert!(output.status.success());
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "unset");
// SAFETY: Cleaning up test env var
unsafe { std::env::remove_var("TEST_INHERITED_VAR") };
});
}
#[test]
fn test_env_after_env_remove() {
smol::block_on(async {
let output = Command::new("/bin/sh")
.args(["-c", "echo ${MY_VAR:-unset}"])
.env_remove("MY_VAR")
.env("MY_VAR", "new_value")
.output()
.await
.expect("failed to run command");
assert!(output.status.success());
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "new_value");
});
}
#[test]
fn test_env_remove_after_env_clear() {
smol::block_on(async {
let output = Command::new("/bin/sh")
.args(["-c", "echo ${MY_VAR:-unset}"])
.env_clear()
.env("MY_VAR", "set_value")
.env_remove("MY_VAR")
.output()
.await
.expect("failed to run command");
assert!(output.status.success());
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "unset");
});
}
#[test]
fn test_stdio_null_stdin() {
smol::block_on(async {
let child = Command::new("/bin/cat")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.spawn()
.expect("failed to spawn");
let output = child.output().await.expect("failed to get output");
assert!(output.status.success());
assert!(
output.stdout.is_empty(),
"stdin from /dev/null should produce no output from cat"
);
});
}
#[test]
fn test_stdio_null_stdout() {
smol::block_on(async {
let mut child = Command::new("/bin/echo")
.args(["hello"])
.stdout(Stdio::null())
.spawn()
.expect("failed to spawn");
assert!(
child.stdout.is_none(),
"stdout should be None when Stdio::null() is used"
);
let status = child.status().await.expect("failed to get status");
assert!(status.success());
});
}
#[test]
fn test_stdio_null_stderr() {
smol::block_on(async {
let mut child = Command::new("/bin/sh")
.args(["-c", "echo error >&2"])
.stderr(Stdio::null())
.spawn()
.expect("failed to spawn");
assert!(
child.stderr.is_none(),
"stderr should be None when Stdio::null() is used"
);
let status = child.status().await.expect("failed to get status");
assert!(status.success());
});
}
#[test]
fn test_stdio_piped_stdin() {
smol::block_on(async {
let mut child = Command::new("/bin/cat")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("failed to spawn");
assert!(
child.stdin.is_some(),
"stdin should be Some when Stdio::piped() is used"
);
if let Some(ref mut stdin) = child.stdin {
stdin
.write_all(b"piped input")
.await
.expect("failed to write");
stdin.close().await.expect("failed to close");
}
drop(child.stdin.take());
let output = child.output().await.expect("failed to get output");
assert!(output.status.success());
assert_eq!(output.stdout, b"piped input");
});
}
}
+202
View File
@@ -0,0 +1,202 @@
use std::collections::HashMap;
use std::hash::Hash;
/// Computes the minimum detail level needed for each item so that no two items
/// share the same description. Items whose descriptions are unique at level 0
/// stay at 0; items that collide get their detail level incremented until either
/// the collision is resolved or increasing the level no longer changes the
/// description (preventing infinite loops for truly identical items).
///
/// The `get_description` closure must return a sequence that eventually reaches
/// a "fixed point" where increasing `detail` no longer changes the output. If
/// an item reaches its fixed point, it is assumed it will no longer change and
/// will no longer be checked for collisions.
pub fn compute_disambiguation_details<T, D>(
items: &[T],
get_description: impl Fn(&T, usize) -> D,
) -> Vec<usize>
where
D: Eq + Hash + Clone,
{
let mut details = vec![0usize; items.len()];
let mut descriptions: HashMap<D, Vec<usize>> = HashMap::default();
let mut current_descriptions: Vec<D> =
items.iter().map(|item| get_description(item, 0)).collect();
loop {
let mut any_collisions = false;
for (index, (item, &detail)) in items.iter().zip(&details).enumerate() {
if detail > 0 {
let new_description = get_description(item, detail);
if new_description == current_descriptions[index] {
continue;
}
current_descriptions[index] = new_description;
}
descriptions
.entry(current_descriptions[index].clone())
.or_default()
.push(index);
}
for (_, indices) in descriptions.drain() {
if indices.len() > 1 {
any_collisions = true;
for index in indices {
details[index] += 1;
}
}
}
if !any_collisions {
break;
}
}
details
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_no_conflicts() {
let items = vec!["alpha", "beta", "gamma"];
let details = compute_disambiguation_details(&items, |item, _detail| item.to_string());
assert_eq!(details, vec![0, 0, 0]);
}
#[test]
fn test_simple_two_way_conflict() {
// Two items with the same base name but different parents.
let items = vec![("src/foo.rs", "foo.rs"), ("lib/foo.rs", "foo.rs")];
let details = compute_disambiguation_details(&items, |item, detail| match detail {
0 => item.1.to_string(),
_ => item.0.to_string(),
});
assert_eq!(details, vec![1, 1]);
}
#[test]
fn test_three_way_conflict() {
let items = vec![
("foo.rs", "a/foo.rs"),
("foo.rs", "b/foo.rs"),
("foo.rs", "c/foo.rs"),
];
let details = compute_disambiguation_details(&items, |item, detail| match detail {
0 => item.0.to_string(),
_ => item.1.to_string(),
});
assert_eq!(details, vec![1, 1, 1]);
}
#[test]
fn test_deeper_conflict() {
// At detail 0, all three show "file.rs".
// At detail 1, items 0 and 1 both show "src/file.rs", item 2 shows "lib/file.rs".
// At detail 2, item 0 shows "a/src/file.rs", item 1 shows "b/src/file.rs".
let items = vec![
vec!["file.rs", "src/file.rs", "a/src/file.rs"],
vec!["file.rs", "src/file.rs", "b/src/file.rs"],
vec!["file.rs", "lib/file.rs", "x/lib/file.rs"],
];
let details = compute_disambiguation_details(&items, |item, detail| {
let clamped = detail.min(item.len() - 1);
item[clamped].to_string()
});
assert_eq!(details, vec![2, 2, 1]);
}
#[test]
fn test_mixed_conflicting_and_unique() {
let items = vec![
("src/foo.rs", "foo.rs"),
("lib/foo.rs", "foo.rs"),
("src/bar.rs", "bar.rs"),
];
let details = compute_disambiguation_details(&items, |item, detail| match detail {
0 => item.1.to_string(),
_ => item.0.to_string(),
});
assert_eq!(details, vec![1, 1, 0]);
}
#[test]
fn test_identical_items_terminates() {
// All items return the same description at every detail level.
// The algorithm must terminate rather than looping forever.
let items = vec!["same", "same", "same"];
let details = compute_disambiguation_details(&items, |item, _detail| item.to_string());
// After bumping to 1, the description doesn't change from level 0,
// so the items are skipped and the loop terminates.
assert_eq!(details, vec![1, 1, 1]);
}
#[test]
fn test_single_item() {
let items = vec!["only"];
let details = compute_disambiguation_details(&items, |item, _detail| item.to_string());
assert_eq!(details, vec![0]);
}
#[test]
fn test_empty_input() {
let items: Vec<&str> = vec![];
let details = compute_disambiguation_details(&items, |item, _detail| item.to_string());
let expected: Vec<usize> = vec![];
assert_eq!(details, expected);
}
#[test]
fn test_duplicate_paths_from_multiple_groups() {
use std::path::Path;
// Simulates the sidebar scenario: a path like /Users/rtfeldman/code/zed
// appears in two project groups (e.g. "zed" alone and "zed, roc").
// After deduplication, only unique paths should be disambiguated.
//
// Paths:
// /Users/rtfeldman/code/worktrees/zed/focal-arrow/zed (group 1)
// /Users/rtfeldman/code/zed (group 2)
// /Users/rtfeldman/code/zed (group 3, same path as group 2)
// /Users/rtfeldman/code/roc (group 3)
//
// A naive flat_map collects duplicates. The duplicate /code/zed entries
// collide with each other and drive the detail to the full path.
// The fix is to deduplicate before disambiguating.
fn path_suffix(path: &Path, detail: usize) -> String {
let mut components: Vec<_> = path
.components()
.rev()
.filter_map(|c| match c {
std::path::Component::Normal(s) => Some(s.to_string_lossy()),
_ => None,
})
.take(detail + 1)
.collect();
components.reverse();
components.join("/")
}
let all_paths: Vec<&Path> = vec![
Path::new("/Users/rtfeldman/code/worktrees/zed/focal-arrow/zed"),
Path::new("/Users/rtfeldman/code/zed"),
Path::new("/Users/rtfeldman/code/roc"),
];
let details =
compute_disambiguation_details(&all_paths, |path, detail| path_suffix(path, detail));
// focal-arrow/zed and code/zed both end in "zed", so they need detail 1.
// "roc" is unique at detail 0.
assert_eq!(details, vec![1, 1, 0]);
assert_eq!(path_suffix(all_paths[0], details[0]), "focal-arrow/zed");
assert_eq!(path_suffix(all_paths[1], details[1]), "code/zed");
assert_eq!(path_suffix(all_paths[2], details[2]), "roc");
}
}
+111
View File
@@ -0,0 +1,111 @@
use crate::ResultExt;
use anyhow::{Result, bail};
use async_fs as fs;
use futures_lite::StreamExt;
use std::path::{Path, PathBuf};
/// Removes all files and directories matching the given predicate
pub async fn remove_matching<F>(dir: &Path, predicate: F)
where
F: Fn(&Path) -> bool,
{
if let Some(mut entries) = fs::read_dir(dir).await.log_err() {
while let Some(entry) = entries.next().await {
if let Some(entry) = entry.log_err() {
let entry_path = entry.path();
if predicate(entry_path.as_path())
&& let Ok(metadata) = fs::metadata(&entry_path).await
{
if metadata.is_file() {
fs::remove_file(&entry_path).await.log_err();
} else {
fs::remove_dir_all(&entry_path).await.log_err();
}
}
}
}
}
}
pub async fn collect_matching<F>(dir: &Path, predicate: F) -> Vec<PathBuf>
where
F: Fn(&Path) -> bool,
{
let mut matching = vec![];
if let Some(mut entries) = fs::read_dir(dir).await.log_err() {
while let Some(entry) = entries.next().await {
if let Some(entry) = entry.log_err()
&& predicate(entry.path().as_path())
{
matching.push(entry.path());
}
}
}
matching
}
pub async fn find_file_name_in_dir<F>(dir: &Path, predicate: F) -> Option<PathBuf>
where
F: Fn(&str) -> bool,
{
if let Some(mut entries) = fs::read_dir(dir).await.log_err() {
while let Some(entry) = entries.next().await {
if let Some(entry) = entry.log_err() {
let entry_path = entry.path();
if let Some(file_name) = entry_path
.file_name()
.map(|file_name| file_name.to_string_lossy())
&& predicate(&file_name)
{
return Some(entry_path);
}
}
}
}
None
}
pub async fn move_folder_files_to_folder<P: AsRef<Path>>(
source_path: P,
target_path: P,
) -> Result<()> {
if !target_path.as_ref().is_dir() {
bail!("Folder not found or is not a directory");
}
let mut entries = fs::read_dir(source_path.as_ref()).await?;
while let Some(entry) = entries.next().await {
let entry = entry?;
let old_path = entry.path();
let new_path = target_path.as_ref().join(entry.file_name());
fs::rename(&old_path, &new_path).await?;
}
fs::remove_dir(source_path).await?;
Ok(())
}
#[cfg(unix)]
/// Set the permissions for the given path so that the file becomes executable.
/// This is a noop for non-unix platforms.
pub async fn make_file_executable(path: &Path) -> std::io::Result<()> {
fs::set_permissions(
path,
<fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
)
.await
}
#[cfg(not(unix))]
#[allow(clippy::unused_async)]
/// Set the permissions for the given path so that the file becomes executable.
/// This is a noop for non-unix platforms.
pub async fn make_file_executable(_path: &Path) -> std::io::Result<()> {
Ok(())
}
+376
View File
@@ -0,0 +1,376 @@
use std::fmt::{Display, Formatter};
/// Generates a URL-friendly slug from heading text (e.g. "Hello World" → "hello-world").
pub fn generate_heading_slug(text: &str) -> String {
text.trim()
.chars()
.filter_map(|c| {
if c.is_alphanumeric() || c == '-' || c == '_' {
Some(c.to_lowercase().next().unwrap_or(c))
} else if c == ' ' {
Some('-')
} else {
None
}
})
.collect()
}
/// Returns true if the URL starts with a URI scheme (RFC 3986 §3.1).
fn has_uri_scheme(url: &str) -> bool {
let mut chars = url.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() => {}
_ => return false,
}
for c in chars {
if c == ':' {
return true;
}
if !(c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') {
return false;
}
}
false
}
/// Splits a relative URL into its path and `#fragment` parts.
/// Absolute URLs are returned as-is with no fragment.
pub fn split_local_url_fragment(url: &str) -> (&str, Option<&str>) {
if has_uri_scheme(url) {
return (url, None);
}
match url.find('#') {
Some(pos) => {
let path = &url[..pos];
let fragment = &url[pos + 1..];
(
path,
if fragment.is_empty() {
None
} else {
Some(fragment)
},
)
}
None => (url, None),
}
}
/// Indicates that the wrapped `String` is markdown text.
#[derive(Debug, Clone)]
pub struct MarkdownString(pub String);
impl Display for MarkdownString {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
/// Escapes markdown special characters in markdown text blocks. Markdown code blocks follow
/// different rules and `MarkdownInlineCode` or `MarkdownCodeBlock` should be used in that case.
///
/// Also escapes the following markdown extensions:
///
/// * `^` for superscripts
/// * `$` for inline math
/// * `~` for strikethrough
///
/// Escape of some characters is unnecessary, because while they are involved in markdown syntax,
/// the other characters involved are escaped:
///
/// * `!`, `]`, `(`, and `)` are used in link syntax, but `[` is escaped so these are parsed as
/// plaintext.
///
/// * `;` is used in HTML entity syntax, but `&` is escaped, so they are parsed as plaintext.
///
/// TODO: There is one escape this doesn't do currently. Period after numbers at the start of the
/// line (`[0-9]*\.`) should also be escaped to avoid it being interpreted as a list item.
pub struct MarkdownEscaped<'a>(pub &'a str);
/// Implements `Display` to format markdown inline code (wrapped in backticks), handling code that
/// contains backticks and spaces. All whitespace is treated as a single space character. For text
/// that does not contain whitespace other than ' ', this escaping roundtrips through
/// pulldown-cmark.
///
/// When used in tables, `|` should be escaped like `\|` in the text provided to this function.
pub struct MarkdownInlineCode<'a>(pub &'a str);
/// Implements `Display` to format markdown code blocks, wrapped in 3 or more backticks as needed.
pub struct MarkdownCodeBlock<'a> {
pub tag: &'a str,
pub text: &'a str,
}
impl Display for MarkdownEscaped<'_> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
let mut start_of_unescaped = None;
for (ix, c) in self.0.char_indices() {
match c {
// Always escaped.
'\\' | '`' | '*' | '_' | '[' | '^' | '$' | '~' | '&' |
// TODO: these only need to be escaped when they are the first non-whitespace
// character of the line of a block. There should probably be both an `escape_block`
// which does this and an `escape_inline` method which does not escape these.
'#' | '+' | '=' | '-' => {
match start_of_unescaped {
None => {}
Some(start_of_unescaped) => {
write!(formatter, "{}", &self.0[start_of_unescaped..ix])?;
}
}
write!(formatter, "\\")?;
// Can include this char in the "unescaped" text since a
// backslash was just emitted.
start_of_unescaped = Some(ix);
}
// Escaped since `<` is used in opening HTML tags. `&lt;` is used since Markdown
// supports HTML entities, and this allows the text to be used directly in HTML.
'<' => {
match start_of_unescaped {
None => {}
Some(start_of_unescaped) => {
write!(formatter, "{}", &self.0[start_of_unescaped..ix])?;
}
}
write!(formatter, "&lt;")?;
start_of_unescaped = None;
}
// Escaped since `>` is used for blockquotes. `&gt;` is used since Markdown supports
// HTML entities, and this allows the text to be used directly in HTML.
'>' => {
match start_of_unescaped {
None => {}
Some(start_of_unescaped) => {
write!(formatter, "{}", &self.0[start_of_unescaped..ix])?;
}
}
write!(formatter, "&gt;")?;
start_of_unescaped = None;
}
_ => {
if start_of_unescaped.is_none() {
start_of_unescaped = Some(ix);
}
}
}
}
if let Some(start_of_unescaped) = start_of_unescaped {
write!(formatter, "{}", &self.0[start_of_unescaped..])?;
}
Ok(())
}
}
impl Display for MarkdownInlineCode<'_> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
// Apache License 2.0, same as this crate.
//
// Copied from `pulldown-cmark-to-cmark-20.0.0` with modifications:
//
// * Handling of all whitespace. pulldown-cmark-to-cmark is anticipating
// `Code` events parsed by pulldown-cmark.
//
// https://github.com/Byron/pulldown-cmark-to-cmark/blob/3c850de2d3d1d79f19ca5f375e1089a653cf3ff7/src/lib.rs#L290
let mut all_whitespace = true;
let text = self
.0
.chars()
.map(|c| {
if c.is_whitespace() {
' '
} else {
all_whitespace = false;
c
}
})
.collect::<String>();
// When inline code has leading and trailing ' ' characters, additional space is needed
// to escape it, unless all characters are space.
if all_whitespace {
write!(formatter, "`{text}`")
} else {
// More backticks are needed to delimit the inline code than the maximum number of
// backticks in a consecutive run.
let backticks = "`".repeat(count_max_consecutive_chars(&text, '`') + 1);
let space = match text.as_bytes() {
&[b'`', ..] | &[.., b'`'] => " ", // Space needed to separate backtick.
&[b' ', .., b' '] => " ", // Space needed to escape inner space.
_ => "", // No space needed.
};
write!(formatter, "{backticks}{space}{text}{space}{backticks}")
}
}
}
impl Display for MarkdownCodeBlock<'_> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
let tag = self.tag;
let text = self.text;
let backticks = "`".repeat(3.max(count_max_consecutive_chars(text, '`') + 1));
write!(formatter, "{backticks}{tag}\n{text}\n{backticks}\n")
}
}
// Copied from `pulldown-cmark-to-cmark-20.0.0` with changed names.
// https://github.com/Byron/pulldown-cmark-to-cmark/blob/3c850de2d3d1d79f19ca5f375e1089a653cf3ff7/src/lib.rs#L1063
// Apache License 2.0, same as this code.
fn count_max_consecutive_chars(text: &str, search: char) -> usize {
let mut in_search_chars = false;
let mut max_count = 0;
let mut cur_count = 0;
for ch in text.chars() {
if ch == search {
cur_count += 1;
in_search_chars = true;
} else if in_search_chars {
max_count = max_count.max(cur_count);
cur_count = 0;
in_search_chars = false;
}
}
max_count.max(cur_count)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_markdown_escaped() {
let input = r#"
# Heading
Another heading
===
Another heading variant
---
Paragraph with [link](https://example.com) and `code`, *emphasis*, and ~strikethrough~.
```
code block
```
List with varying leaders:
- Item 1
* Item 2
+ Item 3
Some math: $`\sqrt{3x-1}+(1+x)^2`$
HTML entity: &nbsp;
"#;
let expected = r#"
\# Heading
Another heading
\=\=\=
Another heading variant
\-\-\-
Paragraph with \[link](https://example.com) and \`code\`, \*emphasis\*, and \~strikethrough\~.
\`\`\`
code block
\`\`\`
List with varying leaders:
\- Item 1
\* Item 2
\+ Item 3
Some math: \$\`\\sqrt{3x\-1}\+(1\+x)\^2\`\$
HTML entity: \&nbsp;
"#;
assert_eq!(MarkdownEscaped(input).to_string(), expected);
}
#[test]
fn test_markdown_inline_code() {
assert_eq!(MarkdownInlineCode(" ").to_string(), "` `");
assert_eq!(MarkdownInlineCode("text").to_string(), "`text`");
assert_eq!(MarkdownInlineCode("text ").to_string(), "`text `");
assert_eq!(MarkdownInlineCode(" text ").to_string(), "` text `");
assert_eq!(MarkdownInlineCode("`").to_string(), "`` ` ``");
assert_eq!(MarkdownInlineCode("``").to_string(), "``` `` ```");
assert_eq!(MarkdownInlineCode("`text`").to_string(), "`` `text` ``");
assert_eq!(
MarkdownInlineCode("some `text` no leading or trailing backticks").to_string(),
"``some `text` no leading or trailing backticks``"
);
}
#[test]
fn test_count_max_consecutive_chars() {
assert_eq!(
count_max_consecutive_chars("``a```b``", '`'),
3,
"the highest seen consecutive segment of backticks counts"
);
assert_eq!(
count_max_consecutive_chars("```a``b`", '`'),
3,
"it can't be downgraded later"
);
}
#[test]
fn test_split_local_url_fragment() {
assert_eq!(split_local_url_fragment("#heading"), ("", Some("heading")));
assert_eq!(
split_local_url_fragment("./file.md#heading"),
("./file.md", Some("heading"))
);
assert_eq!(split_local_url_fragment("./file.md"), ("./file.md", None));
assert_eq!(
split_local_url_fragment("https://example.com#frag"),
("https://example.com#frag", None)
);
assert_eq!(
split_local_url_fragment("mailto:user@example.com"),
("mailto:user@example.com", None)
);
assert_eq!(split_local_url_fragment("#"), ("", None));
assert_eq!(
split_local_url_fragment("../other.md#section"),
("../other.md", Some("section"))
);
assert_eq!(
split_local_url_fragment("123:not-a-scheme#frag"),
("123:not-a-scheme", Some("frag"))
);
}
#[test]
fn test_generate_heading_slug() {
assert_eq!(generate_heading_slug("Hello World"), "hello-world");
assert_eq!(generate_heading_slug("Hello World"), "hello--world");
assert_eq!(generate_heading_slug("Hello-World"), "hello-world");
assert_eq!(
generate_heading_slug("Some **bold** text"),
"some-bold-text"
);
assert_eq!(generate_heading_slug("Let's try with Ü"), "lets-try-with-ü");
assert_eq!(
generate_heading_slug("heading with 123 numbers"),
"heading-with-123-numbers"
);
assert_eq!(
generate_heading_slug("What about (parens)?"),
"what-about-parens"
);
assert_eq!(
generate_heading_slug(" leading spaces "),
"leading-spaces"
);
}
}
+233
View File
@@ -0,0 +1,233 @@
use std::{
hash::{Hash, Hasher},
path::{Path, PathBuf},
sync::Arc,
};
use crate::paths::SanitizedPath;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
/// A list of absolute paths, with an associated display order.
///
/// Two `PathList` values are considered equal if they contain the same paths,
/// regardless of the order in which those paths were originally provided.
///
/// The paths can be retrieved in the original order using `ordered_paths()`.
#[derive(Default, Debug, Clone)]
pub struct PathList {
/// The paths, in lexicographic order.
paths: Arc<[PathBuf]>,
/// The order in which the paths were provided.
///
/// See `ordered_paths()` for a way to get the paths in the original order.
order: Arc<[usize]>,
}
impl PartialEq for PathList {
fn eq(&self, other: &Self) -> bool {
self.paths == other.paths
}
}
impl Eq for PathList {}
impl Hash for PathList {
fn hash<H: Hasher>(&self, state: &mut H) {
self.paths.hash(state);
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedPathList {
pub paths: String,
pub order: String,
}
impl PathList {
pub fn new<P: AsRef<Path>>(paths: &[P]) -> Self {
let mut indexed_paths: Vec<(usize, PathBuf)> = paths
.iter()
.enumerate()
.map(|(ix, path)| (ix, SanitizedPath::new(path).into()))
.collect();
indexed_paths.sort_by(|(_, a), (_, b)| a.cmp(b));
let order = indexed_paths.iter().map(|e| e.0).collect::<Vec<_>>().into();
let paths = indexed_paths
.into_iter()
.map(|e| e.1)
.collect::<Vec<_>>()
.into();
Self { order, paths }
}
pub fn is_empty(&self) -> bool {
self.paths.is_empty()
}
/// Returns a new `PathList` with the given path removed.
pub fn without_path(&self, path_to_remove: &Path) -> PathList {
let paths: Vec<PathBuf> = self
.ordered_paths()
.filter(|p| p.as_path() != path_to_remove)
.cloned()
.collect();
PathList::new(&paths)
}
/// Get the paths in lexicographic order.
pub fn paths(&self) -> &[PathBuf] {
self.paths.as_ref()
}
/// Get the paths in the lexicographic order.
pub fn paths_owned(&self) -> Arc<[PathBuf]> {
self.paths.clone()
}
/// Get the order in which the paths were provided.
pub fn order(&self) -> &[usize] {
self.order.as_ref()
}
/// Get the paths in the original order.
pub fn ordered_paths(&self) -> impl Iterator<Item = &PathBuf> {
self.order
.iter()
.zip(self.paths.iter())
.sorted_by_key(|(i, _)| **i)
.map(|(_, path)| path)
}
pub fn is_lexicographically_ordered(&self) -> bool {
self.order.iter().enumerate().all(|(i, &j)| i == j)
}
pub fn deserialize(serialized: &SerializedPathList) -> Self {
let mut paths: Vec<PathBuf> = if serialized.paths.is_empty() {
Vec::new()
} else {
serialized.paths.split('\n').map(PathBuf::from).collect()
};
let mut order: Vec<usize> = serialized
.order
.split(',')
.filter_map(|s| s.parse().ok())
.collect();
if !paths.is_sorted() || order.len() != paths.len() {
order = (0..paths.len()).collect();
paths.sort();
}
Self {
paths: paths.into(),
order: order.into(),
}
}
pub fn serialize(&self) -> SerializedPathList {
use std::fmt::Write as _;
let mut paths = String::new();
for path in self.paths.iter() {
if !paths.is_empty() {
paths.push('\n');
}
paths.push_str(&path.to_string_lossy());
}
let mut order = String::new();
for ix in self.order.iter() {
if !order.is_empty() {
order.push(',');
}
write!(&mut order, "{}", *ix).unwrap();
}
SerializedPathList { paths, order }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_path_list() {
let list1 = PathList::new(&["a/d", "a/c"]);
let list2 = PathList::new(&["a/c", "a/d"]);
assert_eq!(list1.paths(), list2.paths(), "paths differ");
assert_eq!(list1.order(), &[1, 0], "list1 order incorrect");
assert_eq!(list2.order(), &[0, 1], "list2 order incorrect");
// Same paths in different order are equal (order is display-only).
assert_eq!(
list1, list2,
"same paths with different order should be equal"
);
let list1_deserialized = PathList::deserialize(&list1.serialize());
assert_eq!(list1_deserialized, list1, "list1 deserialization failed");
let list2_deserialized = PathList::deserialize(&list2.serialize());
assert_eq!(list2_deserialized, list2, "list2 deserialization failed");
assert_eq!(
list1.ordered_paths().collect_array().unwrap(),
[&PathBuf::from("a/d"), &PathBuf::from("a/c")],
"list1 ordered paths incorrect"
);
assert_eq!(
list2.ordered_paths().collect_array().unwrap(),
[&PathBuf::from("a/c"), &PathBuf::from("a/d")],
"list2 ordered paths incorrect"
);
}
#[test]
fn test_path_list_ordering() {
let list = PathList::new(&["b", "a", "c"]);
assert_eq!(
list.paths(),
&[PathBuf::from("a"), PathBuf::from("b"), PathBuf::from("c")]
);
assert_eq!(list.order(), &[1, 0, 2]);
assert!(!list.is_lexicographically_ordered());
let serialized = list.serialize();
let deserialized = PathList::deserialize(&serialized);
assert_eq!(deserialized, list);
assert_eq!(
deserialized.ordered_paths().collect_array().unwrap(),
[
&PathBuf::from("b"),
&PathBuf::from("a"),
&PathBuf::from("c")
]
);
let list = PathList::new(&["b", "c", "a"]);
assert_eq!(
list.paths(),
&[PathBuf::from("a"), PathBuf::from("b"), PathBuf::from("c")]
);
assert_eq!(list.order(), &[2, 0, 1]);
assert!(!list.is_lexicographically_ordered());
let serialized = list.serialize();
let deserialized = PathList::deserialize(&serialized);
assert_eq!(deserialized, list);
assert_eq!(
deserialized.ordered_paths().collect_array().unwrap(),
[
&PathBuf::from("b"),
&PathBuf::from("c"),
&PathBuf::from("a"),
]
);
}
}
File diff suppressed because it is too large Load Diff
+92
View File
@@ -0,0 +1,92 @@
use anyhow::{Context as _, Result};
use std::process::Stdio;
/// A wrapper around `smol::process::Child` that ensures all subprocesses
/// are killed when the process is terminated by using process groups.
pub struct Child {
process: smol::process::Child,
}
impl std::ops::Deref for Child {
type Target = smol::process::Child;
fn deref(&self) -> &Self::Target {
&self.process
}
}
impl std::ops::DerefMut for Child {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.process
}
}
impl Child {
#[cfg(not(windows))]
pub fn spawn(
mut command: std::process::Command,
stdin: Stdio,
stdout: Stdio,
stderr: Stdio,
) -> Result<Self> {
crate::set_pre_exec_to_start_new_session(&mut command);
let mut command = smol::process::Command::from(command);
let process = command
.stdin(stdin)
.stdout(stdout)
.stderr(stderr)
.spawn()
.with_context(|| {
format!(
"failed to spawn command {}",
crate::redact::redact_command(&format!("{command:?}"))
)
})?;
Ok(Self { process })
}
#[cfg(windows)]
pub fn spawn(
command: std::process::Command,
stdin: Stdio,
stdout: Stdio,
stderr: Stdio,
) -> Result<Self> {
// TODO(windows): create a job object and add the child process handle to it,
// see https://learn.microsoft.com/en-us/windows/win32/procthread/job-objects
let mut command = smol::process::Command::from(command);
let process = command
.stdin(stdin)
.stdout(stdout)
.stderr(stderr)
.spawn()
.with_context(|| {
format!(
"failed to spawn command {}",
crate::redact::redact_command(&format!("{command:?}"))
)
})?;
Ok(Self { process })
}
pub fn into_inner(self) -> smol::process::Child {
self.process
}
#[cfg(not(windows))]
pub fn kill(&mut self) -> Result<()> {
let pid = self.process.id();
unsafe {
libc::killpg(pid as i32, libc::SIGKILL);
}
Ok(())
}
#[cfg(windows)]
pub fn kill(&mut self) -> Result<()> {
// TODO(windows): terminate the job object in kill
self.process.kill()?;
Ok(())
}
}
+49
View File
@@ -0,0 +1,49 @@
use std::sync::LazyLock;
static REDACT_REGEX: LazyLock<regex::Regex> = LazyLock::new(|| {
regex::Regex::new(r#"([A-Z_][A-Z0-9_]*)=("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+)"#).unwrap()
});
/// Whether a given environment variable name should have its value redacted
pub fn should_redact(env_var_name: &str) -> bool {
const REDACTED_SUFFIXES: &[&str] = &[
"KEY",
"TOKEN",
"PASSWORD",
"SECRET",
"PASS",
"CREDENTIALS",
"LICENSE",
];
REDACTED_SUFFIXES
.iter()
.any(|suffix| env_var_name.ends_with(suffix))
}
/// Redact a string which could include a command with environment variables
pub fn redact_command(command: &str) -> String {
REDACT_REGEX
.replace_all(command, |caps: &regex::Captures| {
let var_name = &caps[1];
let value = &caps[2];
if should_redact(var_name) {
format!(r#"{}="[REDACTED]""#, var_name)
} else {
format!("{}={}", var_name, value)
}
})
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_redact_string_with_multiple_env_vars() {
let input = r#"failed to spawn command cd "/code/something" && ANTHROPIC_API_KEY="sk-ant-api03-WOOOO" COMMAND_MODE="unix2003" GEMINI_API_KEY="AIGEMINIFACE" HOME="/Users/foo""#;
let result = redact_command(input);
let expected = r#"failed to spawn command cd "/code/something" && ANTHROPIC_API_KEY="[REDACTED]" COMMAND_MODE="unix2003" GEMINI_API_KEY="[REDACTED]" HOME="/Users/foo""#;
assert_eq!(result, expected);
}
}
+637
View File
@@ -0,0 +1,637 @@
use crate::paths::{PathStyle, is_absolute};
use anyhow::{Context as _, Result, anyhow};
use serde::{Deserialize, Serialize};
use std::{
borrow::{Borrow, Cow},
fmt,
ops::Deref,
path::{Path, PathBuf},
sync::Arc,
};
/// A file system path that is guaranteed to be relative and normalized.
///
/// This type can be used to represent paths in a uniform way, regardless of
/// whether they refer to Windows or POSIX file systems, and regardless of
/// the host platform.
///
/// Internally, paths are stored in POSIX ('/'-delimited) format, but they can
/// be displayed in either POSIX or Windows format.
///
/// Relative paths are also guaranteed to be valid unicode.
#[repr(transparent)]
#[derive(PartialEq, Eq, Hash, Serialize)]
pub struct RelPath(str);
/// An owned representation of a file system path that is guaranteed to be
/// relative and normalized.
///
/// This type is to [`RelPath`] as [`std::path::PathBuf`] is to [`std::path::Path`]
#[derive(PartialEq, Eq, Clone, Ord, PartialOrd, Serialize)]
pub struct RelPathBuf(String);
impl RelPath {
/// Creates an empty [`RelPath`].
pub fn empty() -> &'static Self {
Self::new_unchecked("")
}
/// Converts a path with a given style into a [`RelPath`].
///
/// Returns an error if the path is absolute, or is not valid unicode.
///
/// This method will normalize the path by removing `.` components,
/// processing `..` components, and removing trailing separators. It does
/// not allocate unless it's necessary to reformat the path.
#[track_caller]
pub fn new<'a>(path: &'a Path, path_style: PathStyle) -> Result<Cow<'a, Self>> {
let mut path = path.to_str().context("non utf-8 path")?;
let (prefixes, suffixes): (&[_], &[_]) = match path_style {
PathStyle::Posix => (&["./"], &['/']),
PathStyle::Windows => (&["./", ".\\"], &['/', '\\']),
};
while prefixes.iter().any(|prefix| path.starts_with(prefix)) {
path = &path[prefixes[0].len()..];
}
while let Some(prefix) = path.strip_suffix(suffixes)
&& !prefix.is_empty()
{
path = prefix;
}
if is_absolute(path, path_style) {
return Err(anyhow!("absolute path not allowed: {path:?}"));
}
let mut string = Cow::Borrowed(path);
if path_style == PathStyle::Windows && path.contains('\\') {
string = Cow::Owned(string.as_ref().replace('\\', "/"))
}
let mut result = match string {
Cow::Borrowed(string) => Cow::Borrowed(Self::new_unchecked(string)),
Cow::Owned(string) => Cow::Owned(RelPathBuf(string)),
};
if result
.components()
.any(|component| component.is_empty() || component == "." || component == "..")
{
let mut normalized = RelPathBuf::new();
for component in result.components() {
match component {
"" => {}
"." => {}
".." => {
if !normalized.pop() {
return Err(anyhow!("path is not relative: {result:?}"));
}
}
other => normalized.push(RelPath::new_unchecked(other)),
}
}
result = Cow::Owned(normalized)
}
Ok(result)
}
/// Converts a path that is already normalized and uses '/' separators
/// into a [`RelPath`] .
///
/// Returns an error if the path is not already in the correct format.
#[track_caller]
pub fn unix<S: AsRef<Path> + ?Sized>(path: &S) -> anyhow::Result<&Self> {
let path = path.as_ref();
match Self::new(path, PathStyle::Posix)? {
Cow::Borrowed(path) => Ok(path),
Cow::Owned(_) => Err(anyhow!("invalid relative path {path:?}")),
}
}
fn new_unchecked(s: &str) -> &Self {
// Safety: `RelPath` is a transparent wrapper around `str`.
unsafe { &*(s as *const str as *const Self) }
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn components(&self) -> RelPathComponents<'_> {
RelPathComponents(&self.0)
}
pub fn ancestors(&self) -> RelPathAncestors<'_> {
RelPathAncestors(Some(&self.0))
}
pub fn file_name(&self) -> Option<&str> {
self.components().next_back()
}
pub fn file_stem(&self) -> Option<&str> {
Some(self.as_std_path().file_stem()?.to_str().unwrap())
}
pub fn extension(&self) -> Option<&str> {
Some(self.as_std_path().extension()?.to_str().unwrap())
}
pub fn parent(&self) -> Option<&Self> {
let mut components = self.components();
components.next_back()?;
Some(components.rest())
}
pub fn starts_with(&self, other: &Self) -> bool {
self.strip_prefix(other).is_ok()
}
pub fn ends_with(&self, other: &Self) -> bool {
self.0
.strip_suffix(&other.0)
.is_some_and(|suffix| suffix.ends_with('/') || suffix.is_empty())
}
pub fn strip_prefix<'a>(&'a self, other: &Self) -> Result<&'a Self, StripPrefixError> {
if other.is_empty() {
return Ok(self);
}
if let Some(suffix) = self.0.strip_prefix(&other.0) {
if let Some(suffix) = suffix.strip_prefix('/') {
return Ok(Self::new_unchecked(suffix));
} else if suffix.is_empty() {
return Ok(Self::empty());
}
}
Err(StripPrefixError)
}
pub fn len(&self) -> usize {
self.0.matches('/').count() + 1
}
pub fn last_n_components(&self, count: usize) -> Option<&Self> {
let len = self.len();
if len >= count {
let mut components = self.components();
for _ in 0..(len - count) {
components.next()?;
}
Some(components.rest())
} else {
None
}
}
pub fn join(&self, other: &Self) -> Arc<Self> {
let result = if self.0.is_empty() {
Cow::Borrowed(&other.0)
} else if other.0.is_empty() {
Cow::Borrowed(&self.0)
} else {
Cow::Owned(format!("{}/{}", &self.0, &other.0))
};
Arc::from(Self::new_unchecked(result.as_ref()))
}
pub fn to_rel_path_buf(&self) -> RelPathBuf {
RelPathBuf(self.0.to_string())
}
pub fn to_arc(&self) -> Arc<Self> {
Arc::from(self)
}
/// Convert the path into the wire representation.
pub fn to_proto(&self) -> String {
self.as_unix_str().to_owned()
}
/// Load the path from its wire representation.
pub fn from_proto(path: &str) -> Result<Arc<Self>> {
Ok(Arc::from(Self::unix(path)?))
}
/// Convert the path into a string with the given path style.
///
/// Whenever a path is presented to the user, it should be converted to
/// a string via this method.
pub fn display(&self, style: PathStyle) -> Cow<'_, str> {
match style {
PathStyle::Posix => Cow::Borrowed(&self.0),
PathStyle::Windows if self.0.contains('/') => Cow::Owned(self.0.replace('/', "\\")),
PathStyle::Windows => Cow::Borrowed(&self.0),
}
}
/// Get the internal unix-style representation of the path.
///
/// This should not be shown to the user.
pub fn as_unix_str(&self) -> &str {
&self.0
}
/// Interprets the path as a [`std::path::Path`], suitable for file system calls.
///
/// This is guaranteed to be a valid path regardless of the host platform, because
/// the `/` is accepted as a path separator on windows.
///
/// This should not be shown to the user.
pub fn as_std_path(&self) -> &Path {
Path::new(&self.0)
}
}
#[derive(Debug)]
pub struct StripPrefixError;
impl std::fmt::Display for StripPrefixError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("prefix not found")
}
}
impl std::error::Error for StripPrefixError {}
impl ToOwned for RelPath {
type Owned = RelPathBuf;
fn to_owned(&self) -> Self::Owned {
self.to_rel_path_buf()
}
}
impl Borrow<RelPath> for RelPathBuf {
fn borrow(&self) -> &RelPath {
self.as_rel_path()
}
}
impl PartialOrd for RelPath {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for RelPath {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.components().cmp(other.components())
}
}
impl fmt::Debug for RelPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl fmt::Debug for RelPathBuf {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl Default for RelPathBuf {
fn default() -> Self {
Self::new()
}
}
impl RelPathBuf {
pub fn new() -> Self {
Self(String::new())
}
pub fn pop(&mut self) -> bool {
if let Some(ix) = self.0.rfind('/') {
self.0.truncate(ix);
true
} else if !self.is_empty() {
self.0.clear();
true
} else {
false
}
}
pub fn push(&mut self, path: &RelPath) {
if !self.is_empty() {
self.0.push('/');
}
self.0.push_str(&path.0);
}
pub fn as_rel_path(&self) -> &RelPath {
RelPath::new_unchecked(self.0.as_str())
}
pub fn set_extension(&mut self, extension: &str) -> bool {
if let Some(filename) = self.file_name() {
let mut filename = PathBuf::from(filename);
filename.set_extension(extension);
self.pop();
self.0.push_str(filename.to_str().unwrap());
true
} else {
false
}
}
}
impl<'de> Deserialize<'de> for RelPathBuf {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let path = String::deserialize(deserializer)?;
let rel_path =
RelPath::new(Path::new(&path), PathStyle::local()).map_err(serde::de::Error::custom)?;
Ok(rel_path.into_owned())
}
}
impl From<RelPathBuf> for Arc<RelPath> {
fn from(value: RelPathBuf) -> Self {
Arc::from(value.as_rel_path())
}
}
impl AsRef<Path> for RelPathBuf {
fn as_ref(&self) -> &Path {
self.as_std_path()
}
}
impl AsRef<Path> for RelPath {
fn as_ref(&self) -> &Path {
self.as_std_path()
}
}
impl AsRef<RelPath> for RelPathBuf {
fn as_ref(&self) -> &RelPath {
self.as_rel_path()
}
}
impl AsRef<RelPath> for RelPath {
fn as_ref(&self) -> &RelPath {
self
}
}
impl Deref for RelPathBuf {
type Target = RelPath;
fn deref(&self) -> &Self::Target {
self.as_ref()
}
}
impl<'a> From<&'a RelPath> for Cow<'a, RelPath> {
fn from(value: &'a RelPath) -> Self {
Self::Borrowed(value)
}
}
impl From<&RelPath> for Arc<RelPath> {
fn from(rel_path: &RelPath) -> Self {
let bytes: Arc<str> = Arc::from(&rel_path.0);
unsafe { Arc::from_raw(Arc::into_raw(bytes) as *const RelPath) }
}
}
#[cfg(any(test, feature = "test-support"))]
#[track_caller]
pub fn rel_path(path: &str) -> &RelPath {
RelPath::unix(path).unwrap()
}
#[cfg(any(test, feature = "test-support"))]
#[track_caller]
pub fn rel_path_buf(path: &str) -> RelPathBuf {
RelPath::unix(path).unwrap().to_rel_path_buf()
}
impl PartialEq<str> for RelPath {
fn eq(&self, other: &str) -> bool {
self.0 == *other
}
}
pub trait PathExt {
fn to_rel_path_buf(&self) -> Result<RelPathBuf>;
}
impl<T: AsRef<Path> + ?Sized> PathExt for T {
fn to_rel_path_buf(&self) -> Result<RelPathBuf> {
Ok(RelPath::new(self.as_ref(), PathStyle::local())?.into_owned())
}
}
#[derive(Default)]
pub struct RelPathComponents<'a>(&'a str);
pub struct RelPathAncestors<'a>(Option<&'a str>);
const SEPARATOR: char = '/';
impl<'a> RelPathComponents<'a> {
pub fn rest(&self) -> &'a RelPath {
RelPath::new_unchecked(self.0)
}
}
impl<'a> Iterator for RelPathComponents<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
if let Some(sep_ix) = self.0.find(SEPARATOR) {
let (head, tail) = self.0.split_at(sep_ix);
self.0 = &tail[1..];
Some(head)
} else if self.0.is_empty() {
None
} else {
let result = self.0;
self.0 = "";
Some(result)
}
}
}
impl<'a> Iterator for RelPathAncestors<'a> {
type Item = &'a RelPath;
fn next(&mut self) -> Option<Self::Item> {
let result = self.0?;
if let Some(sep_ix) = result.rfind(SEPARATOR) {
self.0 = Some(&result[..sep_ix]);
} else if !result.is_empty() {
self.0 = Some("");
} else {
self.0 = None;
}
Some(RelPath::new_unchecked(result))
}
}
impl<'a> DoubleEndedIterator for RelPathComponents<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
if let Some(sep_ix) = self.0.rfind(SEPARATOR) {
let (head, tail) = self.0.split_at(sep_ix);
self.0 = head;
Some(&tail[1..])
} else if self.0.is_empty() {
None
} else {
let result = self.0;
self.0 = "";
Some(result)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use itertools::Itertools;
use pretty_assertions::assert_matches;
#[test]
fn test_rel_path_new() {
assert!(RelPath::new(Path::new("/"), PathStyle::local()).is_err());
assert!(RelPath::new(Path::new("//"), PathStyle::local()).is_err());
assert!(RelPath::new(Path::new("/foo/"), PathStyle::local()).is_err());
let path = RelPath::new("foo/".as_ref(), PathStyle::local()).unwrap();
assert_eq!(path, rel_path("foo").into());
assert_matches!(path, Cow::Borrowed(_));
let path = RelPath::new("foo\\".as_ref(), PathStyle::Windows).unwrap();
assert_eq!(path, rel_path("foo").into());
assert_matches!(path, Cow::Borrowed(_));
assert_eq!(
RelPath::new("foo/bar/../baz/./quux/".as_ref(), PathStyle::local())
.unwrap()
.as_ref(),
rel_path("foo/baz/quux")
);
let path = RelPath::new("./foo/bar".as_ref(), PathStyle::Posix).unwrap();
assert_eq!(path.as_ref(), rel_path("foo/bar"));
assert_matches!(path, Cow::Borrowed(_));
let path = RelPath::new(".\\foo".as_ref(), PathStyle::Windows).unwrap();
assert_eq!(path, rel_path("foo").into());
assert_matches!(path, Cow::Borrowed(_));
let path = RelPath::new("./.\\./foo/\\/".as_ref(), PathStyle::Windows).unwrap();
assert_eq!(path, rel_path("foo").into());
assert_matches!(path, Cow::Borrowed(_));
let path = RelPath::new("foo/./bar".as_ref(), PathStyle::Posix).unwrap();
assert_eq!(path.as_ref(), rel_path("foo/bar"));
assert_matches!(path, Cow::Owned(_));
let path = RelPath::new("./foo/bar".as_ref(), PathStyle::Windows).unwrap();
assert_eq!(path.as_ref(), rel_path("foo/bar"));
assert_matches!(path, Cow::Borrowed(_));
let path = RelPath::new(".\\foo\\bar".as_ref(), PathStyle::Windows).unwrap();
assert_eq!(path.as_ref(), rel_path("foo/bar"));
assert_matches!(path, Cow::Owned(_));
}
#[test]
fn test_rel_path_components() {
let path = rel_path("foo/bar/baz");
assert_eq!(
path.components().collect::<Vec<_>>(),
vec!["foo", "bar", "baz"]
);
assert_eq!(
path.components().rev().collect::<Vec<_>>(),
vec!["baz", "bar", "foo"]
);
let path = rel_path("");
let mut components = path.components();
assert_eq!(components.next(), None);
}
#[test]
fn test_rel_path_ancestors() {
let path = rel_path("foo/bar/baz");
let mut ancestors = path.ancestors();
assert_eq!(ancestors.next(), Some(rel_path("foo/bar/baz")));
assert_eq!(ancestors.next(), Some(rel_path("foo/bar")));
assert_eq!(ancestors.next(), Some(rel_path("foo")));
assert_eq!(ancestors.next(), Some(rel_path("")));
assert_eq!(ancestors.next(), None);
let path = rel_path("foo");
let mut ancestors = path.ancestors();
assert_eq!(ancestors.next(), Some(rel_path("foo")));
assert_eq!(ancestors.next(), Some(RelPath::empty()));
assert_eq!(ancestors.next(), None);
let path = RelPath::empty();
let mut ancestors = path.ancestors();
assert_eq!(ancestors.next(), Some(RelPath::empty()));
assert_eq!(ancestors.next(), None);
}
#[test]
fn test_rel_path_parent() {
assert_eq!(rel_path("foo/bar/baz").parent(), Some(rel_path("foo/bar")));
assert_eq!(rel_path("foo").parent(), Some(RelPath::empty()));
assert_eq!(rel_path("").parent(), None);
}
#[test]
fn test_rel_path_partial_ord_is_compatible_with_std() {
let test_cases = ["a/b/c", "relative/path/with/dot.", "relative/path/with.dot"];
for [lhs, rhs] in test_cases.iter().array_combinations::<2>() {
assert_eq!(
Path::new(lhs).cmp(Path::new(rhs)),
RelPath::unix(lhs).unwrap().cmp(RelPath::unix(rhs).unwrap())
);
}
}
#[test]
fn test_strip_prefix() {
let parent = rel_path("");
let child = rel_path(".foo");
assert!(child.starts_with(parent));
assert_eq!(child.strip_prefix(parent).unwrap(), child);
}
#[test]
fn test_rel_path_constructors_absolute_path() {
assert!(RelPath::new(Path::new("/a/b"), PathStyle::Windows).is_err());
assert!(RelPath::new(Path::new("\\a\\b"), PathStyle::Windows).is_err());
assert!(RelPath::new(Path::new("/a/b"), PathStyle::Posix).is_err());
assert!(RelPath::new(Path::new("C:/a/b"), PathStyle::Windows).is_err());
assert!(RelPath::new(Path::new("C:\\a\\b"), PathStyle::Windows).is_err());
assert!(RelPath::new(Path::new("C:/a/b"), PathStyle::Posix).is_ok());
}
#[test]
fn test_pop() {
let mut path = rel_path("a/b").to_rel_path_buf();
path.pop();
assert_eq!(path.as_rel_path().as_unix_str(), "a");
path.pop();
assert_eq!(path.as_rel_path().as_unix_str(), "");
path.pop();
assert_eq!(path.as_rel_path().as_unix_str(), "");
}
}
+72
View File
@@ -0,0 +1,72 @@
use schemars::{JsonSchema, transform::transform_subschemas};
const DEFS_PATH: &str = "#/$defs/";
/// Replaces the JSON schema definition for some type if it is in use (in the definitions list), and
/// returns a reference to it.
///
/// This asserts that JsonSchema::schema_name() + "2" does not exist because this indicates that
/// there are multiple types that use this name, and unfortunately schemars APIs do not support
/// resolving this ambiguity - see <https://github.com/GREsau/schemars/issues/449>
///
/// This takes a closure for `schema` because some settings types are not available on the remote
/// server, and so will crash when attempting to access e.g. GlobalThemeRegistry.
pub fn replace_subschema<T: JsonSchema>(
generator: &mut schemars::SchemaGenerator,
schema: impl Fn() -> schemars::Schema,
) -> schemars::Schema {
let schema_name = T::schema_name();
let definitions = generator.definitions_mut();
assert!(!definitions.contains_key(&format!("{schema_name}2")));
assert!(definitions.contains_key(schema_name.as_ref()));
definitions.insert(schema_name.to_string(), schema().to_value());
schemars::Schema::new_ref(format!("{DEFS_PATH}{schema_name}"))
}
/// Adds a new JSON schema definition and returns a reference to it. **Panics** if the name is
/// already in use.
pub fn add_new_subschema(
generator: &mut schemars::SchemaGenerator,
name: &str,
schema: serde_json::Value,
) -> schemars::Schema {
let old_definition = generator.definitions_mut().insert(name.to_string(), schema);
assert_eq!(old_definition, None);
schemars::Schema::new_ref(format!("{DEFS_PATH}{name}"))
}
/// Defaults `additionalProperties` to `true`, as if `#[schemars(deny_unknown_fields)]` was on every
/// struct. Skips structs that have `additionalProperties` set (such as if #[serde(flatten)] is used
/// on a map).
#[derive(Clone)]
pub struct DefaultDenyUnknownFields;
impl schemars::transform::Transform for DefaultDenyUnknownFields {
fn transform(&mut self, schema: &mut schemars::Schema) {
if let Some(object) = schema.as_object_mut()
&& object.contains_key("properties")
&& !object.contains_key("additionalProperties")
&& !object.contains_key("unevaluatedProperties")
{
object.insert("additionalProperties".to_string(), false.into());
}
transform_subschemas(self, schema);
}
}
/// Defaults `allowTrailingCommas` to `true`, for use with `json-language-server`.
/// This can be applied to any schema that will be treated as `jsonc`.
///
/// Note that this is non-recursive and only applied to the root schema.
#[derive(Clone)]
pub struct AllowTrailingCommas;
impl schemars::transform::Transform for AllowTrailingCommas {
fn transform(&mut self, schema: &mut schemars::Schema) {
if let Some(object) = schema.as_object_mut()
&& !object.contains_key("allowTrailingCommas")
{
object.insert("allowTrailingCommas".to_string(), true.into());
}
}
}
+7
View File
@@ -0,0 +1,7 @@
pub const fn default_true() -> bool {
true
}
pub fn is_default<T: Default + PartialEq>(value: &T) -> bool {
*value == T::default()
}
File diff suppressed because it is too large Load Diff
+327
View File
@@ -0,0 +1,327 @@
use std::borrow::Cow;
use crate::shell::get_system_shell;
use crate::shell::{Shell, ShellKind};
/// ShellBuilder is used to turn a user-requested task into a
/// program that can be executed by the shell.
pub struct ShellBuilder {
/// The shell to run
program: String,
args: Vec<String>,
interactive: bool,
/// Whether to redirect stdin to /dev/null for the spawned command as a subshell.
redirect_stdin: bool,
kind: ShellKind,
}
impl ShellBuilder {
/// Create a new ShellBuilder as configured.
pub fn new(shell: &Shell, is_windows: bool) -> Self {
let (program, args) = match shell {
Shell::System => (get_system_shell(), Vec::new()),
Shell::Program(shell) => (shell.clone(), Vec::new()),
Shell::WithArguments { program, args, .. } => (program.clone(), args.clone()),
};
let kind = ShellKind::new(&program, is_windows);
Self {
program,
args,
interactive: true,
kind,
redirect_stdin: false,
}
}
pub fn non_interactive(mut self) -> Self {
self.interactive = false;
self
}
/// Returns the label to show in the terminal tab
pub fn command_label(&self, command_to_use_in_label: &str) -> String {
if command_to_use_in_label.trim().is_empty() {
self.program.clone()
} else {
match self.kind {
ShellKind::PowerShell | ShellKind::Pwsh => {
format!("{} -C '{}'", self.program, command_to_use_in_label)
}
ShellKind::Cmd => {
format!("{} /C \"{}\"", self.program, command_to_use_in_label)
}
ShellKind::Posix
| ShellKind::Nushell
| ShellKind::Fish
| ShellKind::Csh
| ShellKind::Tcsh
| ShellKind::Rc
| ShellKind::Xonsh
| ShellKind::Elvish => {
let interactivity = if self.interactive { "-i " } else { "" };
format!(
"{PROGRAM} {interactivity}-c '{command_to_use_in_label}'",
PROGRAM = self.program
)
}
}
}
}
pub fn redirect_stdin_to_dev_null(mut self) -> Self {
self.redirect_stdin = true;
self
}
/// Returns the program and arguments to run this task in a shell.
pub fn build(
mut self,
task_command: Option<String>,
task_args: &[String],
) -> (String, Vec<String>) {
if let Some(task_command) = task_command {
let task_command = if !task_args.is_empty() {
match self.kind.try_quote_prefix_aware(&task_command) {
Some(task_command) => task_command.into_owned(),
None => task_command,
}
} else {
task_command
};
let mut combined_command = task_args.iter().fold(task_command, |mut command, arg| {
command.push(' ');
let shell_variable = self.kind.to_shell_variable(arg);
command.push_str(&match self.kind.try_quote(&shell_variable) {
Some(shell_variable) => shell_variable,
None => Cow::Owned(shell_variable),
});
command
});
if self.redirect_stdin {
match self.kind {
ShellKind::Fish => {
combined_command.insert_str(0, "begin; ");
combined_command.push_str("; end </dev/null");
}
ShellKind::Posix
| ShellKind::Nushell
| ShellKind::Csh
| ShellKind::Tcsh
| ShellKind::Rc
| ShellKind::Xonsh
| ShellKind::Elvish => {
combined_command.insert(0, '(');
combined_command.push_str("\n) </dev/null");
}
ShellKind::PowerShell | ShellKind::Pwsh => {
combined_command.insert_str(0, "$null | & {");
combined_command.push('}');
}
ShellKind::Cmd => {
combined_command.push_str("< NUL");
}
}
}
self.args
.extend(self.kind.args_for_shell(self.interactive, combined_command));
}
(self.program, self.args)
}
// This should not exist, but our task infra is broken beyond repair right now
#[doc(hidden)]
pub fn build_no_quote(
mut self,
task_command: Option<String>,
task_args: &[String],
) -> (String, Vec<String>) {
if let Some(task_command) = task_command {
let mut combined_command = task_args.iter().fold(task_command, |mut command, arg| {
command.push(' ');
command.push_str(&self.kind.to_shell_variable(arg));
command
});
if self.redirect_stdin {
match self.kind {
ShellKind::Fish => {
combined_command.insert_str(0, "begin; ");
combined_command.push_str("; end </dev/null");
}
ShellKind::Posix
| ShellKind::Nushell
| ShellKind::Csh
| ShellKind::Tcsh
| ShellKind::Rc
| ShellKind::Xonsh
| ShellKind::Elvish => {
combined_command.insert(0, '(');
combined_command.push_str("\n) </dev/null");
}
ShellKind::PowerShell | ShellKind::Pwsh => {
combined_command.insert_str(0, "$null | & {");
combined_command.push('}');
}
ShellKind::Cmd => {
combined_command.push_str("< NUL");
}
}
}
self.args
.extend(self.kind.args_for_shell(self.interactive, combined_command));
}
(self.program, self.args)
}
/// Builds a `smol::process::Command` with the given task command and arguments.
///
/// Prefer this over manually constructing a command with the output of `Self::build`,
/// as this method handles `cmd` weirdness on windows correctly.
pub fn build_smol_command(
self,
task_command: Option<String>,
task_args: &[String],
) -> smol::process::Command {
smol::process::Command::from(self.build_std_command(task_command, task_args))
}
/// Builds a `std::process::Command` with the given task command and arguments.
///
/// Prefer this over manually constructing a command with the output of `Self::build`,
/// as this method handles `cmd` weirdness on windows correctly.
pub fn build_std_command(
self,
mut task_command: Option<String>,
task_args: &[String],
) -> std::process::Command {
#[cfg(windows)]
let kind = self.kind;
if task_args.is_empty() {
task_command = task_command
.as_ref()
.map(|cmd| self.kind.try_quote_prefix_aware(cmd).map(Cow::into_owned))
.unwrap_or(task_command);
}
let (program, args) = self.build(task_command, task_args);
let mut child = crate::command::new_std_command(program);
#[cfg(windows)]
if kind == ShellKind::Cmd {
use std::os::windows::process::CommandExt;
for arg in args {
child.raw_arg(arg);
}
} else {
child.args(args);
}
#[cfg(not(windows))]
child.args(args);
child
}
pub fn kind(&self) -> ShellKind {
self.kind
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_nu_shell_variable_substitution() {
let shell = Shell::Program("nu".to_owned());
let shell_builder = ShellBuilder::new(&shell, false);
let (program, args) = shell_builder.build(
Some("echo".into()),
&[
"${hello}".to_string(),
"$world".to_string(),
"nothing".to_string(),
"--$something".to_string(),
"$".to_string(),
"${test".to_string(),
],
);
assert_eq!(program, "nu");
assert_eq!(
args,
vec![
"-i",
"-c",
"echo '$env.hello' '$env.world' nothing '--($env.something)' '$' '${test'"
]
);
}
#[test]
fn redirect_stdin_to_dev_null_precedence() {
let shell = Shell::Program("nu".to_owned());
let shell_builder = ShellBuilder::new(&shell, false);
let (program, args) = shell_builder
.redirect_stdin_to_dev_null()
.build(Some("echo".into()), &["nothing".to_string()]);
assert_eq!(program, "nu");
assert_eq!(args, vec!["-i", "-c", "(echo nothing\n) </dev/null"]);
}
#[test]
fn redirect_stdin_to_dev_null_fish() {
let shell = Shell::Program("fish".to_owned());
let shell_builder = ShellBuilder::new(&shell, false);
let (program, args) = shell_builder
.redirect_stdin_to_dev_null()
.build(Some("echo".into()), &["test".to_string()]);
assert_eq!(program, "fish");
assert_eq!(args, vec!["-i", "-c", "begin; echo test; end </dev/null"]);
}
#[test]
fn redirect_stdin_to_dev_null_preserves_heredoc() {
let shell = Shell::Program("sh".to_owned());
let shell_builder = ShellBuilder::new(&shell, false);
let command = "cat <<EOF\nhello\nEOF";
let (program, args) = shell_builder
.redirect_stdin_to_dev_null()
.build(Some(command.into()), &[]);
assert_eq!(program, "sh");
assert_eq!(
args,
vec!["-i", "-c", "(cat <<EOF\nhello\nEOF\n) </dev/null"]
);
}
#[test]
fn does_not_quote_sole_command_only() {
let shell = Shell::Program("fish".to_owned());
let shell_builder = ShellBuilder::new(&shell, false);
let (program, args) = shell_builder.build(Some("echo".into()), &[]);
assert_eq!(program, "fish");
assert_eq!(args, vec!["-i", "-c", "echo"]);
let shell = Shell::Program("fish".to_owned());
let shell_builder = ShellBuilder::new(&shell, false);
let (program, args) = shell_builder.build(Some("echo oo".into()), &[]);
assert_eq!(program, "fish");
assert_eq!(args, vec!["-i", "-c", "echo oo"]);
}
}
+344
View File
@@ -0,0 +1,344 @@
use std::path::Path;
use anyhow::{Context as _, Result};
use collections::HashMap;
use serde::Deserialize;
use crate::shell::ShellKind;
fn parse_env_map_from_noisy_output(output: &str) -> Result<collections::HashMap<String, String>> {
for (position, _) in output.match_indices('{') {
let candidate = &output[position..];
let mut deserializer = serde_json::Deserializer::from_str(candidate);
if let Ok(env_map) = HashMap::<String, String>::deserialize(&mut deserializer) {
return Ok(env_map);
}
}
anyhow::bail!("Failed to find JSON in shell output: {output}")
}
pub fn print_env() {
let env_vars: HashMap<String, String> = std::env::vars().collect();
let json = serde_json::to_string_pretty(&env_vars).unwrap_or_else(|err| {
eprintln!("Error serializing environment variables: {}", err);
std::process::exit(1);
});
println!("{}", json);
}
/// Capture all environment variables from the login shell in the given directory.
pub async fn capture(
shell_path: impl AsRef<Path>,
args: &[String],
directory: impl AsRef<Path>,
) -> Result<collections::HashMap<String, String>> {
#[cfg(windows)]
return capture_windows(shell_path.as_ref(), args, directory.as_ref()).await;
#[cfg(unix)]
return capture_unix(shell_path.as_ref(), args, directory.as_ref()).await;
}
/// Try to parse the environment output before checking the exit status.
/// The user's shell rc files may contain commands that fail (e.g. editor
/// integrations that call posix_spawnp outside a real PTY), causing a
/// non-zero exit status even though `zed --printenv` ran successfully and
/// produced valid output on its separate fd.
fn parse_env_output(
env_output: &str,
status: &std::process::ExitStatus,
successful_capture_warning: impl FnOnce() -> String,
failed_capture_error: impl FnOnce() -> String,
) -> Result<collections::HashMap<String, String>> {
match parse_env_map_from_noisy_output(env_output) {
Ok(env_map) => {
if !status.success() {
log::warn!("{}", successful_capture_warning());
}
Ok(env_map)
}
Err(parse_error) => {
if !status.success() {
anyhow::bail!(
"{}. Failed to deserialize environment variables from json: {parse_error}. output: {env_output}",
failed_capture_error(),
);
}
anyhow::bail!(
"Failed to deserialize environment variables from json: {parse_error}. output: {env_output}"
);
}
}
}
#[cfg(unix)]
async fn capture_unix(
shell_path: &Path,
args: &[String],
directory: &Path,
) -> Result<collections::HashMap<String, String>> {
use std::os::unix::process::CommandExt;
use crate::command::new_std_command;
let shell_kind = ShellKind::new(shell_path, false);
let quoted_zed_path = super::get_shell_safe_zed_path(shell_kind)?;
let mut command_string = String::new();
let mut command = new_std_command(shell_path);
command.args(args);
// In some shells, file descriptors greater than 2 cannot be used in interactive mode,
// so file descriptor 0 (stdin) is used instead. This impacts zsh, old bash; perhaps others.
// See: https://github.com/zed-industries/zed/pull/32136#issuecomment-2999645482
const FD_STDIN: std::os::fd::RawFd = 0;
const FD_STDOUT: std::os::fd::RawFd = 1;
const FD_STDERR: std::os::fd::RawFd = 2;
let (fd_num, redir) = match shell_kind {
ShellKind::Rc => (FD_STDIN, format!(">[1={}]", FD_STDIN)), // `[1=0]`
ShellKind::Nushell | ShellKind::Tcsh => (FD_STDOUT, "".to_string()),
// xonsh doesn't support redirecting to stdin, and control sequences are printed to
// stdout on startup
ShellKind::Xonsh => (FD_STDERR, "o>e".to_string()),
ShellKind::PowerShell => (FD_STDIN, format!(">{}", FD_STDIN)),
_ => (FD_STDIN, format!(">&{}", FD_STDIN)), // `>&0`
};
match shell_kind {
ShellKind::Csh | ShellKind::Tcsh => {
// For csh/tcsh, login shell requires passing `-` as 0th argument (instead of `-l`)
command.arg0("-");
}
ShellKind::Fish => {
// in fish, asdf, direnv attach to the `fish_prompt` event
command_string.push_str("emit fish_prompt;");
command.arg("-l");
}
_ => {
command.arg("-l");
}
}
match shell_kind {
// Nushell does not allow non-interactive login shells.
// Instead of doing "-l -i -c '<command>'"
// use "-l -e '<command>; exit'" instead
ShellKind::Nushell => command.arg("-e"),
_ => command.args(["-i", "-c"]),
};
// Prefix with "./" if the path starts with "-" to prevent cd from interpreting it as a flag
let dir_str = directory.to_string_lossy();
let dir_str = if dir_str.starts_with('-') {
format!("./{dir_str}").into()
} else {
dir_str
};
let quoted_dir = shell_kind
.try_quote(&dir_str)
.context("unexpected null in directory name")?;
// cd into the directory, triggering directory specific side-effects (asdf, direnv, etc)
command_string.push_str(&format!("cd {};", quoted_dir));
if let Some(prefix) = shell_kind.command_prefix() {
command_string.push(prefix);
}
command_string.push_str(&format!("{} --printenv {}", quoted_zed_path, redir));
if let ShellKind::Nushell = shell_kind {
command_string.push_str("; exit");
}
command.arg(&command_string);
super::set_pre_exec_to_start_new_session(&mut command);
let (env_output, process_output) = spawn_and_read_fd(command, fd_num).await?;
let env_output = String::from_utf8_lossy(&env_output);
parse_env_output(
&env_output,
&process_output.status,
|| {
format!(
"login shell exited with {} but environment was captured successfully. stderr: {:?}",
process_output.status,
String::from_utf8_lossy(&process_output.stderr),
)
},
|| {
format!(
"login shell exited with {}. stdout: {:?}, stderr: {:?}",
process_output.status,
String::from_utf8_lossy(&process_output.stdout),
String::from_utf8_lossy(&process_output.stderr),
)
},
)
}
#[cfg(unix)]
async fn spawn_and_read_fd(
mut command: std::process::Command,
child_fd: std::os::fd::RawFd,
) -> anyhow::Result<(Vec<u8>, std::process::Output)> {
use command_fds::{CommandFdExt, FdMapping};
use std::{io::Read, process::Stdio};
let (mut reader, writer) = std::io::pipe()?;
command.fd_mappings(vec![FdMapping {
parent_fd: writer.into(),
child_fd,
}])?;
let process = smol::process::Command::from(command)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let mut buffer = Vec::new();
reader.read_to_end(&mut buffer)?;
Ok((buffer, process.output().await?))
}
#[cfg(windows)]
async fn capture_windows(
shell_path: &Path,
args: &[String],
directory: &Path,
) -> Result<collections::HashMap<String, String>> {
use std::process::Stdio;
let zed_path =
std::env::current_exe().context("Failed to determine current zed executable path.")?;
let shell_kind = ShellKind::new(shell_path, true);
// Prefix with "./" if the path starts with "-" to prevent cd from interpreting it as a flag
let directory_string = directory.display().to_string();
let directory_string = if directory_string.starts_with('-') {
format!("./{directory_string}")
} else {
directory_string
};
let zed_path_string = zed_path.display().to_string();
let quote_for_shell = |value: &str| {
shell_kind
.try_quote(value)
.map(|quoted| quoted.into_owned())
.context("unexpected null in directory name")
};
let mut cmd = crate::command::new_command(shell_path);
cmd.args(args);
let quoted_directory = quote_for_shell(&directory_string)?;
let quoted_zed_path = quote_for_shell(&zed_path_string)?;
let cmd = match shell_kind {
ShellKind::Csh
| ShellKind::Tcsh
| ShellKind::Rc
| ShellKind::Fish
| ShellKind::Xonsh
| ShellKind::Posix => cmd.args([
"-l",
"-i",
"-c",
&format!("cd {}; {} --printenv", quoted_directory, quoted_zed_path),
]),
ShellKind::PowerShell | ShellKind::Pwsh => cmd.args([
"-NonInteractive",
"-NoProfile",
"-Command",
&format!(
"Set-Location {}; & {} --printenv",
quoted_directory, quoted_zed_path
),
]),
ShellKind::Elvish => cmd.args([
"-c",
&format!("cd {}; {} --printenv", quoted_directory, quoted_zed_path),
]),
ShellKind::Nushell => {
let zed_command = shell_kind
.prepend_command_prefix(&quoted_zed_path)
.into_owned();
cmd.args([
"-c",
&format!("cd {}; {} --printenv", quoted_directory, zed_command),
])
}
ShellKind::Cmd => {
let dir = directory_string.trim_end_matches('\\');
cmd.args(["/d", "/c", "cd", dir, "&&", &zed_path_string, "--printenv"])
}
}
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let output = cmd
.output()
.await
.with_context(|| format!("command {cmd:?}"))?;
let env_output = String::from_utf8_lossy(&output.stdout);
parse_env_output(
&env_output,
&output.status,
|| {
format!(
"Command {cmd:?} exited with {} but environment was captured successfully. stderr: {:?}",
output.status,
String::from_utf8_lossy(&output.stderr),
)
},
|| {
format!(
"Command {cmd:?} failed with {}. stdout: {:?}, stderr: {:?}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
)
},
)
}
#[cfg(test)]
mod tests {
use std::process::ExitStatus;
use super::*;
#[cfg(unix)]
fn exit_status(code: i32) -> ExitStatus {
use std::os::unix::process::ExitStatusExt;
ExitStatus::from_raw(code << 8)
}
#[cfg(windows)]
fn exit_status(code: u32) -> ExitStatus {
use std::os::windows::process::ExitStatusExt;
ExitStatus::from_raw(code)
}
#[test]
fn parse_env_output_accepts_valid_env_when_shell_exits_nonzero() {
let env_json = serde_json::json!({
"PATH": "/usr/bin",
"SHELL": "/bin/zsh",
});
let env_output = format!("shell startup noise\n{env_json}\nshell shutdown noise");
let env_map = parse_env_output(
&env_output,
&exit_status(1),
|| "shell exited with 1 but environment was captured successfully".to_string(),
|| panic!("failed capture error should not be evaluated for valid environment output"),
)
.expect("valid environment output should be returned despite non-zero shell exit");
assert_eq!(env_map.get("PATH").map(String::as_str), Some("/usr/bin"));
assert_eq!(env_map.get("SHELL").map(String::as_str), Some("/bin/zsh"));
}
}
+46
View File
@@ -0,0 +1,46 @@
pub fn format_file_size(size: u64, use_decimal: bool) -> String {
if use_decimal {
if size < 1000 {
format!("{size}B")
} else if size < 1000 * 1000 {
format!("{:.1}KB", size as f64 / 1000.0)
} else {
format!("{:.1}MB", size as f64 / (1000.0 * 1000.0))
}
} else if size < 1024 {
format!("{size}B")
} else if size < 1024 * 1024 {
format!("{:.1}KiB", size as f64 / 1024.0)
} else {
format!("{:.1}MiB", size as f64 / (1024.0 * 1024.0))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_file_size_decimal() {
assert_eq!(format_file_size(0, true), "0B");
assert_eq!(format_file_size(999, true), "999B");
assert_eq!(format_file_size(1000, true), "1.0KB");
assert_eq!(format_file_size(1500, true), "1.5KB");
assert_eq!(format_file_size(999999, true), "1000.0KB");
assert_eq!(format_file_size(1000000, true), "1.0MB");
assert_eq!(format_file_size(1500000, true), "1.5MB");
assert_eq!(format_file_size(10000000, true), "10.0MB");
}
#[test]
fn test_format_file_size_binary() {
assert_eq!(format_file_size(0, false), "0B");
assert_eq!(format_file_size(1023, false), "1023B");
assert_eq!(format_file_size(1024, false), "1.0KiB");
assert_eq!(format_file_size(1536, false), "1.5KiB");
assert_eq!(format_file_size(1048575, false), "1024.0KiB");
assert_eq!(format_file_size(1048576, false), "1.0MiB");
assert_eq!(format_file_size(1572864, false), "1.5MiB");
assert_eq!(format_file_size(10485760, false), "10.0MiB");
}
}
+80
View File
@@ -0,0 +1,80 @@
mod assertions;
mod marked_text;
pub use assertions::*;
pub use marked_text::*;
use git2;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use tempfile::TempDir;
pub struct TempTree {
_temp_dir: TempDir,
path: PathBuf,
}
impl TempTree {
pub fn new(tree: serde_json::Value) -> Self {
let dir = TempDir::new().unwrap();
let path = std::fs::canonicalize(dir.path()).unwrap();
write_tree(path.as_path(), tree);
Self {
_temp_dir: dir,
path,
}
}
pub fn path(&self) -> &Path {
self.path.as_path()
}
}
fn write_tree(path: &Path, tree: serde_json::Value) {
use serde_json::Value;
use std::fs;
if let Value::Object(map) = tree {
for (name, contents) in map {
let mut path = PathBuf::from(path);
path.push(name);
match contents {
Value::Object(_) => {
fs::create_dir(&path).unwrap();
#[cfg(not(target_family = "wasm"))]
if path.file_name() == Some(OsStr::new(".git")) {
git2::Repository::init(path.parent().unwrap()).unwrap();
}
write_tree(&path, contents);
}
Value::Null => {
fs::create_dir(&path).unwrap();
}
Value::String(contents) => {
fs::write(&path, contents).unwrap();
}
_ => {
panic!("JSON object must contain only objects, strings, or null");
}
}
}
} else {
panic!("You must pass a JSON object to this helper")
}
}
pub fn sample_text(rows: usize, cols: usize, start_char: char) -> String {
let mut text = String::new();
for row in 0..rows {
let c: char = (start_char as u32 + row as u32) as u8 as char;
let mut line = c.to_string().repeat(cols);
if row < rows - 1 {
line.push('\n');
}
text += &line;
}
text
}
@@ -0,0 +1,62 @@
pub enum SetEqError<T> {
LeftMissing(T),
RightMissing(T),
}
impl<T> SetEqError<T> {
pub fn map<R, F: FnOnce(T) -> R>(self, update: F) -> SetEqError<R> {
match self {
SetEqError::LeftMissing(missing) => SetEqError::LeftMissing(update(missing)),
SetEqError::RightMissing(missing) => SetEqError::RightMissing(update(missing)),
}
}
}
#[macro_export]
macro_rules! set_eq {
($left:expr,$right:expr) => {{
use util::test::*;
let left = $left;
let right = $right;
let mut result = Ok(());
for right_value in right.iter() {
if !left.contains(right_value) {
result = Err(SetEqError::LeftMissing(right_value.clone()));
break;
}
}
if result.is_ok() {
for left_value in left.iter() {
if !right.contains(left_value) {
result = Err(SetEqError::RightMissing(left_value.clone()));
}
}
}
result
}};
}
#[macro_export]
macro_rules! assert_set_eq {
($left:expr,$right:expr) => {{
use util::test::*;
use util::set_eq;
let left = $left;
let right = $right;
match set_eq!(&left, &right) {
Err(SetEqError::LeftMissing(missing)) => {
panic!("assertion failed: `(left == right)`\n left: {:?}\nright: {:?}\nleft does not contain {:?}", &left, &right, &missing);
},
Err(SetEqError::RightMissing(missing)) => {
panic!("assertion failed: `(left == right)`\n left: {:?}\nright: {:?}\nright does not contain {:?}", &left, &right, &missing);
},
_ => {}
}
}};
}
@@ -0,0 +1,281 @@
use collections::HashMap;
use std::{cmp::Ordering, ops::Range};
/// Construct a string and a list of offsets within that string using a single
/// string containing embedded position markers.
pub fn marked_text_offsets_by(
marked_text: &str,
markers: Vec<char>,
) -> (String, HashMap<char, Vec<usize>>) {
let mut extracted_markers: HashMap<char, Vec<usize>> = Default::default();
let mut unmarked_text = String::new();
for char in marked_text.chars() {
if markers.contains(&char) {
let char_offsets = extracted_markers.entry(char).or_default();
char_offsets.push(unmarked_text.len());
} else {
unmarked_text.push(char);
}
}
(unmarked_text, extracted_markers)
}
/// Construct a string and a list of ranges within that string using a single
/// string containing embedded range markers, using arbitrary characters as
/// range markers. By using multiple different range markers, you can construct
/// ranges that overlap each other.
///
/// The returned ranges will be grouped by their range marking characters.
pub fn marked_text_ranges_by(
marked_text: &str,
markers: Vec<TextRangeMarker>,
) -> (String, HashMap<TextRangeMarker, Vec<Range<usize>>>) {
let all_markers = markers.iter().flat_map(|m| m.markers()).collect();
let (unmarked_text, mut marker_offsets) = marked_text_offsets_by(marked_text, all_markers);
let range_lookup = markers
.into_iter()
.map(|marker| {
(
marker.clone(),
match marker {
TextRangeMarker::Empty(empty_marker_char) => marker_offsets
.remove(&empty_marker_char)
.unwrap_or_default()
.into_iter()
.map(|empty_index| empty_index..empty_index)
.collect::<Vec<Range<usize>>>(),
TextRangeMarker::Range(start_marker, end_marker) => {
let starts = marker_offsets.remove(&start_marker).unwrap_or_default();
let ends = marker_offsets.remove(&end_marker).unwrap_or_default();
assert_eq!(starts.len(), ends.len(), "marked ranges are unbalanced");
starts
.into_iter()
.zip(ends)
.map(|(start, end)| {
assert!(end >= start, "marked ranges must be disjoint");
start..end
})
.collect::<Vec<Range<usize>>>()
}
TextRangeMarker::ReverseRange(start_marker, end_marker) => {
let starts = marker_offsets.remove(&start_marker).unwrap_or_default();
let ends = marker_offsets.remove(&end_marker).unwrap_or_default();
assert_eq!(starts.len(), ends.len(), "marked ranges are unbalanced");
starts
.into_iter()
.zip(ends)
.map(|(start, end)| {
assert!(end >= start, "marked ranges must be disjoint");
end..start
})
.collect::<Vec<Range<usize>>>()
}
},
)
})
.collect();
(unmarked_text, range_lookup)
}
/// Construct a string and a list of ranges within that string using a single
/// string containing embedded range markers. The characters used to mark the
/// ranges are as follows:
///
/// 1. To mark a range of text, surround it with the `«` and `»` angle brackets,
/// which can be typed on a US keyboard with the `alt-|` and `alt-shift-|` keys.
///
/// ```text
/// foo «selected text» bar
/// ```
///
/// 2. To mark a single position in the text, use the `ˇ` caron,
/// which can be typed on a US keyboard with the `alt-shift-t` key.
///
/// ```text
/// the cursors are hereˇ and hereˇ.
/// ```
///
/// 3. To mark a range whose direction is meaningful (like a selection),
/// put a caron character beside one of its bounds, on the inside:
///
/// ```text
/// one «ˇreversed» selection and one «forwardˇ» selection
/// ```
///
/// Any • characters in the input string will be replaced with spaces. This makes
/// it easier to test cases with trailing spaces, which tend to get trimmed from the
/// source code.
#[track_caller]
pub fn marked_text_ranges(
marked_text: &str,
ranges_are_directed: bool,
) -> (String, Vec<Range<usize>>) {
let mut unmarked_text = String::with_capacity(marked_text.len());
let mut ranges = Vec::new();
let mut prev_marked_ix = 0;
let mut current_range_start = None;
let mut current_range_cursor = None;
let marked_text = marked_text.replace('•', " ");
for (marked_ix, marker) in marked_text.match_indices(&['«', '»', 'ˇ']) {
unmarked_text.push_str(&marked_text[prev_marked_ix..marked_ix]);
let unmarked_len = unmarked_text.len();
let len = marker.len();
prev_marked_ix = marked_ix + len;
match marker {
"ˇ" => {
if current_range_start.is_some() {
if current_range_cursor.is_some() {
panic!("duplicate point marker 'ˇ' at index {marked_ix}");
}
current_range_cursor = Some(unmarked_len);
} else {
ranges.push(unmarked_len..unmarked_len);
}
}
"«" => {
if current_range_start.is_some() {
panic!("unexpected range start marker '«' at index {marked_ix}");
}
current_range_start = Some(unmarked_len);
}
"»" => {
let current_range_start = if let Some(start) = current_range_start.take() {
start
} else {
panic!("unexpected range end marker '»' at index {marked_ix}");
};
let mut reversed = false;
if let Some(current_range_cursor) = current_range_cursor.take() {
if current_range_cursor == current_range_start {
reversed = true;
} else if current_range_cursor != unmarked_len {
panic!("unexpected 'ˇ' marker in the middle of a range");
}
} else if ranges_are_directed {
panic!("missing 'ˇ' marker to indicate range direction");
}
ranges.push(if reversed {
unmarked_len..current_range_start
} else {
current_range_start..unmarked_len
});
}
_ => unreachable!(),
}
}
unmarked_text.push_str(&marked_text[prev_marked_ix..]);
(unmarked_text, ranges)
}
#[track_caller]
pub fn marked_text_offsets(marked_text: &str) -> (String, Vec<usize>) {
let (text, ranges) = marked_text_ranges(marked_text, false);
(
text,
ranges
.into_iter()
.map(|range| {
assert_eq!(range.start, range.end);
range.start
})
.collect(),
)
}
pub fn generate_marked_text(
unmarked_text: &str,
ranges: &[Range<usize>],
indicate_cursors: bool,
) -> String {
let mut marked_text = unmarked_text.to_string();
for range in ranges.iter().rev() {
if indicate_cursors {
match range.start.cmp(&range.end) {
Ordering::Less => {
marked_text.insert_str(range.end, "ˇ»");
marked_text.insert(range.start, '«');
}
Ordering::Equal => {
marked_text.insert(range.start, 'ˇ');
}
Ordering::Greater => {
marked_text.insert(range.start, '»');
marked_text.insert_str(range.end, "«ˇ");
}
}
} else {
match range.start.cmp(&range.end) {
Ordering::Equal => {
marked_text.insert(range.start, 'ˇ');
}
_ => {
marked_text.insert(range.end, '»');
marked_text.insert(range.start, '«');
}
}
}
}
marked_text
}
#[derive(Clone, Eq, PartialEq, Hash)]
pub enum TextRangeMarker {
Empty(char),
Range(char, char),
ReverseRange(char, char),
}
impl TextRangeMarker {
fn markers(&self) -> Vec<char> {
match self {
Self::Empty(m) => vec![*m],
Self::Range(l, r) => vec![*l, *r],
Self::ReverseRange(l, r) => vec![*l, *r],
}
}
}
impl From<char> for TextRangeMarker {
fn from(marker: char) -> Self {
Self::Empty(marker)
}
}
impl From<(char, char)> for TextRangeMarker {
fn from((left_marker, right_marker): (char, char)) -> Self {
Self::Range(left_marker, right_marker)
}
}
#[cfg(test)]
mod tests {
use super::{generate_marked_text, marked_text_ranges};
#[allow(clippy::reversed_empty_ranges)]
#[test]
fn test_marked_text() {
let (text, ranges) = marked_text_ranges("one «ˇtwo» «threeˇ» «ˇfour» fiveˇ six", true);
assert_eq!(text, "one two three four five six");
assert_eq!(ranges.len(), 4);
assert_eq!(ranges[0], 7..4);
assert_eq!(ranges[1], 8..13);
assert_eq!(ranges[2], 18..14);
assert_eq!(ranges[3], 23..23);
assert_eq!(
generate_marked_text(&text, &ranges, true),
"one «ˇtwo» «threeˇ» «ˇfour» fiveˇ six"
);
}
}
+33
View File
@@ -0,0 +1,33 @@
use std::time::Duration;
pub fn duration_alt_display(duration: Duration) -> String {
let hours = duration.as_secs() / 3600;
let minutes = (duration.as_secs() % 3600) / 60;
let seconds = duration.as_secs() % 60;
if hours > 0 {
format!("{hours}h {minutes}m {seconds}s")
} else if minutes > 0 {
format!("{minutes}m {seconds}s")
} else {
format!("{seconds}s")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_duration_alt_display() {
use duration_alt_display as f;
assert_eq!("0s", f(Duration::from_secs(0)));
assert_eq!("59s", f(Duration::from_secs(59)));
assert_eq!("1m 0s", f(Duration::from_secs(60)));
assert_eq!("10m 0s", f(Duration::from_secs(600)));
assert_eq!("1h 0m 0s", f(Duration::from_secs(3600)));
assert_eq!("3h 2m 1s", f(Duration::from_secs(3600 * 3 + 60 * 2 + 1)));
assert_eq!("23h 59m 59s", f(Duration::from_secs(3600 * 24 - 1)));
assert_eq!("100h 0m 0s", f(Duration::from_secs(3600 * 100)));
}
}
File diff suppressed because it is too large Load Diff
+36 -10
View File
@@ -25,12 +25,15 @@
pkgs = nixpkgs.legacyPackages.${system};
inherit (pkgs) lib;
toolchain = fenix.packages.${system}.latest.withComponents [
"cargo"
"rustc"
"rust-src"
"rustfmt"
"clippy"
toolchain = fenix.packages.${system}.combine [
(fenix.packages.${system}.latest.withComponents [
"cargo"
"rustc"
"rust-src"
"rustfmt"
"clippy"
])
fenix.packages.${system}.targets.wasm32-unknown-unknown.latest.rust-std
];
craneLib = (crane.mkLib pkgs).overrideToolchain toolchain;
@@ -105,18 +108,41 @@
packages.default = gpui;
devShells.default = pkgs.mkShell {
inputsFrom = [ gpui ];
# Provide rustup's cargo/rustc proxy (so `cargo +toolchain` works for
# the MSRV and WASM-atomics CI checks) plus all the native build deps.
packages = [
toolchain
pkgs.rustup
pkgs.cargo-machete
pkgs.taplo
pkgs.typos
pkgs.just
];
pkgs.nushell
pkgs.cmake
pkgs.pkg-config
pkgs.rustPlatform.bindgenHook
pkgs.fontconfig
pkgs.freetype
pkgs.openssl
pkgs.zlib
] ++ lib.optionals pkgs.stdenv.isDarwin [
pkgs.apple-sdk_15
(pkgs.darwinMinVersionHook "11.0")
] ++ lib.optionals pkgs.stdenv.isLinux linuxLibs;
shellHook = ''
export RUST_BACKTRACE=1
export RUST_SRC_PATH="${toolchain}/lib/rustlib/src/rust/library"
${lib.optionalString pkgs.stdenv.isDarwin ''
# Use the real Xcode SDK (not the nix apple-sdk stub) so that
# `xcrun` can find the system Metal toolchain used by gpui_macos
# to compile its .metal shaders.
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
# The nix `apple-sdk`/xcbuild package installs a stub `xcrun`
# that doesn't know about the system Metal toolchain. Prefer the
# real /usr/bin/xcrun.
mkdir -p /tmp/gpui-ce-bin
ln -sf /usr/bin/xcrun /tmp/gpui-ce-bin/xcrun
export PATH="/tmp/gpui-ce-bin:$PATH"
''}
${lib.optionalString pkgs.stdenv.isLinux ''
export LD_LIBRARY_PATH="${lib.makeLibraryPath linuxLibs}:$LD_LIBRARY_PATH"
''}
+21
View File
@@ -403,12 +403,33 @@ publish dry="false":
error make {msg: "CARGO_REGISTRY_TOKEN is not set"}
}
# Topological publish order. Vendored support crates first, then core,
# then renderers/platform leaves, with gpui_platform LAST (it has
# target-conditional deps on every platform crate).
let crates = [
"crates/gpui_ce_util/Cargo.toml"
"crates/gpui_collections/Cargo.toml"
"crates/gpui_derive_refineable/Cargo.toml"
"crates/gpui_refineable/Cargo.toml"
"crates/gpui_sum_tree/Cargo.toml"
"crates/gpui_scheduler/Cargo.toml"
"crates/gpui_media/Cargo.toml"
"crates/gpui_zed_util/Cargo.toml"
# core
"crates/gpui_shared_string/Cargo.toml"
"crates/gpui_macros/Cargo.toml"
"crates/gpui/Cargo.toml"
# renderers / platform leaves
"crates/gpui_wgpu/Cargo.toml"
"crates/gpui_tokio/Cargo.toml"
"crates/gpui_macos/Cargo.toml"
"crates/gpui_linux/Cargo.toml"
"crates/gpui_windows/Cargo.toml"
"crates/gpui_web/Cargo.toml"
"crates/gpui_elements/Cargo.toml"
"crates/gpui_platform/Cargo.toml"
]
+3 -1
View File
@@ -349,7 +349,9 @@ fn get_tests(t_bin: &str) -> impl ExactSizeIterator<Item = (String, String)> {
);
let out = test_list
.chunks_exact_mut(2)
.as_chunks_mut::<2>()
.0
.iter_mut()
.map(|pair| {
// Be resilient against changes to these constants.
if consts::SUF_NORMAL < consts::SUF_MDATA {
+2
View File
@@ -24,6 +24,8 @@ extend-ignore-re = [
check-filename = true
[default.extend-words]
# Test key prefix used in sum_tree tests (keys starting with "ba")
ba = "ba"
# Screen capture library (zed-scap)
scap = "scap"
# Win32 FORMATETC struct field: Pointer to DVTARGETDEVICE