sysio.nim 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # Nim's standard IO library. It contains high-performance
  10. # routines for reading and writing data to (buffered) files or
  11. # TTYs.
  12. {.push debugger:off .} # the user does not want to trace a part
  13. # of the standard library!
  14. when defined(windows):
  15. proc c_fdopen(filehandle: cint, mode: cstring): File {.
  16. importc: "_fdopen", header: "<stdio.h>".}
  17. else:
  18. proc c_fdopen(filehandle: cint, mode: cstring): File {.
  19. importc: "fdopen", header: "<stdio.h>".}
  20. proc c_fputs(c: cstring, f: File): cint {.
  21. importc: "fputs", header: "<stdio.h>", tags: [WriteIOEffect].}
  22. proc c_fgets(c: cstring, n: cint, f: File): cstring {.
  23. importc: "fgets", header: "<stdio.h>", tags: [ReadIOEffect].}
  24. proc c_fgetc(stream: File): cint {.
  25. importc: "fgetc", header: "<stdio.h>", tags: [ReadIOEffect].}
  26. proc c_ungetc(c: cint, f: File): cint {.
  27. importc: "ungetc", header: "<stdio.h>", tags: [].}
  28. proc c_putc(c: cint, stream: File): cint {.
  29. importc: "putc", header: "<stdio.h>", tags: [WriteIOEffect].}
  30. proc c_fflush(f: File): cint {.
  31. importc: "fflush", header: "<stdio.h>".}
  32. proc c_fclose(f: File): cint {.
  33. importc: "fclose", header: "<stdio.h>".}
  34. proc c_clearerr(f: File) {.
  35. importc: "clearerr", header: "<stdio.h>".}
  36. proc c_feof(f: File): cint {.
  37. importc: "feof", header: "<stdio.h>".}
  38. when not declared(c_fwrite):
  39. proc c_fwrite(buf: pointer, size, n: csize, f: File): cint {.
  40. importc: "fwrite", header: "<stdio.h>".}
  41. # C routine that is used here:
  42. proc c_fread(buf: pointer, size, n: csize, f: File): csize {.
  43. importc: "fread", header: "<stdio.h>", tags: [ReadIOEffect].}
  44. when defined(windows):
  45. when not defined(amd64):
  46. proc c_fseek(f: File, offset: int64, whence: cint): cint {.
  47. importc: "fseek", header: "<stdio.h>", tags: [].}
  48. proc c_ftell(f: File): int64 {.
  49. importc: "ftell", header: "<stdio.h>", tags: [].}
  50. else:
  51. proc c_fseek(f: File, offset: int64, whence: cint): cint {.
  52. importc: "_fseeki64", header: "<stdio.h>", tags: [].}
  53. proc c_ftell(f: File): int64 {.
  54. importc: "_ftelli64", header: "<stdio.h>", tags: [].}
  55. else:
  56. proc c_fseek(f: File, offset: int64, whence: cint): cint {.
  57. importc: "fseeko", header: "<stdio.h>", tags: [].}
  58. proc c_ftell(f: File): int64 {.
  59. importc: "ftello", header: "<stdio.h>", tags: [].}
  60. proc c_ferror(f: File): cint {.
  61. importc: "ferror", header: "<stdio.h>", tags: [].}
  62. proc c_setvbuf(f: File, buf: pointer, mode: cint, size: csize): cint {.
  63. importc: "setvbuf", header: "<stdio.h>", tags: [].}
  64. proc raiseEIO(msg: string) {.noinline, noreturn.} =
  65. sysFatal(IOError, msg)
  66. proc raiseEOF() {.noinline, noreturn.} =
  67. sysFatal(EOFError, "EOF reached")
  68. proc checkErr(f: File) =
  69. if c_ferror(f) != 0:
  70. c_clearerr(f)
  71. raiseEIO("Unknown IO Error")
  72. {.push stackTrace:off, profiler:off.}
  73. proc readBuffer(f: File, buffer: pointer, len: Natural): int =
  74. result = c_fread(buffer, 1, len, f)
  75. if result != len: checkErr(f)
  76. proc readBytes(f: File, a: var openArray[int8|uint8], start, len: Natural): int =
  77. result = readBuffer(f, addr(a[start]), len)
  78. proc readChars(f: File, a: var openArray[char], start, len: Natural): int =
  79. if (start + len) > len(a):
  80. raiseEIO("buffer overflow: (start+len) > length of openarray buffer")
  81. result = readBuffer(f, addr(a[start]), len)
  82. proc write(f: File, c: cstring) =
  83. discard c_fputs(c, f)
  84. checkErr(f)
  85. proc writeBuffer(f: File, buffer: pointer, len: Natural): int =
  86. result = c_fwrite(buffer, 1, len, f)
  87. checkErr(f)
  88. proc writeBytes(f: File, a: openArray[int8|uint8], start, len: Natural): int =
  89. var x = cast[ptr UncheckedArray[int8]](a)
  90. result = writeBuffer(f, addr(x[int(start)]), len)
  91. proc writeChars(f: File, a: openArray[char], start, len: Natural): int =
  92. var x = cast[ptr UncheckedArray[int8]](a)
  93. result = writeBuffer(f, addr(x[int(start)]), len)
  94. proc write(f: File, s: string) =
  95. if writeBuffer(f, cstring(s), s.len) != s.len:
  96. raiseEIO("cannot write string to file")
  97. {.pop.}
  98. when NoFakeVars:
  99. when defined(windows):
  100. const
  101. IOFBF = cint(0)
  102. IONBF = cint(4)
  103. else:
  104. # On all systems I could find, including Linux, Mac OS X, and the BSDs
  105. const
  106. IOFBF = cint(0)
  107. IONBF = cint(2)
  108. else:
  109. var
  110. IOFBF {.importc: "_IOFBF", nodecl.}: cint
  111. IONBF {.importc: "_IONBF", nodecl.}: cint
  112. const
  113. BufSize = 4000
  114. proc close*(f: File) =
  115. if not f.isNil:
  116. discard c_fclose(f)
  117. proc readChar(f: File): char =
  118. let x = c_fgetc(f)
  119. if x < 0:
  120. checkErr(f)
  121. raiseEOF()
  122. result = char(x)
  123. proc flushFile*(f: File) = discard c_fflush(f)
  124. proc getFileHandle*(f: File): FileHandle = c_fileno(f)
  125. proc readLine(f: File, line: var TaintedString): bool =
  126. var pos = 0
  127. # Use the currently reserved space for a first try
  128. var sp = max(line.string.len, 80)
  129. line.string.setLen(sp)
  130. while true:
  131. # memset to \L so that we can tell how far fgets wrote, even on EOF, where
  132. # fgets doesn't append an \L
  133. nimSetMem(addr line.string[pos], '\L'.ord, sp)
  134. var fgetsSuccess = c_fgets(addr line.string[pos], sp.cint, f) != nil
  135. if not fgetsSuccess: checkErr(f)
  136. let m = c_memchr(addr line.string[pos], '\L'.ord, sp)
  137. if m != nil:
  138. # \l found: Could be our own or the one by fgets, in any case, we're done
  139. var last = cast[ByteAddress](m) - cast[ByteAddress](addr line.string[0])
  140. if last > 0 and line.string[last-1] == '\c':
  141. line.string.setLen(last-1)
  142. return last > 1 or fgetsSuccess
  143. # We have to distinguish between two possible cases:
  144. # \0\l\0 => line ending in a null character.
  145. # \0\l\l => last line without newline, null was put there by fgets.
  146. elif last > 0 and line.string[last-1] == '\0':
  147. if last < pos + sp - 1 and line.string[last+1] != '\0':
  148. dec last
  149. line.string.setLen(last)
  150. return last > 0 or fgetsSuccess
  151. else:
  152. # fgets will have inserted a null byte at the end of the string.
  153. dec sp
  154. # No \l found: Increase buffer and read more
  155. inc pos, sp
  156. sp = 128 # read in 128 bytes at a time
  157. line.string.setLen(pos+sp)
  158. proc readLine(f: File): TaintedString =
  159. result = TaintedString(newStringOfCap(80))
  160. if not readLine(f, result): raiseEOF()
  161. proc write(f: File, i: int) =
  162. when sizeof(int) == 8:
  163. if c_fprintf(f, "%lld", i) < 0: checkErr(f)
  164. else:
  165. if c_fprintf(f, "%ld", i) < 0: checkErr(f)
  166. proc write(f: File, i: BiggestInt) =
  167. when sizeof(BiggestInt) == 8:
  168. if c_fprintf(f, "%lld", i) < 0: checkErr(f)
  169. else:
  170. if c_fprintf(f, "%ld", i) < 0: checkErr(f)
  171. proc write(f: File, b: bool) =
  172. if b: write(f, "true")
  173. else: write(f, "false")
  174. proc write(f: File, r: float32) =
  175. if c_fprintf(f, "%.16g", r) < 0: checkErr(f)
  176. proc write(f: File, r: BiggestFloat) =
  177. if c_fprintf(f, "%.16g", r) < 0: checkErr(f)
  178. proc write(f: File, c: char) = discard c_putc(cint(c), f)
  179. proc write(f: File, a: varargs[string, `$`]) =
  180. for x in items(a): write(f, x)
  181. proc readAllBuffer(file: File): string =
  182. # This proc is for File we want to read but don't know how many
  183. # bytes we need to read before the buffer is empty.
  184. result = ""
  185. var buffer = newString(BufSize)
  186. while true:
  187. var bytesRead = readBuffer(file, addr(buffer[0]), BufSize)
  188. if bytesRead == BufSize:
  189. result.add(buffer)
  190. else:
  191. buffer.setLen(bytesRead)
  192. result.add(buffer)
  193. break
  194. proc rawFileSize(file: File): int64 =
  195. # this does not raise an error opposed to `getFileSize`
  196. var oldPos = c_ftell(file)
  197. discard c_fseek(file, 0, 2) # seek the end of the file
  198. result = c_ftell(file)
  199. discard c_fseek(file, oldPos, 0)
  200. proc endOfFile(f: File): bool =
  201. var c = c_fgetc(f)
  202. discard c_ungetc(c, f)
  203. return c < 0'i32
  204. #result = c_feof(f) != 0
  205. proc readAllFile(file: File, len: int64): string =
  206. # We acquire the filesize beforehand and hope it doesn't change.
  207. # Speeds things up.
  208. result = newString(len)
  209. let bytes = readBuffer(file, addr(result[0]), len)
  210. if endOfFile(file):
  211. if bytes < len:
  212. result.setLen(bytes)
  213. else:
  214. # We read all the bytes but did not reach the EOF
  215. # Try to read it as a buffer
  216. result.add(readAllBuffer(file))
  217. proc readAllFile(file: File): string =
  218. var len = rawFileSize(file)
  219. result = readAllFile(file, len)
  220. proc readAll(file: File): TaintedString =
  221. # Separate handling needed because we need to buffer when we
  222. # don't know the overall length of the File.
  223. when declared(stdin):
  224. let len = if file != stdin: rawFileSize(file) else: -1
  225. else:
  226. let len = rawFileSize(file)
  227. if len > 0:
  228. result = readAllFile(file, len).TaintedString
  229. else:
  230. result = readAllBuffer(file).TaintedString
  231. proc writeLn[Ty](f: File, x: varargs[Ty, `$`]) =
  232. for i in items(x):
  233. write(f, i)
  234. write(f, "\n")
  235. proc writeLine[Ty](f: File, x: varargs[Ty, `$`]) =
  236. for i in items(x):
  237. write(f, i)
  238. write(f, "\n")
  239. when declared(stdout):
  240. proc rawEcho(x: string) {.inline, compilerproc.} = write(stdout, x)
  241. proc rawEchoNL() {.inline, compilerproc.} = write(stdout, "\n")
  242. # interface to the C procs:
  243. include "system/widestrs"
  244. when defined(windows) and not defined(useWinAnsi):
  245. when defined(cpp):
  246. proc wfopen(filename, mode: WideCString): pointer {.
  247. importcpp: "_wfopen((const wchar_t*)#, (const wchar_t*)#)", nodecl.}
  248. proc wfreopen(filename, mode: WideCString, stream: File): File {.
  249. importcpp: "_wfreopen((const wchar_t*)#, (const wchar_t*)#, #)", nodecl.}
  250. else:
  251. proc wfopen(filename, mode: WideCString): pointer {.
  252. importc: "_wfopen", nodecl.}
  253. proc wfreopen(filename, mode: WideCString, stream: File): File {.
  254. importc: "_wfreopen", nodecl.}
  255. proc fopen(filename, mode: cstring): pointer =
  256. var f = newWideCString(filename)
  257. var m = newWideCString(mode)
  258. result = wfopen(f, m)
  259. proc freopen(filename, mode: cstring, stream: File): File =
  260. var f = newWideCString(filename)
  261. var m = newWideCString(mode)
  262. result = wfreopen(f, m, stream)
  263. else:
  264. proc fopen(filename, mode: cstring): pointer {.importc: "fopen", noDecl.}
  265. proc freopen(filename, mode: cstring, stream: File): File {.
  266. importc: "freopen", nodecl.}
  267. const
  268. FormatOpen: array[FileMode, string] = ["rb", "wb", "w+b", "r+b", "ab"]
  269. #"rt", "wt", "w+t", "r+t", "at"
  270. # we always use binary here as for Nim the OS line ending
  271. # should not be translated.
  272. when defined(posix) and not defined(nimscript):
  273. when defined(linux) and defined(amd64):
  274. type
  275. Mode {.importc: "mode_t", header: "<sys/types.h>".} = cint
  276. # fillers ensure correct size & offsets
  277. Stat {.importc: "struct stat",
  278. header: "<sys/stat.h>", final, pure.} = object ## struct stat
  279. filler_1: array[24, char]
  280. st_mode: Mode ## Mode of file
  281. filler_2: array[144 - 24 - 4, char]
  282. proc S_ISDIR(m: Mode): bool =
  283. ## Test for a directory.
  284. (m and 0o170000) == 0o40000
  285. else:
  286. type
  287. Mode {.importc: "mode_t", header: "<sys/types.h>".} = cint
  288. Stat {.importc: "struct stat",
  289. header: "<sys/stat.h>", final, pure.} = object ## struct stat
  290. st_mode: Mode ## Mode of file
  291. proc S_ISDIR(m: Mode): bool {.importc, header: "<sys/stat.h>".}
  292. ## Test for a directory.
  293. proc c_fstat(a1: cint, a2: var Stat): cint {.
  294. importc: "fstat", header: "<sys/stat.h>".}
  295. proc open(f: var File, filename: string,
  296. mode: FileMode = fmRead,
  297. bufSize: int = -1): bool =
  298. var p: pointer = fopen(filename, FormatOpen[mode])
  299. if p != nil:
  300. when defined(posix) and not defined(nimscript):
  301. # How `fopen` handles opening a directory is not specified in ISO C and
  302. # POSIX. We do not want to handle directories as regular files that can
  303. # be opened.
  304. var f2 = cast[File](p)
  305. var res: Stat
  306. if c_fstat(getFileHandle(f2), res) >= 0'i32 and S_ISDIR(res.st_mode):
  307. close(f2)
  308. return false
  309. result = true
  310. f = cast[File](p)
  311. if bufSize > 0 and bufSize <= high(cint).int:
  312. discard c_setvbuf(f, nil, IOFBF, bufSize.cint)
  313. elif bufSize == 0:
  314. discard c_setvbuf(f, nil, IONBF, 0)
  315. proc reopen(f: File, filename: string, mode: FileMode = fmRead): bool =
  316. var p: pointer = freopen(filename, FormatOpen[mode], f)
  317. result = p != nil
  318. proc open(f: var File, filehandle: FileHandle, mode: FileMode): bool =
  319. f = c_fdopen(filehandle, FormatOpen[mode])
  320. result = f != nil
  321. proc setFilePos(f: File, pos: int64, relativeTo: FileSeekPos = fspSet) =
  322. if c_fseek(f, pos, cint(relativeTo)) != 0:
  323. raiseEIO("cannot set file position")
  324. proc getFilePos(f: File): int64 =
  325. result = c_ftell(f)
  326. if result < 0: raiseEIO("cannot retrieve file position")
  327. proc getFileSize(f: File): int64 =
  328. var oldPos = getFilePos(f)
  329. discard c_fseek(f, 0, 2) # seek the end of the file
  330. result = getFilePos(f)
  331. setFilePos(f, oldPos)
  332. proc readFile(filename: string): TaintedString =
  333. var f: File
  334. if open(f, filename):
  335. try:
  336. result = readAll(f).TaintedString
  337. finally:
  338. close(f)
  339. else:
  340. sysFatal(IOError, "cannot open: ", filename)
  341. proc writeFile(filename, content: string) =
  342. var f: File
  343. if open(f, filename, fmWrite):
  344. try:
  345. f.write(content)
  346. finally:
  347. close(f)
  348. else:
  349. sysFatal(IOError, "cannot open: ", filename)
  350. proc setStdIoUnbuffered() =
  351. when declared(stdout):
  352. discard c_setvbuf(stdout, nil, IONBF, 0)
  353. when declared(stderr):
  354. discard c_setvbuf(stderr, nil, IONBF, 0)
  355. when declared(stdin):
  356. discard c_setvbuf(stdin, nil, IONBF, 0)
  357. when declared(stdout):
  358. when defined(windows) and compileOption("threads"):
  359. var echoLock: SysLock
  360. initSysLock echoLock
  361. proc echoBinSafe(args: openArray[string]) {.compilerProc.} =
  362. # flockfile deadlocks some versions of Android 5.x.x
  363. when not defined(windows) and not defined(android) and not defined(nintendoswitch):
  364. proc flockfile(f: File) {.importc, noDecl.}
  365. proc funlockfile(f: File) {.importc, noDecl.}
  366. flockfile(stdout)
  367. when defined(windows) and compileOption("threads"):
  368. acquireSys echoLock
  369. for s in args:
  370. discard c_fwrite(s.cstring, s.len, 1, stdout)
  371. const linefeed = "\n" # can be 1 or more chars
  372. discard c_fwrite(linefeed.cstring, linefeed.len, 1, stdout)
  373. discard c_fflush(stdout)
  374. when not defined(windows) and not defined(android) and not defined(nintendoswitch):
  375. funlockfile(stdout)
  376. when defined(windows) and compileOption("threads"):
  377. releaseSys echoLock
  378. {.pop.}