string_func.h File Reference

Functions related to low-level strings. More...

#include "core/bitmath_func.hpp"
#include "string_type.h"

Go to the source code of this file.

Functions

void ttd_strlcat (char *dst, const char *src, size_t size)
 Appends characters from one string to another.
void ttd_strlcpy (char *dst, const char *src, size_t size)
 Copies characters from one buffer to another.
char * strecat (char *dst, const char *src, const char *last)
 Appends characters from one string to another.
char * strecpy (char *dst, const char *src, const char *last)
 Copies characters from one buffer to another.
int CDECL seprintf (char *str, const char *last, const char *format,...) WARN_FORMAT(3
int CDECL char *CDECL str_fmt (const char *str,...) WARN_FORMAT(1
int CDECL char *CDECL void str_validate (char *str, const char *last, bool allow_newlines=false, bool ignore=false)
 Scans the string for valid characters and if it finds invalid ones, replaces them with a question mark '?' (if not ignored).
void str_strip_colours (char *str)
 Scans the string for colour codes and strips them.
void strtolower (char *str)
 Convert a given ASCII string to lowercase.
bool StrValid (const char *str, const char *last)
 Checks whether the given string is valid, i.e.
static bool StrEmpty (const char *s)
 Check if a string buffer is empty.
static size_t ttd_strnlen (const char *str, size_t maxlen)
 Get the length of a string, within a limited buffer.
char * md5sumToString (char *buf, const char *last, const uint8 md5sum[16])
 Convert the md5sum to a hexadecimal string representation.
bool IsValidChar (WChar key, CharSetFilter afilter)
 Only allow certain keys.
size_t Utf8Decode (WChar *c, const char *s)
 Decode and consume the next UTF-8 encoded character.
size_t Utf8Encode (char *buf, WChar c)
 Encode a unicode character and place it in the buffer.
size_t Utf8TrimString (char *s, size_t maxlen)
 Properly terminate an UTF8 string to some maximum length.
static WChar Utf8Consume (const char **s)
static int8 Utf8CharLen (WChar c)
 Return the length of a UTF-8 encoded character.
static int8 Utf8EncodedCharLen (char c)
 Return the length of an UTF-8 encoded value based on a single char.
static bool IsUtf8Part (char c)
static char * Utf8PrevChar (char *s)
 Retrieve the previous UNICODE character in an UTF-8 encoded string.
size_t Utf8StringLength (const char *s)
 Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes that the encoded string contains.
static bool IsTextDirectionChar (WChar c)
 Is the given character a text direction character.
static bool IsPrintable (WChar c)
static bool IsWhitespace (WChar c)
 Check whether UNICODE character is whitespace or not, i.e.
char * strndup (const char *s, size_t len)
char * strcasestr (const char *haystack, const char *needle)

Detailed Description

Functions related to low-level strings.

Note:
Be aware of "dangerous" string functions; string functions that have behaviour that could easily cause buffer overruns and such:
  • strncpy: does not '' terminate when input string is longer than the size of the output string. Use strecpy instead.
  • [v]snprintf: returns the length of the string as it would be written when the output is large enough, so it can be more than the size of the buffer and than can underflow size_t (uint-ish) which makes all subsequent snprintf alikes write outside of the buffer. Use [v]seprintf instead; it will return the number of bytes actually added so no [v]seprintf will cause outside of bounds writes.
  • [v]sprintf: does not bounds checking: use [v]seprintf instead.

Definition in file string_func.h.


Function Documentation

static bool IsTextDirectionChar ( WChar  c  )  [inline, static]

Is the given character a text direction character.

Parameters:
c The character to test.
Returns:
true iff the character is used to influence the text direction.

Definition at line 155 of file string_func.h.

References CHAR_TD_LRE, CHAR_TD_LRM, CHAR_TD_LRO, CHAR_TD_PDF, CHAR_TD_RLE, CHAR_TD_RLM, and CHAR_TD_RLO.

Referenced by FindMissingGlyphs(), FormatStringLinebreaks(), GetStringBoundingBox(), GetStringWidth(), ReallyDoDrawString(), and TruncateString().

bool IsValidChar ( WChar  key,
CharSetFilter  afilter 
)

Only allow certain keys.

You can define the filter to be used. This makes sure no invalid keys can get into an editbox, like BELL.

Parameters:
key character to be checked
afilter the filter to use
Returns:
true or false depending if the character is printable/valid or not

Definition at line 331 of file string.cpp.

References CS_ALPHA, CS_ALPHANUMERAL, CS_HEXADECIMAL, CS_NUMERAL, and CS_NUMERAL_SPACE.

Referenced by IConsoleCmdExec(), OskWindow::OnClick(), IConsoleWindow::OnKeyPress(), TranslateTTDPatchCodes(), and OskWindow::UpdateOskState().

static bool IsWhitespace ( WChar  c  )  [inline, static]

Check whether UNICODE character is whitespace or not, i.e.

whether this is a potential line-break character.

Parameters:
c UNICODE character to check
Returns:
a boolean value whether 'c' is a whitespace character or not
See also:
http://www.fileformat.info/info/unicode/category/Zs/list.htm

Definition at line 187 of file string_func.h.

Referenced by FormatStringLinebreaks(), and IConsoleHistoryAdd().

char* md5sumToString ( char *  buf,
const char *  last,
const uint8  md5sum[16] 
)

Convert the md5sum to a hexadecimal string representation.

Parameters:
buf buffer to put the md5sum into
last last character of buffer (usually lastof(buf))
md5sum the md5sum itself
Returns:
a pointer to the next character after the md5sum

Definition at line 423 of file string.cpp.

References seprintf().

Referenced by HandleSavegameLoadCrash(), IsGoodGRFConfigList(), and PrintGrfInfo().

int CDECL char* CDECL void str_validate ( char *  str,
const char *  last,
bool  allow_newlines,
bool  ignore 
)

Scans the string for valid characters and if it finds invalid ones, replaces them with a question mark '?' (if not ignored).

Parameters:
str the string to validate
last the last valid character of str
allow_newlines whether newlines should be allowed or ignored
ignore whether to ignore or replace with a question mark

Definition at line 186 of file string.cpp.

References Utf8Decode(), and Utf8EncodedCharLen().

Referenced by FiosFileScanner::AddFile(), FiosGetFileList(), GetFileTitle(), IConsolePrint(), Packet::Recv_string(), and SlString().

char* strecat ( char *  dst,
const char *  src,
const char *  last 
)

Appends characters from one string to another.

Appends the source string to the destination string with respect of the terminating null-character and and the last pointer to the last element in the destination buffer. If the last pointer is set to NULL no boundary check is performed.

Note:
usage: strecat(dst, src, lastof(dst));
lastof() applies only to fixed size arrays
Parameters:
dst The buffer containing the target string
src The buffer containing the string to append
last The pointer to the last element of the destination buffer
Returns:
The pointer to the terminating null-character in the destination buffer

Definition at line 117 of file string.cpp.

References strecpy().

Referenced by CloneVehicleName(), DoAutosave(), DrawRoadVehDetails(), GetDebugString(), GetFileTitle(), GetFullFilename(), KeycodeToString(), SaveKeycodes(), and IniFile::SaveToDisk().

char* strecpy ( char *  dst,
const char *  src,
const char *  last 
)

Copies characters from one buffer to another.

Copies the source string to the destination buffer with respect of the terminating null-character and the last pointer to the last element in the destination buffer. If the last pointer is set to NULL no boundary check is performed.

Note:
usage: strecpy(dst, src, lastof(dst));
lastof() applies only to fixed size arrays
Parameters:
dst The destination buffer
src The buffer containing the string to copy
last The pointer to the last element of the destination buffer
Returns:
The pointer to the terminating null-character in the destination buffer

Definition at line 145 of file string.cpp.

References DEBUG, and error().

Referenced by ScenarioScanner::AddFile(), FiosFileScanner::AddFile(), TarScanner::AddFile(), AI_CreateAIDummy(), CloneVehicleName(), DEF_UDP_RECEIVE_COMMAND(), DrawString(), DrawStringMultiLine(), ExtractTar(), FindUnknownGRFName(), FioFOpenFile(), FiosGetFileList(), FormatString(), GamelogRevision(), GenerateTownNameString(), NetworkAddress::GetAddressAsString(), GetFileTitle(), GetKeyboardLayout(), GRFBuildParamList(), IConsoleCopyInParams(), IniSaveSettings(), IsSameAI(), MakeAustrianTownName(), MakeCatalanTownName(), MakeCzechTownName(), MakeDanishTownName(), MakeDutchTownName(), MakeEnglishAdditionalTownName(), MakeEnglishOriginalTownName(), MakeFinnishTownName(), MakeFrenchTownName(), MakeGermanTownName(), MakeHungarianTownName(), MakeItalianTownName(), MakeNorwegianTownName(), MakePolishTownName(), MakeRomanianTownName(), MakeScreenshot(), MakeSillyTownName(), MakeSlovakTownName(), MakeSpanishTownName(), MakeSwedishTownName(), MakeSwissTownName(), MakeTurkishTownName(), NetworkAddChatMessage(), NetworkAddress::NetworkAddress(), NetworkFindBroadcastIPsInternal(), NetworkGameListHandleDelayedInsert(), NetworkSendCommand(), NetworkServerChangeClientName(), NetworkServerSetCompanyPassword(), NetworkUDPQueryServerThread(), NetworkStartServerWindow::OnClick(), SaveLoadWindow::OnClick(), NetworkContentDownloadStatusWindow::OnDownloadProgress(), NetworkStartServerWindow::OnKeyPress(), NetworkGameWindow::OnKeyPress(), AIDebugWindow::OnKeyPress(), CustomCurrencyWindow::OnQueryTextFinished(), NetworkStartServerWindow::OnQueryTextFinished(), ClientNetworkContentSocketHandler::OnReceiveData(), DriverFactoryBase::RegisterDriver(), NetworkAddress::Resolve(), IniFile::SaveToDisk(), FileScanner::Scan(), DriverFactoryBase::SelectDriver(), SetFallbackFont(), SignListWindow::SetFilterString(), ShowHelp(), ShowRefitOptionsList(), strecat(), CrashLog::WriteScreenshot(), and DriverFactoryBase::~DriverFactoryBase().

static bool StrEmpty ( const char *  s  )  [inline, static]

Check if a string buffer is empty.

Parameters:
s The pointer to the firste element of the buffer
Returns:
true if the buffer starts with the terminating null-character or if the given pointer points to NULL else return false

Definition at line 55 of file string_func.h.

Referenced by FiosFileScanner::AddFile(), ServerNetworkAdminSocketHandler::AllowConnection(), CStrA::AppendStr(), AISign::BuildSign(), CmdCompanyCtrl(), CmdFoundTown(), CmdPlaceSign(), CmdRenameCompany(), CmdRenameDepot(), CmdRenameEngine(), CmdRenameGroup(), CmdRenamePresident(), CmdRenameSign(), CmdRenameStation(), CmdRenameTown(), CmdRenameVehicle(), CmdRenameWaypoint(), DEF_UDP_RECEIVE_COMMAND(), NetworkContentListWindow::DrawDetails(), NetworkStartServerWindow::DrawWidget(), NetworkContentDownloadStatusWindow::DrawWidget(), MusicTrackSelectionWindow::DrawWidget(), LandInfoWindow::DrawWidget(), AISettingsWindow::DrawWidget(), GenerateCompanyPasswordHash(), ServerNetworkGameSocketHandler::GetClientName(), NetworkAddress::GetHostname(), GetKeyboardLayout(), GRFConfig::GetName(), GetSavegameFormat(), GRFLoadConfig(), IConsoleHistoryAdd(), AIScanner::ImportLibrary(), InitializeMusic(), NetworkAddress::Listen(), LoadFreeTypeFont(), NetworkAddress::NetworkAddress(), NetworkGameListAddItem(), NetworkGameListHandleDelayedInsert(), NetworkServerSetCompanyPassword(), NetworkStartUp(), NewsDisplayLoadConfig(), NetworkGameWindow::NGameAllowedSorter(), SignListWindow::OnInvalidateData(), AIDebugWindow::OnInvalidateData(), NetworkGameWindow::OnKeyPress(), ScenarioEditorToolbarWindow::OnQueryTextFinished(), TimetableWindow::OnQueryTextFinished(), GameSettingsWindow::OnQueryTextFinished(), OrdersWindow::OnQueryTextFinished(), NewGRFParametersWindow::OnQueryTextFinished(), SpriteAlignerWindow::OnQueryTextFinished(), NetworkJoinStatusWindow::OnQueryTextFinished(), NetworkGameWindow::OnQueryTextFinished(), IndustryViewWindow::OnQueryTextFinished(), CreateScenarioWindow::OnQueryTextFinished(), GenerateLandscapeWindow::OnQueryTextFinished(), SelectCompanyManagerFaceWindow::OnQueryTextFinished(), CheatWindow::OnQueryTextFinished(), AISettingsWindow::OnQueryTextFinished(), RenameSign(), NetworkAddress::Resolve(), SaveToHighScore(), BlitterFactoryBase::SelectBlitter(), DriverFactoryBase::SelectDriver(), SignListWindow::SetFilterString(), AIVehicle::SetName(), AISign::SetName(), AIGroup::SetName(), AICompany::SetName(), AIBaseStation::SetName(), AICompany::SetPresidentName(), BaseMedia< Tbase_set >::SetSet(), MusicTrackSelectionWindow::UpdateWidgetSize(), and LandInfoWindow::UpdateWidgetSize().

void strtolower ( char *  str  ) 

Convert a given ASCII string to lowercase.

NOTE: only support ASCII characters, no UTF8 fancy. As currently the function is only used to lowercase data-filenames if they are not found, this is sufficient. If more, or general functionality is needed, look to r7271 where it was removed because it was broken when using certain locales: eg in Turkish the uppercase 'I' was converted to '?', so just revert to the old functionality

Parameters:
str string to convert

Definition at line 319 of file string.cpp.

Referenced by AIScanner::FindInfo(), FioFOpenFile(), AIScanner::ImportLibrary(), AIScanner::RegisterAI(), AIScanner::RegisterLibrary(), and SimplifyFileName().

bool StrValid ( const char *  str,
const char *  last 
)

Checks whether the given string is valid, i.e.

contains only valid (printable) characters and is properly terminated.

Parameters:
str The string to validate.
last The last character of the string, i.e. the string must be terminated here or earlier.

Definition at line 247 of file string.cpp.

References Utf8Decode(), and Utf8EncodedCharLen().

Referenced by LanguagePackHeader::IsValid().

void ttd_strlcat ( char *  dst,
const char *  src,
size_t  size 
)

Appends characters from one string to another.

Appends the source string to the destination string with respect of the terminating null-character and the maximum size of the destination buffer.

Note:
usage ttd_strlcat(dst, src, lengthof(dst));
lengthof() applies only to fixed size arrays
Parameters:
dst The buffer containing the target string
src The buffer containing the string to append
size The maximum size of the destination buffer

Definition at line 65 of file string.cpp.

References ttd_strlcpy().

Referenced by BuildWithFullPath(), AIInstance::LoadCompatibilityScripts(), and ScriptScanner::ScanDir().

void ttd_strlcpy ( char *  dst,
const char *  src,
size_t  size 
)

Copies characters from one buffer to another.

Copies the source string to the destination buffer with respect of the terminating null-character and the maximum size of the destination buffer.

Note:
usage ttd_strlcpy(dst, src, lengthof(dst));
lengthof() applies only to fixed size arrays
Parameters:
dst The destination buffer
src The buffer containing the string to copy
size The maximum size of the destination buffer

Definition at line 91 of file string.cpp.

Referenced by BuildWithFullPath(), DEF_UDP_RECEIVE_COMMAND(), AIScanner::FindInfo(), FioCreateDirectory(), ServerNetworkGameSocketHandler::GetClientName(), GetClipboardContents(), IConsoleHistoryNavigate(), IniLoadSettings(), AIController::LoadedLibrary(), mkpath(), NewGRFWindow::OnClick(), SaveLoadWindow::OnClick(), ScriptScanner::ScanDir(), SetSettingValue(), and ttd_strlcat().

static size_t ttd_strnlen ( const char *  str,
size_t  maxlen 
) [inline, static]

Get the length of a string, within a limited buffer.

Parameters:
str The pointer to the firste element of the buffer
maxlen The maximum size of the buffer
Returns:
The length of the string

Definition at line 67 of file string_func.h.

static int8 Utf8CharLen ( WChar  c  )  [inline, static]

Return the length of a UTF-8 encoded character.

Parameters:
c Unicode character.
Returns:
Length of UTF-8 encoding for character.

Definition at line 96 of file string_func.h.

Referenced by CopyFromOldName(), FormatString(), FS2OTTD(), InsertTextBufferChar(), InsertTextBufferClipboard(), and UpdateTextBufferSize().

size_t Utf8Decode ( WChar *  c,
const char *  s 
)

Decode and consume the next UTF-8 encoded character.

Parameters:
c Buffer to place decoded character.
s Character stream to retrieve character from.
Returns:
Number of characters in the sequence.

Definition at line 444 of file string.cpp.

References GB(), and HasBit().

Referenced by DrawString(), MoveTextBufferPos(), str_strip_colours(), str_validate(), StrValid(), and TranslateTTDPatchCodes().

size_t Utf8Encode ( char *  buf,
WChar  c 
)

Encode a unicode character and place it in the buffer.

Parameters:
buf Buffer to place character.
c Unicode character to encode.
Returns:
Number of characters in the encoded sequence.

Definition at line 484 of file string.cpp.

References GB().

Referenced by CheckForMissingGlyphsInLoadedLanguagePack(), CopyFromOldName(), DrawNewsString(), UnmappedChoiceList::Flush(), FormatString(), FS2OTTD(), InsertTextBufferChar(), and TranslateTTDPatchCodes().

static int8 Utf8EncodedCharLen ( char  c  )  [inline, static]

Return the length of an UTF-8 encoded value based on a single char.

This char should be the first byte of the UTF-8 encoding. If not, or encoding is invalid, return value is 0

Parameters:
c char to query length of
Returns:
requested size

Definition at line 115 of file string_func.h.

References GB().

Referenced by str_validate(), StrValid(), TranslateTTDPatchCodes(), and Utf8TrimString().

static char* Utf8PrevChar ( char *  s  )  [inline, static]

Retrieve the previous UNICODE character in an UTF-8 encoded string.

Parameters:
s char pointer pointing to (the first char of) the next character
Returns:
a pointer in 's' to the previous UNICODE character's first byte
Note:
The function should not be used to determine the length of the previous encoded char because it might be an invalid/corrupt start-sequence

Definition at line 140 of file string_func.h.

Referenced by FormatStringLinebreaks(), and MoveTextBufferPos().

size_t Utf8StringLength ( const char *  s  ) 

Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes that the encoded string contains.

Parameters:
s The string to get the length for.
Returns:
The length of the string in characters.

Definition at line 300 of file string.cpp.

Referenced by AISign::BuildSign(), CmdFoundTown(), CmdPlaceSign(), CmdRenameCompany(), CmdRenameDepot(), CmdRenameEngine(), CmdRenameGroup(), CmdRenamePresident(), CmdRenameSign(), CmdRenameStation(), CmdRenameTown(), CmdRenameVehicle(), CmdRenameWaypoint(), GenerateCompanyName(), GeneratePresidentName(), AIVehicle::SetName(), AISign::SetName(), AIGroup::SetName(), AICompany::SetName(), AIBaseStation::SetName(), and VerifyTownName().

size_t Utf8TrimString ( char *  s,
size_t  maxlen 
)

Properly terminate an UTF8 string to some maximum length.

Parameters:
s string to check if it needs additional trimming
maxlen the maximum length the buffer can have.
Returns:
the new length in bytes of the string (eg. strlen(new_string)) maxlen is the string length _INCLUDING_ the terminating ''

Definition at line 518 of file string.cpp.

References Utf8EncodedCharLen().

Referenced by NetworkAddChatMessage().


Generated on Thu Jan 20 22:57:54 2011 for OpenTTD by  doxygen 1.6.1