1+ use std:: sync:: Arc ;
2+
3+ #[ cfg( feature = "io-util" ) ]
4+ use bytes:: Buf ;
5+
16use super :: typeid;
27
3- #[ derive( Debug ) ]
8+ #[ derive( Debug , Clone ) ]
49pub ( crate ) enum OwnedBuf {
5- Vec ( Vec < u8 > ) ,
10+ Vec ( VecBuf ) ,
611 #[ cfg( feature = "io-util" ) ]
712 Bytes ( bytes:: Bytes ) ,
813}
914
15+ #[ allow( unused) ]
16+ impl OwnedBuf {
17+ pub ( crate ) fn len ( & self ) -> usize {
18+ match self {
19+ OwnedBuf :: Vec ( vec) => vec. len ( ) ,
20+ #[ cfg( feature = "io-util" ) ]
21+ OwnedBuf :: Bytes ( b) => b. len ( ) ,
22+ }
23+ }
24+
25+ pub ( crate ) fn advance ( & mut self , n : usize ) {
26+ match self {
27+ OwnedBuf :: Vec ( vec) => vec. advance ( n) ,
28+ #[ cfg( feature = "io-util" ) ]
29+ OwnedBuf :: Bytes ( b) => b. advance ( n) ,
30+ }
31+ }
32+
33+ pub ( crate ) fn is_empty ( & self ) -> bool {
34+ match self {
35+ Self :: Vec ( vec) => vec. is_empty ( ) ,
36+ #[ cfg( feature = "io-util" ) ]
37+ Self :: Bytes ( bytes) => bytes. is_empty ( ) ,
38+ }
39+ }
40+ }
41+
42+ /// A Vec-like, reference-counted buffer.
43+ #[ derive( Debug , Clone ) ]
44+ pub ( crate ) struct VecBuf {
45+ data : Arc < [ u8 ] > ,
46+ pos : usize ,
47+ }
48+
49+ impl VecBuf {
50+ fn len ( & self ) -> usize {
51+ self . data . len ( ) . saturating_sub ( self . pos )
52+ }
53+
54+ fn advance ( & mut self , n : usize ) {
55+ self . pos = self . pos . saturating_add ( n) ;
56+ }
57+
58+ fn is_empty ( & self ) -> bool {
59+ self . data . len ( ) . saturating_sub ( self . pos ) == 0
60+ }
61+ }
62+
1063impl AsRef < [ u8 ] > for OwnedBuf {
1164 fn as_ref ( & self ) -> & [ u8 ] {
1265 match self {
13- Self :: Vec ( vec ) => vec ,
66+ Self :: Vec ( VecBuf { data , pos } ) => & data [ * pos.. ] ,
1467 #[ cfg( feature = "io-util" ) ]
1568 Self :: Bytes ( bytes) => bytes,
1669 }
@@ -19,12 +72,22 @@ impl AsRef<[u8]> for OwnedBuf {
1972
2073pub ( crate ) fn upgrade < B : AsRef < [ u8 ] > > ( buf : B ) -> OwnedBuf {
2174 let buf = match unsafe { typeid:: try_transmute :: < B , Vec < u8 > > ( buf) } {
22- Ok ( vec) => return OwnedBuf :: Vec ( vec) ,
75+ Ok ( vec) => {
76+ return OwnedBuf :: Vec ( VecBuf {
77+ data : vec. into ( ) ,
78+ pos : 0 ,
79+ } ) ;
80+ }
2381 Err ( original_buf) => original_buf,
2482 } ;
2583
2684 let buf = match unsafe { typeid:: try_transmute :: < B , String > ( buf) } {
27- Ok ( string) => return OwnedBuf :: Vec ( string. into_bytes ( ) ) ,
85+ Ok ( string) => {
86+ return OwnedBuf :: Vec ( VecBuf {
87+ data : string. into_bytes ( ) . into ( ) ,
88+ pos : 0 ,
89+ } ) ;
90+ }
2891 Err ( original_buf) => original_buf,
2992 } ;
3093
@@ -34,5 +97,8 @@ pub(crate) fn upgrade<B: AsRef<[u8]>>(buf: B) -> OwnedBuf {
3497 Err ( original_buf) => original_buf,
3598 } ;
3699
37- OwnedBuf :: Vec ( buf. as_ref ( ) . to_owned ( ) )
100+ OwnedBuf :: Vec ( VecBuf {
101+ data : buf. as_ref ( ) . to_owned ( ) . into ( ) ,
102+ pos : 0 ,
103+ } )
38104}
0 commit comments