88using System . Buffers ;
99using System . Collections . Generic ;
1010using System . Diagnostics ;
11+ using System . Diagnostics . CodeAnalysis ;
1112using System . Runtime . InteropServices ;
1213
1314using IronPython . Runtime . Exceptions ;
@@ -17,7 +18,20 @@ namespace IronPython.Runtime {
1718 /// Equivalent functionality of CPython's <a href="https://docs.python.org/3/c-api/buffer.html">Buffer Protocol</a>.
1819 /// </summary>
1920 public interface IBufferProtocol {
20- IPythonBuffer GetBuffer ( BufferFlags flags = BufferFlags . Simple ) ;
21+ /// <summary>
22+ /// Exports the object's data as a buffer.
23+ /// </summary>
24+ /// <param name="flags">
25+ /// Flags specifying the type of buffer the consumer is prepared to deal with.
26+ /// </param>
27+ /// <param name="throwOnError">
28+ /// This parameter is advisory: if true, the method may throw <c>BufferError</c> instead of returning null if the buffer type is not supported,
29+ /// with the exception's message providing more information.
30+ /// </param>
31+ /// <returns>
32+ /// An instance of <see cref="IPythonBuffer"/> if the requested buffer type is supported, or null if not.
33+ /// </returns>
34+ IPythonBuffer ? GetBuffer ( BufferFlags flags , bool throwOnError ) ;
2135 }
2236
2337 /// <summary>
@@ -119,16 +133,31 @@ public enum BufferFlags {
119133 #endregion
120134 }
121135
122- internal static class BufferProtocolExtensions {
136+
137+ public static class BufferProtocolExtensions {
138+ public static IPythonBuffer GetBuffer ( this IBufferProtocol bufferProtocol , BufferFlags flags = BufferFlags . Simple )
139+ => bufferProtocol . GetBuffer ( flags , throwOnError : true ) ?? throw new BufferException ( "Buffer type not supported" ) ;
140+
123141 internal static IPythonBuffer ? GetBufferNoThrow ( this IBufferProtocol bufferProtocol , BufferFlags flags = BufferFlags . Simple ) {
124142 try {
125- return bufferProtocol . GetBuffer ( flags ) ;
143+ return bufferProtocol . GetBuffer ( flags , throwOnError : false ) ;
126144 } catch ( BufferException ) {
127145 return null ;
128146 }
129147 }
148+
149+ internal static bool TryGetBuffer ( this IBufferProtocol bufferProtocol , BufferFlags flags , [ NotNullWhen ( true ) ] out IPythonBuffer ? buffer ) {
150+ try {
151+ buffer = bufferProtocol . GetBuffer ( flags , throwOnError : false ) ;
152+ return buffer is not null ;
153+ } catch ( BufferException ) {
154+ buffer = null ;
155+ return false ;
156+ }
157+ }
130158 }
131159
160+
132161 /// <summary>
133162 /// Provides low-level read-write access to byte data of the underlying object.
134163 /// </summary>
0 commit comments