iostream.stream.writen
Writes a numeric value in the given format
from "iostream" import blob
let hp = blob(0)
hp.writen(100, 'i')
hp.seek(0)
println("hp.readn('i') =", hp.readn('i'))hp.readn('i') = 100Parameters
value | number | the value to write |
format | int | a character selecting the numeric type and width to write |
Notes
readn reads back the same eight codes at the same widths:
'b'-unsigned char, 1 byte'c'-signed char, 1 byte'w'-unsigned short, 2 bytes's'-short, 2 bytes'i'- a 32-bit signed integer, 4 bytes'l'- the VM's native integer, 8 bytes (this build always uses a 64-bit integer, even when the target is 32-bit)'f'- a 32-bit IEEE float, 4 bytes'd'- a 64-bit IEEE double, 8 bytes; the value stored is only ever as precise as the 32-bitfloatthis build'snumberalready narrowed it to
Bytes are stored verbatim, in the host's native byte order (little-endian on every platform this engine targets); writen never swaps bytes on its own. Pair it with a byte swap, such as iostream.swap2 or iostream.swap4, before handing the bytes to a big-endian peer.
The same method works on a file: it writes at the file's current position and advances it by the format's width, the same as it moves a blob's cursor. Writing past the current len grows a blob to fit; writing past the end of a file extends the file the same way, since both are ordinary writes to the underlying medium.
Errors
Throws invalid format when format is not one of the eight codes above.
writen also throws io error if the underlying stream cannot store the full width, for example a file opened read-only; a blob's own storage never refuses a write, so this case cannot happen on a blob.
Example
from "iostream" import blob
let b = blob(0) // empty; every write below extends it
b.writen(0x11223344, 'i') // 4 bytes
println("b.len() after writen('i') =", b.len())
b.writen(2.5, 'f') // writing past the end grows the blob, never an error
println("b.len() after writen('f') =", b.len())
b.seek(0)
println("b.readn('i') == 0x11223344 =", b.readn('i') == 0x11223344)
println("b.readn('f') =", b.readn('f'))
try { b.writen(1, 'z') } catch (e) { println("b.writen(1, 'z') throws:", e) } // 'z' is not a format codeb.len() after writen('i') = 4
b.len() after writen('f') = 8
b.readn('i') == 0x11223344 = true
b.readn('f') = 2.5
b.writen(1, 'z') throws: invalid formatSee also
writen | Writes a numeric value in the given format |
readn | Reads a value of the given numeric format and returns it |
seek | Seeks to the given offset; origin is 'b' (begin), 'c' (current) or 'e' (end) |
swap2 | Byte-swaps a 16-bit value |
| stream | class index |