Skip to content

Commit

Permalink
Fix generics
Browse files Browse the repository at this point in the history
  • Loading branch information
Mindgamesnl committed Aug 24, 2023
1 parent 276fc0c commit ac02d23
Showing 1 changed file with 16 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
package com.rpcnis.base.defaults;

import com.rpcnis.base.RpcTransport;
import com.rpcnis.base.enums.Direction;
import com.rpcnis.base.enums.ReadStatus;
import com.rpcnis.base.interfaces.SubscriptionHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class LoopbackTransport implements RpcTransport {

private List<Function<byte[], ReadStatus>> onReceiveFunctions = new ArrayList<>();
private Map<Direction, List<SubscriptionHandler>> onReceiveFunctions = new HashMap<>();

/**
* @param bytes the bytes to send
Expand All @@ -20,25 +24,31 @@ public class LoopbackTransport implements RpcTransport {
* no actual sending is done, as this is a loopback transport meant for testing
*/
@Override
public void send(byte[] bytes) {
for (Function<byte[], ReadStatus> onReceiveFunction : onReceiveFunctions) {
ReadStatus status = onReceiveFunction.apply(bytes);
public void send(Direction direction, byte[] bytes) {
for (SubscriptionHandler onReceiveFunction : onReceiveFunctions.getOrDefault(direction, new ArrayList<>())) {
ReadStatus status = null;
try {
status = onReceiveFunction.onPacket(bytes);
} catch (Exception e) {
e.printStackTrace();
}
if (status == ReadStatus.HANDLED) {
break;
}
}
}

/**
* @param target the direction of the packet we want to listen to
* @param onReceive a function that will be called when a packet is received.
* the function should return a ReadStatus, which will be used to determine if the packet was handled or not.
* if the packet was handled, the transport implementation should stop processing the packet.
* if the packet was not handled, the transport implementation should continue processing the packet.
* the transport implementation should call the onReceive function, regardless of the ReadStatus.
*/
@Override
public void onReceive(Function<byte[], ReadStatus> onReceive) {
onReceiveFunctions.add(onReceive);
public void subscribe(Direction target, SubscriptionHandler onReceive) {
onReceiveFunctions.computeIfAbsent(target, k -> new ArrayList<>()).add(onReceive);
}

/**
Expand Down

0 comments on commit ac02d23

Please sign in to comment.