Skip to content

Commit

Permalink
fix memory leak enumerator (#2174)
Browse files Browse the repository at this point in the history
  • Loading branch information
kronic authored Nov 22, 2023
1 parent 513eaa1 commit 419380c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
3 changes: 3 additions & 0 deletions Changelog.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
11.8.2 -
Fix memory leak in NotEmptyValidator/EmptyValidator (#2174)

11.8.1 - 22 Nov 2023
Fix unintentional behavioural changes in introduced in the previous release as part of #2158

Expand Down
11 changes: 9 additions & 2 deletions src/FluentValidation/Validators/EmptyValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ namespace FluentValidation.Validators;
using System;
using System.Collections;
using System.Collections.Generic;
using Resources;

public class EmptyValidator<T,TProperty> : PropertyValidator<T,TProperty> {

Expand All @@ -42,7 +41,7 @@ public override bool IsValid(ValidationContext<T> context, TProperty value) {
return true;
}

if (value is IEnumerable e && !e.GetEnumerator().MoveNext()) {
if (value is IEnumerable e && IsEmpty(e)) {
return true;
}

Expand All @@ -52,4 +51,12 @@ public override bool IsValid(ValidationContext<T> context, TProperty value) {
protected override string GetDefaultMessageTemplate(string errorCode) {
return Localized(errorCode, Name);
}

private static bool IsEmpty(IEnumerable enumerable) {
var enumerator = enumerable.GetEnumerator();

using (enumerator as IDisposable) {
return !enumerator.MoveNext();
}
}
}
10 changes: 9 additions & 1 deletion src/FluentValidation/Validators/NotEmptyValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public override bool IsValid(ValidationContext<T> context, TProperty value) {
return false;
}

if (value is IEnumerable e && !e.GetEnumerator().MoveNext()) {
if (value is IEnumerable e && IsEmpty(e)) {
return false;
}

Expand All @@ -51,6 +51,14 @@ public override bool IsValid(ValidationContext<T> context, TProperty value) {
protected override string GetDefaultMessageTemplate(string errorCode) {
return Localized(errorCode, Name);
}

private static bool IsEmpty(IEnumerable enumerable) {
var enumerator = enumerable.GetEnumerator();

using (enumerator as IDisposable) {
return !enumerator.MoveNext();
}
}
}

public interface INotEmptyValidator : IPropertyValidator {
Expand Down

0 comments on commit 419380c

Please sign in to comment.