Why i am getting different count every time i run the program?

Hello everyone

i created a small program which count the number of bytes of a file sent over a socket, the program looks like this

use std::time::Instant;

use tokio::net::TcpListener;
use tokio::io::Result;
use tokio::io::BufReader;
use tokio::io::AsyncReadExt;
use console::style;

#[tokio::main]
async fn main() -> Result<()> {
    let mut listener = TcpListener::bind("127.0.0.1:2020").await?;

    println!("[ {} ] Wating for files..", style("START").bold().green());

    loop {
        let (mut stream, addr) = listener.accept().await?;
        let now = Instant::now();

        println!(
            "[  {}  ] Processing file from {}",
            style("NEW").bold().yellow(),
            style(addr).magenta()
        );

        let (reader, _) = stream.split();
        let mut reader = BufReader::new(reader);
        let mut buf = [0; 1024];

        let mut nb_alphas = 0;

        while let Ok(len) = reader.read(&mut buf).await {
            if len == 0 { break }

            for b in buf.iter() {
                match *b {
                    b'a'..=b'z' | b'A'..=b'Z' => {
                        nb_alphas += 1;
                    },
                    _ => { }
                }
            }
        }

        println!();
        println!(" > Number of alphas: {}", nb_alphas);

        // --
        let elapsed = now.elapsed();

        println!(
            "\n--\n{} {}\t{} {}",
            style(elapsed.as_secs_f64()).cyan(),
            style("secs").bold(),
            style(elapsed.as_nanos()).cyan(),
            style("nanos").bold()
        );
    }
}

i send a file using socat like this socat -u FILE:file.txt TCP:127.0.0.1:2020 but the weird thing, is everytime i run th eprogram, the alphas counter gives me different results, and i have no idea why?

this is the output, after a few runs

[ START ] Wating for files..
[  NEW  ] Processing file from 127.0.0.1:41516

 > Number of alphas: 694712146

--
2.718421352 secs        2718421352 nanos
[  NEW  ] Processing file from 127.0.0.1:41518

 > Number of alphas: 694712160

--
2.73934149 secs 2739341490 nanos
[  NEW  ] Processing file from 127.0.0.1:41520

 > Number of alphas: 694712159

--
2.726005681 secs        2726005681 nanos
[  NEW  ] Processing file from 127.0.0.1:41522

 > Number of alphas: 694712171

--
2.737450261 secs        2737450261 nanos
1 Like

i made a small change to the for loop inside from buf.iter() to &buf[..len] and know i get a steady counter, but this raises another questions, since the buffer is already initialized with zeros, why the count is different?

On the second iteration, if the first read is longer than the second, the buffer will contain stuff from the first message after the second message.

2 Likes

@alice since i am sending the same file everytime, shouldn't be constant, maybe ill get a wrong number, but it will be the same on every run, because the buffer is initialized with zeros ??

The size returned by each iteration of reader.read depends on the whims of the network connection, and will definitely change from call to call.

Consider this example of reading [1, 2, 3, 4, 5, 6]:

buf: [0, 0, 0, 0]
read returns 4
buf: [1, 2, 3, 4]
read returns 2
buf: [5, 6, 3, 4]

next run of same data might go like this:

buf: [0, 0, 0, 0]
read returns 3
buf: [1, 2, 3, 0]
read returns 2
buf: [4, 5, 3, 0]
read returns 1
buf: [6, 5, 3, 0]
2 Likes

@alice thank you, that answers my question :smiling_face_with_three_hearts:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.