@@ -321,13 +321,13 @@ public void Disable(IQArray<Qubit> qubitsToDisable)
321321 /// Allocates a qubit.
322322 /// Returns null if the qubit cannot be allocated.
323323 /// </summary>
324- protected virtual Qubit Allocate ( bool usedOnlyForBorrowing )
324+ protected virtual Qubit ? Allocate ( bool usedOnlyForBorrowing )
325325 {
326326 if ( free == None )
327327 {
328328 if ( ! MayExtendCapacity )
329329 {
330- throw new NotEnoughQubits ( 1 , this . FreeQubitsCount ) ;
330+ return null ;
331331 }
332332
333333 long oldNumQubits = NumQubits ;
@@ -398,7 +398,12 @@ protected virtual Qubit Allocate(bool usedOnlyForBorrowing)
398398 /// </summary>
399399 public Qubit Allocate ( )
400400 {
401- return Allocate ( usedOnlyForBorrowing : false ) ;
401+ Qubit ? qb = Allocate ( usedOnlyForBorrowing : false ) ;
402+ if ( qb == null )
403+ {
404+ throw new NotEnoughQubits ( 1 , this . FreeQubitsCount ) ;
405+ }
406+ return qb ;
402407 }
403408
404409 /// <summary>
@@ -424,7 +429,15 @@ public IQArray<Qubit> Allocate(long numToAllocate)
424429 }
425430 for ( int i = 0 ; i < numToAllocate ; i ++ )
426431 {
427- Qubit allocated = Allocate ( usedOnlyForBorrowing : false ) ;
432+ Qubit ? allocated = Allocate ( usedOnlyForBorrowing : false ) ;
433+ if ( allocated == null )
434+ {
435+ for ( int k = 0 ; k < i ; k ++ )
436+ {
437+ Release ( result [ k ] , wasUsedOnlyForBorrowing : false ) ;
438+ }
439+ throw new NotEnoughQubits ( numToAllocate , this . FreeQubitsCount ) ;
440+ }
428441 result . Modify ( i , allocated ) ;
429442 }
430443
@@ -581,7 +594,15 @@ internal IQArray<Qubit> Borrow(long numToBorrow, HashSet<Qubit> qubitsInUse)
581594 { // Not enough qubits to borrow. Allocate what was not borrowed.
582595 for ( long i = numBorrowed ; i < numToBorrow ; i ++ )
583596 {
584- Qubit allocated = Allocate ( usedOnlyForBorrowing : true ) ;
597+ Qubit ? allocated = Allocate ( usedOnlyForBorrowing : true ) ;
598+ if ( allocated == null )
599+ {
600+ for ( long k = numBorrowed ; k < i ; k ++ )
601+ {
602+ Release ( borrowed [ ( int ) k ] , wasUsedOnlyForBorrowing : true ) ;
603+ }
604+ throw new NotEnoughQubits ( numToBorrow , numBorrowed + this . FreeQubitsCount ) ;
605+ }
585606 borrowed . Modify ( i , allocated ) ;
586607 }
587608 }
0 commit comments