Skip to content

Commit

Permalink
whenFit() and Expect.it()
Browse files Browse the repository at this point in the history
  • Loading branch information
yegor256 committed Nov 4, 2024
1 parent 5c618ee commit 532924e
Show file tree
Hide file tree
Showing 6 changed files with 206 additions and 18 deletions.
11 changes: 7 additions & 4 deletions eo-runtime/src/main/java/EOorg/EOeolang/EOnumber$EOtimes.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.eolang.Attr;
import org.eolang.Data;
import org.eolang.Dataized;
import org.eolang.Expect;
import org.eolang.PhDefault;
import org.eolang.Phi;
import org.eolang.Versionized;
Expand All @@ -58,9 +59,11 @@ public final class EOnumber$EOtimes extends PhDefault implements Atom {

@Override
public Phi lambda() {
return new Data.ToPhi(
new Dataized(this.take(Attr.RHO)).asNumber()
* new Dataized(this.take("x")).asNumber()
);
final Double left = new Dataized(this.take(Attr.RHO)).asNumber();
final Double right = new Expect<>(
() -> new Dataized(this.take("x")).asNumber(),
"number.times expects its second argument to be a number"
).it();
return new Data.ToPhi(left * right);
}
}
11 changes: 9 additions & 2 deletions eo-runtime/src/main/java/EOorg/EOeolang/EOtxt/EOsprintf.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import org.eolang.Data;
import org.eolang.Dataized;
import org.eolang.ExFailure;
import org.eolang.Expect;
import org.eolang.PhDefault;
import org.eolang.Phi;
import org.eolang.XmirObject;
Expand Down Expand Up @@ -83,8 +84,14 @@ public EOsprintf() {
public Phi lambda() throws Exception {
final String format = new Dataized(this.take("format")).asString();
final Phi args = this.take("args");
final Phi retriever = args.take("at");
final long length = new Dataized(args.take("length")).asNumber().longValue();
final Phi retriever = new Expect<>(
() -> args.take("at"),
"sprintf expects its second argument to be a tuple with the 'at' attribute"
).it();
final long length = new Expect<>(
() -> new Dataized(args.take("length")).asNumber().longValue(),
"sprintf expects its second argument to be a tuple with the 'length' attribute"
).it();
final List<Object> arguments = new ArrayList<>(0);
String pattern = format;
long index = 0;
Expand Down
47 changes: 36 additions & 11 deletions eo-runtime/src/main/java/org/eolang/BytesRaw.java
Original file line number Diff line number Diff line change
Expand Up @@ -164,20 +164,19 @@ public <T extends Number> T asNumber(final Class<T> type) {
final byte[] ret = this.take();
final Object res;
final ByteBuffer buf = ByteBuffer.wrap(ret);
if (Long.class.equals(type) && ret.length == Long.BYTES) {
res = buf.getLong();
} else if (Integer.class.equals(type) && ret.length == Integer.BYTES) {
res = buf.getInt();
} else if (Double.class.equals(type) && ret.length == Double.BYTES) {
res = buf.getDouble();
} else if (Short.class.equals(type) && ret.length == Short.BYTES) {
res = buf.getShort();
if (Long.class.equals(type)) {
res = BytesRaw.whenFit(buf, ret, Long.class).getLong();
} else if (Integer.class.equals(type)) {
res = BytesRaw.whenFit(buf, ret, Integer.class).getInt();
} else if (Double.class.equals(type)) {
res = BytesRaw.whenFit(buf, ret, Double.class).getDouble();
} else if (Short.class.equals(type)) {
res = BytesRaw.whenFit(buf, ret, Short.class).getShort();
} else {
throw new UnsupportedOperationException(
String.format(
"Unsupported conversion to \"%s\" for %d bytes",
type,
ret.length
"Can't convert %d bytes to \"%s\"",
ret.length, type.getCanonicalName()
)
);
}
Expand Down Expand Up @@ -253,4 +252,30 @@ private static byte numberOfLeadingZeros(final byte num) {
}
return result;
}

/**
* Checks the buffer for its validity.
* @param buf The buffer
* @param bytes The bytes
* @param type The type to fit into
* @return The same buffer
*/
private static ByteBuffer whenFit(final ByteBuffer buf, final byte[] bytes,
final Class<?> type) {
final int expected;
try {
expected = type.getField("BYTES").getInt(null);
} catch (final NoSuchFieldException | IllegalAccessException ex) {
throw new IllegalArgumentException(ex);
}
if (bytes.length != expected) {
throw new ExFailure(
String.format(
"Can't convert %d bytes to %s, exactly %d bytes expected",
bytes.length, type.getName(), expected
)
);
}
return buf;
}
}
82 changes: 82 additions & 0 deletions eo-runtime/src/main/java/org/eolang/Expect.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2024 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package org.eolang;

/**
* This wrapper helps us explain our expectations in an error
* message that we throw.
*
* @param <T> Type of returned value
* @since 0.41.0
*/
public final class Expect<T> {

/**
* The action.
*/
private final Expect.Action<T> action;

/**
* The message.
*/
private final String message;

/**
* Ctor.
* @param act The action
* @param msg Additional explanation
*/
public Expect(final Expect.Action<T> act, final String msg) {
this.action = act;
this.message = msg;
}

/**
* Take the value from the lambda.
* @return The value
* @checkstyle MethodNameCheck (3 lines)
*/
@SuppressWarnings("PMD.ShortMethodName")
public T it() {
try {
return this.action.exec();
} catch (final ExFailure ex) {
throw new ExFailure(this.message, ex);
}
}

/**
* The action.
* @param <T> The type
* @since 0.41.0
*/
public interface Action<T> {
/**
* Run it.
* @return The value
*/
T exec();
}
}
71 changes: 71 additions & 0 deletions eo-runtime/src/test/java/EOorg/EOeolang/EOnumber$EOtimesTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2024 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

/*
* @checkstyle PackageNameCheck (10 lines)
* @checkstyle TrailingCommentCheck (3 lines)
*/
package EOorg.EOeolang; // NOPMD

import org.eolang.Attr;
import org.eolang.Data;
import org.eolang.Dataized;
import org.eolang.PhWith;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
* Test case for {@link EOnumber$EOtimes}.
*
* @since 0.41
* @checkstyle TypeNameCheck (3 lines)
*/
@SuppressWarnings("PMD.AvoidDollarSigns")
final class EOnumber$EOtimesTest {

@Test
void throwsCorrectError() {
MatcherAssert.assertThat(
"the message in the error is correct",
Assertions.assertThrows(
EOerror.ExError.class,
() -> new Dataized(
new PhWith(
new PhWith(
new EOnumber$EOtimes(),
Attr.RHO,
new Data.ToPhi(4L)
),
"x",
new Data.ToPhi(true)
)
).take(),
"multiplies 3 by TRUE and fails with a proper message that explains what happened"
).getMessage(),
Matchers.containsString("number.times expects its second argument to be a number")
);
}
}
2 changes: 1 addition & 1 deletion eo-runtime/src/test/java/org/eolang/BytesOfTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ void checksAsNumberLong() {
void checksUnderflowForLong() {
final Bytes bytes = new BytesOf("A");
Assertions.assertThrows(
UnsupportedOperationException.class,
ExFailure.class,
bytes::asNumber,
AtCompositeTest.TO_ADD_MESSAGE
);
Expand Down

0 comments on commit 532924e

Please sign in to comment.