Coder Social home page Coder Social logo

tortellini's Introduction

Tortellini

The stupid - and I mean really, really stupid - INI file reader and writer for C++11 and above. Calorie free (no dependencies)!

#include <tortellini.hh>

// (optional)
#include <fstream>

int main() {
	tortellini::ini ini;

	// (optional) Read INI in from a file.
	// Default construction and subsequent assignment is just fine, too.
	std::ifstream in("config.ini");
	in >> ini;

	// Retrieval
	//
	// All value retrievals must be done via the "default" operator
	// (the pipe operator).
	//
	// The right-hand-side type is what is returned. Anything other
	// than a string-like type causes a parse (see caveats section below).
	//
	// All keys are case-INsensitive. This includes section headers.
	std::string s          = ini["Section"]["key"] | "default string";
	int i                  = ini["Section"]["key"] | 42;    // default int
	long l                 = ini["Section"]["key"] | 42L;   // default long
	long long ll           = ini["Section"]["key"] | 42LL;  // default long long
	unsigned int u         = ini["Section"]["key"] | 42u;   // default unsigned int
	unsigned long ul       = ini["Section"]["key"] | 42UL;  // default unsigned long
	unsigned long long ull = ini["Section"]["key"] | 42ULL; // default unsigned long long
	float f                = ini["Section"]["key"] | 42.0f; // default float
	double d               = ini["Section"]["key"] | 42.0;  // default double
	long double ld         = ini["Section"]["key"] | 42.0L; // default long double
	bool b                 = ini["Section"]["key"] | true;  // default bool

	// Assignment
	//
	// (This example uses the same key, but of course
	// in reality this would just be overwriting the
	// same key over and over again - probably not
	// what you'd really want. I would hope I wouldn't
	// have to explain this, but you never know.)
	ini["New Section"]["new-key"] = "Noodles are tasty.";
	ini["New Section"]["new-key"] = 1234;
	ini["New Section"]["new-key"] = 1234u;
	ini["New Section"]["new-key"] = 1234L;
	ini["New Section"]["new-key"] = 1234UL;
	ini["New Section"]["new-key"] = 1234LL;
	ini["New Section"]["new-key"] = 1234ULL;
	ini["New Section"]["new-key"] = 1234.0f;
	ini["New Section"]["new-key"] = 1234.0;
	ini["New Section"]["new-key"] = 1234.0L;
	ini["New Section"]["new-key"] = true;

	// "Naked" section (top-most key/value pairs, before a section header)
	// denoted by empty string in section selector
	ini[""]["naked-key"] = "I'll be at the very top, without a section";

	// You can also iterate over all sections
	for (auto &pair : ini) {
		std::cout << pair.name << "\n"; // the name of the section
		int v = pair.section["some-key"] | 1234;
		std::cout << "some-key=" << v << "\n";
	}

	// (optional) Write INI to file.
	std::ofstream out("config.ini");
	out << ini;
}

Things you should know.

This library has very few bells and whistles. It doesn't do anything fancy.

Here are the guarantees/features:

  • Case-insensitive keys and section headers. Reading from a key/section with different cases will work fine, and writing to an existing section/key will preserve the casing.
  • Untouched output (from using stream << ini) is guaranteed to be parsable (by using stream >> ini).
  • Barring I/O issues or exceptions coming from the standard library, Tortellini will not throw or abort (see below section about "invalid data").
  • Pasta in, pasta out. Source strings (from a parse) are preserved to the output. If you use yes instead of true, Tortellini will preserve that (unless the application overwrites the value).
  • yes, 1 and true are all parsable as bool(true). All other values equate to false. NOTE: This means that ini[""]["b"] | true will return false, not true, if the key exists but is not a valid, parsable truth-ey value. This may be counter-intuitive for some users.
  • All values are inherently string, and only parsed when retrieved.

Here are the caveats:

  • Do not store or share anything returned from the subscript operators ([]). They return temporary objects that are meant for short-lived interactions. They are NOT lifetime safe and expect the underlying tortellini::ini instance to subsist beyond their own lifetimes.
  • Invalid keys, values or section names skip the line entirely. This condition is henceforth referred to as "invalid data".
  • Integer overflows when parsing are invalid data.
  • Mismatched ] for a [ line is invalid data. Yes, keys will bleed into the preceding section name. That's user error, not your application's. Embrace it.
  • Empty keys or empty values (excluding leading/trailing whitespace!) are "invalid data" in that they might be valid but not included in the resulting data and thus won't be re-emitted.
  • Empty sections (or sections with 100% invalid data as key/value pairs) are themselves invalid data and are not emitted.
  • [] is a valid section name. It means the "naked" section. Re-emitting the INI will move those keys to the top regardless of where [] is positioned in the input file.
  • No comments are supported; ; is a valid (string) character.
  • No caching or memoization; if you retrieve anything but a std::string, there will be a parse. I never said Tortellini was hyper-over-optimized.

Testing

You can test by running:

mkdir build && cd build
cmake .. -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Debug
cmake --build .
ctest

License

You have two choices in license. Pick whichever one you want. Tortellini is uncucumbered. Go crazy. Eat some pasta.

Unlicense

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>

MIT License

Copyright (c) 2020 Josh Junon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

tortellini's People

Contributors

geekskick avatar plumzero avatar qix- avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tortellini's Issues

The root CMakeLists doesn't export the library

A good practice when writing a library with CMake is to export any public targets. This enables code reuse and the usage of find_package().

Currently the tortelini target isn't being exported nor installed.

We should check whenever the project is a root project (ie. "${CMAKE_SOURCE_DIR} == ${CMAKE_CURRENT_SOURCE_DIR}"), provide an install target and export it.

Reading a bool from a file

With a file containing:

v = hello

and extracting a bool from that using

const auto b = ini[""]["v"] | true;

I would expect the fallback to be the result, but there returned value is false. In tortellini.hh

inline bool operator |(bool fallback) const {
	return _value.empty()
		? fallback
		: (
			   case_insensitive::compare(_value, "1")
			|| case_insensitive::compare(_value, "true")
			|| case_insensitive::compare(_value, "yes")
		);
}

This function only uses the fallback if the _value is empty, and not if the string isn't one of the valid [1|true|yes] options. This can be seen in #5 test.cc line 248.

need fix

Hi, if i use NDEBUG & RELEASE defines in my projetct, then the "strparse" function is not working properly (return only fallback value). could you make this function without try/catch construct?

Безымянный

Reading a char from the file

Using a file containing:

v = 25500

and extracting that using

const char a = init[""]["v"] | 'a';

I would expect that '25500' is out of range, so the fall back is used, but it isn't and the value 0x639c is used instead. This can be seen in #5 on line 292 and 291.

Readme docs for running test are outdated

The readme states you can run tests by running make but this is no longer the case; the library was switched to CMake in order to create a target and to honor the testing flags provided by CMake.

The readme should be updated to reflect this.

mkdir build && cd build
cmake .. -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Debug
cmake --build .
ctest

The above should be tested and, if correct, updated in the readme.

`string` to `long double`

should not this!

    inline double operator |(long double fallback) const {
        return strparse<long double, std::stold>(_value, fallback);
    }

should this?

    inline long double operator |(long double fallback) const {
        return strparse<long double, std::stold>(_value, fallback);
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.