as-wasi icon indicating copy to clipboard operation
as-wasi copied to clipboard

readLine returns null prematurely

Open ColinEberhardt opened this issue 3 years ago • 2 comments

I'm using the following to load a multi-line file into a string array:

  const fileOrNull: Descriptor | null = FileSystem.open(filename, "r");
  if (fileOrNull == null) {
    throw new Error("Could not open the file " + filename);
  }
  const file = changetype<Descriptor>(fileOrNull);

  const lines = new Array<string>();
  let line = changetype<string>(file.readLine());
  do {
    lines.push(line);
    line = changetype<string>(file.readLine());
  } while(line)
  return lines;

However, give the following input:

one
two
three

The result is an array ["one", "two"] - the readLine method appears to return null prematurely

ColinEberhardt avatar Dec 06 '20 20:12 ColinEberhardt

Btw you could nicer cast to non-nullable type without changetype:

  const file = FileSystem.open(filename, "r")
  if (file == null) {
    throw new Error("Could not open the file " + filename)
  }
  const lines: string[] = []
  let line = file!.readLine()
  do {
    lines.push(line!)
    line = file!.readLine()
  } while (line)
  return lines

btw isn't this should be?

const lines: string[] = []
while (true) {
  let line = file!.readLine()
  if (line == null) break
  lines.push(line!)
}
return lines

Regarding issue when readLine return null prematurely it hard to tell.

@jedisct1 btw here should be if (read == 0) here due to read is unsigned type

MaxGraey avatar Dec 06 '20 20:12 MaxGraey

Btw you could nicer cast to non-nullable type without changetype

Good call, I'm not that fluent in TS, so forgot about the non-null assertion operator.

btw isn't this should be? ...

Your code gives the same result, the last line is skipped.

ColinEberhardt avatar Dec 07 '20 08:12 ColinEberhardt