1212// See the License for the specific language governing permissions and
1313// limitations under the License.
1414
15- use std:: sync:: Arc ;
1615use std:: sync:: mpsc;
1716use std:: thread:: JoinHandle ;
1817
19- use arc_swap:: ArcSwapOption ;
2018use logforth_core:: Error ;
2119
2220use crate :: Overflow ;
2321use crate :: Task ;
2422use crate :: channel:: Sender ;
2523
2624#[ derive( Debug ) ]
27- pub ( crate ) struct AsyncState ( ArcSwapOption < State > ) ;
25+ pub ( crate ) struct AsyncState ( Option < State > ) ;
2826
2927#[ derive( Debug ) ]
3028struct State {
@@ -35,20 +33,22 @@ struct State {
3533
3634impl AsyncState {
3735 pub ( crate ) fn new ( overflow : Overflow , sender : Sender < Task > , handle : JoinHandle < ( ) > ) -> Self {
38- Self ( ArcSwapOption :: from ( Some ( Arc :: new ( State {
36+ Self ( Some ( State {
3937 overflow,
4038 sender,
4139 handle,
42- } ) ) ) )
40+ } ) )
4341 }
4442
4543 pub ( crate ) fn send_task ( & self , task : Task ) -> Result < ( ) , Error > {
46- let state = self . 0 . load ( ) ;
4744 // SAFETY: state is always Some before dropped.
48- let state = state. as_ref ( ) . unwrap ( ) ;
49- let sender = & state. sender ;
45+ let State {
46+ overflow,
47+ sender,
48+ handle : _,
49+ } = self . 0 . as_ref ( ) . unwrap ( ) ;
5050
51- match state . overflow {
51+ match overflow {
5252 Overflow :: Block => sender. send ( task) . map_err ( |err| {
5353 Error :: new ( match err. 0 {
5454 Task :: Log { .. } => "failed to send log task to async appender" ,
@@ -65,27 +65,21 @@ impl AsyncState {
6565 } ,
6666 }
6767 }
68-
69- pub ( crate ) fn destroy ( & self ) {
70- if let Some ( state) = self . 0 . swap ( None ) {
71- // SAFETY: state has always one strong count before swapped.
72- let State {
73- overflow : _,
74- sender,
75- handle,
76- } = Arc :: into_inner ( state) . unwrap ( ) ;
77-
78- // drop our sender, threads will break the loop after receiving and processing
79- drop ( sender) ;
80-
81- // wait for the thread to finish
82- handle. join ( ) . expect ( "failed to join async appender thread" ) ;
83- }
84- }
8568}
8669
8770impl Drop for AsyncState {
8871 fn drop ( & mut self ) {
89- self . destroy ( ) ;
72+ // SAFETY: state is always Some before dropped.
73+ let State {
74+ overflow : _,
75+ sender,
76+ handle,
77+ } = self . 0 . take ( ) . unwrap ( ) ;
78+
79+ // drop our sender, threads will break the loop after receiving and processing
80+ drop ( sender) ;
81+
82+ // wait for the thread to finish
83+ handle. join ( ) . expect ( "failed to join async appender thread" ) ;
9084 }
9185}
0 commit comments