String operations

Let’s assume our network can only transfer a constant number L of characters plus meta data in a single message. To deal with that, the sender can split a long message text into small parts of length at most L and send that parts separately. In addition it sends a message part and the part’s position along with an identifier for the complete message and the message’s total length. The receiver on the other hand merges the parts of a message and buffers those arriving out of order. It shall output a message as soon as it completely arrived.

So we need three string operations: get the length, split and merge. Therefor NetSimLan offers the build in functions str_len and sub_str. Strings can be merged by using the + operation.

The function str_len gets the string as parameter and returns the length of the string. The function sub_str gets 3 parameter: The string to split, the start point and the end point of the substring to return. The start point is included, the end point is excluded. For example: sub_str("Hello World!", 6, 11) returns World.

Let’s see how we can solve our problem using that. We use the grid implementation from previous chapter and replace the message function with the following tree functions message, forward and receive. That may results in the following code:

[int, string] buffer;
int L = 5; /* limit for string length per message */
message (string text, int to_id){
    int i; /* startindex of part start */
    int strid = hash(text);
    int len = str_len(text);
    for (i = 0 ; i < len ; i+=L){
        string part = sub_str(text , i , i+L);
        forwardpart(part, to_id, strid, i, len);
forwardpart (string part, int to_id, int strid,
                int start, int totallength){
    if (to_id==id(this)) {
        receivepart (part, strid, start, totallength);
    } else {
        if (nextHop[to_id] == null){
                /* messages shall not be lost, so delay */
                this -> forwardpart (part, to_id, strid,
                                    start, totallength);
        nextHop[to_id] -> forwardpart (part, to_id, strid,
                            start, totallength);
    mark (true);
receivepart (string part, int strid,
                int start, int totallength){
    string previousparts = buffer [strid];
    if ( str_len (previousparts) < start ){
        /* parts arrived out of order. delay this part */
        this -> receivepart (part, strid, start, totallength);
    } else {
        string newparts = previousparts + part;
        if ( str_len(newparts) == totallength ){
            /* message arrived completly */
            print("Message " + newparts + " received.");
            buffer <[strid]< ;
        } else {
            /* parts still missing. Update the buffer */
            buffer [ strid ] = newparts;

Previous: Arrays and Loops Next: Advanced synchronization

The University for the Information Society