Skip to content

Commit

Permalink
Add PowerOfTwo validator
Browse files Browse the repository at this point in the history
  • Loading branch information
wendigo committed Apr 9, 2023
1 parent d387859 commit 14c5638
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/main/java/io/airlift/units/PowerOfTwo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.units;

import javax.validation.Constraint;
import javax.validation.Payload;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({METHOD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = PowerOfTwoValidator.class)
public @interface PowerOfTwo
{
String message() default "is not a power of two";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}
32 changes: 32 additions & 0 deletions src/main/java/io/airlift/units/PowerOfTwoValidator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.units;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PowerOfTwoValidator
implements ConstraintValidator<PowerOfTwo, Integer>
{
@Override
public void initialize(PowerOfTwo powerOfTwo)
{
}

@Override
public boolean isValid(Integer value, ConstraintValidatorContext context)
{
return value == null || Integer.bitCount(value) == 1;
}
}

0 comments on commit 14c5638

Please sign in to comment.