Debian Codegraph @

README.md

raw symbols SCIP
1 <!-- cargo-sync-rdme title [[ -->
2 # daft
3 <!-- cargo-sync-rdme ]] -->
4 <!-- cargo-sync-rdme badge [[ -->
5 ![License: MIT OR Apache-2.0](https://img.shields.io/crates/l/daft.svg?)
6 [![crates.io](https://img.shields.io/crates/v/daft.svg?logo=rust)](https://crates.io/crates/daft)
7 [![docs.rs](https://img.shields.io/docsrs/daft.svg?logo=docs.rs)](https://docs.rs/daft)
8 [![Rust: ^1.81.0](https://img.shields.io/badge/rust-^1.81.0-93450a.svg?logo=rust)](https://doc.rust-lang.org/cargo/reference/manifest.html#the-rust-version-field)
9 <!-- cargo-sync-rdme ]] -->
10 <!-- cargo-sync-rdme rustdoc [[ -->
11 Daft is a library to perform semantic diffs of Rust data structures.
12
13 Daft consists of a trait called [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html), along with [a derive
14 macro](https://docs.rs/daft-derive/0.1.5/daft_derive/derive.Diffable.html) by the same name. This trait represents the
15 notion of a type for which two members can be simultaneously compared.
16
17 ## Features
18
19 * **Recursive diffing** of structs, sets, and maps
20 * **Derive macro** for automatically generating diff types
21 * Choose between **eager** and **lazy** diffing
22 * **No-std compatible**, both with and without `alloc`
23
24 ## Usage
25
26 ````rust
27 use daft::{Diffable, Leaf};
28
29 // Annotate your struct with `#[derive(Diffable)]`:
30 #[derive(Diffable)]
31 struct MyStruct {
32 a: i32,
33 b: String,
34 }
35
36 // This generates a type called MyStructDiff, which looks like:
37 #[automatically_derived]
38 struct MyStructDiff<'daft> {
39 a: Leaf<&'daft i32>,
40 b: Leaf<&'daft str>,
41 }
42
43 // Then, with two instances of MyStruct:
44 let before = MyStruct { a: 1, b: "hello".to_owned() };
45 let after = MyStruct { a: 2, b: "world".to_owned() };
46
47 // You can diff them like so:
48 let diff = before.diff(&after);
49
50 // And compare the results:
51 assert_eq!(*diff.a.before, 1);
52 assert_eq!(*diff.a.after, 2);
53 assert_eq!(diff.b.before, "hello");
54 assert_eq!(diff.b.after, "world");
55 ````
56
57 This crate assigns one side the name *before*, and the other side *after*.
58 These labels are arbitrary: if *before* and *after* are swapped, the diff is
59 reversed.
60
61 ### Diff types
62
63 Currently, daft comes with a few kinds of diff types:
64
65 #### [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) instances
66
67 A [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) represents a logical *leaf node* or *base case* in a diff, i.e. a
68 point at which diffing stops. [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) instances are used for:
69
70 * *Scalar* or *primitive types* like `i32`, `String`, `bool`, etc.
71 * *Enums*, since diffing across variants is usually not meaningful.
72 * Vector and slice types, since there are several reasonable ways to diff
73 vectors (e.g. set-like, ordered, etc.) and we don’t want to make assumptions.
74 * As an opt-in mechanism for struct fields: see
75 [*Recursive diffs*](#recursive-diffs) below for more.
76
77 ##### Example
78
79 A contrived example for integers:
80
81 ````rust
82 use daft::{Diffable, Leaf};
83
84 let diff: Leaf<&i32> = 1_i32.diff(&2);
85 assert_eq!(*diff.before, 1);
86 assert_eq!(*diff.after, 2);
87 ````
88
89 Enums also use `Leaf`:
90
91 ````rust
92 use daft::{Diffable, Leaf};
93
94 // Option<T> uses Leaf:
95 let diff: Leaf<Option<&i32>> = Some(1_i32).diff(&Some(2));
96 assert_eq!(diff.before, Some(&1));
97 assert_eq!(diff.after, Some(&2));
98
99 // Automatically derived enums also use Leaf:
100 #[derive(Debug, PartialEq, Eq, Diffable)]
101 enum MyEnum {
102 A(i32),
103 B(String),
104 }
105
106 let before = MyEnum::A(1);
107 let after = MyEnum::B("hello".to_string());
108
109 let diff: Leaf<&MyEnum> = before.diff(&after);
110 assert_eq!(diff.before, &before);
111 assert_eq!(diff.after, &after);
112 ````
113
114 Vectors use `Leaf` as well:
115
116 ````rust
117 use daft::{Diffable, Leaf};
118
119 let before = vec![1, 2, 3];
120 let after = vec![4, 5, 6];
121 let diff: Leaf<&[i32]> = before.diff(&after);
122 assert_eq!(diff.before, &before);
123 assert_eq!(diff.after, &after);
124 ````
125
126 #### Map diffs
127
128 For [`BTreeMap`] and [`HashMap`], daft has corresponding [`BTreeMapDiff`](https://docs.rs/daft/0.1.5/daft/alloc_impls/struct.BTreeMapDiff.html)
129 and [`HashMapDiff`](https://docs.rs/daft/0.1.5/daft/std_impls/struct.HashMapDiff.html) types. These types have fields for *common*, *added*,
130 and *removed* entries.
131
132 Map diffs are performed eagerly for keys, but values are stored as leaf
133 nodes.
134
135 ##### Example
136
137 ````rust
138 use daft::{Diffable, Leaf, BTreeMapDiff};
139 use std::collections::BTreeMap;
140
141 let mut a = BTreeMap::new();
142 a.insert(1, "one");
143 a.insert(2, "two");
144 a.insert(3, "three");
145
146 let mut b = BTreeMap::new();
147 b.insert(2, "two");
148 b.insert(3, "THREE");
149 b.insert(4, "four");
150
151 let diff: BTreeMapDiff<'_, i32, &str> = a.diff(&b);
152
153 // Added and removed entries are stored as maps:
154 assert_eq!(diff.added, [(&4, &"four")].into_iter().collect());
155 assert_eq!(diff.removed, [(&1, &"one")].into_iter().collect());
156
157 // Common entries are stored as leaf nodes.
158 assert_eq!(
159 diff.common,
160 [
161 (&2, Leaf { before: &"two", after: &"two" }),
162 (&3, Leaf { before: &"three", after: &"THREE" })
163 ]
164 .into_iter().collect(),
165 );
166
167 // If `V` implements `Eq`, unchanged and modified iterators become
168 // available. `unchanged` and `modified` return key-value pairs;
169 // `unchanged_keys` and `modified_keys` return keys; and
170 // `unchanged_values` and `modified_values` return values.
171 //
172 // Here's `unchanged_keys` to get the keys of unchanged entries:
173 assert_eq!(diff.unchanged_keys().collect::<Vec<_>>(), [&2]);
174
175 // `modified_values` returns leaf nodes for modified entries.
176 assert_eq!(
177 diff.modified_values().collect::<Vec<_>>(),
178 [Leaf { before: &"three", after: &"THREE" }],
179 );
180 ````
181
182 #### Set diffs
183
184 For [`BTreeSet`] and [`HashSet`], daft has corresponding [`BTreeSetDiff`](https://docs.rs/daft/0.1.5/daft/alloc_impls/struct.BTreeSetDiff.html)
185 and [`HashSetDiff`](https://docs.rs/daft/0.1.5/daft/std_impls/struct.HashSetDiff.html) types. These types have fields for *common*, *added*,
186 and *removed* entries.
187
188 Set diffs are performed eagerly.
189
190 ##### Example
191
192 ````rust
193 use daft::{Diffable, Leaf, BTreeSetDiff};
194 use std::collections::BTreeSet;
195
196 let a: BTreeSet<i32> = [0, 1, 2, 3, 4, 5].into_iter().collect();
197 let b: BTreeSet<i32> = [3, 4, 5, 6, 7, 8].into_iter().collect();
198 let diff: BTreeSetDiff<'_, i32> = a.diff(&b);
199
200 assert_eq!(diff.common, [&3, &4, &5].into_iter().collect());
201 assert_eq!(diff.added, [&6, &7, &8].into_iter().collect());
202 assert_eq!(diff.removed, [&0, &1, &2].into_iter().collect());
203 ````
204
205 #### Tuple diffs
206
207 For a tuple like `(A, B, C)`, the [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html) implementation is recursive:
208 the diff resolves to `(A::Diff, B::Diff, C::Diff)`.
209
210 ##### Example
211
212 ````rust
213 use daft::{BTreeSetDiff, Diffable, Leaf};
214 use std::collections::BTreeSet;
215
216 let before: (usize, String, BTreeSet<usize>) = (1, "hello".to_owned(), [1, 2, 3].into_iter().collect());
217 let after = (2, "world".to_owned(), [2, 3, 4].into_iter().collect());
218
219 let diff = before.diff(&after);
220 assert_eq!(
221 diff,
222 (
223 Leaf { before: &1, after: &2 },
224 Leaf { before: "hello", after: "world" },
225 BTreeSetDiff {
226 common: [&2, &3].into_iter().collect(),
227 added: [&4].into_iter().collect(),
228 removed: [&1].into_iter().collect(),
229 }
230 ),
231 );
232 ````
233
234 #### Struct diffs
235
236 For structs, the [`Diffable`](https://docs.rs/daft-derive/0.1.5/daft_derive/derive.Diffable.html) derive macro generates
237 a diff type with a field corresponding to each field type. Each field must
238 implement [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html).
239
240 A struct `Foo` gets a corresponding `FooDiff` struct, which has fields
241 corresponding to each field in `Foo`.
242
243 ##### Struct options
244
245 * `#[daft(leaf)]`: if a **struct** is annotated with this, the [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html)
246 implementation for the struct will be a [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) instead of a recursive
247 diff.
248
249 ##### Field options
250
251 * `#[daft(leaf)]`: if a **struct field** is annotated with this, the generated
252 struct’s corresponding field will be a [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html), regardless of the field’s
253 `Diff` type (or even whether it implements [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html) at all).
254 * `#[daft(ignore)]`: the generated struct’s corresponding field is not included
255 in the diff.
256
257 ##### Example
258
259 For an example of structs with named fields, see [*Usage*](#usage) above.
260
261 Tuple-like structs produce tuple-like diff structs:
262
263 ````rust
264 use daft::Diffable;
265 use std::collections::BTreeMap;
266
267 #[derive(Diffable)]
268 struct MyTuple(BTreeMap<i32, &'static str>, i32);
269
270 let before = MyTuple(BTreeMap::new(), 1);
271 let after = MyTuple([(1, "hello")].into_iter().collect(), 2);
272 let diff = before.diff(&after);
273
274 // The generated type is MyTupleDiff(BTreeMapDiff<i32, &str>, Leaf<i32>).
275 assert_eq!(**diff.0.added.get(&1).unwrap(), "hello");
276 assert_eq!(*diff.1.before, 1);
277 assert_eq!(*diff.1.after, 2);
278 ````
279
280 An example with `#[daft(leaf)]` on **structs**:
281
282 ````rust
283 use daft::{Diffable, Leaf};
284
285 #[derive(Diffable)]
286 #[daft(leaf)]
287 struct MyStruct {
288 a: i32,
289 }
290
291 let before = MyStruct { a: 1 };
292 let after = MyStruct { a: 2 };
293 let diff: Leaf<&MyStruct> = before.diff(&after);
294
295 assert_eq!(diff.before.a, 1);
296 assert_eq!(diff.after.a, 2);
297 ````
298
299 An example with `#[daft(leaf)]` on **struct fields**:
300
301 ````rust
302 use daft::{Diffable, Leaf};
303
304 // A simple struct that implements Diffable.
305 #[derive(Debug, PartialEq, Eq, Diffable)]
306 struct InnerStruct {
307 text: &'static str,
308 }
309
310 // A struct that does not implement Diffable.
311 #[derive(Debug, PartialEq, Eq)]
312 struct PlainStruct(usize);
313
314 #[derive(Diffable)]
315 struct OuterStruct {
316 // Ordinarily, InnerStruct would be diffed recursively, but
317 // with #[daft(leaf)], it is treated as a leaf node.
318 #[daft(leaf)]
319 inner: InnerStruct,
320
321 // PlainStruct does not implement Diffable, but using
322 // daft(leaf) allows it to be diffed anyway.
323 #[daft(leaf)]
324 plain: PlainStruct,
325 }
326
327 let before = OuterStruct { inner: InnerStruct { text: "hello" }, plain: PlainStruct(1) };
328 let after = OuterStruct { inner: InnerStruct { text: "world" }, plain: PlainStruct(2) };
329 let diff = before.diff(&after);
330
331 // `OuterStructDiff` does *not* recursively diff `InnerStruct`, but instead
332 // returns a leaf node.
333 assert_eq!(
334 diff.inner,
335 Leaf { before: &InnerStruct { text: "hello" }, after: &InnerStruct { text: "world" } },
336 );
337
338 // But you can continue the recursion anyway, since `InnerStruct` implements
339 // `Diffable`:
340 let inner_diff = diff.inner.diff_pair();
341 assert_eq!(
342 inner_diff,
343 InnerStructDiff { text: Leaf { before: "hello", after: "world" } },
344 );
345
346 // `PlainStruct` can also be compared even though it doesn't implement `Diffable`.
347 assert_eq!(diff.plain, Leaf { before: &PlainStruct(1), after: &PlainStruct(2) });
348 ````
349
350 #### Custom diff types
351
352 The [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html) trait can also be implemented manually for custom behavior.
353
354 In general, most custom implementations will likely use one of the built-in
355 diff types directly.
356
357 #### Example
358
359 Some structs like identifiers should be treated as leaf nodes. This can be
360 implemented via `#[daft(leaf)]`, but also manually:
361
362 ````rust
363 use daft::{Diffable, Leaf};
364
365 struct Identifier(String);
366
367 impl Diffable for Identifier {
368 type Diff<'daft> = Leaf<&'daft Self>;
369
370 fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> {
371 Leaf {
372 before: self,
373 after: other,
374 }
375 }
376 }
377 ````
378
379 ### Type and lifetime parameters
380
381 If a type parameter is specified, the [`Diffable`](https://docs.rs/daft-derive/0.1.5/daft_derive/derive.Diffable.html) derive
382 macro for structs normally requires that the type parameter implement
383 `Diffable`. This is not required if the field is annotated with
384 `#[daft(leaf)]`.
385
386 Daft fully supports types with arbitrary lifetimes. Automatically generated
387 diff structs will have an additional `'daft` lifetime parameter at the
388 beginning, with the requirement that all other lifetime and type parameters
389 outlive it.
390
391 #### Example
392
393 ````rust
394 use daft::Diffable;
395
396 #[derive(Diffable)]
397 struct BorrowedData<'a, 'b, T: Diffable + ?Sized> {
398 a: &'a str,
399 b: &'b T,
400 // TODO: example with daft(leaf)
401 }
402
403 // This generates a struct that looks like:
404 #[automatically_derived]
405 struct BorrowedDataDiff<'daft, 'a: 'daft, 'b: 'daft, T: ?Sized + 'daft> {
406 a: Leaf<'daft, &'a str>,
407 b: T::Diff<'daft>,
408 }
409 ````
410
411 ## Optional features
412
413 * `derive`: Enable the `Diffable` derive macro: **disabled** by default.
414
415 Implementations for standard library types, all **enabled** by default:
416
417 * `alloc`: Enable diffing for types from the [`alloc`](https://doc.rust-lang.org/nightly/alloc/index.html) crate.
418 * `std`: Enable diffing for types from the [`std`](https://doc.rust-lang.org/nightly/std/index.html) crate.
419
420 (With `default-features = false`, daft is no-std compatible.)
421
422 Implementations for third-party types, all **disabled** by default:
423
424 * `uuid1`: Enable diffing for [`uuid::Uuid`](https://docs.rs/uuid/1.12.1/uuid/struct.Uuid.html).
425 * `oxnet01`: Enable diffing for network types from the [`oxnet`](https://docs.rs/oxnet/0.1.0/oxnet/index.html) crate.
426 * `newtype-uuid1`: Enable diffing for [`newtype_uuid::TypedUuid`](https://docs.rs/newtype-uuid/1.2.1/newtype_uuid/struct.TypedUuid.html).
427
428 ## Minimum supported Rust version (MSRV)
429
430 The minimum supported Rust version is **1.81.0**. At any time, at least the
431 last three stable versions of Rust are supported.
432
433 While this crate is a pre-release (0.x.x) it may have its MSRV bumped in a
434 patch release. Once this crate has reached 1.x, any MSRV bump will be
435 accompanied with a new minor version.
436
437 ## Related work
438
439 [Diffus](https://crates.io/crates/diffus) is the original inspiration for
440 this crate and a great alternative. Daft diverges from diffus in a few ways:
441
442 * Daft’s derive macro does not attempt to diff enums with different variants.
443 In practice, we’ve found that diffing enums across different variants is less
444 useful than it first appears.
445
446 * Daft has the notion of a [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) type, which represents an atomic unit.
447 (For example, the [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html) implementation for `i32` is a [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html).)
448 [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html)s are also used for enums, as well as in any other place where lazy
449 diffing is desired.
450
451 * Diffus has a `Same` trait, which is like `Eq` except it’s also implemented
452 for floats. Daft doesn’t have the `Same` trait, and its core
453 functionality forgoes the need for `Eq` entirely.
454
455 For a primitive scalar like `f64`, you’ll get a `Leaf` struct which you can
456 compare with whatever notion of equality you want.
457
458 * Daft uses a [generic associated type (GAT)][GAT] so that the `Diffable`
459 trait no longer needs a lifetime parameter. This leads to simpler usage.
460 (Diffus was written before GATs were available in stable Rust.)
461
462 * Daft uses fewer types in general. For example, diffus wraps its return values
463 in an outer `Edit` type, but daft does not.
464
465 * Daft is no-std-compatible, while diffus requires std.
466
467 [`BTreeMap`]: https://doc.rust-lang.org/nightly/alloc/collections/btree/map/struct.BTreeMap.html
468 [`HashMap`]: https://doc.rust-lang.org/nightly/std/collections/hash/map/struct.HashMap.html
469 [`BTreeSet`]: https://doc.rust-lang.org/nightly/alloc/collections/btree/set/struct.BTreeSet.html
470 [`HashSet`]: https://doc.rust-lang.org/nightly/std/collections/hash/set/struct.HashSet.html
471 [GAT]: https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html
472 <!-- cargo-sync-rdme ]] -->
473
474 ## License
475
476 This project is available under the terms of either the [Apache 2.0 license](LICENSE-APACHE) or the [MIT
477 license](LICENSE-MIT).