water_http 3.4.2-beta.4

fast web http framework that support http 1 and http 2 with very easy use
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
#![allow(async_fn_in_trait)]

use std::ffi::OsStr;
use std::fmt::Display;
use std::future::Future;

use std::io:: SeekFrom;

#[cfg(not(feature = "use_only_http1"))]
use bytes::Bytes;
// use bytes::{BufMut, BytesMut};
#[cfg(not(feature = "use_only_http1"))]
use h2::SendStream;
#[cfg(not(feature = "use_only_http1"))]
use http::{HeaderName, HeaderValue, Response as H2Response, response::Builder as H2ResponseBuilder};
use integer_to_bytes::HumanInt;
use serde::de::Error;
use serde::Serialize;
use tokio::io::{ AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use crate::http::{FileRSender, ResponseData};
use crate::http::status_code::{HttpStatusCode as StatusCode, HttpStatusCode};
use crate::server::connection::handle_responding;
use crate::server::errors::{ServerError, WaterErrors};
use crate::server::{get_server_config, Http1Context, WRITING_FILES_BUF_LEN};
#[cfg(feature = "use_io_uring")]
use crate::server::HttpStream;
#[cfg(not(feature = "use_only_http1"))]
use crate::server::Http2Context;




/// for providing easy access and use for sends methods
/// and providing infra structure for http protocols handling
pub  trait HttpSenderTrait {
   /// for setting http status code for response
   fn send_status_code(&mut self,http_status: StatusCode);

    /// to send partial response
   fn send_data_partial(&mut self,data:ResponseData);

    /// send final response or full response
   fn send_data_as_final_response(&mut self,data:ResponseData)->impl Future<Output=Result<(),()>>;

    /// for setting header key value to response holder

   fn set_header<K:Display, V:Display>(&mut self,key:K,value:V);
    /// for setting header with the highest efficiency
   fn set_header_ef<'h,K:Into<HeaderBytes<'h>>, V:Into<HeaderBytes<'h>>>(&mut self,key:K,value:V);

    fn send_json<JSON:Serialize>(&mut self,value:&JSON)->
    impl Future<Output=serde_json::Result<()>>;

    /// to send [&str] as response to client
   fn send_str(&mut self,data:&'static str)
    -> impl Future<Output=Result<(),()>>;


    #[cfg(not(feature = "use_io_uring"))]
   /// to send files as response to client ,
   ///and it takes [FileRSender]
   fn send_file(&mut self,path:FileRSender<'_>)->
                                                     impl Future<
                                                         Output = SendingFileResults> + Send;


    /// for flushing response stream into route connection
    async fn flush(&mut self)->Result<(),()>;

    #[cfg(not(feature = "use_tokio_send"))]
    /// for writing custom bytes to the stream
    fn write_custom_bytes(&mut self,bytes:&[u8])->
     impl Future<
     Output = Result<(),WaterErrors<'_>>> ;
    #[cfg(feature = "use_tokio_send")]
    /// for writing custom bytes to the stream
    fn write_custom_bytes(&mut self,bytes:&[u8])->
     impl Future<
     Output = Result<(),WaterErrors<'_>>> + Send;

    fn extend_write_buffer(&mut self,bytes:&[u8]);
}



#[cfg(not(feature = "use_only_http1"))]

/// Http2 Sender for providing [HttpSenderTrait] implementations for http context that using http 2 protocol to serve connections
#[doc(hidden)]
pub struct  Http2Sender<'a,'b> {
    context:&'a mut Http2Context<'b>,
    send_stream: Option<SendStream<Bytes>>,
    response_builder:Option<H2ResponseBuilder>
}
#[cfg(not(feature = "use_only_http1"))]

impl <'a,'b> Http2Sender<'a,'b>{
    pub (crate) fn new(
        context:&'a mut Http2Context<'b>,
    )->Http2Sender<'a,'b> {
        Http2Sender {
            context,
            send_stream: None,
            response_builder:None
        }
    }

    fn handle_content_type_while_sending_file(&mut self,file_content_type:&Option<&str>,file_name:&OsStr,content_disposition:Option<&String>){
        match file_content_type {
            None => {
                self.set_header_ef("Content-Type","Application/octet-stream");
                self.set_header_ef("Content-Disposition",format!("attachment; filename=\"{}\"",file_name.to_str().unwrap_or("")));
            }
            Some(content_type) => {
                self.set_header("Content-Type",content_type);
                if let Some(cd) = content_disposition {
                    self.set_header_ef("Content-Disposition",format!("{cd}; filename=\"{}\"",file_name.to_str().unwrap_or("")));
                }
            }
        }
    }


    async fn write_headers_and_get_ready(&mut self) -> Result<(), ()> {
        if self.send_stream.is_none() {
            if let Some(response_builder) = self.response_builder.take() {
                if let Ok( bb ) = response_builder.body(()) {
                    let   sender = &mut self.context.request_batch.1;
                    if let Ok(stream) = sender.send_response(bb,false) {
                        self.send_stream = Some(stream);
                        return Ok(())
                    }
                }
            }
        }else {return  Ok(())}
        return Err(())
    }
}
#[cfg(not(feature = "use_only_http1"))]

impl<'a,'b> HttpSenderTrait for Http2Sender<'a,'b> {
    fn send_status_code(&mut self, http_status: StatusCode) {
        if self.response_builder.is_some() {return;}
        let   response = H2Response::
            builder().
            status(http_status.status.get());
        self.response_builder = Some(response);
    }

    fn extend_write_buffer(&mut self,bytes:&[u8]){
        if let Some(send_stream) = &mut self.send_stream {
            _= send_stream.send_data(Bytes::copy_from_slice(bytes),false);
        }
    }
    fn send_data_partial(&mut self, data: ResponseData) {
        let data = data.as_bytes().to_vec();
        if let Some(ref mut stream) = self.send_stream {
            _=stream.send_data(Bytes::from(data),false);
            return;
        } else if let Some( response_builder) = self.response_builder.take() {
            let   sender = &mut self.context.request_batch.1;
            if let Ok(mut stream) = sender.send_response(response_builder.body(()).unwrap(),false) {
                _=stream.send_data(Bytes::from(data),false);
            }
        }
    }

    async fn send_data_as_final_response(&mut self, data: ResponseData<'_>)->Result<(),()> {

        return if let Some(ref mut stream) = self.send_stream {
            let data = data.as_bytes().to_vec();
            _=stream.send_data(Bytes::from(data),true);
             Ok(())
        } else if let Some( response_builder) = self.response_builder.take() {
            let data = data.as_bytes().to_vec();
            let   sender = &mut self.context.request_batch.1;
            if let Ok( bb ) = response_builder.body(()) {
                if let Ok(mut stream) = sender.send_response(bb,false) {
                    _=stream.send_data(Bytes::from(data),true);
                    return Ok(())
                }
            }

             Err(())
        } else {
            self.send_status_code(StatusCode::OK);
            if let Some( response_builder) = self.response_builder.take() {
                let data = data.as_bytes().to_vec();
                let   sender = &mut self.context.request_batch.1;
                if let Ok( bb ) = response_builder.body(()) {
                    if let Ok(mut stream) = sender.send_response(bb,false) {
                        _=stream.send_data(Bytes::from(data),true);
                        return Ok(())
                    }
                }
            }
             Err(())
        }
    }

    fn set_header<K: Display, V: Display>(&mut self, key: K, value: V) {
        let is_status_written = self.response_builder.is_some();
        if !is_status_written {return;}
        let res = self.response_builder.as_mut();
        if let Some(res) = res {
            if let Some(headers ) = res.headers_mut() {
                headers.insert(HeaderName::from_bytes(
                    format!("{key}").as_bytes()
                ).unwrap(),HeaderValue::from_bytes(
                    format!("{value}").as_bytes()
                ).unwrap());
            }
        } else {
            self.send_status_code(StatusCode::OK);
            self.set_header(key,value);
        }
    }

    fn set_header_ef<'h,K: Into<HeaderBytes<'h>>, V: Into<HeaderBytes<'h>>>(&mut self, key: K, value: V) {
        let is_status_written = self.response_builder.is_some();
        if !is_status_written {return;}
        let res = self.response_builder.as_mut();
        if let Some(res) = res {

            let mut ito = itoa::Buffer::new();


            let key =key.into();
            let value =value.into();
            if let Some(headers ) = res.headers_mut() {
                headers.insert(HeaderName::from_bytes(
                   if let HeaderBytes::Usize(n) = key {
                       ito.format(n).as_bytes()
                    } else { key.as_bytes() }
                ).unwrap(),HeaderValue::from_bytes(
                    if let HeaderBytes::Usize(n) = value {
                        ito.format(n).as_bytes()
                    } else { value.as_bytes() }
                ).unwrap());
            }
        } else {
            self.send_status_code(StatusCode::OK);
            self.set_header_ef(key,value);
        }
    }

    async fn send_json<JSON: Serialize>(&mut self, value: &JSON)->serde_json::Result<()>{
        self.set_header_ef("content-type","application/json");
        return match serde_json::to_vec(&value) {
            Ok(data) => {
                _=self.send_data_as_final_response(ResponseData::Slice(
                    data.as_ref()
                )).await;
                Ok(())
            }
            Err(e) => {  Err(e)}
        }

    }

    async fn send_str(&mut self, data: &'static str)->Result<(),()> {
        self.send_data_as_final_response(ResponseData::Str(data)).await
    }

    #[cfg(not(feature = "use_io_uring"))]
    async fn send_file(&mut self,mut pc: FileRSender<'_>)-> SendingFileResults {


        #[cfg(not(feature = "use_io_uring"))]
        // preparing file
        let mut file = match tokio::fs::File::open(pc.path).await {
            Ok(f) => {f}
            Err(_) => {return SendingFileResults::ErrorWhileOpeningTheFile}
        };

        #[cfg(feature = "use_io_uring")]
            let mut file = match tokio_uring::fs::File::open(pc.path).await {
            Ok(f) => {f}
            Err(_) => {return SendingFileResults::ErrorWhileOpeningTheFile}
        };
        let meta = match file.metadata().await {
            Ok(m) => {m}
            Err(_) => { return SendingFileResults::ErrorWhileOpeningTheFile}
        };
        let  file_size  = meta.len() as usize;
        let file_name = match pc.path.file_name() {
            None => { return SendingFileResults::FileNotFound}
            Some(f) => {f}
        };
        let file_content_type = crate::util::content_type_from_file_path(&pc.path);
        let mut start = 0_usize;
        let mut end = file_size;

        // check if we need to send the whole file or just range of it
        match pc.range {
            None => {
                self.send_status_code(HttpStatusCode::OK);
            }
            Some(ranges) => {
                start = ranges.0.unwrap_or(0);
                end = ranges.1.unwrap_or({
                    (start + pc.buffer_size_for_reading_from_file_and_writing_to_stream)
                        .min(file_size)
                });
                if (end - start)  == file_size {
                    self.send_status_code(HttpStatusCode::OK);
                } else {
                    self.send_status_code(HttpStatusCode::PARTIAL_CONTENT);
                }
            }
        }
        self.handle_content_type_while_sending_file(&file_content_type,file_name,pc.content_disposition.as_ref());
        if end >= file_size { end = file_size;}
        if end < start { end = (start + pc.buffer_size_for_reading_from_file_and_writing_to_stream).min(file_size)}
        if  start == end || start > end || end > file_size {
            return SendingFileResults::RangesNotSatisfied
        }
        let mut to_send = end - start  ;
        if to_send != file_size {
            self.set_header("Content-Range",format!("bytes {start}-{}/{}",{end-1},file_size));
        }
        self.set_header("Content-Length",to_send);
        if file.seek(SeekFrom::Start(start as u64)).await.is_err() {return SendingFileResults::RangesNotSatisfied}
        let mut buffer = Vec::with_capacity(
            WRITING_FILES_BUF_LEN.min(
                to_send
            )
        );

        if self.write_headers_and_get_ready().await.is_err() {
            return SendingFileResults::ErrorWhileSendingBytesToClient;
        }
        while to_send > 0 {
            buffer.clear();
            match file.read_buf(&mut buffer).await {
                Ok(size) => {
                    let index = to_send.min(size);
                    if let Some(ref mut callback) = pc.edit_each_chunk {
                        callback(&mut buffer[..index]);
                    }
                    if self.write_custom_bytes(&buffer[..index]).await.is_err() {
                        return SendingFileResults::ErrorWhileSendingBytesToClient
                    }
                    to_send -= index;
                    continue;
                }
                Err(_) => {
                    return  SendingFileResults::ReadingFileBytesError
                }
            }

        }
        return SendingFileResults::Success
    }





    async fn flush(&mut self) -> Result<(), ()> {
        if self.send_stream.is_none() {
            if let Some(response_builder) = self.response_builder.take() {
                if let Ok( bb ) = response_builder.body(()) {
                    let   sender = &mut self.context.request_batch.1;
                    if let Ok(stream) = sender.send_response(bb,true) {
                        self.send_stream = Some(stream);
                        return Ok(())
                    }
                }
            }
        }
        return Err(())
    }

    async fn write_custom_bytes(&mut self, bytes: &[u8]) -> Result<(), WaterErrors<'_>> {
        if let Some(send_stream) = &mut self.send_stream {
            if let Ok(_) = send_stream.send_data(Bytes::copy_from_slice(bytes),false) {
                return  Ok(())
            }
        }

        Err(
            WaterErrors::Server(
                ServerError::WRITING_TO_STREAM_ERROR
            )
        )
    }
}



/// for sending http response to all supported protocols by the crate
pub  enum HttpSender<'a,'context,const HEADERS_COUNT:usize,const QUERY_COUNT:usize> {
    H1(Http1Sender<'a,'context,HEADERS_COUNT,QUERY_COUNT>),
    #[cfg(not(feature = "use_only_http1"))]
    H2(Http2Sender<'a,'context>),
}

 impl<'a,'context,const HEADERS_COUNT:usize,const QUERY_COUNT:usize> HttpSenderTrait
 for HttpSender<'a,'context,HEADERS_COUNT,QUERY_COUNT>
 {
    fn send_status_code(&mut self, http_status: StatusCode) {
        match self {
            HttpSender::H1(h1) => {
                h1.send_status_code(http_status)
            }
            #[cfg(not(feature = "use_only_http1"))]
            HttpSender::H2(h2) => {
                h2.send_status_code(http_status)
            }
        }
    }

    fn send_data_partial(&mut self, data: ResponseData) {
        match self {
            HttpSender::H1(h1) => {
                h1.send_data_partial(data)
            }
            #[cfg(not(feature = "use_only_http1"))]
            HttpSender::H2(h2) => {
                h2.send_data_partial(data)
            }
        }
    }

   async fn send_data_as_final_response(&mut self, data: ResponseData<'_>)->Result<(),()> {
        match self {
            HttpSender::H1(h1) => {
                h1.send_data_as_final_response(data).await
            }
            #[cfg(not(feature = "use_only_http1"))]
            HttpSender::H2(h2) => {
                h2.send_data_as_final_response(data).await
            }
        }
    }

    fn set_header<K: Display, V: Display>(&mut self, key: K, value: V) {
        match self {
            HttpSender::H1(h1) => {
                h1.set_header(key,value)
            }
            #[cfg(not(feature = "use_only_http1"))]
            HttpSender::H2(h2) => {
                h2.set_header(key,value)
            }
        }
    }

     fn set_header_ef<'h,K: Into<HeaderBytes<'h>>, V: Into<HeaderBytes<'h>>>(&mut self, key: K, value: V) {
            match self {
                HttpSender::H1(h1) => {
                    h1.set_header_ef(key,value)
                }
                #[cfg(not(feature = "use_only_http1"))]
                HttpSender::H2(h2) => {
                    h2.set_header_ef(key,value)
                }
            }
     }

     async fn send_json<JSON: Serialize>(&mut self, value: &JSON)->serde_json::Result<()>{
         match self {
             HttpSender::H1(h1) => {h1.send_json(value).await}
             #[cfg(not(feature = "use_only_http1"))]
             HttpSender::H2(h2) => {h2.send_json(value).await}
         }
     }

     #[inline(always)]
     async fn send_str(&mut self, data: &'static str)->Result<(),()> {
        match self {
            HttpSender::H1(h1) => {
                h1.send_str(data).await
            }
            #[cfg(not(feature = "use_only_http1"))]
            HttpSender::H2(h2) => {
                h2.send_str(data).await
            }
        }
    }

     #[cfg(not(feature = "use_io_uring"))]

    async fn send_file(&mut self, pc: FileRSender<'_>) ->SendingFileResults {
        match self {
            HttpSender::H1(h1) => {h1.send_file(pc).await}
            #[cfg(not(feature = "use_only_http1"))]
            HttpSender::H2(h2) => {h2.send_file(pc).await}
        }
    }

     async fn flush(&mut self) -> Result<(), ()> {
         match self {
             HttpSender::H1(h1) => {h1.flush().await}
             #[cfg(not(feature = "use_only_http1"))]
             HttpSender::H2(h2) => {h2.flush().await}
         }
     }

     async fn write_custom_bytes(&mut self, bytes: &[u8]) -> Result<(), WaterErrors<'_>> {
         match self {
             HttpSender::H1(h1) => {h1.write_custom_bytes(bytes).await}
             #[cfg(not(feature = "use_only_http1"))]
             HttpSender::H2(h2) => {h2.write_custom_bytes(bytes).await}
         }
     }

     fn extend_write_buffer(&mut self, bytes: &[u8]) {
         match self {
             HttpSender::H1(h1) => {h1.extend_write_buffer(bytes)}
             #[cfg(not(feature = "use_only_http1"))]
             HttpSender::H2(h2) => {h2.extend_write_buffer(bytes)}
         }
     }
 }


