PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
stringinfo.c File Reference
#include "postgres.h"
#include "lib/stringinfo.h"
#include "utils/memutils.h"
Include dependency graph for stringinfo.c:

Go to the source code of this file.

Functions

StringInfo makeStringInfo (void)
 
void initStringInfo (StringInfo str)
 
void resetStringInfo (StringInfo str)
 
void appendStringInfo (StringInfo str, const char *fmt,...)
 
int appendStringInfoVA (StringInfo str, const char *fmt, va_list args)
 
void appendStringInfoString (StringInfo str, const char *s)
 
void appendStringInfoChar (StringInfo str, char ch)
 
void appendStringInfoSpaces (StringInfo str, int count)
 
void appendBinaryStringInfo (StringInfo str, const char *data, int datalen)
 
void enlargeStringInfo (StringInfo str, int needed)
 

Function Documentation

void appendBinaryStringInfo ( StringInfo  str,
const char *  data,
int  datalen 
)

Definition at line 208 of file stringinfo.c.

References Assert, StringInfoData::data, enlargeStringInfo(), StringInfoData::len, and NULL.

Referenced by add_indent(), appendStringInfoRegexpSubstr(), appendStringInfoString(), appendStringInfoText(), buf_add_txid(), buf_init(), bytea_string_agg_transfn(), config_enum_get_options(), CopyReadLine(), CopyReadLineText(), CopySendData(), CopySendString(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), GetOldFunctionMessage(), HandleParallelMessages(), hstore_to_json(), hstore_to_json_loose(), hstore_to_jsonb_loose(), int8_avg_deserialize(), json_lex_string(), jsonb_put_escaped_value(), JsonbToCStringWorker(), log_line_prefix(), map_sql_identifier_to_xml_name(), map_xml_name_to_sql_identifier(), numeric_avg_deserialize(), numeric_deserialize(), numeric_poly_deserialize(), parse_fcall_arguments(), parse_fcall_arguments_20(), pg_decode_message(), plpgsql_append_source_text(), pq_getstring(), pq_sendbytes(), pq_sendcountedtext(), pq_sendfloat4(), pq_sendint(), pq_sendint64(), pq_sendstring(), pq_sendtext(), process_pipe_input(), range_recv(), replace_text(), replace_text_regexp(), TQSendRecordInfo(), unaccent_lexize(), write_csvlog(), XLogInsertRecord(), and XLogWalRcvProcessMsg().

209 {
210  Assert(str != NULL);
211 
212  /* Make more room if needed */
213  enlargeStringInfo(str, datalen);
214 
215  /* OK, append the data */
216  memcpy(str->data + str->len, data, datalen);
217  str->len += datalen;
218 
219  /*
220  * Keep a trailing null in place, even though it's probably useless for
221  * binary data. (Some callers are dealing with text but call this because
222  * their input isn't null-terminated.)
223  */
224  str->data[str->len] = '\0';
225 }
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:245
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
void appendStringInfo ( StringInfo  str,
const char *  fmt,
  ... 
)

Definition at line 78 of file stringinfo.c.

References appendStringInfoVA(), generate_unaccent_rules::args, and enlargeStringInfo().

