@@ -951,18 +951,29 @@ public DirectoryMeta Read(EndianReader reader)
951951 // SIMD go brrrrrrrrrrr
952952 if ( reader . BaseStream is MemoryStream ms )
953953 {
954- byte [ ] buffer = ms . GetBuffer ( ) ;
955- int pos = ( int ) ms . Position ;
956- int end = ( int ) ms . Length ;
957- int idx = buffer . AsSpan ( pos , end - pos ) . IndexOf ( endMarker ) ;
958- if ( idx >= 0 )
954+ if ( ms . TryGetBuffer ( out ArraySegment < byte > seg ) )
959955 {
960- entry . objBytes = new byte [ idx ] ;
961- Buffer . BlockCopy ( buffer , pos , entry . objBytes , 0 , idx ) ;
956+ var span = seg . AsSpan ( ( int ) ms . Position , ( int ) ( ms . Length - ms . Position ) ) ;
957+ int idx = span . IndexOf ( endMarker ) ;
958+
959+ if ( idx >= 0 )
960+ {
961+ entry . objBytes = span . Slice ( 0 , idx ) . ToArray ( ) ;
962+ }
963+ else
964+ {
965+ entry . objBytes = Array . Empty < byte > ( ) ;
966+ }
962967 }
963968 else
964969 {
965- entry . objBytes = Array . Empty < byte > ( ) ;
970+ // fallback
971+ var span = ms . ToArray ( ) . AsSpan ( ( int ) ms . Position ) ;
972+ int idx = span . IndexOf ( endMarker ) ;
973+
974+ entry . objBytes = idx >= 0
975+ ? span . Slice ( 0 , idx ) . ToArray ( )
976+ : Array . Empty < byte > ( ) ;
966977 }
967978 }
968979 else
@@ -1079,17 +1090,39 @@ public void ReadEntry(EndianReader reader, DirectoryMeta.Entry entry)
10791090 ReadOnlySpan < byte > unknownEndMarker = stackalloc byte [ ] { 0xAD , 0xDE , 0xAD , 0xDE } ;
10801091 if ( reader . BaseStream is MemoryStream ums )
10811092 {
1082- byte [ ] buffer = ums . GetBuffer ( ) ;
1083- int pos = ( int ) ums . Position ;
1084- int end = ( int ) ums . Length ;
1085- int idx = buffer . AsSpan ( pos , end - pos ) . IndexOf ( unknownEndMarker ) ;
1086- if ( idx >= 0 )
1093+ if ( ums . TryGetBuffer ( out ArraySegment < byte > seg ) )
10871094 {
1088- ums . Position = pos + idx + 4 ; // skip past end marker
1095+ int pos = ( int ) ums . Position ;
1096+ int len = ( int ) ums . Length - pos ;
1097+
1098+ var span = seg . AsSpan ( pos , len ) ;
1099+ int idx = span . IndexOf ( unknownEndMarker ) ;
1100+
1101+ if ( idx >= 0 )
1102+ {
1103+ ums . Position = pos + idx + unknownEndMarker . Length ;
1104+ }
1105+ else
1106+ {
1107+ throw new EndOfStreamException (
1108+ "Could not find end marker for unknown entry type " + entry . type . value ) ;
1109+ }
10891110 }
10901111 else
10911112 {
1092- throw new EndOfStreamException ( "Could not find end marker for unknown entry type " + entry . type . value ) ;
1113+ // fallback
1114+ var span = ums . ToArray ( ) . AsSpan ( ( int ) ums . Position ) ;
1115+ int idx = span . IndexOf ( unknownEndMarker ) ;
1116+
1117+ if ( idx >= 0 )
1118+ {
1119+ ums . Position += idx + unknownEndMarker . Length ;
1120+ }
1121+ else
1122+ {
1123+ throw new EndOfStreamException (
1124+ "Could not find end marker for unknown entry type " + entry . type . value ) ;
1125+ }
10931126 }
10941127 }
10951128 else
0 commit comments