/// Http2 Sender for providing [HttpSenderTrait] implementations for http context that using http 1 protocol to serve connections

#[doc(hidden)]
pub  struct Http1Sender<'a,'context,const HEADERS_COUNT:usize,const QUERY_COUNT:usize
> {
    pub context:&'a mut Http1Context<'context,HEADERS_COUNT,QUERY_COUNT>,
    is_status_written:bool,
}

impl <'a,'context,const HEADERS_COUNT:usize,const QUERY_COUNT:usize> Http1Sender<'a,'context,
  HEADERS_COUNT,QUERY_COUNT
> {
    pub (crate) fn new(
       context: &'a mut Http1Context<'context,HEADERS_COUNT,QUERY_COUNT>,
    )->Http1Sender<'a,'context,HEADERS_COUNT,QUERY_COUNT>{
        Http1Sender {
            context,
            is_status_written:false,
        }
    }


    pub (crate) async fn write_bytes(&mut self,bytes:&[u8])->Result<(),()>{
        #[cfg(feature = "use_io_uring")]
        {
            match self.context.stream {
                #[cfg(feature = "support_tls")]
                HttpStream::AsyncSecure(_) => {
                    todo!()
                }
                HttpStream::Async(s) => {
                    let bs = water_buffer::helper::BytesSliceWrapper::new(bytes);
                    let (r,_) = s.write_all(bs).await;
                    if r.is_err() {return  Err(())}
                    return  Ok(())
                }
            }
        }
        #[cfg(not(feature = "use_io_uring"))]
        {
            match self.context.stream.write_all(bytes).await {
                Ok(_) => {Ok(())}
                Err(_) => {Err(())}
            }
        }
    }

    fn handle_content_type_while_sending_file(&mut self,file_content_type:&Option<&str>,file_name:&OsStr,content_disposition:Option<&String>){
        match file_content_type {
            None => {
                self.set_header_ef("Content-Type","Application/octet-stream");
                self.set_header_ef("Content-Disposition",format!("attachment; filename=\"{}\"",file_name.to_str().unwrap_or("")));
            }
            Some(content_type) => {
                self.set_header("Content-Type",content_type);
                if let Some(cd) = content_disposition {
                    self.set_header_ef("Content-Disposition",format!("{cd}; filename=\"{}\"",file_name.to_str().unwrap_or("")));
                }
            }
        }
    }
}
impl<'a,'context,const HEADERS_COUNT:usize,const QUERY_COUNT:usize> HttpSenderTrait for
Http1Sender <'a,'context,HEADERS_COUNT,QUERY_COUNT>  {

    #[inline(always)]
    fn extend_write_buffer(&mut self,bytes:&[u8]){
        self.context.response_buffer.extend_from_slice(bytes);
    }
    #[inline(always)]
    fn send_status_code(&mut self, http_status: StatusCode) {
        if self.is_status_written {return;}
        let buf = &mut self.context.response_buffer;
        buf.extend_from_slice(b"HTTP/1.1 ");
        // let mut iota_buffer = itoa::Buffer::new();
        // let num_str = iota_buffer.format(http_status.status.get());
        let v = http_status.status.get();
        #[cfg(not(feature = "use_io_uring"))]
        {
            v.put_into(*buf);
        }
        #[cfg(feature = "use_io_uring")]
        {
            v.put_into(buf) ;
        }
        buf.extend_from_slice(b" ");
        buf.extend_from_slice(http_status.label.as_bytes());
        buf.extend_from_slice(b"\r\n");
        self.is_status_written = true;
    }

    #[inline]
    fn send_data_partial(&mut self, data: ResponseData) {
        let bytes = data.as_bytes();
        self.context.response_buffer.extend_from_slice(b"\r\n");
        self.context.response_buffer.extend_from_slice(bytes);
    }

    #[inline]
    async fn send_data_as_final_response(&mut self, data: ResponseData<'_>) -> Result<(),()> {

        let ref en_configurations = get_server_config().responding_encoding_configurations;

        let data = data.as_bytes();
        let len = data.len();
        if en_configurations.is_not_none() && data.len() >= en_configurations.threshold_for_encoding_response  {
            let accept_encoding = self.context
                .request.headers().get_as_str("Accept-Encoding");
            if let Some(accept_encoding ) = accept_encoding {
                let encoder = en_configurations.encode(
                    accept_encoding.into(),
                    data
                ).await;
                if let Some(encoder )  = encoder {
                    self.set_header_ef("Content-Encoding",encoder.logic);
                    let data = encoder.data;
                    self.context.response_buffer.extend_from_slice(format!("Content-Length: {}\r\n\r\n",data.len()).as_bytes());
                    self.context.response_buffer.extend_from_slice(data.as_ref());
                    return Ok(())
                }
            }

        }
        // let mut buffer = itoa::Buffer::new();
        self.context.response_buffer.extend_from_slice(b"Content-Length: ");
        // self.context.response_buffer.extend_from_slice(buffer.format(data.len()).as_bytes());
        // extend_with_int_human(self.context.response_buffer,data.len());
        #[cfg(feature = "use_io_uring")]
        {
            let  buf = &mut self.context.response_buffer;
            len.put_into(buf);
        }
        #[cfg(not(feature = "use_io_uring"))]
        {
            len.put_into(self.context.response_buffer);
        }
        self.context.response_buffer.extend_from_slice(b"\r\n\r\n");
        self.context.response_buffer.extend_from_slice(data);
        Ok(())
    }

    fn set_header<K:Display, V:Display>(&mut self, key: K, value: V) {
        if !self.is_status_written { self.send_status_code(StatusCode::OK);}
        self.context.response_buffer.extend_from_slice(format!("{key}: {value}\r\n").as_bytes());
    }

    fn set_header_ef<'h,K: Into<HeaderBytes<'h>>, V: Into<HeaderBytes<'h>>>(&mut self, key: K, value: V) {
        if !self.is_status_written { self.send_status_code(StatusCode::OK);}
        let key_bytes = key.into();
        let value_bytes = value.into();

        if let HeaderBytes::Usize(u) = key_bytes {
            // let mut buffer = itoa::Buffer::new();
            // self.context.response_buffer.extend_from_slice(buffer.format(u).as_bytes());
            #[cfg(not(feature = "use_io_uring"))]
            u.put_into(self.context.response_buffer);
            #[cfg(feature = "use_io_uring")]
            {
                u.put_into(&mut self.context.response_buffer);
            }
        } else {
            self.context.response_buffer.extend_from_slice(key_bytes.as_bytes());
        }
        self.context.response_buffer.extend_from_slice(b": ");
        if let HeaderBytes::Usize(v) = value_bytes {
            // let mut bb = itoa::Buffer::new();
            // self.context.response_buffer.extend_from_slice(bb.format(v).as_bytes());
            #[cfg(not(feature = "use_io_uring"))]
            v.put_into(self.context.response_buffer);

            #[cfg(feature = "use_io_uring")]
            v.put_into(&mut self.context.response_buffer);
        } else {
            self.context.response_buffer.extend_from_slice(value_bytes.as_bytes());
        }
        self.context.response_buffer.extend_from_slice(b"\r\n");
    }

    async fn send_json<JSON: Serialize>(&mut self, value: &JSON)->serde_json::Result<()> {
        self.set_header_ef("content-type","application/json");
        match serde_json::to_vec(value) {
            Ok(data) => {
                if self.send_data_as_final_response(ResponseData::Slice(data.as_ref())).await.is_ok() {
                    return Ok(())
                }
                Err(serde_json::Error::custom("fail"))
            }
            Err(e) => {return Err(e)}
        }

    }

    async fn send_str(&mut self,data: &'static str) -> Result<(),()> {
        self.send_status_code(StatusCode::OK);
        self.send_data_as_final_response(ResponseData::Str(data)).await
    }


    #[cfg(not(feature = "use_io_uring"))]
    async fn send_file(&mut self,mut pc: FileRSender<'_>)-> SendingFileResults {


        #[cfg(not(feature = "use_io_uring"))]
            // preparing file
            let mut file = match tokio::fs::File::open(pc.path).await {
            Ok(f) => {f}
            Err(_) => {return SendingFileResults::ErrorWhileOpeningTheFile}
        };

        #[cfg(feature = "use_io_uring")]
            let mut file = match tokio_uring::fs::File::open(pc.path).await {
            Ok(f) => {f}
            Err(_) => {return SendingFileResults::ErrorWhileOpeningTheFile}
        };
        let meta = match file.metadata().await {
            Ok(m) => {m}
            Err(_) => { return SendingFileResults::ErrorWhileOpeningTheFile}
        };
        let  file_size   = meta.len() as usize;

        let file_name = match pc.path.file_name() {
            None => { return SendingFileResults::FileNotFound}
            Some(f) => {f}
        };
        let file_content_type = crate::util::content_type_from_file_path(&pc.path);
        let mut start = 0_usize;
        let mut end = file_size;

        // check if we need to send the whole file or just range of it
        match pc.range {
            None => {
                self.send_status_code(HttpStatusCode::OK);
            }
            Some(ranges) => {
                start = ranges.0.unwrap_or(0);
                end = ranges.1.unwrap_or({
                    (start + pc.buffer_size_for_reading_from_file_and_writing_to_stream)
                        .min(file_size)
                });
                if (end - start)  == file_size {
                    self.send_status_code(HttpStatusCode::OK);
                } else {
                    self.send_status_code(HttpStatusCode::PARTIAL_CONTENT);
                }
            }
        }

        self.handle_content_type_while_sending_file(&file_content_type,file_name,pc.content_disposition.as_ref());


        if end >= file_size { end = file_size;}
        if end < start { end = (start + pc.buffer_size_for_reading_from_file_and_writing_to_stream).min(file_size)}

        if  start == end || start > end || end > file_size {
            return SendingFileResults::RangesNotSatisfied
        }
        let mut to_send = end - start  ;

        if to_send != file_size {
            self.set_header("Content-Range",format!("bytes {start}-{}/{}",{end-1},file_size));
        }

        self.set_header("Content-Length",to_send);
        if file.seek(SeekFrom::Start(start as u64)).await.is_err() {return SendingFileResults::RangesNotSatisfied}
        let mut buffer = Vec::with_capacity(
            WRITING_FILES_BUF_LEN.min(
                to_send
            )
        );
        if self.flush().await.is_err() || self.write_bytes(b"\r\n").await.is_err() { return  SendingFileResults::ErrorWhileSendingBytesToClient}

        while to_send > 0 {
            buffer.clear();
           match file.read_buf(&mut buffer).await {
               Ok(size) => {
                   let index = to_send.min(size);
                   if let Some(ref mut callback) = pc.edit_each_chunk {
                       callback(&mut buffer[..index]);
                   }
                   if self.write_bytes(&buffer[..index]).await.is_err() {
                       return SendingFileResults::ErrorWhileSendingBytesToClient
                   }
                   to_send -= index;
                   continue;
               }
               Err(_) => {
                   return  SendingFileResults::ReadingFileBytesError
               }
           }

        }
        return SendingFileResults::Success
    }


    #[cfg(feature = "use_io_uring")]
    async fn flush(&mut self) -> Result<(),()>{
        if handle_responding(unsafe{self.context.response_buffer.unsafe_clone()},self.context.stream).await.is_err() {
            return Err(())
        }
        Ok(())
    }

    #[cfg(not(feature = "use_io_uring"))]
     async fn flush(&mut self) -> Result<(),()>{
         if handle_responding(self.context.response_buffer,self.context.stream).await.is_err() {
             return Err(())
         }
         Ok(())
    }


    #[cfg(feature = "use_io_uring")]
    async fn write_custom_bytes(&mut self, bytes: &[u8]) -> Result<(), WaterErrors<'_>> {
        self.context.response_buffer.extend_from_slice(bytes);
        if handle_responding(unsafe{self.context.response_buffer.unsafe_clone()},self.context.stream).await.is_err() {
            return Err(WaterErrors::Server(ServerError::WRITING_TO_STREAM_ERROR))
        }
        Ok(())
    }
    #[cfg(not(feature = "use_io_uring"))]
    async fn write_custom_bytes(&mut self, bytes: &[u8]) -> Result<(), WaterErrors<'_>> {
        self.context.response_buffer.extend_from_slice(bytes);
        if handle_responding(self.context.response_buffer,self.context.stream).await.is_err() {
            return Err(WaterErrors::Server(ServerError::WRITING_TO_STREAM_ERROR))
        }
        Ok(())
    }
}