Referenced by _outAgg(), _outConstraint(), _outForeignKeyCacheInfo(), _outForeignKeyOptInfo(), _outGatherMerge(), _outGroup(), _outList(), _outMergeAppend(), _outMergeJoin(), _outPathTarget(), _outRecursiveUnion(), _outSetOp(), _outSort(), _outUnique(), _outValue(), _outWindowAgg(), appendFunctionName(), array_to_text_internal(), bqarr_in(), brin_desc(), btree_desc(), build_tuplestore_recursively(), BuildIndexValueDescription(), checkSharedDependencies(), clog_desc(), commit_ts_desc(), ConvertTriggerToFK(), copy_table(), create_cursor(), database_to_xml_internal(), datum_to_json(), dbase_desc(), dblink_close(), dblink_fdw_validator(), dblink_fetch(), dblink_open(), DeadLockReport(), decompile_column_index_array(), deparseAnalyzeSizeSql(), deparseArrayExpr(), deparseBoolExpr(), deparseColumnRef(), deparseConst(), deparseFromExprForRel(), deparseFuncExpr(), deparseInsertSql(), deparseLockingClause(), deparseOperatorName(), deparseRangeTblRef(), deparseRelabelType(), deparseRelation(), deparseScalarArrayOpExpr(), deparseUpdateSql(), deparseVar(), desc_recompress_leaf(), DescribeLockTag(), do_pg_start_backup(), DropSubscription(), errdetail_params(), escape_json(), ExecBuildSlotPartitionKeyDescription(), ExecEvalXmlExpr(), execute_extension_script(), ExplainIndexScanDetails(), ExplainNode(), ExplainOnePlan(), ExplainOpenGroup(), ExplainProperty(), ExplainPropertyList(), ExplainTargetRel(), ExportSnapshot(), fetch_remote_table_info(), file_fdw_validator(), flatten_reloptions(), flatten_set_variable_args(), foreign_grouping_ok(), foreign_join_ok(), format_expr_params(), format_node_dump(), format_operator_internal(), format_preparedparamsdata(), format_procedure_internal(), FreePageManagerDump(), FreePageManagerDumpBtree(), FreePageManagerDumpSpans(), fsm_page_contents(), funcname_signature_string(), generate_operator_name(), generic_desc(), get_agg_expr(), get_coercion_expr(), get_connect_string(), get_const_collation(), get_const_expr(), get_delete_query_def(), get_from_clause_coldeflist(), get_from_clause_item(), get_func_expr(), get_insert_query_def(), get_opclass_name(), get_oper_expr(), get_parameter(), get_rule_expr(), get_rule_expr_funccall(), get_rule_orderby(), get_rule_sortgroupclause(), get_rule_windowclause(), get_select_query_def(), get_sql_delete(), get_sql_insert(), get_sql_update(), get_sublink_expr(), get_tablefunc(), get_tablesample_def(), get_target_list(), get_tuple_of_interest(), get_update_query_def(), get_utility_query_def(), get_variable(), get_windowfunc_expr(), getObjectDescription(), getObjectIdentityParts(), getOpFamilyDescription(), getOpFamilyIdentity(), getRelationDescription(), gin_desc(), hash_desc(), heap2_desc(), heap_desc(), incompatible_module_error(), initialize_worker_spi(), KnownAssignedXidsDisplay(), lazy_scan_heap(), lazy_vacuum_rel(), libpqrcv_create_slot(), libpqrcv_startstreaming(), log_line_prefix(), logicalmsg_desc(), make_ruledef(), make_temptable_name_n(), map_multipart_sql_identifier_to_xml_name(), map_sql_catalog_to_xmlschema_types(), map_sql_identifier_to_xml_name(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), map_sql_type_to_xmlschema_type(), map_sql_typecoll_to_xmlschema_types(), multixact_desc(), mv_GenerateOper(), mxid_to_string(), op_signature_string(), out_gistxlogPageSplit(), out_member(), outBitmapset(), outDatum(), pair_encode(), pg_decode_commit_txn(), pg_decode_message(), pg_dependencies_out(), pg_get_constraintdef_worker(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_partkeydef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_ndistinct_out(), pg_output_begin(), pgp_armor_encode(), PLy_traceback(), populate_array_report_expected_array(), postgres_fdw_validator(), postgresAcquireSampleRowsFunc(), postgresGetForeignRelSize(), postgresImportForeignSchema(), postgresql_fdw_validator(), pretty_format_node_dump(), print_function_arguments(), print_function_trftypes(), print_literal(), printRemoteParam(), printRemotePlaceholder(), processIndirection(), ProcSleep(), query_to_xml_internal(), quote_object_name(), quote_qualified_identifier(), refresh_by_match_merge(), relmap_desc(), replorigin_desc(), report_triggers(), reportDependentObjects(), ri_add_cast_to(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_Initial_Check(), ri_restrict_del(), ri_restrict_upd(), schema_get_xml_visible_tables(), schema_to_xml_internal(), send_message_to_frontend(), send_message_to_server_log(), sepgsql_attribute_post_create(), sepgsql_audit_log(), sepgsql_database_post_create(), sepgsql_proc_post_create(), sepgsql_relation_post_create(), sepgsql_schema_post_create(), seq_desc(), serialize_deflist(), show_buffer_usage(), show_hash_info(), show_sort_info(), show_sortorder_options(), show_tablesample(), show_tidbitmap_info(), ShowTransactionStateRec(), ShowUsage(), smgr_desc(), spg_desc(), SPI_sql_row_to_xmlelement(), standby_desc(), standby_desc_invalidations(), standby_desc_running_xacts(), StartupXLOG(), storeObjectDescription(), table_to_xml_internal(), tblspc_desc(), tuple_to_stringinfo(), txid_snapshot_out(), typeStringToTypeName(), write_csvlog(), xact_desc(), xact_desc_abort(), xact_desc_assignment(), xact_desc_commit(), xlog_desc(), xlog_outdesc(), XLogInsertRecord(), xmldata_root_element_end(), xmldata_root_element_start(), xmlpi(), xpath_table(), and xsd_schema_element_start().

79 {
80  for (;;)
81  {
82  va_list args;
83  int needed;
84 
85  /* Try to format the data. */
86  va_start(args, fmt);
87  needed = appendStringInfoVA(str, fmt, args);
88  va_end(args);
89 
90  if (needed == 0)
91  break; /* success */
92 
93  /* Increase the buffer size and try again. */
94  enlargeStringInfo(str, needed);
95  }
96 }
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:245
int appendStringInfoVA(StringInfo str, const char *fmt, va_list args)
Definition: stringinfo.c:114
void appendStringInfoChar ( StringInfo  str,
char  ch 
)

Definition at line 169 of file stringinfo.c.

Referenced by _outAExpr(), _outList(), _outValue(), appendConditions(), appendContextKeyword(), appendStringInfoRegexpSubstr(), appendTypeNameToBuffer(), array_dim_to_json(), brin_page_items(), BuildIndexValueDescription(), circle_out(), composite_to_json(), ConvertTriggerToFK(), cube_out(), cursor_to_xml(), database_to_xml_internal(), DeadLockReport(), deparseAggref(), deparseArrayExpr(), deparseArrayRef(), deparseBoolExpr(), deparseColumnRef(), deparseDistinctExpr(), deparseFromExprForRel(), deparseFuncExpr(), deparseInsertSql(), deparseNullTest(), deparseOpExpr(), deparseRangeTblRef(), deparseScalarArrayOpExpr(), deparseSortGroupClause(), deparseStringLiteral(), do_pg_start_backup(), escape_param_str(), exec_stmt_raise(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExplainBeginOutput(), ExplainCloseGroup(), ExplainJSONLineEnding(), ExplainNode(), ExplainOpenGroup(), ExplainProperty(), ExplainPropertyList(), ExplainPropertyListNested(), ExplainSeparatePlans(), ExplainXMLTag(), ExplainYAMLLineStarting(), fetch_table_list(), format_procedure_internal(), FreePageManagerDumpBtree(), FreePageManagerDumpSpans(), funcname_signature_string(), generate_operator_name(), get_agg_expr(), get_basic_select_query(), get_coercion_expr(), get_column_alias_list(), get_delete_query_def(), get_from_clause_coldeflist(), get_from_clause_item(), get_func_expr(), get_insert_query_def(), get_oper_expr(), get_parameter(), get_range_partbound_string(), get_rule_expr(), get_rule_expr_paren(), get_rule_groupingset(), get_rule_sortgroupclause(), get_rule_windowspec(), get_setop_query(), get_special_variable(), get_sql_insert(), get_sublink_expr(), get_tablefunc(), get_tablesample_def(), get_update_query_def(), get_update_query_targetlist_def(), get_values_def(), get_variable(), get_windowfunc_expr(), get_with_clause(), hstore_to_json(), hstore_to_json_loose(), incompatible_module_error(), InteractiveBackend(), json_agg_transfn(), json_build_array(), json_build_object(), json_lex_string(), json_object(), json_object_two_arg(), libpqrcv_startstreaming(), log_line_prefix(), make_ruledef(), make_viewdef(), mxid_to_string(), NameListToQuotedString(), NameListToString(), outBitmapset(), outDatum(), outNode(), outToken(), path_encode(), pg_decode_change(), pg_dependencies_out(), pg_get_constraintdef_worker(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_partkeydef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_ndistinct_out(), pg_split_opts(), pgp_armor_encode(), postgresImportForeignSchema(), pq_send_ascii_string(), print_function_arguments(), print_function_rettype(), print_literal(), printSubscripts(), query_to_xml_internal(), range_bound_escape(), range_deparse(), range_parse_bound(), record_in(), record_out(), reportDependentObjects(), RI_Initial_Check(), schema_to_xml_internal(), send_message_to_frontend(), send_message_to_server_log(), sepgsql_proc_post_create(), serialize_deflist(), show_buffer_usage(), show_modifytable_info(), show_tablesample(), show_tidbitmap_info(), simple_quote_literal(), SPI_sql_row_to_xmlelement(), storeObjectDescription(), stringlist_to_identifierstr(), tuple_to_stringinfo(), txid_snapshot_out(), TypeNameListToString(), uuid_out(), write_csvlog(), xlog_outdesc(), and xmlpi().

170 {
171  /* Make more room if needed */
172  if (str->len + 1 >= str->maxlen)
173  enlargeStringInfo(str, 1);
174 
175  /* OK, append the character */
176  str->data[str->len] = ch;
177  str->len++;
178  str->data[str->len] = '\0';
179 }
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:245
void appendStringInfoSpaces ( StringInfo  str,
int  count 
)

Definition at line 187 of file stringinfo.c.

References StringInfoData::data, enlargeStringInfo(), and StringInfoData::len.

Referenced by appendContextKeyword(), ExplainCloseGroup(), ExplainDummyGroup(), ExplainNode(), ExplainOpenGroup(), ExplainProperty(), ExplainPropertyList(), ExplainPropertyListNested(), ExplainXMLTag(), ExplainYAMLLineStarting(), log_line_prefix(), show_buffer_usage(), show_hash_info(), show_modifytable_info(), show_sort_info(), show_tablesample(), show_tidbitmap_info(), and text_format_append_string().

188 {
189  if (count > 0)
190  {
191  /* Make more room if needed */
192  enlargeStringInfo(str, count);
193 
194  /* OK, append the spaces */
195  while (--count >= 0)
196  str->data[str->len++] = ' ';
197  str->data[str->len] = '\0';
198  }
199 }
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:245
void appendStringInfoString ( StringInfo  str,
const char *  s 
)

Definition at line 157 of file stringinfo.c.

Referenced by _outAConst(), _outAExpr(), _outAgg(), _outBoolExpr(), _outConst(), _outConstraint(), _outCustomPath(), _outCustomScan(), _outForeignKeyCacheInfo(), _outForeignKeyOptInfo(), _outGatherMerge(), _outGroup(), _outMergeAppend(), _outMergeJoin(), _outPathInfo(), _outPathTarget(), _outQuery(), _outRecursiveUnion(), _outSetOp(), _outSort(), _outUnique(), _outValue(), _outWindowAgg(), appendAggOrderBy(), appendConditions(), appendContextKeyword(), appendFunctionName(), appendGroupByClause(), appendOrderByClause(), appendTypeNameToBuffer(), array_dim_to_json(), array_to_json_internal(), array_to_text_internal(), brin_page_items(), build_tuplestore_recursively(), BuildIndexValueDescription(), composite_to_json(), concat_internal(), config_enum_get_options(), ConvertTriggerToFK(), cube_out(), database_to_xml_internal(), database_to_xmlschema_internal(), datum_to_json(), DeadLockReport(), decompile_column_index_array(), deparseAggref(), deparseAnalyzeSizeSql(), deparseAnalyzeSql(), deparseArrayExpr(), deparseBoolExpr(), deparseColumnRef(), deparseConst(), deparseDeleteSql(), deparseDirectDeleteSql(), deparseDirectUpdateSql(), deparseDistinctExpr(), deparseExplicitTargetList(), deparseFromExpr(), deparseFromExprForRel(), deparseFuncExpr(), deparseInsertSql(), deparseLockingClause(), deparseNullTest(), deparseOperatorName(), deparseRangeTblRef(), deparseSelectSql(), deparseSelectStmtForRel(), deparseSubqueryTargetList(), deparseTargetList(), deparseUpdateSql(), errdetail_params(), escape_json(), escape_xml(), estimate_path_cost_size(), exec_stmt_raise(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), execute_extension_script(), ExplainBeginOutput(), ExplainDummyGroup(), ExplainEndOutput(), ExplainIndexScanDetails(), ExplainNode(), ExplainOneUtility(), ExplainOpenGroup(), ExplainProperty(), ExplainPropertyList(), ExplainPropertyListNested(), ExplainQuery(), ExplainTargetRel(), ExplainXMLTag(), ExportSnapshot(), fetch_table_list(), flatten_reloptions(), flatten_set_variable_args(), format_expr_params(), format_operator_internal(), format_preparedparamsdata(), format_procedure_internal(), FreePageManagerDump(), funcname_signature_string(), generate_operator_name(), get_agg_expr(), get_basic_select_query(), get_column_alias_list(), get_const_expr(), get_from_clause(), get_from_clause_coldeflist(), get_from_clause_item(), get_func_expr(), get_insert_query_def(), get_query_def(), get_range_partbound_string(), get_rule_expr(), get_rule_expr_funccall(), get_rule_groupingset(), get_rule_orderby(), get_rule_windowclause(), get_rule_windowspec(), get_select_query_def(), get_setop_query(), get_sql_delete(), get_sql_insert(), get_sql_update(), get_sublink_expr(), get_tablefunc(), get_tablesample_def(), get_target_list(), get_tuple_of_interest(), get_update_query_def(), get_update_query_targetlist_def(), get_utility_query_def(), get_values_def(), get_variable(), get_windowfunc_expr(), get_with_clause(), getConstraintTypeDescription(), getObjectIdentityParts(), getObjectTypeDescription(), getProcedureTypeDescription(), getRelationIdentity(), getRelationTypeDescription(), gin_desc(), hstore_to_json(), hstore_to_json_loose(), incompatible_module_error(), json_agg_transfn(), json_build_array(), json_build_object(), json_object(), json_object_agg_transfn(), json_object_two_arg(), jsonb_put_escaped_value(), libpqrcv_create_slot(), libpqrcv_startstreaming(), log_line_prefix(), make_ruledef(), make_temptable_name_n(), map_multipart_sql_identifier_to_xml_name(), map_sql_catalog_to_xmlschema_types(), map_sql_identifier_to_xml_name(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), map_sql_type_to_xmlschema_type(), map_sql_value_to_xml_value(), map_xml_name_to_sql_identifier(), NameListToQuotedString(), NameListToString(), op_signature_string(), out_infobits(), out_member(), outDatum(), outNode(), outToken(), pg_decode_change(), pg_decode_commit_txn(), pg_dependencies_out(), pg_extension_update_paths(), pg_get_constraintdef_worker(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_partkeydef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_ndistinct_out(), pg_output_begin(), pgp_armor_encode(), PLy_traceback(), postgresImportForeignSchema(), print_function_arguments(), print_function_rettype(), print_function_trftypes(), print_literal(), quote_qualified_identifier(), range_deparse(), refresh_by_match_merge(), report_triggers(), ri_Check_Pk_Match(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), ri_GenerateQual(), RI_Initial_Check(), ri_ReportViolation(), ri_restrict_del(), ri_restrict_upd(), schema_to_xml_internal(), schema_to_xmlschema_internal(), send_message_to_frontend(), send_message_to_server_log(), sepgsql_proc_post_create(), serialize_deflist(), show_buffer_usage(), show_modifytable_info(), show_sort_group_keys(), show_sortorder_options(), show_tablesample(), show_tidbitmap_info(), ShowUsage(), single_encode(), smgr_desc(), sn_scalar(), spg_desc(), SPI_sql_row_to_xmlelement(), standby_desc_invalidations(), standby_desc_running_xacts(), StartupXLOG(), stringlist_to_identifierstr(), text_format_append_string(), transform_string_values_scalar(), tuple_to_stringinfo(), write_auto_conf_file(), write_csvlog(), xact_desc_abort(), xact_desc_assignment(), xact_desc_commit(), xlog_desc(), xlog_outdesc(), XLogInsertRecord(), xml_out_internal(), xmlcomment(), xmlconcat(), xmldata_root_element_start(), xmlpi(), xmlroot(), xsd_schema_element_end(), and xsd_schema_element_start().

158 {
159  appendBinaryStringInfo(str, s, strlen(s));
160 }
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:208
int appendStringInfoVA ( StringInfo  str,
const char *  fmt,
va_list  args 
)

Definition at line 114 of file stringinfo.c.

References Assert, StringInfoData::data, StringInfoData::len, StringInfoData::maxlen, NULL, and pvsnprintf().

Referenced by appendStringInfo(), and PLy_elog().

115 {
116  int avail;
117  size_t nprinted;
118 
119  Assert(str != NULL);
120 
121  /*
122  * If there's hardly any space, don't bother trying, just fail to make the
123  * caller enlarge the buffer first. We have to guess at how much to
124  * enlarge, since we're skipping the formatting work.
125  */
126  avail = str->maxlen - str->len;
127  if (avail < 16)
128  return 32;
129 
130  nprinted = pvsnprintf(str->data + str->len, (size_t) avail, fmt, args);
131 
132  if (nprinted < (size_t) avail)
133  {
134  /* Success. Note nprinted does not include trailing null. */
135  str->len += (int) nprinted;
136  return 0;
137  }
138 
139  /* Restore the trailing null so that str is unmodified. */
140  str->data[str->len] = '\0';
141 
142  /*
143  * Return pvsnprintf's estimate of the space needed. (Although this is
144  * given as a size_t, we know it will fit in int because it's not more
145  * than MaxAllocSize.)
146  */
147  return (int) nprinted;
148 }
size_t pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
Definition: psprintf.c:104
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
void enlargeStringInfo ( StringInfo  str,
int  needed 
)

Definition at line 245 of file stringinfo.c.

References StringInfoData::data, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, StringInfoData::len, MaxAllocSize, StringInfoData::maxlen, and repalloc().

Referenced by appendBinaryStringInfo(), appendStringInfo(), appendStringInfoChar(), appendStringInfoSpaces(), CopyReadAttributesCSV(), CopyReadAttributesText(), CopyReadBinaryAttribute(), GetOldFunctionMessage(), JsonbToCStringWorker(), logicalrep_write_tuple(), pgp_armor_decode(), pgp_armor_encode(), PLy_elog(), pq_getmessage(), reserveFromBuffer(), and XLogSendPhysical().

246 {
247  int newlen;
248 
249  /*
250  * Guard against out-of-range "needed" values. Without this, we can get
251  * an overflow or infinite loop in the following.
252  */
253  if (needed < 0) /* should not happen */
254  elog(ERROR, "invalid string enlargement request size: %d", needed);
255  if (((Size) needed) >= (MaxAllocSize - (Size) str->len))
256  ereport(ERROR,
257  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
258  errmsg("out of memory"),
259  errdetail("Cannot enlarge string buffer containing %d bytes by %d more bytes.",
260  str->len, needed)));
261 
262  needed += str->len + 1; /* total space required now */
263 
264  /* Because of the above test, we now have needed <= MaxAllocSize */
265 
266  if (needed <= str->maxlen)
267  return; /* got enough space already */
268 
269  /*
270  * We don't want to allocate just a little more space with each append;
271  * for efficiency, double the buffer size each time it overflows.
272  * Actually, we might need to more than double it if 'needed' is big...
273  */
274  newlen = 2 * str->maxlen;
275  while (needed > newlen)
276  newlen = 2 * newlen;
277 
278  /*
279  * Clamp to MaxAllocSize in case we went past it. Note we are assuming
280  * here that MaxAllocSize <= INT_MAX/2, else the above loop could
281  * overflow. We will still have newlen >= needed.
282  */
283  if (newlen > (int) MaxAllocSize)
284  newlen = (int) MaxAllocSize;
285 
286  str->data = (char *) repalloc(str->data, newlen);
287 
288  str->maxlen = newlen;
289 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define MaxAllocSize
Definition: memutils.h:40
size_t Size
Definition: c.h:356
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:963
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
void initStringInfo ( StringInfo  str)

Definition at line 46 of file stringinfo.c.

References StringInfoData::data, StringInfoData::maxlen, palloc(), and resetStringInfo().

Referenced by array_to_text_internal(), BeginCopyFrom(), bmsToString(), bqarr_in(), brin_page_items(), build_tuplestore_recursively(), BuildIndexValueDescription(), CheckSCRAMAuth(), checkSharedDependencies(), circle_out(), concat_internal(), config_enum_get_options(), convertToJsonb(), ConvertTriggerToFK(), copy_table(), create_cursor(), cube_out(), cursor_to_xml(), dblink_close(), dblink_fdw_validator(), dblink_fetch(), dblink_open(), DeadLockReport(), deparse_expression_pretty(), deparseAnalyzeSizeSql(), deparseFromExprForRel(), do_pg_start_backup(), DropSubscription(), errdetail_params(), escape_param_str(), escape_xml(), estimate_path_cost_size(), exec_replication_command(), exec_stmt_raise(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecEvalXmlExpr(), execute_extension_script(), expand_fmt_string(), ExportSnapshot(), fetch_remote_table_info(), fetch_table_list(), file_fdw_validator(), flatten_reloptions(), flatten_set_variable_args(), format_expr_params(), format_node_dump(), format_operator_internal(), format_preparedparamsdata(), format_procedure_internal(), FreePageManagerDump(), fsm_page_contents(), funcname_signature_string(), generate_operator_name(), get_connect_string(), get_from_clause(), get_sql_delete(), get_sql_insert(), get_sql_update(), get_target_list(), get_tuple_of_interest(), getObjectDescription(), getObjectIdentityParts(), getObjectTypeDescription(), HandleParallelMessages(), hstore_to_json(), hstore_to_json_loose(), hstore_to_jsonb_loose(), incompatible_module_error(), initialize_worker_spi(), int8_avg_deserialize(), json_object(), json_object_two_arg(), KnownAssignedXidsDisplay(), lazy_scan_heap(), lazy_vacuum_rel(), libpqrcv_create_slot(), libpqrcv_startstreaming(), make_temptable_name_n(), makeStringInfo(), map_multipart_sql_identifier_to_xml_name(), map_sql_catalog_to_xmlschema_types(), map_sql_identifier_to_xml_name(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), map_sql_type_to_xmlschema_type(), map_sql_typecoll_to_xmlschema_types(), map_sql_value_to_xml_value(), map_xml_name_to_sql_identifier(), mxid_to_string(), NameListToQuotedString(), NameListToString(), nodeToString(), numeric_avg_deserialize(), numeric_deserialize(), numeric_poly_deserialize(), op_signature_string(), parse_fcall_arguments(), parse_fcall_arguments_20(), path_encode(), pg_armor(), pg_dearmor(), pg_dependencies_out(), pg_extension_update_paths(), pg_get_constraintdef_worker(), pg_get_function_arguments(), pg_get_function_identity_arguments(), pg_get_function_result(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_partkeydef_worker(), pg_get_ruledef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_get_viewdef_worker(), pg_ndistinct_out(), pg_split_opts(), PLy_elog(), PLy_traceback(), populate_array_report_expected_array(), postgres_fdw_validator(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresGetForeignPlan(), postgresImportForeignSchema(), PostgresMain(), postgresPlanDirectModify(), postgresPlanForeignModify(), postgresql_fdw_validator(), pq_beginmessage(), pq_begintypsend(), pretty_format_node_dump(), print_function_rettype(), process_pipe_input(), ProcSleep(), quote_object_name(), quote_qualified_identifier(), range_bound_escape(), range_deparse(), range_parse_bound(), range_recv(), record_in(), record_out(), recv_password_packet(), refresh_by_match_merge(), replace_text(), replace_text_regexp(), reportDependentObjects(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), RI_Initial_Check(), ri_ReportViolation(), ri_restrict_del(), ri_restrict_upd(), rm_redo_error_callback(), schema_get_xml_visible_tables(), send_message_to_frontend(), send_message_to_server_log(), sepgsql_attribute_post_create(), sepgsql_audit_log(), sepgsql_database_post_create(), sepgsql_proc_post_create(), sepgsql_relation_post_create(), sepgsql_schema_post_create(), serialize_deflist(), show_sort_group_keys(), ShowTransactionStateRec(), ShowUsage(), StartupXLOG(), stringlist_to_identifierstr(), table_to_xml_internal(), text_format(), TQSendRecordInfo(), txid_snapshot_out(), TypeNameListToString(), TypeNameToString(), typeStringToTypeName(), unaccent_lexize(), uuid_out(), WalReceiverMain(), write_auto_conf_file(), write_csvlog(), XLogInsertRecord(), xml_out_internal(), xmlcomment(), xmlconcat(), xmlpi(), xmlroot(), XmlTableGetValue(), and xpath_table().

47 {
48  int size = 1024; /* initial default buffer size */
49 
50  str->data = (char *) palloc(size);
51  str->maxlen = size;
52  resetStringInfo(str);
53 }
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
void * palloc(Size size)
Definition: mcxt.c:849