Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚡️ Faster canShrinkWithoutContext for constants #5372

Merged
merged 6 commits into from
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/curvy-dingos-sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"fast-check": minor
---

⚡️ Faster `canShrinkWithoutContext` for constants
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
import { Arbitrary } from '../../check/arbitrary/definition/Arbitrary';
import { Value } from '../../check/arbitrary/definition/Value';
import { cloneMethod, hasCloneMethod } from '../../check/symbols';
import { Set, safeHas } from '../../utils/globals';

const safeObjectIs = Object.is;

/** @internal */
export class ConstantArbitrary<T> extends Arbitrary<T> {
private fastValues: FastConstantValuesLookup<T> | undefined;

constructor(readonly values: T[]) {
super();
}
Expand All @@ -20,12 +23,13 @@
return new Value(value, idx, () => value[cloneMethod]());
}
canShrinkWithoutContext(value: unknown): value is T {
for (let idx = 0; idx !== this.values.length; ++idx) {
if (safeObjectIs(this.values[idx], value)) {
return true;
}
if (this.values.length === 1) {
return safeObjectIs(this.values[0], value);
}
return false;
if (this.fastValues === undefined) {
this.fastValues = new FastConstantValuesLookup(this.values);

Check warning on line 30 in packages/fast-check/src/arbitrary/_internals/ConstantArbitrary.ts

View workflow job for this annotation

GitHub Actions / Format & Lint

'FastConstantValuesLookup' was used before it was defined
}
return this.fastValues.has(value);
}
shrink(value: T, context?: unknown): Stream<Value<T>> {
if (context === 0 || safeObjectIs(value, this.values[0])) {
Expand All @@ -34,3 +38,36 @@
return Stream.of(new Value(this.values[0], 0));
}
}

/** @internal */
class FastConstantValuesLookup<T> {
private readonly hasMinusZero: boolean;
private readonly hasPlusZero: boolean;
private readonly fastValues: Set<unknown>;

constructor(readonly values: T[]) {
this.fastValues = new Set(this.values);

let hasMinusZero = false;
let hasPlusZero = false;
if (safeHas(this.fastValues, 0)) {
for (let idx = 0; idx !== this.values.length; ++idx) {
const value = this.values[idx];
hasMinusZero = hasMinusZero || safeObjectIs(value, -0);
hasPlusZero = hasPlusZero || safeObjectIs(value, 0);
}
}
this.hasMinusZero = hasMinusZero;
this.hasPlusZero = hasPlusZero;
}

has(value: unknown): value is T {
if (value === 0) {
if (safeObjectIs(value, 0)) {
return this.hasPlusZero;
}
return this.hasMinusZero;
}
return safeHas(this.fastValues, value);
}
}
14 changes: 14 additions & 0 deletions packages/fast-check/src/utils/globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,19 +268,33 @@
// Set

const untouchedAdd = Set.prototype.add;
const untouchedHas = Set.prototype.has;
function extractAdd(instance: Set<unknown>) {
try {
return instance.add;
} catch (err) {
return undefined;
}
}
function extractHas(instance: Set<unknown>) {
try {
return instance.has;
} catch (err) {
return undefined;
}

Check warning on line 284 in packages/fast-check/src/utils/globals.ts

View check run for this annotation

Codecov / codecov/patch

packages/fast-check/src/utils/globals.ts#L283-L284

Added lines #L283 - L284 were not covered by tests
}
export function safeAdd<T>(instance: Set<T>, value: T): Set<T> {
if (extractAdd(instance) === untouchedAdd) {
return instance.add(value);
}
return safeApply(untouchedAdd, instance, [value]);
}
export function safeHas<T>(instance: Set<T>, value: T): boolean {
if (extractHas(instance) === untouchedHas) {
return instance.has(value);
}
return safeApply(untouchedHas, instance, [value]);
}

Check warning on line 297 in packages/fast-check/src/utils/globals.ts

View check run for this annotation

Codecov / codecov/patch

packages/fast-check/src/utils/globals.ts#L296-L297

Added lines #L296 - L297 were not covered by tests

// String

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ describe('ConstantArbitrary', () => {
});

describe('canShrinkWithoutContext', () => {
it("should mark value as 'canShrinkWithoutContext' whenever one of the original values is equal regarding Object.is", () =>
it("should mark value as 'canShrinkWithoutContext' whenever one of the original values is equal regarding Object.is", () => {
fc.assert(
fc.property(fc.array(fc.anything(), { minLength: 1 }), fc.nat(), (values, mod) => {
// Arrange
Expand All @@ -126,7 +126,24 @@ describe('ConstantArbitrary', () => {
// Assert
expect(out).toBe(true);
}),
));
);
});

it("should not mark value as 'canShrinkWithoutContext' if none of the original values is equal regarding Object.is", () => {
fc.assert(
fc.property(fc.uniqueArray(fc.anything(), { minLength: 2, comparator: 'SameValue' }), (values) => {
// Arrange
const [selectedValue, ...acceptedValues] = values;

// Act
const arb = new ConstantArbitrary(acceptedValues);
const out = arb.canShrinkWithoutContext(selectedValue); // selectedValue is unique for SameValue comparison (Object.is)

// Assert
expect(out).toBe(false);
}),
);
});

it('should not detect values not equal regarding to Object.is', () => {
// Arrange
Expand All @@ -141,33 +158,43 @@ describe('ConstantArbitrary', () => {
expect(out).toBe(false); // Object.is([], []) is falsy
});

it.each([{ source: -0 }, { source: 0 }, { source: 48 }])(
'should not accept to shrink -$source if built with $source',
({ source }) => {
// Arrange
const arb = new ConstantArbitrary([source]);

// Act
const out = arb.canShrinkWithoutContext(-source);

// Assert
expect(out).toBe(false);
},
);

it.each([{ source: -0 }, { source: 0 }, { source: 48 }, { source: Number.NaN }])(
'should accept to shrink $source if built with $source',
({ source }) => {
// Arrange
const arb = new ConstantArbitrary([source]);

// Act
const out = arb.canShrinkWithoutContext(source);

// Assert
expect(out).toBe(true);
},
);
it.each([
{ source: -0, count: 1 },
{ source: 0, count: 1 },
{ source: 48, count: 1 },
{ source: -0, count: 25 },
{ source: 0, count: 25 },
{ source: 48, count: 25 },
])('should not accept to shrink -$source if built with $source (count: $count)', ({ source, count }) => {
// Arrange
const arb = new ConstantArbitrary(Array(count).fill(source));

// Act
const out = arb.canShrinkWithoutContext(-source);

// Assert
expect(out).toBe(false);
});

it.each([
{ source: -0, count: 1 },
{ source: 0, count: 1 },
{ source: 48, count: 1 },
{ source: Number.NaN, count: 1 },
{ source: -0, count: 25 },
{ source: 0, count: 25 },
{ source: 48, count: 25 },
{ source: Number.NaN, count: 25 },
])('should accept to shrink $source if built with $source (count: $count)', ({ source, count }) => {
// Arrange
const arb = new ConstantArbitrary(Array(count).fill(source));

// Act
const out = arb.canShrinkWithoutContext(source);

// Assert
expect(out).toBe(true);
});
});

describe('shrink', () => {
Expand Down