strports.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. /* Copyright (C) 1995,1996,1998,1999,2000,2001,2002, 2003, 2005, 2006, 2009, 2010, 2011 Free Software Foundation, Inc.
  2. *
  3. * This library is free software; you can redistribute it and/or
  4. * modify it under the terms of the GNU Lesser General Public License
  5. * as published by the Free Software Foundation; either version 3 of
  6. * the License, or (at your option) any later version.
  7. *
  8. * This library is distributed in the hope that it will be useful, but
  9. * WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. * Lesser General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Lesser General Public
  14. * License along with this library; if not, write to the Free Software
  15. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. * 02110-1301 USA
  17. */
  18. #ifdef HAVE_CONFIG_H
  19. # include <config.h>
  20. #endif
  21. #include "libguile/_scm.h"
  22. #include <stdio.h>
  23. #ifdef HAVE_UNISTD_H
  24. #include <unistd.h>
  25. #endif
  26. #include "libguile/bytevectors.h"
  27. #include "libguile/eval.h"
  28. #include "libguile/ports.h"
  29. #include "libguile/read.h"
  30. #include "libguile/root.h"
  31. #include "libguile/strings.h"
  32. #include "libguile/modules.h"
  33. #include "libguile/validate.h"
  34. #include "libguile/deprecation.h"
  35. #include "libguile/srfi-4.h"
  36. #include "libguile/strports.h"
  37. #ifdef HAVE_STRING_H
  38. #include <string.h>
  39. #endif
  40. /* {Ports - string ports}
  41. *
  42. */
  43. /* NOTES:
  44. write_buf/write_end point to the ends of the allocated bytevector.
  45. read_buf/read_end in principle point to the part of the bytevector which
  46. has been written to, but this is only updated after a flush.
  47. read_pos and write_pos in principle should be equal, but this is only true
  48. when rw_active is SCM_PORT_NEITHER.
  49. ENHANCE-ME - output blocks:
  50. The current code keeps an output string as a single block. That means
  51. when the size is increased the entire old contents must be copied. It'd
  52. be more efficient to begin a new block when the old one is full, so
  53. there's no re-copying of previous data.
  54. To make seeking efficient, keeping the pieces in a vector might be best,
  55. though appending is probably the most common operation. The size of each
  56. block could be progressively increased, so the bigger the string the
  57. bigger the blocks.
  58. When `get-output-string' is called the blocks have to be coalesced into a
  59. string, the result could be kept as a single big block. If blocks were
  60. strings then `get-output-string' could notice when there's just one and
  61. return that with a copy-on-write (though repeated calls to
  62. `get-output-string' are probably unlikely).
  63. Another possibility would be to extend the port mechanism to let SCM
  64. strings come through directly from `display' and friends. That way if a
  65. big string is written it can be kept as a copy-on-write, saving time
  66. copying and maybe saving some space. */
  67. scm_t_bits scm_tc16_strport;
  68. static int
  69. stfill_buffer (SCM port)
  70. {
  71. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  72. if (pt->read_pos >= pt->read_end)
  73. return EOF;
  74. else
  75. return scm_return_first_int (*pt->read_pos, port);
  76. }
  77. /* Change the size of a port's bytevector to NEW_SIZE. This doesn't
  78. change `read_buf_size'. */
  79. static void
  80. st_resize_port (scm_t_port *pt, scm_t_off new_size)
  81. {
  82. SCM old_stream = SCM_PACK (pt->stream);
  83. const signed char *src = SCM_BYTEVECTOR_CONTENTS (old_stream);
  84. SCM new_stream = scm_c_make_bytevector (new_size);
  85. signed char *dst = SCM_BYTEVECTOR_CONTENTS (new_stream);
  86. unsigned long int old_size = SCM_BYTEVECTOR_LENGTH (old_stream);
  87. unsigned long int min_size = min (old_size, new_size);
  88. scm_t_off index = pt->write_pos - pt->write_buf;
  89. pt->write_buf_size = new_size;
  90. memcpy (dst, src, min_size);
  91. scm_remember_upto_here_1 (old_stream);
  92. /* reset buffer. */
  93. {
  94. pt->stream = SCM_UNPACK (new_stream);
  95. pt->read_buf = pt->write_buf = (unsigned char *)dst;
  96. pt->read_pos = pt->write_pos = pt->write_buf + index;
  97. pt->write_end = pt->write_buf + pt->write_buf_size;
  98. pt->read_end = pt->read_buf + pt->read_buf_size;
  99. }
  100. }
  101. /* Ensure that `write_pos' < `write_end' by enlarging the buffer when
  102. necessary. Update `read_buf' to account for written chars. The
  103. buffer is enlarged geometrically. */
  104. static void
  105. st_flush (SCM port)
  106. {
  107. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  108. if (pt->write_pos == pt->write_end)
  109. st_resize_port (pt, pt->write_buf_size * 2);
  110. pt->read_pos = pt->write_pos;
  111. if (pt->read_pos > pt->read_end)
  112. {
  113. pt->read_end = (unsigned char *) pt->read_pos;
  114. pt->read_buf_size = pt->read_end - pt->read_buf;
  115. }
  116. pt->rw_active = SCM_PORT_NEITHER;
  117. }
  118. static void
  119. st_write (SCM port, const void *data, size_t size)
  120. {
  121. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  122. const char *input = (char *) data;
  123. while (size > 0)
  124. {
  125. int space = pt->write_end - pt->write_pos;
  126. int write_len = (size > space) ? space : size;
  127. memcpy ((char *) pt->write_pos, input, write_len);
  128. pt->write_pos += write_len;
  129. size -= write_len;
  130. input += write_len;
  131. if (write_len == space)
  132. st_flush (port);
  133. }
  134. }
  135. static void
  136. st_end_input (SCM port, int offset)
  137. {
  138. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  139. if (pt->read_pos - pt->read_buf < offset)
  140. scm_misc_error ("st_end_input", "negative position", SCM_EOL);
  141. pt->write_pos = (unsigned char *) (pt->read_pos = pt->read_pos - offset);
  142. pt->rw_active = SCM_PORT_NEITHER;
  143. }
  144. static scm_t_off
  145. st_seek (SCM port, scm_t_off offset, int whence)
  146. {
  147. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  148. scm_t_off target;
  149. if (pt->rw_active == SCM_PORT_READ && offset == 0 && whence == SEEK_CUR)
  150. /* special case to avoid disturbing the unread-char buffer. */
  151. {
  152. if (pt->read_buf == pt->putback_buf)
  153. {
  154. target = pt->saved_read_pos - pt->saved_read_buf
  155. - (pt->read_end - pt->read_pos);
  156. }
  157. else
  158. {
  159. target = pt->read_pos - pt->read_buf;
  160. }
  161. }
  162. else
  163. /* all other cases. */
  164. {
  165. if (pt->rw_active == SCM_PORT_WRITE)
  166. st_flush (port);
  167. if (pt->rw_active == SCM_PORT_READ)
  168. scm_end_input (port);
  169. switch (whence)
  170. {
  171. case SEEK_CUR:
  172. target = pt->read_pos - pt->read_buf + offset;
  173. break;
  174. case SEEK_END:
  175. target = pt->read_end - pt->read_buf + offset;
  176. break;
  177. default: /* SEEK_SET */
  178. target = offset;
  179. break;
  180. }
  181. if (target < 0)
  182. scm_misc_error ("st_seek", "negative offset", SCM_EOL);
  183. if (target >= pt->write_buf_size)
  184. {
  185. if (!(SCM_CELL_WORD_0 (port) & SCM_WRTNG))
  186. {
  187. if (target > pt->write_buf_size)
  188. {
  189. scm_misc_error ("st_seek",
  190. "seek past end of read-only strport",
  191. SCM_EOL);
  192. }
  193. }
  194. else if (target == pt->write_buf_size)
  195. st_resize_port (pt, target * 2);
  196. }
  197. pt->read_pos = pt->write_pos = pt->read_buf + target;
  198. if (pt->read_pos > pt->read_end)
  199. {
  200. pt->read_end = (unsigned char *) pt->read_pos;
  201. pt->read_buf_size = pt->read_end - pt->read_buf;
  202. }
  203. }
  204. return target;
  205. }
  206. static void
  207. st_truncate (SCM port, scm_t_off length)
  208. {
  209. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  210. if (length > pt->write_buf_size)
  211. st_resize_port (pt, length);
  212. pt->read_buf_size = length;
  213. pt->read_end = pt->read_buf + length;
  214. if (pt->read_pos > pt->read_end)
  215. pt->read_pos = pt->read_end;
  216. if (pt->write_pos > pt->read_end)
  217. pt->write_pos = pt->read_end;
  218. }
  219. /* The initial size in bytes of a string port's buffer. */
  220. #define INITIAL_BUFFER_SIZE 128
  221. /* Return a new string port with MODES. If STR is #f, a new backing
  222. buffer is allocated; otherwise STR must be a string and a copy of it
  223. serves as the buffer for the new port. */
  224. SCM
  225. scm_mkstrport (SCM pos, SCM str, long modes, const char *caller)
  226. {
  227. SCM z, buf;
  228. scm_t_port *pt;
  229. size_t str_len, c_pos;
  230. char *c_buf;
  231. if (!((modes & SCM_WRTNG) || (modes & SCM_RDNG)))
  232. scm_misc_error ("scm_mkstrport", "port must read or write", SCM_EOL);
  233. scm_dynwind_begin (0);
  234. scm_i_dynwind_pthread_mutex_lock (&scm_i_port_table_mutex);
  235. z = scm_new_port_table_entry (scm_tc16_strport);
  236. pt = SCM_PTAB_ENTRY(z);
  237. if (scm_is_false (str))
  238. {
  239. /* Allocate a new buffer to write to. */
  240. str_len = INITIAL_BUFFER_SIZE;
  241. buf = scm_c_make_bytevector (str_len);
  242. c_buf = (char *) SCM_BYTEVECTOR_CONTENTS (buf);
  243. /* Reset `read_buf_size'. It will contain the actual number of
  244. bytes written to PT. */
  245. pt->read_buf_size = 0;
  246. c_pos = 0;
  247. }
  248. else
  249. {
  250. /* STR is a string. */
  251. char *copy;
  252. SCM_ASSERT (scm_is_string (str), str, SCM_ARG1, caller);
  253. /* Create a copy of STR in the encoding of PT. */
  254. copy = scm_to_stringn (str, &str_len, pt->encoding,
  255. SCM_FAILED_CONVERSION_ERROR);
  256. buf = scm_c_make_bytevector (str_len);
  257. c_buf = (char *) SCM_BYTEVECTOR_CONTENTS (buf);
  258. memcpy (c_buf, copy, str_len);
  259. free (copy);
  260. c_pos = scm_to_unsigned_integer (pos, 0, str_len);
  261. pt->read_buf_size = str_len;
  262. }
  263. SCM_SETSTREAM (z, SCM_UNPACK (buf));
  264. SCM_SET_CELL_TYPE (z, scm_tc16_strport | modes);
  265. pt->write_buf = pt->read_buf = (unsigned char *) c_buf;
  266. pt->read_pos = pt->write_pos = pt->read_buf + c_pos;
  267. pt->write_buf_size = str_len;
  268. pt->write_end = pt->read_end = pt->read_buf + pt->read_buf_size;
  269. pt->rw_random = 1;
  270. scm_dynwind_end ();
  271. /* Ensure WRITE_POS is writable. */
  272. if ((modes & SCM_WRTNG) && pt->write_pos == pt->write_end)
  273. st_flush (z);
  274. scm_i_set_conversion_strategy_x (z, SCM_FAILED_CONVERSION_ERROR);
  275. return z;
  276. }
  277. /* Create a new string from the buffer of PORT, a string port, converting from
  278. PORT's encoding to the standard string representation. */
  279. SCM
  280. scm_strport_to_string (SCM port)
  281. {
  282. SCM str;
  283. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  284. if (pt->rw_active == SCM_PORT_WRITE)
  285. st_flush (port);
  286. if (pt->read_buf_size == 0)
  287. return scm_nullstr;
  288. if (pt->encoding == NULL)
  289. {
  290. char *buf;
  291. str = scm_i_make_string (pt->read_buf_size, &buf, 0);
  292. memcpy (buf, pt->read_buf, pt->read_buf_size);
  293. }
  294. else
  295. str = scm_from_stringn ((char *)pt->read_buf, pt->read_buf_size,
  296. pt->encoding, pt->ilseq_handler);
  297. scm_remember_upto_here_1 (port);
  298. return str;
  299. }
  300. SCM_DEFINE (scm_object_to_string, "object->string", 1, 1, 0,
  301. (SCM obj, SCM printer),
  302. "Return a Scheme string obtained by printing @var{obj}.\n"
  303. "Printing function can be specified by the optional second\n"
  304. "argument @var{printer} (default: @code{write}).")
  305. #define FUNC_NAME s_scm_object_to_string
  306. {
  307. SCM port, result;
  308. if (!SCM_UNBNDP (printer))
  309. SCM_VALIDATE_PROC (2, printer);
  310. port = scm_mkstrport (SCM_INUM0, SCM_BOOL_F,
  311. SCM_OPN | SCM_WRTNG, FUNC_NAME);
  312. if (SCM_UNBNDP (printer))
  313. scm_write (obj, port);
  314. else
  315. scm_call_2 (printer, obj, port);
  316. result = scm_strport_to_string (port);
  317. /* Explicitly close PORT so that the iconv CDs associated with it are
  318. deallocated right away. This is important because CDs use a lot of
  319. memory that's not visible to the GC, so not freeing them can lead
  320. to almost large heap usage. See
  321. <http://wingolog.org/archives/2011/02/25/ports-weaks-gc-and-dark-matter>
  322. for details. */
  323. scm_close_port (port);
  324. return result;
  325. }
  326. #undef FUNC_NAME
  327. SCM_DEFINE (scm_call_with_output_string, "call-with-output-string", 1, 0, 0,
  328. (SCM proc),
  329. "Calls the one-argument procedure @var{proc} with a newly created output\n"
  330. "port. When the function returns, the string composed of the characters\n"
  331. "written into the port is returned.")
  332. #define FUNC_NAME s_scm_call_with_output_string
  333. {
  334. SCM p;
  335. p = scm_mkstrport (SCM_INUM0, SCM_BOOL_F,
  336. SCM_OPN | SCM_WRTNG,
  337. FUNC_NAME);
  338. scm_call_1 (proc, p);
  339. return scm_get_output_string (p);
  340. }
  341. #undef FUNC_NAME
  342. SCM_DEFINE (scm_call_with_input_string, "call-with-input-string", 2, 0, 0,
  343. (SCM string, SCM proc),
  344. "Calls the one-argument procedure @var{proc} with a newly\n"
  345. "created input port from which @var{string}'s contents may be\n"
  346. "read. The value yielded by the @var{proc} is returned.")
  347. #define FUNC_NAME s_scm_call_with_input_string
  348. {
  349. SCM p = scm_mkstrport(SCM_INUM0, string, SCM_OPN | SCM_RDNG, FUNC_NAME);
  350. return scm_call_1 (proc, p);
  351. }
  352. #undef FUNC_NAME
  353. SCM_DEFINE (scm_open_input_string, "open-input-string", 1, 0, 0,
  354. (SCM str),
  355. "Take a string and return an input port that delivers characters\n"
  356. "from the string. The port can be closed by\n"
  357. "@code{close-input-port}, though its storage will be reclaimed\n"
  358. "by the garbage collector if it becomes inaccessible.")
  359. #define FUNC_NAME s_scm_open_input_string
  360. {
  361. SCM p = scm_mkstrport(SCM_INUM0, str, SCM_OPN | SCM_RDNG, FUNC_NAME);
  362. return p;
  363. }
  364. #undef FUNC_NAME
  365. SCM_DEFINE (scm_open_output_string, "open-output-string", 0, 0, 0,
  366. (void),
  367. "Return an output port that will accumulate characters for\n"
  368. "retrieval by @code{get-output-string}. The port can be closed\n"
  369. "by the procedure @code{close-output-port}, though its storage\n"
  370. "will be reclaimed by the garbage collector if it becomes\n"
  371. "inaccessible.")
  372. #define FUNC_NAME s_scm_open_output_string
  373. {
  374. SCM p;
  375. p = scm_mkstrport (SCM_INUM0, SCM_BOOL_F,
  376. SCM_OPN | SCM_WRTNG,
  377. FUNC_NAME);
  378. return p;
  379. }
  380. #undef FUNC_NAME
  381. SCM_DEFINE (scm_get_output_string, "get-output-string", 1, 0, 0,
  382. (SCM port),
  383. "Given an output port created by @code{open-output-string},\n"
  384. "return a string consisting of the characters that have been\n"
  385. "output to the port so far.")
  386. #define FUNC_NAME s_scm_get_output_string
  387. {
  388. SCM_VALIDATE_OPOUTSTRPORT (1, port);
  389. return scm_strport_to_string (port);
  390. }
  391. #undef FUNC_NAME
  392. /* Given a null-terminated string EXPR containing a Scheme expression
  393. read it, and return it as an SCM value. */
  394. SCM
  395. scm_c_read_string (const char *expr)
  396. {
  397. SCM port = scm_mkstrport (SCM_INUM0,
  398. scm_from_locale_string (expr),
  399. SCM_OPN | SCM_RDNG,
  400. "scm_c_read_string");
  401. SCM form;
  402. form = scm_read (port);
  403. scm_close_port (port);
  404. return form;
  405. }
  406. /* Given a null-terminated string EXPR containing Scheme program text,
  407. evaluate it, and return the result of the last expression evaluated. */
  408. SCM
  409. scm_c_eval_string (const char *expr)
  410. {
  411. return scm_eval_string (scm_from_locale_string (expr));
  412. }
  413. SCM
  414. scm_c_eval_string_in_module (const char *expr, SCM module)
  415. {
  416. return scm_eval_string_in_module (scm_from_locale_string (expr), module);
  417. }
  418. SCM_DEFINE (scm_eval_string_in_module, "eval-string", 1, 1, 0,
  419. (SCM string, SCM module),
  420. "Evaluate @var{string} as the text representation of a Scheme\n"
  421. "form or forms, and return whatever value they produce.\n"
  422. "Evaluation takes place in the given module, or the current\n"
  423. "module when no module is given.\n"
  424. "While the code is evaluated, the given module is made the\n"
  425. "current one. The current module is restored when this\n"
  426. "procedure returns.")
  427. #define FUNC_NAME s_scm_eval_string_in_module
  428. {
  429. static SCM eval_string = SCM_BOOL_F, k_module = SCM_BOOL_F;
  430. if (scm_is_false (eval_string))
  431. {
  432. eval_string = scm_c_public_lookup ("ice-9 eval-string", "eval-string");
  433. k_module = scm_from_locale_keyword ("module");
  434. }
  435. if (SCM_UNBNDP (module))
  436. module = scm_current_module ();
  437. else
  438. SCM_VALIDATE_MODULE (2, module);
  439. return scm_call_3 (scm_variable_ref (eval_string), string, k_module, module);
  440. }
  441. #undef FUNC_NAME
  442. SCM
  443. scm_eval_string (SCM string)
  444. {
  445. return scm_eval_string_in_module (string, SCM_UNDEFINED);
  446. }
  447. static scm_t_bits
  448. scm_make_stptob ()
  449. {
  450. scm_t_bits tc = scm_make_port_type ("string", stfill_buffer, st_write);
  451. scm_set_port_end_input (tc, st_end_input);
  452. scm_set_port_flush (tc, st_flush);
  453. scm_set_port_seek (tc, st_seek);
  454. scm_set_port_truncate (tc, st_truncate);
  455. return tc;
  456. }
  457. void
  458. scm_init_strports ()
  459. {
  460. scm_tc16_strport = scm_make_stptob ();
  461. #include "libguile/strports.x"
  462. }
  463. /*
  464. Local Variables:
  465. c-file-style: "gnu"
  466. End:
  467. */