datafusion_expr/udwf.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! [`WindowUDF`]: User Defined Window Functions
19
20use arrow::compute::SortOptions;
21use std::cmp::Ordering;
22use std::hash::{Hash, Hasher};
23use std::{
24 any::Any,
25 fmt::{self, Debug, Display, Formatter},
26 sync::Arc,
27};
28
29use arrow::datatypes::{DataType, FieldRef};
30
31use crate::expr::WindowFunction;
32use crate::udf_eq::UdfEq;
33use crate::{
34 function::WindowFunctionSimplification, Expr, PartitionEvaluator, Signature,
35};
36use datafusion_common::{not_impl_err, Result};
37use datafusion_doc::Documentation;
38use datafusion_expr_common::dyn_eq::{DynEq, DynHash};
39use datafusion_functions_window_common::expr::ExpressionArgs;
40use datafusion_functions_window_common::field::WindowUDFFieldArgs;
41use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
42use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
43
44/// Logical representation of a user-defined window function (UDWF).
45///
46/// A Window Function is called via the SQL `OVER` clause:
47///
48/// ```sql
49/// SELECT first_value(col) OVER (PARTITION BY a, b ORDER BY c) FROM foo;
50/// ```
51///
52/// A UDWF is different from a user defined function (UDF) in that it is
53/// stateful across batches.
54///
55/// See the documentation on [`PartitionEvaluator`] for more details
56///
57/// 1. For simple use cases, use [`create_udwf`] (examples in
58/// [`simple_udwf.rs`]).
59///
60/// 2. For advanced use cases, use [`WindowUDFImpl`] which provides full API
61/// access (examples in [`advanced_udwf.rs`]).
62///
63/// # API Note
64/// This is a separate struct from `WindowUDFImpl` to maintain backwards
65/// compatibility with the older API.
66///
67/// [`PartitionEvaluator`]: crate::PartitionEvaluator
68/// [`create_udwf`]: crate::expr_fn::create_udwf
69/// [`simple_udwf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/simple_udwf.rs
70/// [`advanced_udwf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/advanced_udwf.rs
71#[derive(Debug, Clone, PartialOrd)]
72pub struct WindowUDF {
73 inner: Arc<dyn WindowUDFImpl>,
74}
75
76/// Defines how the WindowUDF is shown to users
77impl Display for WindowUDF {
78 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
79 write!(f, "{}", self.name())
80 }
81}
82
83impl PartialEq for WindowUDF {
84 fn eq(&self, other: &Self) -> bool {
85 self.inner.dyn_eq(other.inner.as_any())
86 }
87}
88
89impl Eq for WindowUDF {}
90
91impl Hash for WindowUDF {
92 fn hash<H: Hasher>(&self, state: &mut H) {
93 self.inner.dyn_hash(state)
94 }
95}
96
97impl WindowUDF {
98 /// Create a new `WindowUDF` from a `[WindowUDFImpl]` trait object
99 ///
100 /// Note this is the same as using the `From` impl (`WindowUDF::from`)
101 pub fn new_from_impl<F>(fun: F) -> WindowUDF
102 where
103 F: WindowUDFImpl + 'static,
104 {
105 Self::new_from_shared_impl(Arc::new(fun))
106 }
107
108 /// Create a new `WindowUDF` from a `[WindowUDFImpl]` trait object
109 pub fn new_from_shared_impl(fun: Arc<dyn WindowUDFImpl>) -> WindowUDF {
110 Self { inner: fun }
111 }
112
113 /// Return the underlying [`WindowUDFImpl`] trait object for this function
114 pub fn inner(&self) -> &Arc<dyn WindowUDFImpl> {
115 &self.inner
116 }
117
118 /// Adds additional names that can be used to invoke this function, in
119 /// addition to `name`
120 ///
121 /// If you implement [`WindowUDFImpl`] directly you should return aliases directly.
122 pub fn with_aliases(self, aliases: impl IntoIterator<Item = &'static str>) -> Self {
123 Self::new_from_impl(AliasedWindowUDFImpl::new(Arc::clone(&self.inner), aliases))
124 }
125
126 /// creates a [`Expr`] that calls the window function with default
127 /// values for `order_by`, `partition_by`, `window_frame`.
128 ///
129 /// See [`ExprFunctionExt`] for details on setting these values.
130 ///
131 /// This utility allows using a user defined window function without
132 /// requiring access to the registry, such as with the DataFrame API.
133 ///
134 /// [`ExprFunctionExt`]: crate::expr_fn::ExprFunctionExt
135 pub fn call(&self, args: Vec<Expr>) -> Expr {
136 let fun = crate::WindowFunctionDefinition::WindowUDF(Arc::new(self.clone()));
137
138 Expr::from(WindowFunction::new(fun, args))
139 }
140
141 /// Returns this function's name
142 ///
143 /// See [`WindowUDFImpl::name`] for more details.
144 pub fn name(&self) -> &str {
145 self.inner.name()
146 }
147
148 /// Returns the aliases for this function.
149 pub fn aliases(&self) -> &[String] {
150 self.inner.aliases()
151 }
152
153 /// Returns this function's signature (what input types are accepted)
154 ///
155 /// See [`WindowUDFImpl::signature`] for more details.
156 pub fn signature(&self) -> &Signature {
157 self.inner.signature()
158 }
159
160 /// Do the function rewrite
161 ///
162 /// See [`WindowUDFImpl::simplify`] for more details.
163 pub fn simplify(&self) -> Option<WindowFunctionSimplification> {
164 self.inner.simplify()
165 }
166
167 /// Expressions that are passed to the [`PartitionEvaluator`].
168 ///
169 /// See [`WindowUDFImpl::expressions`] for more details.
170 pub fn expressions(&self, expr_args: ExpressionArgs) -> Vec<Arc<dyn PhysicalExpr>> {
171 self.inner.expressions(expr_args)
172 }
173 /// Return a `PartitionEvaluator` for evaluating this window function
174 pub fn partition_evaluator_factory(
175 &self,
176 partition_evaluator_args: PartitionEvaluatorArgs,
177 ) -> Result<Box<dyn PartitionEvaluator>> {
178 self.inner.partition_evaluator(partition_evaluator_args)
179 }
180
181 /// Returns the field of the final result of evaluating this window function.
182 ///
183 /// See [`WindowUDFImpl::field`] for more details.
184 pub fn field(&self, field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
185 self.inner.field(field_args)
186 }
187
188 /// Returns custom result ordering introduced by this window function
189 /// which is used to update ordering equivalences.
190 ///
191 /// See [`WindowUDFImpl::sort_options`] for more details.
192 pub fn sort_options(&self) -> Option<SortOptions> {
193 self.inner.sort_options()
194 }
195
196 /// See [`WindowUDFImpl::coerce_types`] for more details.
197 pub fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
198 self.inner.coerce_types(arg_types)
199 }
200
201 /// Returns the reversed user-defined window function when the
202 /// order of evaluation is reversed.
203 ///
204 /// See [`WindowUDFImpl::reverse_expr`] for more details.
205 pub fn reverse_expr(&self) -> ReversedUDWF {
206 self.inner.reverse_expr()
207 }
208
209 /// Returns the documentation for this Window UDF.
210 ///
211 /// Documentation can be accessed programmatically as well as
212 /// generating publicly facing documentation.
213 pub fn documentation(&self) -> Option<&Documentation> {
214 self.inner.documentation()
215 }
216}
217
218impl<F> From<F> for WindowUDF
219where
220 F: WindowUDFImpl + Send + Sync + 'static,
221{
222 fn from(fun: F) -> Self {
223 Self::new_from_impl(fun)
224 }
225}
226
227/// Trait for implementing [`WindowUDF`].
228///
229/// This trait exposes the full API for implementing user defined window functions and
230/// can be used to implement any function.
231///
232/// While the trait depends on [`DynEq`] and [`DynHash`] traits, these should not be
233/// implemented directly. Instead, implement [`Eq`] and [`Hash`] and leverage the
234/// blanket implementations of [`DynEq`] and [`DynHash`].
235///
236/// See [`advanced_udwf.rs`] for a full example with complete implementation and
237/// [`WindowUDF`] for other available options.
238///
239///
240/// [`advanced_udwf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/advanced_udwf.rs
241/// # Basic Example
242/// ```
243/// # use std::any::Any;
244/// # use std::sync::LazyLock;
245/// # use arrow::datatypes::{DataType, Field, FieldRef};
246/// # use datafusion_common::{DataFusionError, plan_err, Result};
247/// # use datafusion_expr::{col, Signature, Volatility, PartitionEvaluator, WindowFrame, ExprFunctionExt, Documentation};
248/// # use datafusion_expr::{WindowUDFImpl, WindowUDF};
249/// # use datafusion_functions_window_common::field::WindowUDFFieldArgs;
250/// # use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
251/// # use datafusion_expr::window_doc_sections::DOC_SECTION_ANALYTICAL;
252///
253/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
254/// struct SmoothIt {
255/// signature: Signature,
256/// }
257///
258/// impl SmoothIt {
259/// fn new() -> Self {
260/// Self {
261/// signature: Signature::uniform(1, vec![DataType::Int32], Volatility::Immutable),
262/// }
263/// }
264/// }
265///
266/// static DOCUMENTATION: LazyLock<Documentation> = LazyLock::new(|| {
267/// Documentation::builder(DOC_SECTION_ANALYTICAL, "smooths the windows", "smooth_it(2)")
268/// .with_argument("arg1", "The int32 number to smooth by")
269/// .build()
270/// });
271///
272/// fn get_doc() -> &'static Documentation {
273/// &DOCUMENTATION
274/// }
275///
276/// /// Implement the WindowUDFImpl trait for SmoothIt
277/// impl WindowUDFImpl for SmoothIt {
278/// fn as_any(&self) -> &dyn Any { self }
279/// fn name(&self) -> &str { "smooth_it" }
280/// fn signature(&self) -> &Signature { &self.signature }
281/// // The actual implementation would smooth the window
282/// fn partition_evaluator(
283/// &self,
284/// _partition_evaluator_args: PartitionEvaluatorArgs,
285/// ) -> Result<Box<dyn PartitionEvaluator>> {
286/// unimplemented!()
287/// }
288/// fn field(&self, field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
289/// if let Some(DataType::Int32) = field_args.get_input_field(0).map(|f| f.data_type().clone()) {
290/// Ok(Field::new(field_args.name(), DataType::Int32, false).into())
291/// } else {
292/// plan_err!("smooth_it only accepts Int32 arguments")
293/// }
294/// }
295/// fn documentation(&self) -> Option<&Documentation> {
296/// Some(get_doc())
297/// }
298/// }
299///
300/// // Create a new WindowUDF from the implementation
301/// let smooth_it = WindowUDF::from(SmoothIt::new());
302///
303/// // Call the function `add_one(col)`
304/// // smooth_it(speed) OVER (PARTITION BY car ORDER BY time ASC)
305/// let expr = smooth_it.call(vec![col("speed")])
306/// .partition_by(vec![col("car")])
307/// .order_by(vec![col("time").sort(true, true)])
308/// .window_frame(WindowFrame::new(None))
309/// .build()
310/// .unwrap();
311/// ```
312pub trait WindowUDFImpl: Debug + DynEq + DynHash + Send + Sync {
313 /// Returns this object as an [`Any`] trait object
314 fn as_any(&self) -> &dyn Any;
315
316 /// Returns this function's name
317 fn name(&self) -> &str;
318
319 /// Returns any aliases (alternate names) for this function.
320 ///
321 /// Note: `aliases` should only include names other than [`Self::name`].
322 /// Defaults to `[]` (no aliases)
323 fn aliases(&self) -> &[String] {
324 &[]
325 }
326
327 /// Returns the function's [`Signature`] for information about what input
328 /// types are accepted and the function's Volatility.
329 fn signature(&self) -> &Signature;
330
331 /// Returns the expressions that are passed to the [`PartitionEvaluator`].
332 fn expressions(&self, expr_args: ExpressionArgs) -> Vec<Arc<dyn PhysicalExpr>> {
333 expr_args.input_exprs().into()
334 }
335
336 /// Invoke the function, returning the [`PartitionEvaluator`] instance
337 fn partition_evaluator(
338 &self,
339 partition_evaluator_args: PartitionEvaluatorArgs,
340 ) -> Result<Box<dyn PartitionEvaluator>>;
341
342 /// Optionally apply per-UDWF simplification / rewrite rules.
343 ///
344 /// This can be used to apply function specific simplification rules during
345 /// optimization. The default implementation does nothing.
346 ///
347 /// Note that DataFusion handles simplifying arguments and "constant
348 /// folding" (replacing a function call with constant arguments such as
349 /// `my_add(1,2) --> 3` ). Thus, there is no need to implement such
350 /// optimizations manually for specific UDFs.
351 ///
352 /// Example:
353 /// [`advanced_udwf.rs`]: <https://github.com/apache/arrow-datafusion/blob/main/datafusion-examples/examples/advanced_udwf.rs>
354 ///
355 /// # Returns
356 /// [None] if simplify is not defined or,
357 ///
358 /// Or, a closure with two arguments:
359 /// * 'window_function': [crate::expr::WindowFunction] for which simplified has been invoked
360 /// * 'info': [crate::simplify::SimplifyInfo]
361 fn simplify(&self) -> Option<WindowFunctionSimplification> {
362 None
363 }
364
365 /// The [`FieldRef`] of the final result of evaluating this window function.
366 ///
367 /// Call `field_args.name()` to get the fully qualified name for defining
368 /// the [`FieldRef`]. For a complete example see the implementation in the
369 /// [Basic Example](WindowUDFImpl#basic-example) section.
370 fn field(&self, field_args: WindowUDFFieldArgs) -> Result<FieldRef>;
371
372 /// Allows the window UDF to define a custom result ordering.
373 ///
374 /// By default, a window UDF doesn't introduce an ordering.
375 /// But when specified by a window UDF this is used to update
376 /// ordering equivalences.
377 fn sort_options(&self) -> Option<SortOptions> {
378 None
379 }
380
381 /// Coerce arguments of a function call to types that the function can evaluate.
382 ///
383 /// This function is only called if [`WindowUDFImpl::signature`] returns [`crate::TypeSignature::UserDefined`]. Most
384 /// UDWFs should return one of the other variants of `TypeSignature` which handle common
385 /// cases
386 ///
387 /// See the [type coercion module](crate::type_coercion)
388 /// documentation for more details on type coercion
389 ///
390 /// For example, if your function requires a floating point arguments, but the user calls
391 /// it like `my_func(1::int)` (aka with `1` as an integer), coerce_types could return `[DataType::Float64]`
392 /// to ensure the argument was cast to `1::double`
393 ///
394 /// # Parameters
395 /// * `arg_types`: The argument types of the arguments this function with
396 ///
397 /// # Return value
398 /// A Vec the same length as `arg_types`. DataFusion will `CAST` the function call
399 /// arguments to these specific types.
400 fn coerce_types(&self, _arg_types: &[DataType]) -> Result<Vec<DataType>> {
401 not_impl_err!("Function {} does not implement coerce_types", self.name())
402 }
403
404 /// Allows customizing the behavior of the user-defined window
405 /// function when it is evaluated in reverse order.
406 fn reverse_expr(&self) -> ReversedUDWF {
407 ReversedUDWF::NotSupported
408 }
409
410 /// Returns the documentation for this Window UDF.
411 ///
412 /// Documentation can be accessed programmatically as well as
413 /// generating publicly facing documentation.
414 fn documentation(&self) -> Option<&Documentation> {
415 None
416 }
417}
418
419pub enum ReversedUDWF {
420 /// The result of evaluating the user-defined window function
421 /// remains identical when reversed.
422 Identical,
423 /// A window function which does not support evaluating the result
424 /// in reverse order.
425 NotSupported,
426 /// Customize the user-defined window function for evaluating the
427 /// result in reverse order.
428 Reversed(Arc<WindowUDF>),
429}
430
431impl PartialEq for dyn WindowUDFImpl {
432 fn eq(&self, other: &Self) -> bool {
433 self.dyn_eq(other.as_any())
434 }
435}
436
437// TODO (https://github.com/apache/datafusion/issues/17064) PartialOrd is not consistent with PartialEq for `dyn WindowUDFImpl` and it should be
438impl PartialOrd for dyn WindowUDFImpl {
439 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
440 match self.name().partial_cmp(other.name()) {
441 Some(Ordering::Equal) => self.signature().partial_cmp(other.signature()),
442 cmp => cmp,
443 }
444 }
445}
446
447/// WindowUDF that adds an alias to the underlying function. It is better to
448/// implement [`WindowUDFImpl`], which supports aliases, directly if possible.
449#[derive(Debug, PartialEq, Eq, Hash)]
450struct AliasedWindowUDFImpl {
451 inner: UdfEq<Arc<dyn WindowUDFImpl>>,
452 aliases: Vec<String>,
453}
454
455impl AliasedWindowUDFImpl {
456 pub fn new(
457 inner: Arc<dyn WindowUDFImpl>,
458 new_aliases: impl IntoIterator<Item = &'static str>,
459 ) -> Self {
460 let mut aliases = inner.aliases().to_vec();
461 aliases.extend(new_aliases.into_iter().map(|s| s.to_string()));
462
463 Self {
464 inner: inner.into(),
465 aliases,
466 }
467 }
468}
469
470#[warn(clippy::missing_trait_methods)] // Delegates, so it should implement every single trait method
471impl WindowUDFImpl for AliasedWindowUDFImpl {
472 fn as_any(&self) -> &dyn Any {
473 self
474 }
475
476 fn name(&self) -> &str {
477 self.inner.name()
478 }
479
480 fn signature(&self) -> &Signature {
481 self.inner.signature()
482 }
483
484 fn expressions(&self, expr_args: ExpressionArgs) -> Vec<Arc<dyn PhysicalExpr>> {
485 expr_args
486 .input_exprs()
487 .first()
488 .map_or(vec![], |expr| vec![Arc::clone(expr)])
489 }
490
491 fn partition_evaluator(
492 &self,
493 partition_evaluator_args: PartitionEvaluatorArgs,
494 ) -> Result<Box<dyn PartitionEvaluator>> {
495 self.inner.partition_evaluator(partition_evaluator_args)
496 }
497
498 fn aliases(&self) -> &[String] {
499 &self.aliases
500 }
501
502 fn simplify(&self) -> Option<WindowFunctionSimplification> {
503 self.inner.simplify()
504 }
505
506 fn field(&self, field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
507 self.inner.field(field_args)
508 }
509
510 fn sort_options(&self) -> Option<SortOptions> {
511 self.inner.sort_options()
512 }
513
514 fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
515 self.inner.coerce_types(arg_types)
516 }
517
518 fn reverse_expr(&self) -> ReversedUDWF {
519 self.inner.reverse_expr()
520 }
521
522 fn documentation(&self) -> Option<&Documentation> {
523 self.inner.documentation()
524 }
525}
526
527// Window UDF doc sections for use in public documentation
528pub mod window_doc_sections {
529 use datafusion_doc::DocSection;
530
531 pub fn doc_sections() -> Vec<DocSection> {
532 vec![
533 DOC_SECTION_AGGREGATE,
534 DOC_SECTION_RANKING,
535 DOC_SECTION_ANALYTICAL,
536 ]
537 }
538
539 pub const DOC_SECTION_AGGREGATE: DocSection = DocSection {
540 include: true,
541 label: "Aggregate Functions",
542 description: Some("All aggregate functions can be used as window functions."),
543 };
544
545 pub const DOC_SECTION_RANKING: DocSection = DocSection {
546 include: true,
547 label: "Ranking Functions",
548 description: None,
549 };
550
551 pub const DOC_SECTION_ANALYTICAL: DocSection = DocSection {
552 include: true,
553 label: "Analytical Functions",
554 description: None,
555 };
556}
557
558#[cfg(test)]
559mod test {
560 use crate::{PartitionEvaluator, WindowUDF, WindowUDFImpl};
561 use arrow::datatypes::{DataType, FieldRef};
562 use datafusion_common::Result;
563 use datafusion_expr_common::signature::{Signature, Volatility};
564 use datafusion_functions_window_common::field::WindowUDFFieldArgs;
565 use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
566 use std::any::Any;
567 use std::cmp::Ordering;
568 use std::hash::{DefaultHasher, Hash, Hasher};
569
570 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
571 struct AWindowUDF {
572 signature: Signature,
573 }
574
575 impl AWindowUDF {
576 fn new() -> Self {
577 Self {
578 signature: Signature::uniform(
579 1,
580 vec![DataType::Int32],
581 Volatility::Immutable,
582 ),
583 }
584 }
585 }
586
587 /// Implement the WindowUDFImpl trait for AddOne
588 impl WindowUDFImpl for AWindowUDF {
589 fn as_any(&self) -> &dyn Any {
590 self
591 }
592 fn name(&self) -> &str {
593 "a"
594 }
595 fn signature(&self) -> &Signature {
596 &self.signature
597 }
598 fn partition_evaluator(
599 &self,
600 _partition_evaluator_args: PartitionEvaluatorArgs,
601 ) -> Result<Box<dyn PartitionEvaluator>> {
602 unimplemented!()
603 }
604 fn field(&self, _field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
605 unimplemented!()
606 }
607 }
608
609 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
610 struct BWindowUDF {
611 signature: Signature,
612 }
613
614 impl BWindowUDF {
615 fn new() -> Self {
616 Self {
617 signature: Signature::uniform(
618 1,
619 vec![DataType::Int32],
620 Volatility::Immutable,
621 ),
622 }
623 }
624 }
625
626 /// Implement the WindowUDFImpl trait for AddOne
627 impl WindowUDFImpl for BWindowUDF {
628 fn as_any(&self) -> &dyn Any {
629 self
630 }
631 fn name(&self) -> &str {
632 "b"
633 }
634 fn signature(&self) -> &Signature {
635 &self.signature
636 }
637 fn partition_evaluator(
638 &self,
639 _partition_evaluator_args: PartitionEvaluatorArgs,
640 ) -> Result<Box<dyn PartitionEvaluator>> {
641 unimplemented!()
642 }
643 fn field(&self, _field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
644 unimplemented!()
645 }
646 }
647
648 #[test]
649 fn test_partial_eq() {
650 let a1 = WindowUDF::from(AWindowUDF::new());
651 let a2 = WindowUDF::from(AWindowUDF::new());
652 let eq = a1 == a2;
653 assert!(eq);
654 assert_eq!(a1, a2);
655 assert_eq!(hash(a1), hash(a2));
656 }
657
658 #[test]
659 fn test_partial_ord() {
660 let a1 = WindowUDF::from(AWindowUDF::new());
661 let a2 = WindowUDF::from(AWindowUDF::new());
662 assert_eq!(a1.partial_cmp(&a2), Some(Ordering::Equal));
663
664 let b1 = WindowUDF::from(BWindowUDF::new());
665 assert!(a1 < b1);
666 assert!(!(a1 == b1));
667 }
668
669 fn hash<T: Hash>(value: T) -> u64 {
670 let hasher = &mut DefaultHasher::new();
671 value.hash(hasher);
672 hasher.finish()
673 }
674}