Stories
Slash Boxes
Comments

SoylentNews is people

Log In

Log In

Create Account  |  Retrieve Password


SubStrings, a way to have safe C strings!

Posted by Subsentient on Tuesday November 17 2015, @05:35AM (#1591)
5 Comments
Code

I've recently done some touchups to my SubStrings library, and have reminded myself of my own undying glory, er, I mean, come to the conclusion that it's useful enough to warrant me advertising it a little bit. I use it in a large percentage of my projects nowadays. I thought I'd showcase part of what makes it awesome to me.

Before we begin, there is one thing I must mention: SubStrings is only designed to work well with null terminated strings only. It's almost certainly unsafe to use it for anything else.
And, one last thing: This is indeed a C library, written in C89 and works in C. The OOP appearance, such as SubStrings.Length(), is function pointer trickery for cleanliness' sake. SubStrings is also a non-hosted library, meaning it has no dependencies, and can thus even be used in your bootloader's source code.

String copy and concatenation, truly safe
SubStrings copy and concatenation functions have precise bounds checking, and always result in a null terminated string, and, if the size parameter is given accurately, SubStrings never has buffer overflows. Let's illustrate.

#include "substrings/substrings.h"

void MyFunc(void)
{
   char Array[1024];

   //So, the maximum string data copied will be sizeof Array - 1, so there is room for the '\0'.
   SubStrings.Copy(Array, "My string is awesome!", sizeof Array);

   /*SubStrings.Cat's size parameter needs to be the *maximum capacity* of the destination. You don't need to subtract from
   the max size each iteration of a loop. SubStrings knows how to do it.*/
   SubStrings.Cat(Array, " And it merges really nice too!", sizeof Array);
}

strcpy and strcat() are in general, unsafe, and strncat and strncpy have differing and confusing behavior. SubStrings eliminates these problems with one consistent approach for concatenation and copy operations.

All the necessities provided

SubStrings also provides all the other functions you might want for basic string operations, including Length(), Compare(), NCompare() [analogous to strncmp()], Find(), and CFind() [Find a single character], and FindAnyOf() [Analogous to strchr()].
Find() and CFind() accept another, new argument, allowing you to directly request the N-th occurrence of the matching string/characters. There is also IsLowerS, IsLowerC, IsUpperC, and conversion functions like LowerS, LowerC, UpperS, and UpperC.

In general, functions ending in S deal with strings, and functions ending in C deal with single characters.

High level stuff is here too
Some of the cooler stuff is stuff you might expect to find in Python.
Stuff like StartsWith, EndsWith, Replace, Strip, Reverse, and StripLeadingChars and StripTrailingChars.

And some original ideas too
There are other functions, like Extract(), which pulls the string content that's in between two sequences.
Let's have an example.

#include "substrings/substrings.h"

int main(int argc, char **argv)
{
    int Inc = 1;
    char Buf[256];

    for (; Inc < argc; ++Inc)
    {
        if (SubStrings.StartsWith("--config=", argv[Inc]))
        {
             SubStrings.Extract(Buf, sizeof Buf, "=", NULL, argv[Inc]);
             DoSomething(Buf);
         }
     }
}

What's happening here is that Extract is pulling the data that starts after the =, and since the next parameter is NULL, it reads on until the end of the string. This makes handling command line arguments marginally simpler.

There's other goodies, like SubStrings.CopyUntil(). Let's take a look.

#include "substrings/substrings.h"

void MyFunc(void)
{
    const char *const String = "Wibble[END]Nurble[END]Aburble[END]Farts";
    const char *Iter = String;
    char Buf[256];
    while (SubStrings.CopyUntil(Buf, sizeof Buf, &Iter, "[END]", true))
    {
         puts(Buf);
    }
}

This produces the output:

Wibble
Nurble
Aburble
Farts

I actually find myself using CopyUntil and its sister function CopyUntilC quite often. Then there's SubStrings.Line.GetLine(), which is a specialized CopyUntil that helps with processing multi-line C strings.

Lastly, there's another useful function, Split().

#include "substrings/substrings.h"

void MyFunc(void)
{
    const char *String = "Gerbil|Wibble";
    char One[256], Two[256];

    SubStrings.Split(One, Two, "|", String, SPLIT_HALFONE);
}

Now, One[] contains "Gerbil|" and Two[] contains "Wibble". You can specify to discard the split tokens, or put them in half one or two. The options are SPLIT_NOKEEP, SPLIT_HALFONE, and SPLIT_HALFTWO. Because Split() doesn't ask for buffer sizes for the sake of convenience, the way to do it safely is to make sure that both One and Two will be able to hold the entire length of String, if needed.

This library is getting more touchups. You can find the github here, and the SubStrings homepage here.

Thoughts, ideas or suggestions? Let me know.

October 28, 2015: Republican Debate #3

Posted by takyon on Thursday October 29 2015, @03:03AM (#1551)
1 Comment

Bizarre, campy song "explains" China's 13th 5-year plan

Posted by takyon on Tuesday October 27 2015, @09:40PM (#1550)
0 Comments

The Life of a Busker

Posted by MichaelDavidCrawford on Thursday October 22 2015, @02:19AM (#1539)
11 Comments
Business

I've been singing on the street for tips. I don't make a whole lot, I'm doing pretty good if I can pay for a Starbucks at the end of the day. Sometimes I can buy a bag of rice and a couple cans of beans to cook on my campstove.

Today wasn't looking so good. I wasn't into it mentally and was not making any tips but even so I persisted as I knew that, at the low rate I generally get tipped that random fluctuations are significant.

Then just now, behind Powells City of Books at 11th and Couch in Portland's Pearl District, some joker heckled me the ENTIRE time I was singing - all the way through all eight of my songs.

What he didn't realize is that I am from Kuro5hin.

Right then I earned nine bucks in tips; all day before that I only made $1.35. As we parted I waved my cash in his face then said "Learn to sing Sir, and we could be a duet".

U.S. Military Actions Abroad, 1798-2015

Posted by takyon on Wednesday October 21 2015, @01:39AM (#1537)
1 Comment
Business

Uses of Force Abroad 1798-2015, and More from CRS

A newly updated tabulation of U.S. military actions has been prepared by the Congressional Research Service, up to and including the October 14, 2015 deployment of 90 U.S. troops to Cameroon. The CRS listing does not include covert actions, disaster relief operations or training exercises. See Instances of Use of United States Armed Forces Abroad, 1798-2015, October 15, 2015.

[other CRS reports listed at source]

The PDF is 38 pages.

Congressional Research Service

British aid worker dies at Istanbul airport

Posted by isostatic on Tuesday October 20 2015, @01:39PM (#1535)
1 Comment
News

A very strange case this one

A British Aid Worker -- the Iraq director of an organization promoting journalism in conflict zones -- was found dead in toilets in Istanbul Airport.

The official story is that she was on her way back to Erbil having attended the funeral of her predecessor (who was killed in a car bomb a couple of weeks ago). She apparently missed her connecting flight to Erbil, and was told that she'd have to buy a new ticket.

The local media say that having been told this, she burst out in tears as she didn't have the money, then go to the toilets and hang herself using her shoelaces. Last minute tickets Istanbul to Erbil on tonight's flight is about £100, or £150 for the next direct BA plane back to London.

CCTV in Istanbul airport near the toilets apparently wasn't working

IWPR stated

"Apparently the CCTV cameras in the airport that filmed her were not on, were not functioning or the tapes were not available.

"We need to get CCTV from Heathrow to find out whether she was wearing boots with laces when she left."

ctv news | telegraph | ibtimes

October 13, 2015: U.S. Democratic Primary Debate #1

Posted by takyon on Monday October 12 2015, @06:30PM (#1519)
6 Comments
News

Previously:

The candidates participating in the debate are Lincoln Chafee, Hillary Clinton, Martin O'Malley, Bernie Sanders, and Jim Webb. Larry Lessig did not make the cut. CNN coverage begins at 8:30 PM EDT, the debate begins at 9 PM EDT and ends at 11 PM EDT.

Links:

The first debate is scheduled for October 13, 2015, at the Wynn hotel in Las Vegas, beginning at 9 p.m. Eastern time. It will air on CNN, and will also be broadcast on radio by Westwood One [AUDIO-only should be available online via CBS Radio]. Anderson Cooper will be the moderator of the debate, with Dana Bash and Juan Carlos Lopez asking additional questions and Don Lemon presenting questions submitted by voters via Facebook.

To be invited to the debate, a candidate must have achieved an average of at least 1% in three recognized national polls released between August 1 and October 10. In addition, a candidate must either have filed a statement of candidacy with the Federal Election Commission or declare that one will be filed by October 14, the day after the debate. The latter criterion would accommodate Vice President Joe Biden if he decided to enter the presidential race as late as the day of the debate.

Should Vice President Biden decide to enter the race and take part in the debate, there would be a podium placed on the stage for him as well.

Google's .bro file format changed to .br

Posted by takyon on Sunday October 11 2015, @10:27PM (#1516)
2 Comments
/dev/random

Journals: Soylent controversial topic containment zone?

Google's .bro file format changed to .br after gender politics worries

In late September, Google released a compression algorithm called Brotli and gave files it makes the extension “.bro”.

But last week the extension was changed to “.br”.

The reason for the change is threads like this one, in which posters suggest that “'bro' has a gender problem” and “comes of[f] misogynistic and unprofessional due to the world it lives in.”

[...]

Wikipedia

BBC Trending: Drawing of a 6-year-old Syrian girl, racist?

Posted by takyon on Thursday October 08 2015, @08:40PM (#1511)
11 Comments
/dev/random

BBC Trending: Is this manga cartoon of a six-year-old Syrian girl racist?

"I want to live a safe and clean life, eat gourmet food, go out, wear pretty things, and live a luxurious life… all at the expense of someone else," reads the text on the illustration above. "I have an idea. I'll become a refugee."

The image and caption were posted by a right-wing Japanese artist last month. Now, more than 10,000 people have signed a Change.org petition in Japanese urging Facebook to take it down. The petition, posted by an account calling itself the "Don't Allow Racism Group", claims that several people have reported the illustration and demands that "Facebook must recognize an illustration insulting Syrian refugees as racism."

Although the Japan Times reported that Facebook did not take the picture down, saying it did not go against community guidelines, the artist herself removed the picture. But she remains defiant about her motivations for posting it in the first place. Toshiko Hasumi told BBC Trending that she believed the people signing the petition were left-wing activists. "I draw many political mangas [Japanese comics] which are not favourable to them," she said. "This is why they targeted me."

Give-a-shitness, I lack it

Posted by Subsentient on Thursday October 08 2015, @03:21PM (#1508)
5 Comments
Code

Lately I've been working on some goofy projects like WZBlue, my gtk+ lobby monitor for Warzone 2100. But there's other projects I'm having trouble getting any momentum going again. Two good examples are my packrat package manager, which has stalled, and NEXUS, which I want to add ignore support to, but haven't had the drive to actually complete that work. I simply seem to not give a flying fuck.

I don't seem to care much about my normal projects anymore. I enjoy working with GTK, my latest pet, but I'm in the process of learning C++, which knocks the steam out of any C-based GTK+ projects I might envision. I already know C very well, so I'm expanding to be able to read and write C++ as well.

I'm always tired from the still-untreated chronic exhaustion, and coupled with this severe lack of motivation, I find myself watching south park all day and sleeping constantly. I haven't done much coding beyond my little WZBlue project in the last two months.

A couple months back, I wrote a crude AI in Javascript for "High Oil" Warzone 2100, called RatBot, but it's not done and has some strange and rather severe bugs I need to work out. For one, it performs far better in non-networked skirmish than multiplayer, which really, are the same thing, except skirmish has no networking. I've ran into such severe bugs, I kinda stopped working on it altogether for a while. I think of all the projects on the table, that's the one most likely to get me working again.

I'm not a depressed person, I've never been diagnosed with depression, and it usually takes a decent sized reason for me to get all depressed. They've tested my thyroid, it came back normal. No anemia, or sleep apnea.

What am I going to do...