File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -353,6 +353,53 @@ public void Clear(bool reuseBuffer = false)
353353 position = 0 ;
354354 }
355355
356+ /// <summary>
357+ /// Writes a collection of elements.
358+ /// </summary>
359+ /// <param name="collection">A collection of elements.</param>
360+ /// <exception cref="ArgumentNullException"><paramref name="collection"/> is <see langword="null"/>.</exception>
361+ public void Write ( IEnumerable < T > collection )
362+ {
363+ ArgumentNullException . ThrowIfNull ( collection ) ;
364+
365+ switch ( collection )
366+ {
367+ case List < T > list :
368+ Write ( CollectionsMarshal . AsSpan ( list ) ) ;
369+ break ;
370+ case T [ ] array :
371+ Write ( new ReadOnlySpan < T > ( array ) ) ;
372+ break ;
373+ case string str :
374+ Write ( Unsafe . BitCast < ReadOnlyMemory < char > , ReadOnlyMemory < T > > ( str . AsMemory ( ) ) . Span ) ;
375+ break ;
376+ case ArraySegment < T > segment :
377+ Write ( segment . AsSpan ( ) ) ;
378+ break ;
379+ default :
380+ WriteSlow ( collection ) ;
381+ break ;
382+ }
383+ }
384+
385+ private void WriteSlow ( IEnumerable < T > collection )
386+ {
387+ using var enumerator = collection . GetEnumerator ( ) ;
388+ if ( collection . TryGetNonEnumeratedCount ( out var count ) )
389+ {
390+ var buffer = InternalGetSpan ( count ) ;
391+ for ( var i = 0 ; i < buffer . Length && enumerator . MoveNext ( ) ; i ++ )
392+ {
393+ buffer [ i ] = enumerator . Current ;
394+ }
395+ }
396+
397+ while ( enumerator . MoveNext ( ) )
398+ {
399+ Add ( enumerator . Current ) ;
400+ }
401+ }
402+
356403 /// <summary>
357404 /// Releases internal buffer used by this builder.
358405 /// </summary>
You can’t perform that action at this time.
0 commit comments