/// defining sending file behavior
#[derive(Debug)]
pub enum SendingFileResults {
    /// if file path is not real file
    FileNotFound,
    /// error while reading file data
    ReadingFileBytesError,
    /// error while opening an existing file
    ErrorWhileOpeningTheFile,
    /// error while sending file data bytes to the client
    ErrorWhileSendingBytesToClient,
    /// when incoming request is not correct
    RangesNotSatisfied,
    /// when sending file successfully to the client
    Success
}

impl SendingFileResults {

    /// when sending file completed successfully
    pub fn is_success(&self)->bool{
        if let SendingFileResults::Success = self { return true}
        false
    }
}

/// for constructing efficient bytes injector
pub enum HeaderBytes<'a> {
    Str(&'static str),
    StringSlice(&'a str),
    Slice(&'a [u8]),
    String(String),
    Usize(usize),
    Vec(Vec<u8>),
}

impl<'a> HeaderBytes<'a> {
    /// convert any type of supported data to &[u8]
    pub fn as_bytes(&self)->&'_ [u8] {

        match self {
            HeaderBytes::Str(s) => {s.as_bytes()}
            HeaderBytes::Slice(s) => {s}
            HeaderBytes::String(s) => {(*s).as_bytes()}

            HeaderBytes::StringSlice(a) => {(*a).as_bytes()}
            HeaderBytes::Vec(r) => {r.as_slice()}
            _=>panic!("can not convert to bytes")
        }
    }
}

impl<'a> Into<HeaderBytes<'a>> for &'a [u8] {
    fn into(self) -> HeaderBytes<'a> {
        HeaderBytes::Slice(self)
    }
}

impl <'a> Into<HeaderBytes<'a>> for usize {
    fn into(self) -> HeaderBytes<'a> {
        HeaderBytes::Usize(self)
    }
}
impl  Into<HeaderBytes<'_>> for Vec<u8> {
    fn into(self) -> HeaderBytes<'static> {
        HeaderBytes::Vec(self)
    }
}


impl<'a> Into<HeaderBytes<'a>> for &'a String {
    fn into(self) -> HeaderBytes<'a> {
        HeaderBytes::StringSlice(self)
    }
}
impl<'a> Into<HeaderBytes<'a>> for  String {
    fn into(self) -> HeaderBytes<'a> {
        HeaderBytes::String(self)
    }
}


impl Into<HeaderBytes<'_>> for &'static str {
    fn into(self) -> HeaderBytes<'static> {
        HeaderBytes::Str(self)
    }

}