From 5b59ac64fe0b40023d81e8c60db10b260f110813 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 07:20:18 -0600 Subject: [PATCH 1/6] refactor(data): accessors for a layer's rows and fields, and a count of direct uses (#2431) Adds RowRef and accessors on Features (row, rows, value, geometry, column, set_value, set_geometry, add/remove/replace_column, push_row, remove_row, retain_rows, truncate_rows, to_rows) over today's Arc>, with no change in behaviour. Dataset's own reads move onto them. `cargo xtask rows` counts direct uses of the rows outside rustgis-data through the compiler: the count-row-uses feature deprecates Feature's fields and the row vector's methods, and each such warning is one use. CI fails when the count rises above xtask/row-uses.txt (822). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 20 +- AGENTS.md | 3 + crates/data/Cargo.toml | 3 + crates/data/src/lib.rs | 18 +- crates/data/src/row_access.rs | 396 ++++++++++++++++++++++++++++++++++ xtask/row-uses.txt | 7 + xtask/src/changed.rs | 2 + xtask/src/main.rs | 16 +- xtask/src/rows.rs | 217 +++++++++++++++++++ 9 files changed, 669 insertions(+), 13 deletions(-) create mode 100644 crates/data/src/row_access.rs create mode 100644 xtask/row-uses.txt create mode 100644 xtask/src/rows.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2a3e0e1e80..fb7aec41b4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -199,6 +199,24 @@ jobs: - name: Test hygiene run: cargo run --locked -q -p xtask -- test-hygiene + # Direct uses of a layer's rows outside rustgis-data may not rise above xtask/row-uses.txt + # (`cargo xtask rows`, #2431). The compiler counts them as deprecation warnings, so this job + # leaves warnings as warnings; the lint job denies them in the normal build. + rows: + name: Direct row uses + runs-on: ubuntu-latest + env: + RUSTFLAGS: "" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + # Only main saves the cache (see test-rust.yml). + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Count direct row uses + run: cargo run --locked -q -p xtask -- rows + # The packages whose tests this run needs, for `test` (.github/scripts/test-selection.sh). Only # tests are narrowed: lint, the wasm build, licences and the schema check run whole every time. select: @@ -298,7 +316,7 @@ jobs: # unless their conditions below hold (the same as on the jobs), and every other job always runs. tests_pass: name: Tests pass - needs: [lint, wasm, ios, android, licenses, schema, plan, select, test] + needs: [lint, wasm, ios, android, licenses, schema, rows, plan, select, test] if: ${{ always() }} runs-on: ubuntu-latest steps: diff --git a/AGENTS.md b/AGENTS.md index 8365884d24..0189f8fe12 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -136,6 +136,9 @@ the pull request which of these it reaches and why the rest don't apply: `#[ignore = "reason"]` on ignored tests; prefer completion or progress signals. `cargo xtask memory` (in CI on Linux) fails when a command line workflow's peak memory grows past its limit in `xtask/memory-limits.txt`; a change that lowers one commits the lower limit with it. +`cargo xtask rows` (also in CI) fails when code outside `rustgis-data` uses a layer's rows directly +(`Feature` fields, the row vector) more often than `xtask/row-uses.txt` allows: use the accessors on +`Features` (`row`, `rows`, `value`, `set_value`, …), and `--update` when you lower the count (#2431). While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes and those that depend on them (and `test-hygiene` on the whole workspace), or everything when a changed file such as `Cargo.lock` is outside every package and nothing includes it. diff --git a/crates/data/Cargo.toml b/crates/data/Cargo.toml index 46a7de0958..d5e3d7bac6 100644 --- a/crates/data/Cargo.toml +++ b/crates/data/Cargo.toml @@ -85,6 +85,9 @@ rustix = { version = "1.1", features = ["process", "fs"] } pdf = ["dep:hayro"] # The JSON Schema of the saved types (`cargo xtask schema`). schema = ["dep:schemars", "rustgis-geom/schema"] +# Marks direct uses of the row vector and of `Feature`'s fields as deprecated, so that +# `cargo xtask rows` can count them outside this crate (#2431). Nothing else turns it on. +count-row-uses = [] [dev-dependencies] # Writing sample GeoParquet files. diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 44dfa796b6..9c793a84a1 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -43,6 +43,7 @@ pub mod provenance; pub mod publish; pub mod query; pub mod raster; +mod row_access; pub mod rows; pub mod s3_address; pub mod secrets; @@ -61,6 +62,7 @@ pub mod zip; pub use date::{Date, DateTime}; pub use geometry::{Geometry, GeometryType, Measure, VertexId, ambiguous_area_message, pole_loop_count, pole_loop_message}; +pub use row_access::RowRef; pub use rustgis_geom::{Coord, Extent}; pub use value::{Field, FieldType, Value}; @@ -200,8 +202,11 @@ mod secret_redaction_tests { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct Feature { + #[cfg_attr(feature = "count-row-uses", deprecated(note = "read rows through `Features::row`/`rows` (`RowRef`); see cargo xtask rows"))] pub id: u64, + #[cfg_attr(feature = "count-row-uses", deprecated(note = "read rows through `Features::row`/`rows` (`RowRef`); see cargo xtask rows"))] pub geometry: Option, + #[cfg_attr(feature = "count-row-uses", deprecated(note = "read rows through `Features::row`/`rows` (`RowRef`); see cargo xtask rows"))] pub attrs: Vec, } @@ -230,6 +235,7 @@ impl Features { } /// The rows, taking them out of the share (copying them only when another copy holds them). + #[cfg_attr(feature = "count-row-uses", deprecated(note = "use `Features::to_rows` or the row accessors; see cargo xtask rows"))] pub fn into_vec(self) -> Vec { std::sync::Arc::unwrap_or_clone(self.rows) } @@ -385,7 +391,7 @@ impl Dataset { if self.windowed { return 0; } - self.features.iter().flat_map(|f| &f.attrs).filter(|v| v.is_non_finite()).count() + self.features.rows().flat_map(RowRef::values).filter(|v| v.is_non_finite()).count() } /// How many of its features have a coordinate that isn't a number (NaN, infinity), which a @@ -395,7 +401,7 @@ impl Dataset { if self.windowed { return 0; } - self.features.iter().filter(|f| f.geometry.as_ref().is_some_and(|g| !g.is_finite())).count() + self.features.rows().filter(|r| r.geometry().is_some_and(|g| !g.is_finite())).count() } } @@ -708,11 +714,11 @@ impl Dataset { /// Value of `field` for feature `row` (Null when out of range). pub fn value(&self, row: usize, field: usize) -> &Value { - self.features.get(row).and_then(|f| f.attrs.get(field)).unwrap_or(&Value::Null) + self.features.value(row, field) } pub fn extent(&self) -> Extent { - self.features.iter().filter_map(|f| f.geometry.as_ref()).fold(Extent::EMPTY, |e, g| e.union(&g.extent())) + self.features.rows().filter_map(RowRef::geometry).fold(Extent::EMPTY, |e, g| e.union(&g.extent())) } /// Pushes a feature with the next id, padding/truncating attributes to the schema. @@ -735,9 +741,7 @@ impl Dataset { return i; } self.fields.push(Field::new(name, ty)); - for f in &mut self.features { - f.attrs.push(Value::Null); - } + self.features.add_column(Value::Null); self.fields.len() - 1 } diff --git a/crates/data/src/row_access.rs b/crates/data/src/row_access.rs new file mode 100644 index 0000000000..713bc6580d --- /dev/null +++ b/crates/data/src/row_access.rs @@ -0,0 +1,396 @@ +//! Reading and changing a layer's rows through [`Features`] without depending on how they are +//! stored (#2431). Today the rows are one shared `Vec`, and any change copies all of them +//! for Undo. The plan is to keep attribute values in columns split into shared chunks, so that an +//! edit copies one chunk. Code that goes through these accessors keeps working when that happens; +//! code that reads a [`Feature`]'s fields or the row vector directly has to change with it, and +//! `cargo xtask rows` counts it outside this crate. +//! +//! Row positions stay dense: removing a row moves the rows after it up, as today. + +use crate::{Feature, Features, Geometry, Value}; +use std::sync::Arc; + +/// One row of a layer, read where it is stored: its id, geometry and values. A view rather than +/// a `&Feature`, which a layer stored as columns won't have to lend. +#[derive(Clone, Copy, Debug)] +pub struct RowRef<'a> { + row: &'a Feature, +} + +impl<'a> RowRef<'a> { + /// The row's id. + pub fn id(self) -> u64 { + self.row.id + } + + /// The row's geometry, if it has one. + pub fn geometry(self) -> Option<&'a Geometry> { + self.row.geometry.as_ref() + } + + /// The value of field `field`, or Null where the row has none. + pub fn value(self, field: usize) -> &'a Value { + self.row.attrs.get(field).unwrap_or(&Value::Null) + } + + /// The row's values in field order. + pub fn values(self) -> impl ExactSizeIterator + DoubleEndedIterator + Clone + 'a { + self.row.attrs.iter() + } + + /// A copy of the row, for code that keeps or hands on whole rows (a clipboard, a writer, an + /// output layer). + pub fn to_feature(self) -> Feature { + self.row.clone() + } +} + +impl Features { + /// How many rows there are. + pub fn len(&self) -> usize { + self.rows.len() + } + + /// Whether there are no rows. + pub fn is_empty(&self) -> bool { + self.rows.is_empty() + } + + /// Row `row`, if there is one. + pub fn row(&self, row: usize) -> Option> { + self.rows.get(row).map(|row| RowRef { row }) + } + + /// Every row, in order. + pub fn rows(&self) -> impl ExactSizeIterator> + DoubleEndedIterator + Clone + '_ { + self.rows.iter().map(|row| RowRef { row }) + } + + /// The value of field `field` in row `row`, or Null where there is none: a cell read without + /// going through the row, which stays one lookup when values are kept by column. + pub fn value(&self, row: usize, field: usize) -> &Value { + self.row(row).map_or(&Value::Null, |r| r.value(field)) + } + + /// The geometry of row `row`, if the row exists and has one. + pub fn geometry(&self, row: usize) -> Option<&Geometry> { + self.row(row).and_then(RowRef::geometry) + } + + /// Field `field`'s value in every row, in order (Null where a row has none): what a whole-column + /// read (a statistic, a renderer's classes) will get without visiting other fields. + pub fn column(&self, field: usize) -> impl ExactSizeIterator + DoubleEndedIterator + Clone + '_ { + self.rows().map(move |r| r.value(field)) + } + + /// Sets field `field` of row `row` to `value`, returning the value it replaced; `None`, and + /// nothing changes, when the row or the field doesn't exist. + pub fn set_value(&mut self, row: usize, field: usize, value: Value) -> Option { + self.rows.get(row)?.attrs.get(field)?; + let cell = Arc::make_mut(&mut self.rows).get_mut(row)?.attrs.get_mut(field)?; + Some(std::mem::replace(cell, value)) + } + + /// Sets row `row`'s geometry, returning the one it replaced; `None`, and nothing changes, when + /// there is no row `row`. + pub fn set_geometry(&mut self, row: usize, geometry: Option) -> Option> { + self.rows.get(row)?; + let old = &mut Arc::make_mut(&mut self.rows).get_mut(row)?.geometry; + Some(std::mem::replace(old, geometry)) + } + + /// Adds a column after the last, holding `value` in every row (Add Field): one new column + /// when values are kept by column, not a change to every row. + pub fn add_column(&mut self, value: Value) { + for f in Arc::make_mut(&mut self.rows) { + // Exactly one more slot: a doubled capacity in every row would cost more than the column. + f.attrs.reserve_exact(1); + f.attrs.push(value.clone()); + } + } + + /// Removes column `field` from every row that has it (Delete Field). + pub fn remove_column(&mut self, field: usize) { + if self.rows.iter().all(|f| f.attrs.len() <= field) { + return; + } + for f in Arc::make_mut(&mut self.rows) { + if field < f.attrs.len() { + f.attrs.remove(field); + } + } + } + + /// Replaces column `field` with `values`, one per row in order, returning the old column + /// (Calculate Field): the change a column-shaped edit records. Gives `values` back, and + /// nothing changes, when there isn't one per row or a row has no field `field`. + pub fn replace_column(&mut self, field: usize, values: Vec) -> Result, Vec> { + if values.len() != self.rows.len() || self.rows.iter().any(|f| f.attrs.len() <= field) { + return Err(values); + } + let rows = Arc::make_mut(&mut self.rows); + let old = rows.iter_mut().zip(values).filter_map(|(f, v)| f.attrs.get_mut(field).map(|c| std::mem::replace(c, v))).collect(); + Ok(old) + } + + /// Appends `feature` as the last row, keeping its id. + pub fn push_row(&mut self, feature: Feature) { + let id = feature.id; + Arc::make_mut(&mut self.rows).push(feature); + self.max_id = self.max_id.map(|m| m.max(id)); + } + + /// Removes row `row`, moving the rows after it up one, and returns it; `None`, and nothing + /// changes, when there is no row `row`. + pub fn remove_row(&mut self, row: usize) -> Option { + if row >= self.rows.len() { + return None; + } + self.max_id = None; + Some(Arc::make_mut(&mut self.rows).remove(row)) + } + + /// Keeps the rows `keep` says yes to, in order. + pub fn retain_rows(&mut self, mut keep: impl FnMut(RowRef<'_>) -> bool) { + self.max_id = None; + Arc::make_mut(&mut self.rows).retain(|row| keep(RowRef { row })); + } + + /// Keeps the first `len` rows. + pub fn truncate_rows(&mut self, len: usize) { + if len < self.rows.len() { + self.max_id = None; + Arc::make_mut(&mut self.rows).truncate(len); + } + } + + /// A copy of every row as a [`Feature`]: for tests and for code that needs the rows as a list, + /// at the cost of building it. + pub fn to_rows(&self) -> Vec { + self.rows.to_vec() + } +} + +#[cfg(test)] +mod tests { + use crate::{Dataset, Feature, Field, FieldType, Geometry, GeometryType, Value}; + + fn layer() -> Dataset { + let fields = vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Integer)]; + let mut ds = Dataset::new("t", GeometryType::Point, fields); + ds.push(Some(Geometry::Point(rustgis_geom::Coord::new(1.0, 2.0))), vec![Value::Text("a".into()), Value::Int(1)]); + ds.push(None, vec![Value::Text("b".into()), Value::Int(2)]); + ds.push(Some(Geometry::Point(rustgis_geom::Coord::new(3.0, 4.0))), vec![Value::Text("c".into())]); + ds + } + + #[test] + fn reads_match_the_rows() { + let ds = layer(); + let f = &ds.features; + assert_eq!((f.len(), f.is_empty()), (3, false)); + for (r, row) in f.rows().enumerate() { + assert_eq!(row.to_feature(), ds.features[r]); + assert_eq!(row.id(), ds.features[r].id); + assert_eq!(row.geometry(), f.geometry(r)); + assert_eq!(row.values().cloned().collect::>(), ds.features[r].attrs); + } + assert_eq!(f.value(1, 1), &Value::Int(2)); + // Padded by `push`, so the short row reads Null; past the end is Null too. + assert_eq!(f.value(2, 1), &Value::Null); + assert_eq!((f.value(9, 0), f.value(0, 9)), (&Value::Null, &Value::Null)); + assert!(f.row(3).is_none() && f.geometry(1).is_none()); + assert_eq!(f.column(0).map(Value::to_string).collect::>(), ["a", "b", "c"]); + assert_eq!(f.rows().rev().map(|r| r.id()).collect::>(), [3, 2, 1]); + assert_eq!(f.to_rows(), ds.features.to_vec()); + } + + #[test] + fn a_change_copies_the_rows_only_when_it_changes_something() { + let ds = layer(); + let mut copy = ds.features.clone(); + assert_eq!(copy.set_value(0, 5, Value::Null), None); + assert_eq!(copy.set_value(7, 0, Value::Null), None); + assert_eq!(copy.set_geometry(7, None), None); + assert_eq!(copy.replace_column(0, vec![Value::Null]), Err(vec![Value::Null])); + copy.remove_column(5); + copy.truncate_rows(3); + assert_eq!(copy.remove_row(3), None); + assert!(copy.shares(&ds.features)); + + assert_eq!(copy.set_value(0, 1, Value::Int(10)), Some(Value::Int(1))); + assert!(!copy.shares(&ds.features)); + assert_eq!((ds.features.value(0, 1), copy.value(0, 1)), (&Value::Int(1), &Value::Int(10))); + assert_eq!(copy.set_geometry(1, ds.features.geometry(0).cloned()), Some(None)); + assert_eq!(copy.geometry(1), ds.features.geometry(0)); + } + + #[test] + fn columns_change_in_every_row() { + let mut ds = layer(); + assert_eq!(ds.ensure_field("flag", FieldType::Boolean), 2); + assert_eq!(ds.features.column(2).cloned().collect::>(), [Value::Null, Value::Null, Value::Null]); + let old = ds.features.replace_column(1, vec![Value::Int(7), Value::Int(8), Value::Int(9)]); + assert_eq!(old, Ok(vec![Value::Int(1), Value::Int(2), Value::Null])); + ds.features.remove_column(0); + assert_eq!(ds.features.row(2).map(|r| r.values().cloned().collect::>()), Some(vec![Value::Int(9), Value::Null])); + } + + #[test] + fn removing_rows_keeps_them_dense_and_ids_fresh() { + let mut ds = layer(); + assert_eq!(ds.features.remove_row(1).map(|f| f.id), Some(2)); + assert_eq!(ds.features.rows().map(|r| r.id()).collect::>(), [1, 3]); + // As through the vector: the largest id is searched for again, so it can be reused. + ds.features.retain_rows(|r| r.id() != 3); + ds.push(None, vec![]); + assert_eq!(ds.features.rows().map(|r| r.id()).collect::>(), [1, 2]); + ds.features.truncate_rows(1); + ds.features.push_row(Feature { id: 40, geometry: None, attrs: vec![Value::Null, Value::Null] }); + ds.push(None, vec![]); + assert_eq!(ds.features.rows().map(|r| r.id()).collect::>(), [1, 40, 41]); + } +} + +/// With the `count-row-uses` feature, which only `cargo xtask rows` turns on, the row vector's +/// methods are reached through these deprecated copies (and [`Feature`]'s fields are deprecated), +/// so the compiler names every place that uses them. Each behaves exactly as the vector's own, +/// reached through `Deref` or `DerefMut` as before. +#[cfg(feature = "count-row-uses")] +mod counted { + use crate::{Feature, Features}; + use std::ops::{Deref, DerefMut}; + use std::slice::SliceIndex; + + impl Features { + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn get>(&self, i: I) -> Option<&I::Output> { + self.deref().get(i) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn get_mut>(&mut self, i: I) -> Option<&mut I::Output> { + self.deref_mut().get_mut(i) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn iter(&self) -> std::slice::Iter<'_, Feature> { + self.deref().iter() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Feature> { + self.deref_mut().iter_mut() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn first(&self) -> Option<&Feature> { + self.deref().first() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn first_mut(&mut self) -> Option<&mut Feature> { + self.deref_mut().first_mut() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn last(&self) -> Option<&Feature> { + self.deref().last() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn push(&mut self, f: Feature) { + self.deref_mut().push(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn pop(&mut self) -> Option { + self.deref_mut().pop() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn remove(&mut self, i: usize) -> Feature { + self.deref_mut().remove(i) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn retain bool>(&mut self, f: F) { + self.deref_mut().retain(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn truncate(&mut self, n: usize) { + self.deref_mut().truncate(n) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn clear(&mut self) { + self.deref_mut().clear() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn extend>(&mut self, it: I) { + self.deref_mut().extend(it) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn reverse(&mut self) { + self.deref_mut().reverse() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn sort_by_key K>(&mut self, f: F) { + self.deref_mut().sort_by_key(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn to_vec(&self) -> Vec { + self.deref().to_vec() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn as_slice(&self) -> &[Feature] { + self.deref().as_slice() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn chunks(&self, n: usize) -> std::slice::Chunks<'_, Feature> { + self.deref().chunks(n) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn windows(&self, n: usize) -> std::slice::Windows<'_, Feature> { + self.deref().windows(n) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn contains(&self, f: &Feature) -> bool { + self.deref().contains(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn capacity(&self) -> usize { + self.deref().capacity() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn reserve(&mut self, n: usize) { + self.deref_mut().reserve(n) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn try_reserve(&mut self, n: usize) -> Result<(), std::collections::TryReserveError> { + self.deref_mut().try_reserve(n) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn try_reserve_exact(&mut self, n: usize) -> Result<(), std::collections::TryReserveError> { + self.deref_mut().try_reserve_exact(n) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn shrink_to_fit(&mut self) { + self.deref_mut().shrink_to_fit() + } + } +} diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt new file mode 100644 index 0000000000..9b8ba706b6 --- /dev/null +++ b/xtask/row-uses.txt @@ -0,0 +1,7 @@ +# Direct uses of a layer's rows outside rustgis-data: the row vector behind `Features`, or a +# `Feature`'s `id`, `geometry` and `attrs`, in the workspace's libraries and programs (`cargo xtask +# rows`, xtask/src/rows.rs). Moving rows to columns (#2431) needs this at zero, so it only comes +# down: new code reads and changes rows through the accessors on `Features` +# (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and +# commit this file with it. +count = 822 diff --git a/xtask/src/changed.rs b/xtask/src/changed.rs index 102959a070..600478e976 100644 --- a/xtask/src/changed.rs +++ b/xtask/src/changed.rs @@ -320,6 +320,8 @@ pub fn run(root: &Path, args: &[String]) -> Result<(), String> { .and_then(|_| super::cargo(&clippy)) .and_then(|_| super::cargo(&test)) .and_then(|_| super::layers()) + // Counted across the workspace: a change anywhere can add a direct use. + .and_then(|_| super::rows::run(root, &[])) // The project schema is generated from types in rustgis-engine and below, so any // change there (which checks rustgis-engine too) checks it. .and_then(|_| if checked.contains("rustgis-engine") { super::schema(true) } else { Ok(()) })?; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index b91556b52b..a71f008c54 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,11 +1,14 @@ -//! `cargo xtask ci | changed [--list] [base] | layers | memory [--cli ] [--update] | test-hygiene | notices [--check] | schema [--check] | web-pwa ` +//! `cargo xtask ci | changed [--list] [base] | layers | memory [--cli ] [--update] | rows [--update] [--list] | test-hygiene | notices [--check] | schema [--check] | web-pwa ` //! //! - `layers`: enforces the crate layering (nothing below L6 may depend on egui/eframe/rfd). //! - `memory [--cli ] [--update]`: the command line's peak memory on generated data, per //! workflow and as a multiple of loading alone, checked against `xtask/memory-limits.txt` //! (Linux; see `memory.rs`). +//! - `rows [--update] [--list]`: direct uses of a layer's rows outside `rustgis-data`, which +//! may not rise above the count in `xtask/row-uses.txt` (see `rows.rs`). //! - `test-hygiene`: timer waits in tests need same-line reasons; ignored tests need reasons. -//! - `ci`: test hygiene, fmt, clippy -D warnings, tests, layering and the project schema check. +//! - `ci`: test hygiene, fmt, clippy -D warnings, tests, layering, direct row uses and the +//! project schema check. //! - `changed [--list] [base]`: the same, on only the packages a branch changes and those that //! depend on them (see `changed.rs`). //! - `notices [--check]`: writes the third-party licence notices the packages ship (see @@ -18,6 +21,7 @@ mod changed; mod memory; mod notices; +mod rows; mod test_hygiene; use std::process::{Command, ExitCode}; @@ -75,14 +79,15 @@ fn cargo(args: &[&str]) -> Result<(), String> { if st.success() { Ok(()) } else { Err(format!("cargo {} failed", args.join(" "))) } } -/// `cargo xtask ci`: test hygiene, fmt, clippy with warnings as errors, tests, layering and the -/// project schema check, on the whole workspace. +/// `cargo xtask ci`: test hygiene, fmt, clippy with warnings as errors, tests, layering, direct row +/// uses and the project schema check, on the whole workspace. fn ci() -> Result<(), String> { test_hygiene::run(&root())?; cargo(&["fmt", "--all", "--check"]) .and_then(|_| cargo(&["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"])) .and_then(|_| cargo(&["test", "--workspace", "-q"])) .and_then(|_| layers()) + .and_then(|_| rows::run(&root(), &[])) .and_then(|_| schema(true)) } @@ -202,6 +207,7 @@ fn main() -> ExitCode { let r = match task.as_str() { "layers" => layers(), "test-hygiene" => test_hygiene::run(&root()), + "rows" => rows::run(&root(), &std::env::args().skip(2).collect::>()), "memory" => memory::run(&root(), &std::env::args().skip(2).collect::>()), "ci" => ci(), "changed" => changed::run(&root(), &std::env::args().skip(2).collect::>()), @@ -228,7 +234,7 @@ fn main() -> ExitCode { Some(other) => Err(format!("unknown argument {other}: usage: cargo xtask schema [--check]")), }, "web-pwa" => web_pwa(std::env::args().nth(2)), - _ => Err("usage: cargo xtask ci | changed [--list] [base] | layers | memory [--cli ] [--update] | test-hygiene | notices [--check] | schema [--check] | web-pwa ".into()), + _ => Err("usage: cargo xtask ci | changed [--list] [base] | layers | memory [--cli ] [--update] | rows [--update] [--list] | test-hygiene | notices [--check] | schema [--check] | web-pwa ".into()), }; match r { Ok(()) => ExitCode::SUCCESS, diff --git a/xtask/src/rows.rs b/xtask/src/rows.rs new file mode 100644 index 0000000000..fe26e0efa5 --- /dev/null +++ b/xtask/src/rows.rs @@ -0,0 +1,217 @@ +//! `cargo xtask rows [--update] [--list]`: counts the places outside `rustgis-data` that use a +//! layer's rows directly (the row vector behind `Features`, or a `Feature`'s `id`, `geometry` and +//! `attrs`) instead of the row accessors, and fails when there are more than `xtask/row-uses.txt` +//! allows (#2431). Moving the rows to columns needs that number at zero; this stops it growing in +//! the meantime. +//! +//! The compiler finds them, not a pattern: `cargo check` of the workspace's libraries and programs +//! (not tests, examples or benches) with `rustgis-data`'s `count-row-uses` feature, which marks the +//! fields and the vector's methods deprecated, and every "use of deprecated" warning with their +//! note outside `crates/data/` is one use. Other types with fields of the same names are never +//! counted. Not counted: indexing (`features[i]`), iterating `&features` in a `for` loop and +//! lending it as a `&[Feature]`, unless the row's fields are read. +//! +//! When the count falls, `--update` writes the new one; it never raises it. `--list` prints each +//! use (`file:line:column`). + +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; +use std::process::{Command, Stdio}; + +const FILE: &str = "xtask/row-uses.txt"; + +/// What the deprecation notes on the counted items end with, and nothing else's does. The message +/// names the item by the path it was reached through (`rustgis_engine::rustgis_data::Feature`). +const NOTE: &str = "see cargo xtask rows"; + +/// A counted use: the file (from the workspace root), line and column. +type Use = (String, u64, u64); + +/// The uses in `cargo check --message-format=json` output. +fn uses(output: &str) -> BTreeSet { + let mut found = BTreeSet::new(); + for line in output.lines() { + let Ok(m) = serde_json::from_str::(line) else { continue }; + let msg = &m["message"]; + let text = msg["message"].as_str().unwrap_or(""); + if m["reason"] != "compiler-message" || msg["code"]["code"] != "deprecated" || !text.contains(NOTE) { + continue; + } + let Some(span) = msg["spans"].as_array().and_then(|s| s.iter().find(|s| s["is_primary"] == true)) else { continue }; + let file = span["file_name"].as_str().unwrap_or("").replace('\\', "/"); + if file.starts_with("crates/data/") || file.is_empty() { + continue; + } + found.insert((file, span["line_start"].as_u64().unwrap_or(0), span["column_start"].as_u64().unwrap_or(0))); + } + found +} + +/// The package directory a file is in (`crates/engine`), for the per-package summary. +fn package(file: &str) -> String { + file.split('/').take(2).collect::>().join("/") +} + +/// The count `text` (the contents of [`FILE`]) allows. +fn allowed(text: &str) -> Result { + text.lines() + .filter(|l| !l.starts_with('#') && !l.trim().is_empty()) + .find_map(|l| l.split_once('=').filter(|(k, _)| k.trim() == "count").map(|(_, v)| v.trim().to_string())) + .ok_or_else(|| format!("{FILE}: no `count = ` line"))? + .parse() + .map_err(|e| format!("{FILE}: count: {e}")) +} + +/// [`FILE`] with its count set to `count`, comments kept. +fn with_count(text: &str, count: usize) -> String { + let mut out: String = text.lines().take_while(|l| l.starts_with('#') || l.trim().is_empty()).map(|l| format!("{l}\n")).collect(); + out.push_str(&format!("count = {count}\n")); + out +} + +/// `RUSTFLAGS` without `-D warnings`, which would turn the counted warnings into errors and stop +/// the packages after the first one with a use from being checked at all. +fn flags_without_deny_warnings(flags: &str) -> String { + let mut kept = Vec::new(); + let mut words = flags.split_whitespace().peekable(); + while let Some(w) = words.next() { + if w == "-Dwarnings" || w == "--deny=warnings" { + continue; + } + if (w == "-D" || w == "--deny") && words.peek() == Some(&"warnings") { + words.next(); + continue; + } + kept.push(w); + } + kept.join(" ") +} + +/// Runs the check build and returns the uses it reports. +fn measure(root: &Path) -> Result, String> { + let args = + ["check", "--workspace", "--lib", "--bins", "--locked", "--features", "rustgis-data/count-row-uses", "--message-format=json"]; + println!("$ cargo {}", args.join(" ")); + let mut cmd = Command::new(env!("CARGO")); + cmd.args(args).current_dir(root).stderr(Stdio::inherit()); + if let Ok(flags) = std::env::var("RUSTFLAGS") { + cmd.env("RUSTFLAGS", flags_without_deny_warnings(&flags)); + } + let out = cmd.output().map_err(|e| e.to_string())?; + if !out.status.success() { + return Err("rows: the check build failed, so nothing was counted (the errors are above)".into()); + } + Ok(uses(&String::from_utf8_lossy(&out.stdout))) +} + +/// Runs `cargo xtask rows` with the arguments after `rows`. +pub fn run(root: &Path, args: &[String]) -> Result<(), String> { + const USAGE: &str = "usage: cargo xtask rows [--update] [--list]"; + let (mut update, mut list) = (false, false); + for a in args { + match a.as_str() { + "--update" => update = true, + "--list" => list = true, + _ => return Err(USAGE.into()), + } + } + let path = root.join(FILE); + let text = std::fs::read_to_string(&path).map_err(|e| format!("{FILE}: {e}"))?; + let limit = allowed(&text)?; + let found = measure(root)?; + if list { + found.iter().for_each(|(f, l, c)| println!("{f}:{l}:{c}")); + } + let mut by_package: BTreeMap = BTreeMap::new(); + found.iter().for_each(|(f, _, _)| *by_package.entry(package(f)).or_default() += 1); + let summary: Vec = by_package.iter().map(|(p, n)| format!("{p} {n}")).collect(); + let count = found.len(); + println!("rows: {count} direct uses of a layer's rows outside rustgis-data (allowed: {limit}): {}", summary.join(", ")); + if count > limit { + return Err(format!( + "rows: {} more direct uses of a layer's rows than {FILE} allows. Read and change rows through the accessors on \ + `Features` (`row`, `rows`, `value`, `geometry`, `column`, `set_value`, `set_geometry`, `push_row`, `remove_row`, \ + `retain_rows`, ...; crates/data/src/row_access.rs) rather than a `Feature`'s fields or the row vector. \ + `cargo xtask rows --list` prints every use.", + count - limit + )); + } + if count < limit { + if update { + std::fs::write(&path, with_count(&text, count)).map_err(|e| format!("{FILE}: {e}"))?; + println!("rows: wrote {count} to {FILE}"); + } else { + println!("rows: {} fewer than allowed: run `cargo xtask rows --update` and commit {FILE}", limit - count); + } + } + println!("rows: ok"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn message(code: &str, text: &str, file: &str, line: u64) -> String { + serde_json::json!({ + "reason": "compiler-message", + "message": { + "message": text, + "code": { "code": code }, + "spans": [ + { "file_name": "elsewhere.rs", "line_start": 1, "column_start": 1, "is_primary": false }, + { "file_name": file, "line_start": line, "column_start": 9, "is_primary": true } + ] + } + }) + .to_string() + } + + #[test] + fn counts_deprecated_row_uses_outside_the_data_crate_once_each() { + let field = "use of deprecated field `rustgis_engine::rustgis_data::Feature::attrs`: read rows ...; see cargo xtask rows"; + let method = "use of deprecated method `rustgis_data::row_access::counted::::get`: ...; see cargo xtask rows"; + let output = [ + message("deprecated", field, "crates/engine/src/lib.rs", 10), + // The same warning twice (a package's library and program share a file). + message("deprecated", field, "crates/engine/src/lib.rs", 10), + message("deprecated", method, "crates/map/src/lib.rs", 3), + // In the data crate, which owns the rows. + message("deprecated", field, "crates/data/src/io.rs", 5), + // Something else deprecated, and another warning. + message("deprecated", "use of deprecated function `egui::old`", "crates/ui-egui/src/lib.rs", 7), + message("unused_variables", "unused variable: see cargo xtask rows", "crates/map/src/lib.rs", 4), + "not json".to_string(), + r#"{"reason":"compiler-artifact"}"#.to_string(), + ] + .join("\n"); + let found = uses(&output); + assert_eq!( + found.into_iter().collect::>(), + [("crates/engine/src/lib.rs".to_string(), 10, 9), ("crates/map/src/lib.rs".to_string(), 3, 9)] + ); + } + + #[test] + fn the_stored_count_reads_and_rewrites_keeping_its_comments() { + let text = "# why\n# how\n\ncount = 42\n"; + assert_eq!(allowed(text), Ok(42)); + assert_eq!(with_count(text, 40), "# why\n# how\n\ncount = 40\n"); + assert!(allowed("# nothing\n").is_err()); + assert!(allowed("count = many\n").is_err()); + } + + #[test] + fn deny_warnings_is_taken_out_of_rustflags_and_nothing_else() { + assert_eq!(flags_without_deny_warnings("-D warnings -C debuginfo=1"), "-C debuginfo=1"); + assert_eq!(flags_without_deny_warnings("-Dwarnings --deny=warnings --deny warnings -D unsafe_code"), "-D unsafe_code"); + assert_eq!(flags_without_deny_warnings(""), ""); + } + + #[test] + fn the_stored_count_parses() { + let text = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("row-uses.txt")).unwrap(); + assert!(allowed(&text).is_ok()); + } +} From 2cd72b15f35a95ed3ae8d3b193c667d43206607b Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 08:17:46 -0600 Subject: [PATCH 2/6] fix(xtask): the row count survives a lint cap and shows a failed build's errors - `cargo xtask rows` forces `deprecated` to warn, so `--cap-lints` can't hide the uses and let `--update` store too low a count, and reads `CARGO_ENCODED_RUSTFLAGS` when it is set. - A failed check build prints the compiler's errors, which `--message-format=json` sends to stdout. - The count is 823 on current main (three uses added since the branch began). - `retain_rows` keeps the rows shared when it keeps them all. - The doc says code built only for another target isn't counted. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/row_access.rs | 12 +++++-- xtask/row-uses.txt | 2 +- xtask/src/rows.rs | 64 ++++++++++++++++++++++++++++------- 3 files changed, 62 insertions(+), 16 deletions(-) diff --git a/crates/data/src/row_access.rs b/crates/data/src/row_access.rs index 713bc6580d..0c52e94d78 100644 --- a/crates/data/src/row_access.rs +++ b/crates/data/src/row_access.rs @@ -150,10 +150,17 @@ impl Features { Some(Arc::make_mut(&mut self.rows).remove(row)) } - /// Keeps the rows `keep` says yes to, in order. + /// Keeps the rows `keep` says yes to, in order, asking it once per row. When it keeps them + /// all, nothing changes and the rows stay shared. pub fn retain_rows(&mut self, mut keep: impl FnMut(RowRef<'_>) -> bool) { + let kept: Vec = self.rows.iter().map(|row| keep(RowRef { row })).collect(); + if kept.iter().all(|k| *k) { + return; + } self.max_id = None; - Arc::make_mut(&mut self.rows).retain(|row| keep(RowRef { row })); + // `Vec::retain` visits each row once, in order. + let mut kept = kept.into_iter(); + Arc::make_mut(&mut self.rows).retain(|_| kept.next().unwrap_or(true)); } /// Keeps the first `len` rows. @@ -216,6 +223,7 @@ mod tests { copy.remove_column(5); copy.truncate_rows(3); assert_eq!(copy.remove_row(3), None); + copy.retain_rows(|_| true); assert!(copy.shares(&ds.features)); assert_eq!(copy.set_value(0, 1, Value::Int(10)), Some(Value::Int(1))); diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 9b8ba706b6..53f968dd99 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 822 +count = 823 diff --git a/xtask/src/rows.rs b/xtask/src/rows.rs index fe26e0efa5..568c49a1b5 100644 --- a/xtask/src/rows.rs +++ b/xtask/src/rows.rs @@ -9,7 +9,8 @@ //! fields and the vector's methods deprecated, and every "use of deprecated" warning with their //! note outside `crates/data/` is one use. Other types with fields of the same names are never //! counted. Not counted: indexing (`features[i]`), iterating `&features` in a `for` loop and -//! lending it as a `&[Feature]`, unless the row's fields are read. +//! lending it as a `&[Feature]`, unless the row's fields are read; and code built only for another +//! target (`cfg(target_arch = "wasm32")`, Android, iOS), since only this computer's build is checked. //! //! When the count falls, `--update` writes the new one; it never raises it. `--list` prints each //! use (`file:line:column`). @@ -70,11 +71,13 @@ fn with_count(text: &str, count: usize) -> String { out } -/// `RUSTFLAGS` without `-D warnings`, which would turn the counted warnings into errors and stop -/// the packages after the first one with a use from being checked at all. -fn flags_without_deny_warnings(flags: &str) -> String { +/// The compiler flags for the check build: `flags` (the caller's) without `-D warnings`, which +/// would turn the counted warnings into errors and stop the packages after the first one with a +/// use from being checked at all, and with `deprecated` forced to warn, so that a lint cap +/// (`--cap-lints`) can't hide the uses and let `--update` store too low a count. +fn check_flags(flags: &[&str]) -> Vec { let mut kept = Vec::new(); - let mut words = flags.split_whitespace().peekable(); + let mut words = flags.iter().copied().peekable(); while let Some(w) = words.next() { if w == "-Dwarnings" || w == "--deny=warnings" { continue; @@ -83,9 +86,20 @@ fn flags_without_deny_warnings(flags: &str) -> String { words.next(); continue; } - kept.push(w); + kept.push(w.to_string()); } - kept.join(" ") + kept.extend(["--force-warn".to_string(), "deprecated".to_string()]); + kept +} + +/// The rendered errors in `cargo check --message-format=json` output. +fn errors(output: &str) -> Vec { + output + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|m| m["reason"] == "compiler-message" && m["message"]["level"] == "error") + .filter_map(|m| m["message"]["rendered"].as_str().map(str::to_string)) + .collect() } /// Runs the check build and returns the uses it reports. @@ -95,11 +109,22 @@ fn measure(root: &Path) -> Result, String> { println!("$ cargo {}", args.join(" ")); let mut cmd = Command::new(env!("CARGO")); cmd.args(args).current_dir(root).stderr(Stdio::inherit()); - if let Ok(flags) = std::env::var("RUSTFLAGS") { - cmd.env("RUSTFLAGS", flags_without_deny_warnings(&flags)); + // Cargo reads `CARGO_ENCODED_RUSTFLAGS` (words split by 0x1f) before `RUSTFLAGS`. Setting the + // flags replaces a config file's `rustflags`; those only matter for linking, which a check skips. + match std::env::var("CARGO_ENCODED_RUSTFLAGS").ok().filter(|f| !f.is_empty()) { + Some(flags) => { + let words: Vec<&str> = flags.split('\u{1f}').collect(); + cmd.env("CARGO_ENCODED_RUSTFLAGS", check_flags(&words).join("\u{1f}")); + } + None => { + let flags = std::env::var("RUSTFLAGS").unwrap_or_default(); + let words: Vec<&str> = flags.split_whitespace().collect(); + cmd.env("RUSTFLAGS", check_flags(&words).join(" ")); + } } let out = cmd.output().map_err(|e| e.to_string())?; if !out.status.success() { + errors(&String::from_utf8_lossy(&out.stdout)).iter().for_each(|e| eprint!("{e}")); return Err("rows: the check build failed, so nothing was counted (the errors are above)".into()); } Ok(uses(&String::from_utf8_lossy(&out.stdout))) @@ -203,10 +228,23 @@ mod tests { } #[test] - fn deny_warnings_is_taken_out_of_rustflags_and_nothing_else() { - assert_eq!(flags_without_deny_warnings("-D warnings -C debuginfo=1"), "-C debuginfo=1"); - assert_eq!(flags_without_deny_warnings("-Dwarnings --deny=warnings --deny warnings -D unsafe_code"), "-D unsafe_code"); - assert_eq!(flags_without_deny_warnings(""), ""); + fn deny_warnings_is_taken_out_of_rustflags_and_deprecated_forced_to_warn() { + let f = |s: &str| check_flags(&s.split_whitespace().collect::>()).join(" "); + assert_eq!(f("-D warnings -C debuginfo=1"), "-C debuginfo=1 --force-warn deprecated"); + assert_eq!(f("-Dwarnings --deny=warnings --deny warnings -D unsafe_code"), "-D unsafe_code --force-warn deprecated"); + assert_eq!(f("--cap-lints=allow"), "--cap-lints=allow --force-warn deprecated"); + assert_eq!(f(""), "--force-warn deprecated"); + } + + #[test] + fn a_failed_check_shows_its_errors() { + let out = concat!( + r#"{"reason":"compiler-message","message":{"level":"error","rendered":"error[E0425]: x\n"}}"#, + "\n", + r#"{"reason":"compiler-message","message":{"level":"warning","rendered":"warning: y\n"}}"#, + "\nnot json\n" + ); + assert_eq!(errors(out), vec!["error[E0425]: x\n".to_string()]); } #[test] From 8f96610f3c982319bda9e11f5e5433ac4df42300 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 09:03:56 -0600 Subject: [PATCH 3/6] fix(data): row accessors call the copy hook, and every common vector method is counted - Every change through the accessors copies shared rows through one helper that first calls the hook `before_rows_copy` sets, as `DerefMut` does, so Add Field through `add_column` frees older Undo steps before copying again (#2445). A test checks a change to shared rows calls it and a change that copies nothing doesn't. - The count also covers `insert`, `drain`, `append`, `split_off`, `swap`, `swap_remove`, `resize`, `resize_with`, `retain_mut`, `dedup_by_key`, the sorts and binary searches by closure, `last_mut`, `split_at`, `split_at_mut`, `as_mut_slice`, `chunks_mut`, `chunks_exact`, `split_first` and `split_last`. No code uses them today; the count stays 823. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/row_access.rs | 160 +++++++++++++++++++++++++++++++--- xtask/src/rows.rs | 3 +- 2 files changed, 152 insertions(+), 11 deletions(-) diff --git a/crates/data/src/row_access.rs b/crates/data/src/row_access.rs index 0c52e94d78..8c3406e426 100644 --- a/crates/data/src/row_access.rs +++ b/crates/data/src/row_access.rs @@ -87,7 +87,7 @@ impl Features { /// nothing changes, when the row or the field doesn't exist. pub fn set_value(&mut self, row: usize, field: usize, value: Value) -> Option { self.rows.get(row)?.attrs.get(field)?; - let cell = Arc::make_mut(&mut self.rows).get_mut(row)?.attrs.get_mut(field)?; + let cell = self.rows_mut().get_mut(row)?.attrs.get_mut(field)?; Some(std::mem::replace(cell, value)) } @@ -95,14 +95,14 @@ impl Features { /// there is no row `row`. pub fn set_geometry(&mut self, row: usize, geometry: Option) -> Option> { self.rows.get(row)?; - let old = &mut Arc::make_mut(&mut self.rows).get_mut(row)?.geometry; + let old = &mut self.rows_mut().get_mut(row)?.geometry; Some(std::mem::replace(old, geometry)) } /// Adds a column after the last, holding `value` in every row (Add Field): one new column /// when values are kept by column, not a change to every row. pub fn add_column(&mut self, value: Value) { - for f in Arc::make_mut(&mut self.rows) { + for f in self.rows_mut() { // Exactly one more slot: a doubled capacity in every row would cost more than the column. f.attrs.reserve_exact(1); f.attrs.push(value.clone()); @@ -114,7 +114,7 @@ impl Features { if self.rows.iter().all(|f| f.attrs.len() <= field) { return; } - for f in Arc::make_mut(&mut self.rows) { + for f in self.rows_mut() { if field < f.attrs.len() { f.attrs.remove(field); } @@ -128,7 +128,7 @@ impl Features { if values.len() != self.rows.len() || self.rows.iter().any(|f| f.attrs.len() <= field) { return Err(values); } - let rows = Arc::make_mut(&mut self.rows); + let rows = self.rows_mut(); let old = rows.iter_mut().zip(values).filter_map(|(f, v)| f.attrs.get_mut(field).map(|c| std::mem::replace(c, v))).collect(); Ok(old) } @@ -136,10 +136,18 @@ impl Features { /// Appends `feature` as the last row, keeping its id. pub fn push_row(&mut self, feature: Feature) { let id = feature.id; - Arc::make_mut(&mut self.rows).push(feature); + self.rows_mut().push(feature); self.max_id = self.max_id.map(|m| m.max(id)); } + /// The rows for a change, copied first when another owner (an Undo snapshot) shares them. + /// Every change goes through it, so the hook [`crate::before_rows_copy`] sets runs before a + /// copy, as it does through `DerefMut`. + fn rows_mut(&mut self) -> &mut Vec { + self.before_copy(); + Arc::make_mut(&mut self.rows) + } + /// Removes row `row`, moving the rows after it up one, and returns it; `None`, and nothing /// changes, when there is no row `row`. pub fn remove_row(&mut self, row: usize) -> Option { @@ -147,7 +155,7 @@ impl Features { return None; } self.max_id = None; - Some(Arc::make_mut(&mut self.rows).remove(row)) + Some(self.rows_mut().remove(row)) } /// Keeps the rows `keep` says yes to, in order, asking it once per row. When it keeps them @@ -160,14 +168,14 @@ impl Features { self.max_id = None; // `Vec::retain` visits each row once, in order. let mut kept = kept.into_iter(); - Arc::make_mut(&mut self.rows).retain(|_| kept.next().unwrap_or(true)); + self.rows_mut().retain(|_| kept.next().unwrap_or(true)); } /// Keeps the first `len` rows. pub fn truncate_rows(&mut self, len: usize) { if len < self.rows.len() { self.max_id = None; - Arc::make_mut(&mut self.rows).truncate(len); + self.rows_mut().truncate(len); } } @@ -180,7 +188,7 @@ impl Features { #[cfg(test)] mod tests { - use crate::{Dataset, Feature, Field, FieldType, Geometry, GeometryType, Value}; + use crate::{Dataset, Feature, Features, Field, FieldType, Geometry, GeometryType, Value}; fn layer() -> Dataset { let fields = vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Integer)]; @@ -233,6 +241,23 @@ mod tests { assert_eq!(copy.geometry(1), ds.features.geometry(0)); } + #[test] + fn a_change_that_copies_shared_rows_calls_the_copy_hook_first() { + let ds = layer(); + let mut copy = ds.features.clone(); + let fired = |copy: &mut Features, change: &dyn Fn(&mut Features)| crate::before_rows_copy(Box::new(|| {}), || change(copy)).1; + assert!(!fired(&mut copy, &|f| { + f.set_value(9, 0, Value::Null); + })); + assert!(fired(&mut copy, &|f| f.add_column(Value::Null))); + // The rows are its own now: nothing more to copy. + assert!(!fired(&mut copy, &|f| { + f.set_value(0, 0, Value::Null); + })); + let mut other = ds.features.clone(); + assert!(fired(&mut other, &|f| f.truncate_rows(1))); + } + #[test] fn columns_change_in_every_row() { let mut ds = layer(); @@ -400,5 +425,120 @@ mod counted { pub fn shrink_to_fit(&mut self) { self.deref_mut().shrink_to_fit() } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn insert(&mut self, i: usize, f: Feature) { + self.deref_mut().insert(i, f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn drain>(&mut self, r: R) -> std::vec::Drain<'_, Feature> { + self.deref_mut().drain(r) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn append(&mut self, other: &mut Vec) { + self.deref_mut().append(other) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn split_off(&mut self, at: usize) -> Vec { + self.deref_mut().split_off(at) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn swap(&mut self, a: usize, b: usize) { + self.deref_mut().swap(a, b) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn swap_remove(&mut self, i: usize) -> Feature { + self.deref_mut().swap_remove(i) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn resize(&mut self, n: usize, f: Feature) { + self.deref_mut().resize(n, f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn resize_with Feature>(&mut self, n: usize, f: F) { + self.deref_mut().resize_with(n, f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn retain_mut bool>(&mut self, f: F) { + self.deref_mut().retain_mut(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn dedup_by_key K>(&mut self, f: F) { + self.deref_mut().dedup_by_key(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn sort_by std::cmp::Ordering>(&mut self, f: F) { + self.deref_mut().sort_by(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn sort_unstable_by std::cmp::Ordering>(&mut self, f: F) { + self.deref_mut().sort_unstable_by(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn sort_unstable_by_key K>(&mut self, f: F) { + self.deref_mut().sort_unstable_by_key(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn binary_search_by std::cmp::Ordering>(&self, f: F) -> Result { + self.deref().binary_search_by(f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn binary_search_by_key B>(&self, b: &B, f: F) -> Result { + self.deref().binary_search_by_key(b, f) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn last_mut(&mut self) -> Option<&mut Feature> { + self.deref_mut().last_mut() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn split_at(&self, mid: usize) -> (&[Feature], &[Feature]) { + self.deref().split_at(mid) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn split_at_mut(&mut self, mid: usize) -> (&mut [Feature], &mut [Feature]) { + self.deref_mut().split_at_mut(mid) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn as_mut_slice(&mut self) -> &mut [Feature] { + self.deref_mut().as_mut_slice() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn chunks_mut(&mut self, n: usize) -> std::slice::ChunksMut<'_, Feature> { + self.deref_mut().chunks_mut(n) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn chunks_exact(&self, n: usize) -> std::slice::ChunksExact<'_, Feature> { + self.deref().chunks_exact(n) + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn split_first(&self) -> Option<(&Feature, &[Feature])> { + self.deref().split_first() + } + + #[deprecated(note = "use the row accessors (`Features::row`, `rows`, `set_value`, ...); see cargo xtask rows")] + pub fn split_last(&self) -> Option<(&Feature, &[Feature])> { + self.deref().split_last() + } } } diff --git a/xtask/src/rows.rs b/xtask/src/rows.rs index 568c49a1b5..ba01636836 100644 --- a/xtask/src/rows.rs +++ b/xtask/src/rows.rs @@ -9,7 +9,8 @@ //! fields and the vector's methods deprecated, and every "use of deprecated" warning with their //! note outside `crates/data/` is one use. Other types with fields of the same names are never //! counted. Not counted: indexing (`features[i]`), iterating `&features` in a `for` loop and -//! lending it as a `&[Feature]`, unless the row's fields are read; and code built only for another +//! lending it as a `&[Feature]`, unless the row's fields are read; a vector or slice method with no +//! deprecated copy in `row_access.rs` (the common ones all have one); and code built only for another //! target (`cfg(target_arch = "wasm32")`, Android, iOS), since only this computer's build is checked. //! //! When the count falls, `--update` writes the new one; it never raises it. `--list` prints each From 0d3375c966b4b59c43e5b162967c6c89c46f416e Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 20:30:30 -0600 Subject: [PATCH 4/6] chore(xtask): record the 839 direct row uses on current main Co-Authored-By: Claude Opus 5.5 --- xtask/row-uses.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 53f968dd99..e6016f6342 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 823 +count = 839 From fe950072ed2bc12d936fda712c797a34c590615d Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 20:31:18 -0600 Subject: [PATCH 5/6] docs(agents): say what the row-use count leaves out Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 6149cf224b..3362dfb5ad 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -152,6 +152,8 @@ its limit in `xtask/memory-limits.txt`; a change that lowers one commits the low `cargo xtask rows` (also in CI) fails when code outside `rustgis-data` uses a layer's rows directly (`Feature` fields, the row vector) more often than `xtask/row-uses.txt` allows: use the accessors on `Features` (`row`, `rows`, `value`, `set_value`, …), and `--update` when you lower the count (#2431). +It counts only the libraries and programs built for the host, not tests, examples, benches or code +built only for other targets; use the accessors there too. While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes and those that depend on them (and `test-hygiene` on the whole workspace), or everything when a changed file such as `Cargo.lock` is outside every package and nothing includes it. From bd101b476597228baf6f6f8952404ff6dc9a0a5f Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 20:33:35 -0600 Subject: [PATCH 6/6] docs(agents): the row-use count leaves out indexing alone Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 3362dfb5ad..76a5649243 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -153,7 +153,8 @@ its limit in `xtask/memory-limits.txt`; a change that lowers one commits the low (`Feature` fields, the row vector) more often than `xtask/row-uses.txt` allows: use the accessors on `Features` (`row`, `rows`, `value`, `set_value`, …), and `--update` when you lower the count (#2431). It counts only the libraries and programs built for the host, not tests, examples, benches or code -built only for other targets; use the accessors there too. +built only for other targets, nor a row indexed without reading a field (`features[i]` alone); use +the accessors there too. While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes and those that depend on them (and `test-hygiene` on the whole workspace), or everything when a changed file such as `Cargo.lock` is outside every package and nothing includes it.