99//! needs to read-after-write from a file, then it would be added to this
1010//! abstraction.
1111
12+ use std:: cmp:: max;
1213use std:: fs;
1314use std:: io;
1415use std:: path:: { Path , PathBuf } ;
1516use std:: string:: ToString ;
1617use std:: sync:: mpsc:: Sender ;
18+ use std:: thread:: available_parallelism;
19+ use threadpool:: ThreadPool ;
1720
1821pub ( crate ) trait PathError {
1922 fn new < S , P : AsRef < Path > > ( e : S , path : P ) -> Self
@@ -24,11 +27,21 @@ pub(crate) trait PathError {
2427pub ( crate ) struct DocFS {
2528 sync_only : bool ,
2629 errors : Option < Sender < String > > ,
30+ pool : ThreadPool ,
2731}
2832
2933impl DocFS {
3034 pub ( crate ) fn new ( errors : Sender < String > ) -> DocFS {
31- DocFS { sync_only : false , errors : Some ( errors) }
35+ const MINIMUM_NB_THREADS : usize = 2 ;
36+ DocFS {
37+ sync_only : false ,
38+ errors : Some ( errors) ,
39+ pool : ThreadPool :: new (
40+ available_parallelism ( )
41+ . map ( |nb| max ( nb. get ( ) , MINIMUM_NB_THREADS ) )
42+ . unwrap_or ( MINIMUM_NB_THREADS ) ,
43+ ) ,
44+ }
3245 }
3346
3447 pub ( crate ) fn set_sync_only ( & mut self , sync_only : bool ) {
@@ -54,12 +67,11 @@ impl DocFS {
5467 where
5568 E : PathError ,
5669 {
57- #[ cfg( windows) ]
5870 if !self . sync_only {
5971 // A possible future enhancement after more detailed profiling would
6072 // be to create the file sync so errors are reported eagerly.
6173 let sender = self . errors . clone ( ) . expect ( "can't write after closing" ) ;
62- rayon :: spawn ( move || {
74+ self . pool . execute ( move || {
6375 fs:: write ( & path, contents) . unwrap_or_else ( |e| {
6476 sender. send ( format ! ( "\" {}\" : {}" , path. display( ) , e) ) . unwrap_or_else ( |_| {
6577 panic ! ( "failed to send error on \" {}\" " , path. display( ) )
@@ -70,9 +82,12 @@ impl DocFS {
7082 fs:: write ( & path, contents) . map_err ( |e| E :: new ( e, path) ) ?;
7183 }
7284
73- #[ cfg( not( windows) ) ]
74- fs:: write ( & path, contents) . map_err ( |e| E :: new ( e, path) ) ?;
75-
7685 Ok ( ( ) )
7786 }
7887}
88+
89+ impl Drop for DocFS {
90+ fn drop ( & mut self ) {
91+ self . pool . join ( ) ;
92+ }
93+ }
0 commit comments