@@ -380,26 +380,22 @@ IEnumerator IEnumerable.GetEnumerator() {
380380 public sealed class MemoryBufferProtocolWrapper < T > : IBufferProtocol where T : unmanaged {
381381 private readonly ReadOnlyMemory < T > _rom ;
382382 private readonly Memory < T > ? _memory ;
383- private readonly string ? _format ;
383+ private readonly char _format ;
384384
385- public MemoryBufferProtocolWrapper ( ReadOnlyMemory < T > memory , string ? format = null ) {
385+ public MemoryBufferProtocolWrapper ( ReadOnlyMemory < T > memory ) {
386386 _rom = memory ;
387387 _memory = null ;
388- _format = format ;
388+ _format = GetFormatChar ( ) ;
389389 }
390390
391- public MemoryBufferProtocolWrapper ( Memory < T > memory , string ? format = null ) {
391+ public MemoryBufferProtocolWrapper ( Memory < T > memory ) {
392392 _rom = memory ;
393393 _memory = memory ;
394- _format = format ;
394+ _format = GetFormatChar ( ) ;
395395 }
396396
397397 public IPythonBuffer ? GetBuffer ( BufferFlags flags , bool throwOnError ) {
398- if ( _memory . HasValue ) {
399- return new MemoryBufferWrapper ( this , flags ) ;
400- }
401-
402- if ( flags . HasFlag ( BufferFlags . Writable ) ) {
398+ if ( flags . HasFlag ( BufferFlags . Writable ) && ! _memory . HasValue ) {
403399 if ( throwOnError ) {
404400 throw Operations . PythonOps . BufferError ( "ReadOnlyMemory is not writable." ) ;
405401 }
@@ -409,6 +405,23 @@ public MemoryBufferProtocolWrapper(Memory<T> memory, string? format = null) {
409405 return new MemoryBufferWrapper ( this , flags ) ;
410406 }
411407
408+ private static char GetFormatChar ( )
409+ => Type . GetTypeCode ( typeof ( T ) ) switch {
410+ TypeCode . SByte => 'b' ,
411+ TypeCode . Byte => 'B' ,
412+ TypeCode . Char => 'u' ,
413+ TypeCode . Int16 => 'h' ,
414+ TypeCode . UInt16 => 'H' ,
415+ TypeCode . Int32 => 'i' ,
416+ TypeCode . UInt32 => 'I' ,
417+ TypeCode . Int64 => 'q' ,
418+ TypeCode . UInt64 => 'Q' ,
419+ TypeCode . Single => 'f' ,
420+ TypeCode . Double => 'd' ,
421+ _ => throw new ArgumentException ( "Unsupported type" ) ,
422+ } ;
423+
424+
412425 private sealed unsafe class MemoryBufferWrapper : IPythonBuffer {
413426 private readonly MemoryBufferProtocolWrapper < T > _wrapper ;
414427 private readonly BufferFlags _flags ;
@@ -435,7 +448,7 @@ public Span<byte> AsSpan()
435448
436449 public int Offset => 0 ;
437450
438- public string ? Format => _flags . HasFlag ( BufferFlags . Format ) ? _wrapper . _format : null ;
451+ public string ? Format => _flags . HasFlag ( BufferFlags . Format ) ? _wrapper . _format . ToString ( ) : null ;
439452
440453 public int ItemCount => _wrapper . _rom . Length ;
441454
0 commit comments