repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
kriskate/motor-on-roller-blind-ws
src/OTASetup.h
#include <ArduinoOTA.h> void otaSetup(char *config_name) { // Authentication to avoid unauthorized updates //ArduinoOTA.setPassword(<PASSWORD>); ArduinoOTA.setHostname(config_name); ArduinoOTA.onStart([]() { Serial.println(F("Start")); }); ArduinoOTA.onEnd([]() { Serial.println(F("\nEnd")); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println(F("Auth Failed")); else if (error == OTA_BEGIN_ERROR) Serial.println(F("Begin Failed")); else if (error == OTA_CONNECT_ERROR) Serial.println(F("Connect Failed")); else if (error == OTA_RECEIVE_ERROR) Serial.println(F("Receive Failed")); else if (error == OTA_END_ERROR) Serial.println(F("End Failed")); }); ArduinoOTA.begin(); }
kriskate/motor-on-roller-blind-ws
src/WiFiManagerSetup.h
#include <WiFi.h> #include <WiFiManager.h> #include <WiFiUdp.h> //Configure Default Settings for Access Point logon String APid = "Blinds AP"; //Name of access point String APpw = ""; //Hardcoded password for access point char config_name[40] = "blinds"; //WIFI config: Bonjour name of device char config_rotation[40] = "false"; //WIFI config: Detault rotation is CCW WiFiManagerParameter custom_config_name(); String *wifiManagerSetup(void (*saveConfigCallback)(), char *mqtt_server, char *mqtt_port) { //Set the WIFI hostname WiFi.setHostname(config_name); //Define customer parameters for WIFI Manager WiFiManagerParameter custom_config_name("Name", "Bonjour name", config_name, 40); WiFiManagerParameter custom_rotation("Rotation", "Clockwise rotation", config_rotation, 40); WiFiManagerParameter custom_text("<p><b>Optional MQTT server parameters:</b></p>"); WiFiManagerParameter custom_mqtt_server("server", "MQTT server", mqtt_server, 40); WiFiManagerParameter custom_mqtt_port("port", "MQTT port", mqtt_port, 6); WiFiManagerParameter custom_mqtt_uid("uid", "MQTT username", mqtt_server, 40); WiFiManagerParameter custom_mqtt_pwd("pwd", "MQTT password", mqtt_server, 40); WiFiManagerParameter custom_text2("<script>t = document.createElement('div');t2 = document.createElement('input');t2.setAttribute('type', 'checkbox');t2.setAttribute('id', 'tmpcheck');t2.setAttribute('style', 'width:10%');t2.setAttribute('onclick', \"if(document.getElementById('Rotation').value == 'false'){document.getElementById('Rotation').value = 'true'} else {document.getElementById('Rotation').value = 'false'}\");t3 = document.createElement('label');tn = document.createTextNode('Clockwise rotation');t3.appendChild(t2);t3.appendChild(tn);t.appendChild(t3);document.getElementById('Rotation').style.display='none';document.getElementById(\"Rotation\").parentNode.insertBefore(t, document.getElementById(\"Rotation\"));</script>"); //Setup WIFI Manager WiFiManager wifiManager; //reset settings - for testing //clean FS, for testing //helper.resetsettings(wifiManager); wifiManager.setSaveConfigCallback(saveConfigCallback); //add all your parameters here wifiManager.addParameter(&custom_config_name); wifiManager.addParameter(&custom_rotation); wifiManager.addParameter(&custom_text); wifiManager.addParameter(&custom_mqtt_server); wifiManager.addParameter(&custom_mqtt_port); wifiManager.addParameter(&custom_mqtt_uid); wifiManager.addParameter(&custom_mqtt_pwd); wifiManager.addParameter(&custom_text2); wifiManager.autoConnect(APid.c_str(), APpw.c_str()); Serial.println("--- setup wifiManager done"); String paramsValues[8] = { custom_config_name.getValue(), custom_rotation.getValue(), custom_text.getValue(), custom_mqtt_server.getValue(), custom_mqtt_port.getValue(), custom_mqtt_uid.getValue(), custom_mqtt_pwd.getValue(), custom_text2.getValue()}; return paramsValues; }
kriskate/motor-on-roller-blind-ws
src/MQTTSetup.h
<reponame>kriskate/motor-on-roller-blind-ws<gh_stars>0 #include <ArduinoJson.h> #include <WiFiClient.h> #include <PubSubClient.h> WiFiClient espClient; PubSubClient psclient(espClient); //MQTT client boolean mqttActive = true; char mqtt_server[40]; //WIFI config: MQTT server config (optional) char mqtt_port[6] = "1883"; //WIFI config: MQTT port config (optional) char mqtt_uid[40]; //WIFI config: MQTT server username (optional) char mqtt_pwd[40]; //WIFI config: MQTT server password (optional) void loadMQTT(JsonVariant json) { strcpy(mqtt_server, json["mqtt_server"]); strcpy(mqtt_port, json["mqtt_port"]); strcpy(mqtt_uid, json["mqtt_uid"]); strcpy(mqtt_pwd, json["mqtt_pwd"]); } void mqttSetup(void (*processMsg)(String res, uint8_t clientnum)) { /* Setup connection for MQTT and for subscribed messages IF a server address has been entered */ Serial.println("MQTTTTT " + String(mqtt_server)); if (String(mqtt_server) != "") { Serial.println(F("Registering MQTT server")); psclient.setServer(mqtt_server, String(mqtt_port).toInt()); psclient.setCallback([&](char *topic, byte *payload, unsigned int length) { Serial.print(F("Message arrived [")); Serial.print(topic); Serial.print(F("] ")); String res = ""; for (int i = 0; i < length; i++) { res += String((char)payload[i]); } processMsg(res, 0); }); } else { mqttActive = false; Serial.println(F("NOTE: No MQTT server address has been registered. Only using websockets")); } }
kriskate/motor-on-roller-blind-ws
src/WebServerSetup.h
<reponame>kriskate/motor-on-roller-blind-ws #include <WebServer.h> #include "index_html.h" #include <ESPmDNS.h> #include <WiFi.h> // Version number for checking if there are new code releases and notifying the user String version = "1.3.3"; WebServer server(80); // TCP server at port 80 will respond to HTTP requests void handleRoot() { server.send(200, "text/html", INDEX_HTML); } void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } void serverSetup(char *config_name) { /* Setup multi DNS (Bonjour) */ if (MDNS.begin(config_name)) { Serial.println(F("MDNS responder started")); MDNS.addService("http", "tcp", 80); MDNS.addService("ws", "tcp", 81); } else { Serial.println(F("Error setting up MDNS responder!")); while (1) { delay(1000); } } Serial.print("Connect to http://" + String(config_name) + ".local or http://"); Serial.println(WiFi.localIP()); //Start HTTP server server.on("/", handleRoot); server.onNotFound(handleNotFound); server.begin(); //Update webpage INDEX_HTML.replace("{VERSION}", "V" + version); INDEX_HTML.replace("{NAME}", String(config_name)); }
kriskate/motor-on-roller-blind-ws
src/WebSocketsSetup.h
#include <WebSocketsServer.h> WebSocketsServer webSocket = WebSocketsServer(81); // WebSockets will respond on port 81 void webSocketsSetup(void (*processMsg)(String res, uint8_t clientnum)) { //Start websocket webSocket.begin(); webSocket.onEvent([&](uint8_t num, WStype_t type, uint8_t *payload, size_t length) { switch (type) { case WStype_TEXT: Serial.printf("[%u] get Text: %s\n", num, payload); String res = (char *)payload; //Send to common MQTT and websocket function processMsg(res, num); break; } }); }
mdr78/dpdk-simple-app
simple.c
<reponame>mdr78/dpdk-simple-app<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <stdbool.h> #include <rte_eal.h> #include <rte_common.h> #include <rte_ethdev.h> #include <rte_ether.h> #include <rte_log.h> #include <rte_mbuf.h> #include <rte_version.h> static volatile bool force_quit; /* Macros for printing using RTE_LOG */ #define RTE_LOGTYPE_APP RTE_LOGTYPE_USER1 #define NUM_MBUFS 8191 #define MBUF_CACHE_SIZE 250 #define BURST_SIZE 32 #define RX_RING_SIZE 128 #define TX_RING_SIZE 512 /*static uint8_t forwarding_lcore = 1;*/ static uint8_t mac_swap = 1; static int check_link_status(uint16_t nb_ports) { struct rte_eth_link link; uint8_t port; for (port = 0; port < nb_ports; port++) { rte_eth_link_get(port, &link); if (link.link_status == ETH_LINK_DOWN) { RTE_LOG(INFO, APP, "Port: %u Link DOWN\n", port); return -1; } RTE_LOG(INFO, APP, "Port: %u Link UP Speed %u\n", port, link.link_speed); } return 0; } static void simple_mac_swap(struct rte_mbuf **bufs, uint16_t nb_mbufs) { #if RTE_VERSION >= RTE_VERSION_NUM(19,11,0,16) struct rte_ether_hdr *eth; struct rte_ether_addr tmp; struct rte_mbuf *m; uint16_t buf; for (buf = 0; buf < nb_mbufs; buf++) { m = bufs[buf]; eth = rte_pktmbuf_mtod(m, struct rte_ether_hdr *); rte_ether_addr_copy(&eth->s_addr, &tmp); rte_ether_addr_copy(&eth->d_addr, &eth->s_addr); rte_ether_addr_copy(&tmp, &eth->d_addr); } #else struct ether_hdr *eth; struct ether_addr tmp; struct rte_mbuf *m; uint16_t buf; for (buf = 0; buf < nb_mbufs; buf++) { m = bufs[buf]; eth = rte_pktmbuf_mtod(m, struct ether_hdr *); ether_addr_copy(&eth->s_addr, &tmp); ether_addr_copy(&eth->d_addr, &eth->s_addr); ether_addr_copy(&tmp, &eth->d_addr); } #endif } int lcore_main(void *arg) { /*unsigned int lcore_id = rte_lcore_id();*/ #if RTE_VERSION >= RTE_VERSION_NUM(19,11,0,16) const uint8_t nb_ports = rte_eth_dev_count_avail(); #else const uint8_t nb_ports = rte_eth_dev_count(); #endif uint8_t port; uint8_t dest_port; /*if (lcore_id != forwarding_lcore) { RTE_LOG(INFO, APP, "lcore %u exiting\n", lcore_id); return 0; }*/ /* Run until the application is quit or killed. */ while (!force_quit) { /* * Receive packets on a port and forward them * on the paired port. * The mapping is 0 -> 1, 1 -> 0, 2 -> 3, 3 -> 2, etc. */ for (port = 0; port < nb_ports; port++) { struct rte_mbuf *bufs[BURST_SIZE]; uint16_t nb_rx; uint16_t nb_tx; uint16_t buf; /* Get burst of RX packets, * from first port of pair. */ nb_rx = rte_eth_rx_burst(port, 0, bufs, BURST_SIZE); if (unlikely(nb_rx == 0)) continue; if (mac_swap) simple_mac_swap(bufs, nb_rx); /* Send burst of TX packets, * to second port of pair. */ dest_port = port ^ 1; nb_tx = rte_eth_tx_burst(dest_port, 0, bufs, nb_rx); /* Free any unsent packets. */ if (unlikely(nb_tx < nb_rx)) { for (buf = nb_tx; buf < nb_rx; buf++) rte_pktmbuf_free(bufs[buf]); } } } return 0; } static inline int port_init(uint8_t port, struct rte_mempool *mbuf_pool) { struct rte_eth_conf port_conf = { #if RTE_VERSION >= RTE_VERSION_NUM(19,11,0,16) .rxmode = { .max_rx_pkt_len = RTE_ETHER_MAX_LEN } #else .rxmode = { .max_rx_pkt_len = ETHER_MAX_LEN } #endif }; const uint16_t nb_rx_queues = 1; const uint16_t nb_tx_queues = 1; int ret; uint16_t q; /* Configure the Ethernet device. */ ret = rte_eth_dev_configure(port, nb_rx_queues, nb_tx_queues, &port_conf); if (ret != 0) return ret; /* Allocate and set up 1 RX queue per Ethernet port. */ for (q = 0; q < nb_rx_queues; q++) { ret= rte_eth_rx_queue_setup(port, q, RX_RING_SIZE, rte_eth_dev_socket_id(port), NULL, mbuf_pool); if (ret < 0) return ret; } /* Allocate and set up 1 TX queue per Ethernet port. */ for (q = 0; q < nb_tx_queues; q++) { ret= rte_eth_tx_queue_setup(port, q, TX_RING_SIZE, rte_eth_dev_socket_id(port), NULL); if (ret < 0) return ret; } /* Start the Ethernet port. */ ret = rte_eth_dev_start(port); if (ret < 0) return ret; /* Enable RX in promiscuous mode for the Ethernet device. */ rte_eth_promiscuous_enable(port); return 0; } static void print_stats(void) { struct rte_eth_stats stats; #if RTE_VERSION >= RTE_VERSION_NUM(19,11,0,16) uint8_t nb_ports = rte_eth_dev_count_avail(); #else uint8_t nb_ports = rte_eth_dev_count(); #endif uint8_t port; for (port = 0; port < nb_ports; port++) { printf("\nStatistics for port %u\n", port); rte_eth_stats_get(port, &stats); printf("Rx:%9"PRIu64" Tx:%9"PRIu64" dropped:%9"PRIu64"\n", stats.ipackets, stats.opackets, stats.imissed); } } static void signal_handler(int signum) { if (signum == SIGINT || signum == SIGTERM) { printf("\n\nSignal %d received, preparing to exit...\n", signum); force_quit = true; print_stats(); } } int main(int argc, char *argv[]) { int ret; uint8_t nb_ports; struct rte_mempool *mbuf_pool; uint8_t portid; /* * EAL: Environment Abstract Layer" * * eal gets parameters from cli, returns number of parsed args * * cpu_init: fill cpu_info structure * log_init * config_init: create memory configuration in shared memory * pci_init: scan pci bus * memory_init (hugepages) * memzone_init: initialize memzone subsystem * alarm_init: for timer interrupts * timer_init * plugin init * dev_init: initialize and probe virtual devices * intr_init: create an interrupt handler thread * lcore_init: create a thread per lcore * pci_probe: probe all physical devices */ ret = rte_eal_init(argc, argv); if (ret < 0) rte_exit(EXIT_FAILURE, "EAL Init failed\n"); argc -= ret; argv += ret; force_quit = false; signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); /* * Check that there is an even number of ports to * send/receive on. */ #if RTE_VERSION >= RTE_VERSION_NUM(19,11,0,16) nb_ports = rte_eth_dev_count_avail(); #else nb_ports = rte_eth_dev_count(); #endif if (nb_ports < 2 || (nb_ports & 1)) rte_exit(EXIT_FAILURE, "Invalid port number\n"); RTE_LOG(INFO, APP, "Number of ports:%u\n", nb_ports); /* Creates a new mbuf mempool */ mbuf_pool = rte_pktmbuf_pool_create("MBUF_POOL", NUM_MBUFS * nb_ports, MBUF_CACHE_SIZE, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id()); if (mbuf_pool == NULL) rte_exit(EXIT_FAILURE, "mbuf_pool create failed\n"); /* Initialize all ports. */ for (portid = 0; portid < nb_ports; portid++) if (port_init(portid, mbuf_pool) != 0) rte_exit(EXIT_FAILURE, "port init failed\n"); if (mac_swap) RTE_LOG(INFO, APP, "MAC address swapping enabled\n"); ret = check_link_status(nb_ports); if (ret < 0) RTE_LOG(WARNING, APP, "Some ports are down\n"); rte_eal_mp_remote_launch(lcore_main, NULL, SKIP_MASTER); rte_eal_mp_wait_lcore(); /* There is no un-init for eal */ return 0; }
NullSeile/UITools
src/Widget.h
#pragma once #include "Button.h" #include "Slider.h" #include "Sprite.h" #include "Text.h" #include "Line.h" #include "Rectangle.h" #include "Circle.h" #include "Graph.h" #include "InteractiveGraph.h" #include "ToggleButton.h" #include "Event.h" namespace ui { class Widget { private: std::vector<ui::UIObject*> m_objects; public: Widget(); ~Widget(); void Update(const sf::RenderWindow& window); void CheckInput(const sf::RenderWindow& window, ui::Event& e); void Draw(sf::RenderWindow& window); void BeginPlay(); void ClearAll(); void AddObject(ui::UIObject* newObject); const std::vector<ui::UIObject*>& GetObjects(); template<typename T> T* Get(const std::string& id); template<typename T> void Clear(); ui::UIObject* GetUIObject(const std::string& id); }; template<typename T> void Widget::Clear() { m_objects.erase(std::remove_if(m_objects.begin(), m_objects.end(), [](ui::UIObject* o) { return dynamic_cast<T*>(o); }), m_objects.end()); } template<typename T> inline T * Widget::Get(const std::string& id) { for (ui::UIObject* x : m_objects) { auto y = dynamic_cast<T*>(x); if (!y) continue; if (y->id == id) return y; } return nullptr; } }
NullSeile/UITools
src/Graph.h
#pragma once #include "UIObject.h" #include "Interactuable.h" namespace ui { struct ArrowDef { float width = 5; sf::Color color = sf::Color::Black; }; struct PlotDef { float width = 2; sf::Color color = sf::Color::Black; bool cyclic = false; bool optimize = true; }; struct ScatterDef { float radius = 1; sf::Color color = sf::Color::Black; }; class Graph : public ui::UIObject { private: ui::Vec2f m_pos; ui::Vec2f m_size; ui::Vec2f m_xRange; ui::Vec2f m_yRange; sf::Color m_backColor; sf::Color m_axisColor; float m_axisWidth; float m_gridWidth; std::function<float(const float& x)> m_function; std::vector<std::pair<std::vector<ui::Vec2f>, ScatterDef>> m_scatters; std::vector<std::pair<std::vector<ui::Vec2f>, PlotDef>> m_plots; std::vector<std::pair<std::pair<ui::Vec2f, ui::Vec2f>, ArrowDef>> m_arrows; ui::Vec2f CalculateAxisStep(); public: Graph(const std::string& id); void SetPosition(const ui::Vec2f& pos); void SetSize(const ui::Vec2f& size); void SetRange(const ui::Vec2f& xRange, const ui::Vec2f& yRange); void SetXRange(const ui::Vec2f& range); void SetYRange(const ui::Vec2f& range); void SetBackgrowndColor(const sf::Color& color); void SetAxisColor(const sf::Color& color); void SetAxisWidth(const float& width); ui::Vec2f MapPosToCoords(const ui::Vec2f& pos); ui::Vec2f MapCoordsToPos(const ui::Vec2f& coords); void ClearAll(); void ClearArrows(); void ClearPlots(); ui::Vec2f GetPosition(); ui::Vec2f GetRange(); ui::Vec2f GetSize(); void Fit(const float& margin = 0.05f); //void Recalculate(); void Scatter(const std::vector<ui::Vec2f>& data, const ScatterDef& props = ScatterDef()); void Plot(const std::vector<ui::Vec2f>& data, const PlotDef& props = PlotDef()); void Arrow(const ui::Vec2f& pos, const ui::Vec2f& size, const ArrowDef& props = ArrowDef()); void Draw(sf::RenderWindow& window) override; ~Graph(); }; }
NullSeile/UITools
src/Global.h
<filename>src/Global.h #pragma once #define _USE_MATH_DEFINES #include <SFML\Graphics.hpp> #include <iostream> #include <vector> #include <fstream> #include <iomanip> #include <functional> #include <sstream> #include <iomanip> #include <cmath> #include <math.h> #include "Vec2.h" #ifndef PI #define PI M_PI #endif typedef unsigned int uint; namespace ui { typedef Vec2<float> Vec2f; typedef Vec2<double> Vec2d; typedef Vec2<int> Vec2i; typedef Vec2<uint> Vec2u; inline double map(const double& value, const double& inputMin, const double& inputMax, const double& outputMin, const double& outputMax) { return outputMin + ((outputMax - outputMin) / (inputMax - inputMin)) * (value - inputMin); } inline float map(const float& value, const float& inputMin, const float& inputMax, const float& outputMin, const float& outputMax) { return outputMin + ((outputMax - outputMin) / (inputMax - inputMin)) * (value - inputMin); } inline float snap(const float& value, const float& step) { if (step == 0) return value; else return roundf(value / step) * step; } template<typename T> inline T RadToDeg(const T& rad) { return (rad * (T)180) / (T)PI; } template<typename T> inline T DegToRad(const T& deg) { return (deg * (T)PI) / (T)180; } //inline bool inBetween() }
NullSeile/UITools
src/Rectangle.h
<filename>src/Rectangle.h<gh_stars>1-10 #pragma once #include "Global.h" #include "UIObject.h" namespace ui { class Rectangle : public sf::RectangleShape, public ui::UIObject { public: Rectangle(const std::string& id); void Draw(sf::RenderWindow& window) override; }; }
NullSeile/UITools
src/Line.h
<gh_stars>1-10 #pragma once #include "Global.h" #include "UIObject.h" namespace ui { class Line : public ui::UIObject { private: float m_width; ui::Vec2f m_iPos; ui::Vec2f m_fPos; sf::RectangleShape shape; void Reset(); public: Line(const std::string& id, const ui::Vec2f& iPos, const ui::Vec2f& fPos); void Draw(sf::RenderWindow& window) override; void SetWidth(const float& width); void SetColor(const sf::Color& color); void SetOutlineThickness(const float& width); void SetOutlineColor(const sf::Color& color); void SetStartPos(const ui::Vec2f& pos); ui::Vec2f GetStartPos(); void SetEndPos(const ui::Vec2f& pos); ui::Vec2f GetEndPos(); ~Line(); }; }
NullSeile/UITools
src/Sprite.h
#pragma once #include "Global.h" #include "UIObject.h" namespace ui { class Sprite : public sf::Sprite, public ui::UIObject { public: Sprite(const std::string& id); void Draw(sf::RenderWindow& window) override; }; }
NullSeile/UITools
src/Button.h
#pragma once #define m_BUTTON #include "Global.h" #include "UIObject.h" #include "Interactuable.h" namespace ui { class Button : public ui::UIObject, public ui::Interactuable { private: std::function<void(ui::UIObject* self)> m_clickFunction; bool m_hasClickFuncion = false; bool m_able = true; public: // Constructor Button(const std::string& id); // Generals void CheckInput(const sf::RenderWindow& window, ui::Event& e) override; void Update(const sf::RenderWindow& window) override; void Draw(sf::RenderWindow& window) override; // Set void SetClickFunction(const std::function<void(ui::UIObject* self)>& function); void SetAble(const bool& able); // Get bool GetAble(); std::function<void(Button* self)> GetClickEvent(); ui::Vec2f GetPosition(); // Variables sf::Text text; sf::RectangleShape shape; }; }
NullSeile/UITools
src/Event.h
#pragma once #include "UIObject.h" namespace ui { class Event : public sf::Event { public: bool handled = false; }; }
NullSeile/UITools
src/Slider.h
#pragma once #include "Global.h" #include "UIObject.h" #include "Interactuable.h" namespace ui { class Slider : public ui::UIObject, public ui::Interactuable { private: bool m_pressed = false; float m_value = 0; float m_offset = 0; bool m_showValue = true; ui::Vec2f m_range = { 0, 255 }; float m_step = 0.f; uint m_textPrecision = 2; sf::RectangleShape m_slider; sf::Text m_text; sf::RectangleShape m_body; bool m_hasCustomReleasedFunction = false; std::function<void(UIObject* self)> m_releasedFunction; public: Slider(const std::string& id, const sf::Font& font); // General void CheckInput(const sf::RenderWindow& window, ui::Event& e) override; void Update(const sf::RenderWindow& window) override; void Draw(sf::RenderWindow& window) override; void SetReleasedFunction(const std::function<void(UIObject* self)>& function); // Set void SetValue(const float& value); void SetPosition(const ui::Vec2f& position); void SetPosition(const float& x, const float& y); void SetSize(const float& width, const float& heigth); void SetSize(const ui::Vec2f& size); void SetStep(const float& step); void SetRange(const ui::Vec2f& range); void SetTextPrecision(uint textPrecision); void ShowValue(bool show); // Get ui::Vec2f GetRange(); sf::RectangleShape& GetBody(); sf::RectangleShape& GetHandle(); sf::Text& GetText(); // Get float GetValue() const; bool IsPressed() const; }; }
NullSeile/UITools
src/UIObject.h
#pragma once #include "Global.h" namespace ui { class UIObject { protected: std::function<void(UIObject* self)> m_updateFunction; std::function<void(UIObject* self)> m_beginPlayFunction; bool m_hasCustomUpdateFunction = false; bool m_hasCustomBeginPlayFunction = false; public: UIObject(const std::string& id); ~UIObject(); // Generals virtual void Update(const sf::RenderWindow& window); virtual void Draw(sf::RenderWindow& window) = 0; virtual void BeginPlay(); // Set void SetUpdateFunction(const std::function<void(UIObject* self)>& function); void SetBeginPlayFunction(const std::function<void(UIObject* self)>& function); // Variables const std::string id; }; }
NullSeile/UITools
src/Interactuable.h
<filename>src/Interactuable.h #pragma once #include "Global.h" #include "Event.h" namespace ui { class Interactuable { protected: bool m_blockEvent = true; public: Interactuable(); virtual void CheckInput(const sf::RenderWindow& window, ui::Event& e) = 0; void BlockEvent(bool block); ~Interactuable(); }; }
NullSeile/UITools
src/Vec2.h
#pragma once #include <SFML/System/Vector2.hpp> #include <iostream> namespace ui { template<typename T> class Vec2 : public sf::Vector2<T> { public: T& min; T& max; Vec2() : sf::Vector2<T>() , min(this->x) , max(this->y) { } Vec2(T X, T Y) : sf::Vector2<T>(X, Y) , min(this->x) , max(this->y) { } template<typename U> Vec2(const Vec2<U>& vector) : sf::Vector2<T>(vector) , min(this->x) , max(this->y) { } template<typename U> Vec2(const sf::Vector2<U>& vector) : sf::Vector2<T>(vector) , min(this->x) , max(this->y) { } Vec2(const sf::Vector2<T>& vector) : sf::Vector2<T>(vector) , min(this->x) , max(this->y) { } T Length() const { return sqrt(this->x * this->x + this->y * this->y); } T Angle() const { return (atan2(this->y, this->x) * (T)180) / (T)M_PI; } Vec2& operator =(const Vec2& vec) { sf::Vector2<T>::operator =(vec); return *this; } }; template<typename T> std::ostream& operator<<(std::ostream& os, const Vec2<T>& vec) { os << "(" << vec.x << ", " << vec.y << ")"; return os; } template <typename T> inline Vec2<T> operator -(const Vec2<T>& right) { return Vec2<T>(-right.x, -right.y); } template <typename T> inline Vec2<T>& operator +=(Vec2<T>& left, const Vec2<T>& right) { left.x += right.x; left.y += right.y; return left; } template <typename T> inline Vec2<T>& operator -=(Vec2<T>& left, const Vec2<T>& right) { left.x -= right.x; left.y -= right.y; return left; } template <typename T> inline Vec2<T> operator +(const Vec2<T>& left, const Vec2<T>& right) { return Vec2<T>(left.x + right.x, left.y + right.y); } template <typename T> inline Vec2<T> operator -(const Vec2<T>& left, const Vec2<T>& right) { return Vec2<T>(left.x - right.x, left.y - right.y); } template <typename T> inline Vec2<T> operator *(const Vec2<T>& left, T right) { return Vec2<T>(left.x * right, left.y * right); } template <typename T> inline Vec2<T> operator *(T left, const Vec2<T>& right) { return Vec2<T>(right.x * left, right.y * left); } template <typename T> inline Vec2<T>& operator *=(Vec2<T>& left, T right) { left.x *= right; left.y *= right; return left; } template <typename T> inline Vec2<T> operator /(const Vec2<T>& left, T right) { return Vec2<T>(left.x / right, left.y / right); } template <typename T> inline Vec2<T>& operator /=(Vec2<T>& left, T right) { left.x /= right; left.y /= right; return left; } template <typename T> inline bool operator ==(const Vec2<T>& left, const Vec2<T>& right) { return (left.x == right.x) && (left.y == right.y); } //////////////////////////////////////////////////////////// template <typename T> inline bool operator !=(const Vec2<T>& left, const Vec2<T>& right) { return (left.x != right.x) || (left.y != right.y); } }
NullSeile/UITools
UITools.h
<gh_stars>1-10 #pragma once #include "src/Widget.h"
NullSeile/UITools
src/Circle.h
#pragma once #include "Global.h" #include "UIObject.h" namespace ui { class Circle : public sf::CircleShape, public UIObject { public: Circle(const std::string& id); void Draw(sf::RenderWindow& window) override; }; }
NullSeile/UITools
src/InteractiveGraph.h
#pragma once #include "Graph.h" namespace ui { class InteractiveGraph : public Graph, public Interactuable { private: ui::Vec2f m_startPos; float m_zoom; ui::Vec2f m_center; ui::Vec2f m_view; bool m_mousePressed; float m_aspect; void UpdateView(); public: InteractiveGraph(const std::string& id); void Update(const sf::RenderWindow& window) override; void CheckInput(const sf::RenderWindow& window, ui::Event& e) override; void SetZoom(const float& zoom); void SetCenter(const ui::Vec2f& center); }; }
NullSeile/UITools
src/Text.h
<filename>src/Text.h #pragma once #include "Global.h" #include "UIObject.h" namespace ui { class Text : public sf::Text, public ui::UIObject { public: // Constructor Text(const std::string& id); // Generals void Draw(sf::RenderWindow& window) override; }; }
pilihp64/Crackbot
plugins/sandbox/code.c
#include <lua5.1/lua.h> #include <lua5.1/lualib.h> #include <lua5.1/lauxlib.h> #ifdef WIN32 #include <windows.h> #endif #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define MEMLIMIT 5000000 //20MB static int memused = 0; void *alloc(void *ud, void *ptr, size_t osize, size_t nsize) { if(nsize) { if(memused + nsize - osize> MEMLIMIT) return NULL; memused += nsize - osize; return realloc(ptr, nsize); } else { memused -= osize; free(ptr); return NULL; } } static int panic(lua_State *l) { (void)l; printf("PANIC: unprotected error in call to Lua API (%s)\n", lua_tostring(l, -1)); return 0; } int luaL_tostring (lua_State *L, int n) { luaL_checkany(L, n); switch (lua_type(L, n)) { case LUA_TNUMBER: lua_pushstring(L, lua_tostring(L, n)); break; case LUA_TSTRING: lua_pushvalue(L, n); break; case LUA_TBOOLEAN: lua_pushstring(L, (lua_toboolean(L, n) ? "true" : "false")); break; case LUA_TNIL: lua_pushliteral(L, "nil"); break; default: lua_pushfstring(L, "%s: %p", lua_typename(L, lua_type(L, n)), lua_topointer(L, n)); break; } return 1; } static lua_State *l; void *thread(void *n) { int p = lua_gettop(l); if(lua_pcall(l, 0, LUA_MULTRET, 0)) { luaL_tostring(l, -1); printf("runtime error: %s\n", lua_tostring(l, -1)); lua_pop(l, 1); } else { int c = lua_gettop(l); for(;c >= p;p++) { luaL_tostring(l, p); printf("%s\n", lua_tostring(l, -1)); lua_pop(l, 1); } } exit(0); } int main(int argc, char *argv[]) { if(argc<2) return 0; l = lua_newstate(&alloc, NULL); lua_atpanic(l, &panic); luaL_openlibs(l); luaL_dostring(l,"math.randomseed(os.time())\n\ dofile('derp.lua')\n\ dofile('tableSave.lua')\n\ cashList = table.load('plugins/gameUsers.txt')\n\ table.load, table.save = nil\n\ debug,loadfile,module,require,dofile,package,os.remove,os.tmpname,os.rename,os.execute,os.getenv,string.dump=nil\n\ io={write=io.write}\n\ "); const char *h = argv[1]; char *code = (char*)malloc(strlen(h)/2+1); char *c = code; for(;*h && h[1];h+=2) { *(c++) = (*h - 'A') * 16 + (h[1] - 'A'); } *c = 0; if (luaL_loadbuffer(l, code, strlen(code), "@bot")) { printf("syntax error: %s\n", lua_tostring(l, -1)); return 0; } pthread_t th; pthread_create(&th, NULL, &thread, NULL); #ifdef WIN32 Sleep(500); #else sleep(1); #endif pthread_cancel(th); printf("time limit exceeded\n"); }
7PintsOfCherryGarcia/sqzlib
src/sqzlib/sqz_data.h
#include <zlib.h> #define LOAD_SIZE 4L*1024L*1024L #define NAME_SIZE 1L*1024L*1024L #define B64 sizeof(uint64_t) #define HEADLEN 8 #define NEND 128 #define MAGIC 151324677 #define NBLK 255U #define QBLK 63U #define EBLK 0U #define FQH '@' #define FAH '>' #define FQS '+' #define NL '\n' /* "sqzfastx_t" libsqueezma main data loading structure. Defines the buffers and flags for reading sequencing data into. */ typedef struct { uint8_t nthread; uint8_t endthread; //flags char endflag; //Sequece has not completely been read into a buffer flag char cmpflag; //data members uint64_t size; //Amount of sequence read. uint64_t offset; uint8_t *seq; uint8_t *qlt; uint8_t *namebuffer; uint8_t *readbuffer; uint64_t namesize; uint64_t namepos; //return members uint64_t n; uint64_t bases; uint64_t blks; //Partially loaded sequence uint8_t *pseq; uint8_t *pqlt; uint64_t psize; //Partially decoded sequences uint64_t rem; //Length of sequence remaining to be read uint64_t prevlen; //Size of sequence currently being read } sqzfastx_t; typedef struct { //Code data buffer uint8_t *blkbuff; //Buffer to hold encoded fastX data uint64_t blksize; //Size of blkbuff uint64_t mblksize;//Max size of blkbuff uint64_t blkpos; //Position within blkbuff uint64_t namepos; //Position within namebuffer TODO Rethink this memeber uint64_t prevlen; //How much of current sequence had been decoded uint8_t newblk; //flag //Compression members uint8_t *cmpbuff; //Buffer to hold compressed blk data uint64_t cmpsize; uint64_t mcmpsize;//Max size of cmpbuff uint64_t cmppos; } sqzblock_t; typedef struct sqzFile_s { FILE *fp; gzFile gzfp; sqzfastx_t *sqz; sqzblock_t *blk; uint64_t size; uint8_t ff; uint8_t fmt; uint8_t libfmt; uint64_t filepos; } *sqzFile; int64_t sqz_gzread(sqzFile sqzfp, void *buff, uint32_t len);
7PintsOfCherryGarcia/sqzlib
src/sqzlib/sqz_init.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include "sqz_data.h" sqzfastx_t *sqz_fastxinit(uint8_t fmt, uint64_t size) { uint8_t ret = 1; sqzfastx_t *sqz = calloc(1, sizeof(sqzfastx_t)); if (!sqz) return NULL; sqz->namesize = NAME_SIZE; sqz->endthread = 128U; sqz->size = size; sqz->seq = malloc(size + 1); if (!sqz->seq) goto exit; sqz->seq[size] = '\0'; sqz->namebuffer = malloc(NAME_SIZE); if (!sqz->namebuffer) goto exit; sqz->pseq = malloc(16384); if (!sqz->pseq) goto exit; sqz->psize = 16384; //Get file format if reading an sqz file (lower 3 bits of fmt) switch (fmt & 7) { case 0: goto exit; case 1: //FASTA do nothing, everything allocated break; case 2: //FASTQ sqz->qlt = malloc(size + 1); if (!sqz->qlt) goto exit; sqz->qlt[size] = 0; sqz->pqlt = malloc(16384); if (!sqz->pqlt) goto exit; break; case 5: sqz->readbuffer = malloc(size + 1); if (!sqz->readbuffer) goto exit; sqz->readbuffer[size] = 0; break; case 6: sqz->readbuffer = malloc(size + 1); if (!sqz->readbuffer) goto exit; sqz->readbuffer[size] = '\0'; break; } ret = 0; exit: if (ret) { free(sqz->seq),free(sqz->qlt),free(sqz->namebuffer); free(sqz->readbuffer); return NULL; } return sqz; } void sqz_fastxkill(sqzfastx_t *sqz) { if (sqz) { free(sqz->seq); free(sqz->namebuffer); free(sqz->readbuffer); free(sqz->qlt); free(sqz->pseq); free(sqz->pqlt); free(sqz); } } sqzblock_t *sqz_sqzblkinit(uint64_t size) { sqzblock_t *blk = malloc(sizeof(sqzblock_t)); if (!blk) return NULL; //Encoding buffer blk->blkbuff = malloc(2*size); if (!blk->blkbuff) { free(blk); return NULL; } blk->blksize = 2*size; blk->mblksize = 2*size; blk->blkpos = 0; blk->namepos = 0; blk->prevlen = 0; blk->newblk = 1; //Compression buffer blk->cmpbuff = malloc(2*size); if (!blk->cmpbuff) { free(blk->blkbuff); free(blk); return NULL; } blk->cmpsize = 2*size; blk->mcmpsize = 2*size; blk->cmppos = 0; return blk; } void sqz_blkkill(sqzblock_t *blk) { if (blk) { free(blk->blkbuff); free(blk->cmpbuff); free(blk); } } uint64_t sqz_seqsinblk(sqzblock_t *blk) { uint64_t s = *(uint64_t *)( blk->blkbuff + ( blk->blksize - B64 ) ); uint64_t d = blk->blksize - B64 - s; char *names = (char *)(blk->blkbuff + d); uint64_t p = 0; uint64_t n = 0; while (p != s) { n++; p += strlen(names + p) + 1; } return n; }
7PintsOfCherryGarcia/sqzlib
src/sqzlib/sqz_zlib.c
<filename>src/sqzlib/sqz_zlib.c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <zlib.h> #include "sqz_data.h" int64_t sqz_gzread(sqzFile sqzfp, void *buff, uint32_t len) { return (int64_t)gzread(sqzfp->gzfp, buff, len); } void sqz_gzdump(sqzFile sqzfp, const char *ofile) { uint8_t *buff = NULL; FILE *ofp = NULL; ofp = fopen(ofile, "w"); if (!ofp) goto exit; buff = malloc(LOAD_SIZE); if (!buff) goto exit; uint32_t read; while ( (read = gzread(sqzfp->gzfp, buff, LOAD_SIZE)) ) { fwrite(buff, read, 1, ofp); } exit: if (ofp) fclose(ofp); if (buff) free(buff); } sqzFile sqz_gzopen(const char *filename, sqzFile sqzfp, const char *mode) { sqzfp->gzfp = gzopen(filename, mode); if (!sqzfp->gzfp) { free(sqzfp); return NULL; } return sqzfp; } size_t sqz_deflate(sqzblock_t *blk, int level) { int ret; size_t wbytes = 0; size_t have; z_stream strm; // allocate deflate state strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; ret = deflateInit(&strm, level); if (ret != Z_OK) { fprintf(stderr, "[sqzlib ZLIB ERROR]: Failed to init stream.\n"); return (size_t)ret; } //Main compression loop strm.avail_in = blk->blkpos; strm.next_in = blk->blkbuff; do { strm.avail_out = blk->cmpsize; strm.next_out = blk->cmpbuff; ret = deflate(&strm, Z_FINISH); /* no bad return value */ if ( ret == Z_STREAM_ERROR ) { fprintf(stderr, "[sqzlib ZLIB ERROR]: Deflate error.\n"); return (size_t)ret; /* state not clobbered */ } //check there is enough space in buffer have = blk->cmpsize - strm.avail_out; if ( (wbytes + have) > blk->cmpsize) { fprintf(stderr, "[sqzlib ZLIB ERROR]: Compression error.\n"); ret = Z_ERRNO; break; } wbytes += have; } while (strm.avail_out == 0); //Check compression went well if (ret != Z_STREAM_END) wbytes = 0; deflateEnd(&strm); return wbytes; } uint64_t sqz_inflate(sqzblock_t *blk) { //TODO test with internal memory area to put decompressed data + memcpy int ret; size_t wbytes = 0; size_t have; z_stream strm; // allocate deflate state strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; ret = inflateInit(&strm); if (ret != Z_OK) { fprintf(stderr, "[sqzlib ZLIB ERROR]: Failed to init stream.\n"); return (size_t)ret; } //Main compression loop strm.avail_in = blk->cmpsize; strm.next_in = blk->cmpbuff; do { strm.avail_out = blk->blksize; strm.next_out = blk->blkbuff; ret = inflate(&strm, Z_SYNC_FLUSH); /* no bad return value */ switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; break; case Z_DATA_ERROR: break; case Z_MEM_ERROR: break; case Z_STREAM_ERROR: fprintf(stderr, "[sqzlib ZLIB ERROR]: inflate error.\n"); return (size_t)ret; /* state not clobbered */ } //check there is enough space in buffer have = blk->blksize - strm.avail_out; //fprintf(stderr, "**\t\tdcp: %lu\n", blk->blksize); if ( (wbytes + have) > blk->blksize) { fprintf(stderr, "[sqzlib ZLIB ERROR]: Decompression error %lu.\n", have); ret = Z_ERRNO; break; } //Write to output buffer, keep track of written bytes wbytes += have; } while (strm.avail_out == 0); //Check compression went well if (ret != Z_STREAM_END) wbytes = 0; inflateEnd(&strm); return wbytes; }
7PintsOfCherryGarcia/sqzlib
src/sqzlib/sqz_filefun.c
<reponame>7PintsOfCherryGarcia/sqzlib #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include "sqz_data.h" char zbytes[4] = {0, 0, 0, 0}; uint8_t magic1[4] = {5, 8, 5, 9}; uint8_t magic2[4] = {9, 5, 8, 5}; unsigned char cmpflag = 1; uint8_t sqz_getformat(sqzFile sqzfp); sqzfastx_t *sqz_fastxinit(uint8_t fmt, uint64_t size); sqzblock_t *sqz_sqzblkinit(uint64_t size); void sqz_fastxkill(sqzfastx_t *sqz); void sqz_blkkill(sqzblock_t *blk); uint64_t sqz_inflate(sqzblock_t *blk); uint64_t sqz_fastXdecode(sqzblock_t *blk, uint8_t *buff, uint64_t buffsize, uint8_t fqflag); FILE *fdopen(int fd, const char *mode); sqzFile sqz_gzopen(const char *filename, sqzFile sqzfp, const char *mode); size_t sqz_deflate(sqzblock_t *blk, int level); int64_t sqz_zstdcompress(sqzblock_t *blk, int level); uint64_t sqz_zstddecompress(sqzblock_t *blk); static void sqz_fastxreset(sqzfastx_t *sqz) { sqz->endflag = 0; sqz->cmpflag = 0; sqz->offset = 0; sqz->namepos = 0; sqz->n = 0; sqz->bases = 0; sqz->rem = 0; sqz->prevlen = 0; } static void sqz_blkreset(sqzblock_t *blk) { blk->blkpos = 0; blk->namepos = 0; blk->newblk = 1; blk->cmppos = 0; } static void sqz_decode(sqzfastx_t *sqz, sqzblock_t *blk, uint8_t fmt, uint64_t klibl) { switch (fmt) { case 2: sqz->offset = sqz_fastXdecode(blk, sqz->readbuffer, klibl, 1); break; case 1: sqz->offset = sqz_fastXdecode(blk, sqz->readbuffer, klibl, 0); break; } } int64_t sqz_blkcompress(sqzblock_t *blk, int level, uint8_t libfmt) { switch (libfmt) { case 1: return sqz_deflate(blk, level); case 2: return sqz_zstdcompress(blk, level); } return -1; } uint64_t sqzdecompress(sqzblock_t *blk, uint8_t libfmt) { switch (libfmt) { case 1: return sqz_inflate(blk); case 2: return sqz_zstddecompress(blk); } return 0; } void sqzrewind(sqzFile sqzfp) { sqz_fastxreset(sqzfp->sqz); sqz_blkreset(sqzfp->blk); fseek(sqzfp->fp, HEADLEN, SEEK_SET); sqzfp->filepos = ftell(sqzfp->fp); sqzfp->ff = 0; } char sqz_filehead(uint8_t fmt, uint8_t libfmt, FILE *ofp) { char wbytes = 0; if ( 4 != (wbytes += fwrite(magic1, 1, 4, ofp)) ) return 0; if ( 5 != (wbytes += fwrite(&fmt, 1, 1, ofp)) ) return 0; //Compression library if ( 6 != (wbytes += fwrite(&libfmt, 1, 1, ofp)) ) return 0; if ( 8 != (wbytes += fwrite(zbytes, 1, 2, ofp)) ) return 0; return wbytes; } char sqz_filetail(uint64_t numseqs, uint64_t nblocks, FILE *ofp) { if ( 4 != fwrite(zbytes, 1, 4, ofp) ) { return 0; } if ( 1 != fwrite(&numseqs, B64, 1, ofp) ) { return 0; } if ( 2 != fwrite(zbytes, 1, 2, ofp) ) { return 0; } if ( 1 != fwrite(&nblocks, B64, 1, ofp) ) { return 0; } if ( 2 != fwrite(zbytes, 1, 2, ofp) ) { return 0; } if ( 4 != fwrite(magic2, 1, 4, ofp) ) { return 0; } return 1; } char sqz_blkdump(void *cmpbuff, uint64_t *blksize, uint64_t cmpsize, FILE *ofp) { size_t wbytes = 0; //Write uncompressed number of bytes in block wbytes += fwrite(blksize, B64, 1, ofp); //Write compressed number of bytes in block wbytes += fwrite(&cmpsize, B64, 1, ofp); //Write block wbytes += fwrite(cmpbuff, cmpsize, 1, ofp); if (wbytes != 3) return 0; return 1; } uint64_t sqz_filesize(sqzFile fp) { if (!fp) return 0; long current = ftell(fp->fp); fseek(fp->fp, 0, SEEK_END); long s = ftell(fp->fp); fseek(fp->fp, current, SEEK_SET); return (uint64_t)(s - 28); } int sqz_fseek(sqzFile sqzfp, long offset, int whence) { return fseek(sqzfp->fp, offset, whence); } uint64_t sqz_fread(void *ptr, uint64_t size, uint64_t nmemb, sqzFile sqzfp) { return fread(ptr, size, nmemb, sqzfp->fp); } uint64_t sqz_getfilepos(sqzFile sqzfp) { return ( sqzfp->filepos = ftell(sqzfp->fp) ); } uint8_t sqz_sqzisfq(sqzFile sqzfp) { return (sqzfp->fmt & 3) == 2 ? 1 : 0; } uint8_t sqz_sqzgetcmplib(sqzFile sqzfp) { return sqzfp->fmt >> 3; } sqzblock_t *sqz_sqzgetblk(sqzFile sqzfp) { return sqzfp->blk; } uint8_t sqz_format(sqzFile sqzfp) { return sqzfp->fmt; } sqzFile sqzopen(const char *filename, const char *mode) { sqzFile sqzfp = calloc(1, sizeof(struct sqzFile_s)); if (!sqzfp) return NULL; sqzfp->fp = fopen(filename, mode); if ( !(sqzfp->fp) ) { free(sqzfp); return NULL; } sqz_gzopen(filename, sqzfp, mode); if ( (!sqzfp->fp) || !sqzfp) { free(sqzfp); return NULL; } sqzfp->fmt = sqz_getformat(sqzfp); //If not sqz format, no need for the rest of members if ( !(sqzfp->fmt & 4) ) return sqzfp; sqzfp->libfmt = sqzfp->fmt >> 3; sqzfp->ff = 0; sqzfp->size = sqz_filesize(sqzfp); fseek(sqzfp->fp, HEADLEN, SEEK_SET); sqzfp->filepos = ftell(sqzfp->fp); sqzfp->blk = sqz_sqzblkinit(LOAD_SIZE); if (!sqzfp->blk) { fclose(sqzfp->fp); free(sqzfp); return NULL; } sqzfp->sqz = sqz_fastxinit(sqzfp->fmt, LOAD_SIZE); if (!sqzfp->sqz) { fclose(sqzfp->fp); free(sqzfp); return NULL; } return sqzfp; } sqzFile sqzdopen(int fd, const char *mode) { return NULL; } void sqzclose(sqzFile sqzfp) { fclose(sqzfp->fp); gzclose(sqzfp->gzfp); if (sqzfp->sqz) sqz_fastxkill(sqzfp->sqz); if (sqzfp->blk) sqz_blkkill(sqzfp->blk); free(sqzfp); } uint8_t sqz_readblksize(sqzblock_t *blk, sqzFile sqzfp, uint8_t libfmt) { uint8_t ret = 0; FILE *fp = sqzfp->fp; uint64_t cmpsize; uint64_t dcpsize; uint64_t nelem; nelem = fread(&dcpsize, B64, 1, fp); nelem += fread(&cmpsize, B64, 1, fp); if ( cmpsize > (blk->mcmpsize) ) { blk->cmpbuff = realloc(blk->cmpbuff, cmpsize); if ( !(blk->cmpbuff) ) goto exit; blk->mcmpsize = cmpsize; } if ( dcpsize > (blk->mblksize) ) { blk->blkbuff = realloc(blk->blkbuff, dcpsize); if ( !(blk->blkbuff) ) goto exit; blk->mblksize = dcpsize; } blk->cmpsize = cmpsize; blk->blksize = dcpsize; if ( (cmpsize != fread(blk->cmpbuff, 1, cmpsize, fp)) || (nelem != 2) ) goto exit; if (dcpsize != sqzdecompress(blk, libfmt)) goto exit; blk->newblk = 1; ret = 1; exit: return ret; } int64_t sqzread(sqzFile file, void *buff, uint64_t len) { if (!file || !buff) return -1; if ( !(file->fmt & 4) ) return sqz_gzread(file, buff, (uint32_t)len); sqzfastx_t *sqz = file->sqz; sqzblock_t *blk = file->blk; uint8_t fmt = file->fmt & 3; uint8_t *outbuff = (uint8_t *)buff; int64_t read = 0; switch (file->ff & 127) { case 0: { if (!sqz_readblksize(file->blk, file, file->libfmt)) goto error; if ( (uint64_t)ftell(file->fp) == file->size) file->ff |= 128U; sqz_decode(sqz, blk, fmt, LOAD_SIZE); read = sqz->offset > len ? len : sqz->offset; memcpy(outbuff, sqz->readbuffer, read); sqz->rem += read; sqz->offset -= read; if (sqz->offset < len) file->ff = (file->ff & 128) | 2U; else file->ff = (file->ff & 128) | 1U; return read; } case 1: //Data just need to be copied { memcpy(outbuff, sqz->readbuffer + sqz->rem, len); sqz->rem += len; sqz->offset -= len; if (sqz->offset < len) file->ff = (file->ff & 128U) | 2U; return len; } case 2: //Data can be copied but entire buffer can't be filled { ; uint64_t outpos; uint64_t leftover = sqz->offset; memcpy(outbuff, sqz->readbuffer + sqz->rem, sqz->offset); outpos = leftover; if (blk->newblk) sqz_decode(sqz, blk, fmt, LOAD_SIZE); else { if (file->ff & 128U) { file->ff = 3U; return leftover; } else { if (!sqz_readblksize(file->blk, file, file->libfmt)) goto error; if (ftell(file->fp) == (long)file->size) file->ff |= 128U; sqz_decode(sqz, blk, fmt, LOAD_SIZE); } } read = sqz->offset > ( len - leftover) ? (len - leftover) : sqz->offset; memcpy(outbuff + outpos, sqz->readbuffer, read); sqz->offset -= read; outpos += read; sqz->rem = read; if (outpos < len) { if (file->ff & 128U) { file->ff = 3U; return outpos; } else { if (!sqz_readblksize(file->blk, file, file->libfmt)) goto error; if (ftell(file->fp) == (long)file->size) file->ff |= 128U; sqz_decode(sqz, blk, fmt, LOAD_SIZE); read = sqz->offset > (len-outpos) ? (len-outpos) : sqz->offset; memcpy(outbuff + outpos, sqz->readbuffer, read); sqz->offset -= read; sqz->rem = read; outpos += read; } } if (sqz->offset < len) file->ff = (file->ff & 128U) | 2U; else file->ff = (file->ff & 128U) | 1U; return outpos; } case 3: return 0; } error: return -1; } uint64_t sqz_getblocks(sqzFile sqzfp) { uint64_t n; if (!sqzfp) return 0; if (!(sqzfp->fmt & 4)) return 0; long current = ftell(sqzfp->fp); if (fseek(sqzfp->fp, -14, SEEK_END)) return 0; if (!fread(&n, B64, 1, sqzfp->fp)) return 0; if (fseek(sqzfp->fp, current, SEEK_SET)) return 0; return n; } uint8_t sqz_go2blockn(sqzFile sqzfp, uint64_t n) { if ( (n > sqz_getblocks(sqzfp)) ) return 1; uint64_t blkn = 0; uint64_t blks = 0; uint64_t blkr = 0; if (fseek(sqzfp->fp, HEADLEN, SEEK_SET)) return 1; while (blkn < n) { if (fseek(sqzfp->fp, 8, SEEK_CUR)) return 1; blkr = fread(&blks, B64, 1, sqzfp->fp); if (blkr) { if(fseek(sqzfp->fp, blks, SEEK_CUR)) return 1; sqzfp->filepos = ftell(sqzfp->fp); blkn++; } else return 1; } return 0; } uint64_t sqz_loadblk(sqzblock_t *blk, uint8_t **buff, uint64_t s, uint8_t fqflag) { uint64_t p = 0; uint64_t d; while (blk->newblk) { d = sqz_fastXdecode(blk, *buff + p, s, fqflag); if (d == s) { s <<= 2; *buff = realloc(*buff, s); if (!buff) return 0; } p += d; } return p; }
7PintsOfCherryGarcia/sqzlib
examples/countseqs.c
<gh_stars>1-10 #include "sqzlib.h" #include "klib/kseq.h" KSEQ_INIT(sqzFile, sqzread) int main(int argc, char *argv[]) { int ret = 1; if (argc == 1) { printf("Usage: countseqs <file>\n"); return 0; } sqzFile sqzfp; kseq_t *seq; int l; size_t n = 0; sqzfp = sqzopen(argv[1], "r"); if ( !sqzfp ) return -1; seq = kseq_init(sqzfp); while ( (l = kseq_read(seq)) >= 0) ++n; if (l != -1) { fprintf(stderr, "ERROR: malformated FASTX\n"); goto exit; } fprintf(stderr, "%lu sequences\n", n); ret = 0; exit: kseq_destroy(seq); sqzclose(sqzfp); return ret; }
7PintsOfCherryGarcia/sqzlib
src/pthread/sqz_pthread.c
<filename>src/pthread/sqz_pthread.c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <zlib.h> #include <pthread.h> #include "../sqzlib/sqzlib.h" #include "klib/kseq.h" //int64_t sqzread(sqzFile file, void *buff, uint64_t len); KSEQ_INIT(sqzFile, sqzread) typedef struct { pthread_mutex_t mtx; pthread_cond_t conscond; pthread_cond_t readcond; pthread_cond_t intraconscond; pthread_attr_t thatt; int goread; int gocons; int doneq; int wakethreadn; int threadid; int nthread; const char *ifile; const char *ofile; sqzfastx_t **sqzqueue; FILE *ofp; uint8_t fqflag; uint8_t libfmt; } sqzthread_t; static void sqz_threadwait(int *flag, pthread_cond_t *cond, pthread_mutex_t *mtx) { while (!(*flag)) { pthread_cond_wait(cond, mtx); } } static void sqz_syncwakeup(int *flag, pthread_cond_t *cond, pthread_mutex_t *mtx, int n) { if (n == *flag) { pthread_cond_broadcast(cond); return; } while (*flag != n) pthread_cond_wait(cond, mtx); } static int sqz_getthreadid(sqzthread_t *sqzthread) { pthread_mutex_lock(&(sqzthread->mtx)); int id = sqzthread->threadid++; sqz_threadwait(&(sqzthread->gocons), &(sqzthread->conscond), &(sqzthread->mtx)); //Thread wakes up, now it has to wait for all other threads to wake up sqzthread->wakethreadn++; //Go to sleep again until all threads have woken up sqz_syncwakeup(&(sqzthread->wakethreadn), &(sqzthread->intraconscond), &(sqzthread->mtx), sqzthread->nthread); pthread_mutex_unlock(&(sqzthread->mtx)); return id; } static void sqz_wakereader(sqzthread_t *sqzthread) { pthread_mutex_lock(&(sqzthread->mtx)); sqzthread->doneq++; if (sqzthread->nthread == sqzthread->doneq) { sqzthread->doneq = 0; sqzthread->goread = 1; pthread_cond_signal(&(sqzthread->readcond)); } sqzthread->gocons = 0; sqz_threadwait(&(sqzthread->gocons), &(sqzthread->conscond), &(sqzthread->mtx)); //Thread wakes up and increases flag sqzthread->wakethreadn++; //Thread goes to sleep again until all threads have woken up sqz_syncwakeup(&(sqzthread->wakethreadn), &(sqzthread->intraconscond), &(sqzthread->mtx), sqzthread->nthread); pthread_mutex_unlock(&(sqzthread->mtx)); } static sqzfastx_t **sqz_sqzqueueinit(uint8_t nthread, uint8_t fmt) { sqzfastx_t **sqzqueue = calloc(nthread, sizeof(sqzfastx_t*)); if (!sqzqueue) return NULL; for (int i = 0; i < nthread; i++) if ( !(sqzqueue[i] = sqz_fastxinit(fmt, LOAD_SIZE)) ) { for(int j = 0; j < i; j++) sqz_fastxkill(sqzqueue[j]); return NULL; } return sqzqueue; } static void *sqz_consumerthread(void *thread_data) { sqzthread_t *sqzthread = thread_data; uint64_t cbytes = 0; sqzblock_t *blk = sqz_sqzblkinit(100UL*1024UL*1024UL); if (!blk) goto exit; int id = sqz_getthreadid(sqzthread); sqzfastx_t *sqz = sqzthread->sqzqueue[id - 1]; uint8_t fqflag = sqzthread->fqflag; int libfmt = sqzthread->libfmt; //Do some work if there is available data while (sqz->endthread & 128) { //bit 7 is on if there is still data //Encode data sqz_fastXencode(sqz, blk, fqflag); //Compress block cbytes = sqz_blkcompress(blk, 9, libfmt); //Write compressed block to output file pthread_mutex_lock(&(sqzthread->mtx)); sqz_blkdump(blk->cmpbuff, &(blk->blkpos), cbytes, sqzthread->ofp); fflush(sqzthread->ofp); blk->blkpos = 0; sqz->namepos = 0; sqz->endflag = 0; sqz->blks++; pthread_mutex_unlock(&(sqzthread->mtx)); //bit 1 is on if thread had data, but reader has finished if (sqz->endthread & 1) break; //Thread done, signal reader and go to sleep until new data arrives sqz_wakereader(sqzthread); } exit: sqz_blkkill(blk); pthread_exit(NULL); } static void sqz_wakeconsumers(sqzthread_t *sqzthread) { pthread_mutex_lock(&(sqzthread->mtx)); sqzthread->goread = 0; sqzthread->gocons = 1; sqzthread->wakethreadn = 0; pthread_cond_broadcast(&(sqzthread->conscond)); sqz_threadwait(&(sqzthread->goread), &(sqzthread->readcond), &(sqzthread->mtx)); pthread_mutex_unlock(&(sqzthread->mtx)); } static void *sqz_dcpthread(void *thread_data) { sqzthread_t *sqzthread = (sqzthread_t *)thread_data; uint8_t nthread = sqzthread->nthread; uint8_t *outbuff = NULL; uint8_t *filebuff = NULL; uint64_t dsize = 0; pthread_mutex_lock(&(sqzthread->mtx)); int id = sqzthread->threadid++; pthread_mutex_unlock(&(sqzthread->mtx)); sqzFile sqzfp = sqzopen(sqzthread->ifile, "rb"); if (!sqzfp) goto exit; uint8_t fqflag = sqz_sqzisfq(sqzfp); uint8_t libfmt = sqz_sqzgetcmplib(sqzfp); sqzblock_t *blk = sqz_sqzgetblk(sqzfp); outbuff = malloc(LOAD_SIZE); if (!outbuff) goto exit; filebuff = malloc(LOAD_SIZE); if (!filebuff) goto exit; uint64_t fbsize = LOAD_SIZE; uint64_t fbpos = 0; uint64_t nblk = sqz_getblocks(sqzfp); if (!nblk) goto exit; uint64_t currentblk = (uint64_t)id; while (currentblk < nblk) { if (sqz_go2blockn(sqzfp, currentblk)) { fprintf(stderr, "[sqz ERROR]: Failed to read number of blocks.\n"); goto exit; } if (!sqz_readblksize(blk, sqzfp, libfmt)) { fprintf(stderr, "[sqz ERROR]: Failed to read block %lu.\n", currentblk); goto exit; } do { dsize = sqz_fastXdecode(blk, outbuff, LOAD_SIZE, fqflag); if ( (fbpos + dsize) >= fbsize) { fbsize *= 2; filebuff = realloc(filebuff, fbsize); if (!filebuff) goto exit; } memcpy(filebuff + fbpos, outbuff, dsize); fbpos += dsize; } while (blk->newblk); pthread_mutex_lock(&(sqzthread->mtx)); fwrite(filebuff, fbpos, 1, sqzthread->ofp); fflush(sqzthread->ofp); pthread_mutex_unlock(&(sqzthread->mtx)); fbpos = 0; currentblk += nthread; } exit: if(sqzfp) sqzclose(sqzfp); if(outbuff) free(outbuff); if (filebuff) free(filebuff); pthread_exit(NULL); } static void *sqz_decompressor(void *thread_data) { sqzthread_t *sqzthread = (sqzthread_t *)thread_data; sqzFile sqzfp = sqzopen(sqzthread->ifile, "rb"); if (!sqzfp) goto exit; uint8_t fmt = sqz_format(sqzfp); if ( !(fmt & 4) ) { fprintf(stderr, "[sqz WARNING]: Not an sqz file\n"); sqz_gzdump(sqzfp, sqzthread->ofile); sqzclose(sqzfp); } else { sqzclose(sqzfp); sqzthread->ofp = fopen(sqzthread->ofile, "wb"); if (!sqzthread->ofp) goto exit; pthread_t *consumer_pool = malloc(sqzthread->nthread * sizeof(pthread_t)); for (int i = 0; i < sqzthread->nthread; i++) if (pthread_create(consumer_pool + i, &(sqzthread->thatt), sqz_dcpthread, (void *)thread_data)) goto exit; for (int i = 0; i < sqzthread->nthread; i++) if (pthread_join(consumer_pool[i], NULL)) fprintf(stderr, "[sqz ERROR]: Thread error join\n"); free(consumer_pool); fclose(sqzthread->ofp); } exit: return NULL; } static void *sqz_compressor(void *thread_data) { sqzthread_t *sqzthread = (sqzthread_t *)thread_data; sqzthread->threadid++; sqzfastx_t **sqzqueue = NULL; kseq_t *seq = NULL; pthread_t *consumer_pool = NULL; sqzFile sqzfp = sqzopen(sqzthread->ifile, "r"); if (!sqzfp) goto exit; uint8_t fmt = sqz_format(sqzfp); uint8_t nthread = sqzthread->nthread; sqzqueue = sqz_sqzqueueinit(nthread, fmt & 3); if (!sqzqueue) goto exit; sqzthread->sqzqueue = sqzqueue; uint8_t fqflag = sqz_sqzisfq(sqzfp); sqzthread->fqflag = fqflag; //Initialize kseq object seq = kseq_init(sqzfp); if (!seq) goto exit; //Open output file and write sqz header sqzthread->ofp = fopen(sqzthread->ofile, "wb"); if (!sqzthread->ofp) goto exit; if ( !sqz_filehead(sqzthread->fqflag ? 2 : 1, sqzthread->libfmt, sqzthread->ofp) ) { fclose(sqzthread->ofp); return NULL; } fflush(sqzthread->ofp); //Start consumer pool consumer_pool = malloc(nthread * sizeof(pthread_t)); if (!consumer_pool) goto exit; for (int i = 0; i < nthread; i++) //TODO indicate error if (pthread_create(consumer_pool + i, &(sqzthread->thatt), sqz_consumerthread, (void *)thread_data)) goto exit; int thcounter = 0; while (sqz_loadfastX(sqzqueue[thcounter], fqflag, seq)) { thcounter++; if (nthread == thcounter) { thcounter = 0; sqz_wakeconsumers(sqzthread); } } if (thcounter % nthread) { //Set bit 1 of threads that got some data for (int i = 0; i < thcounter; i++) sqzqueue[i]->endthread |= 1; } //Unset bit 7 from rest of threads for (int i = thcounter; i < nthread; i++) sqzqueue[i]->endthread &= 127; //Wake consumers one last time sqzthread->goread = 0; sqzthread->gocons = 1; sqzthread->wakethreadn = 0; pthread_cond_broadcast(&(sqzthread->conscond)); //Wait until done for (int i = 0; i < nthread; i++) if (pthread_join(consumer_pool[i], NULL)) fprintf(stderr, "[sqz ERROR]: Thread error join\n"); //Log number of sequences and blocks uint64_t n = 0; uint64_t b = 0; for (int i = 0; i < nthread; i++) { b += sqzqueue[i]->blks; n += sqzqueue[i]->n; } sqz_filetail(n, b, sqzthread->ofp); exit: if (consumer_pool) free(consumer_pool); if (seq) kseq_destroy(seq); if (sqzfp) sqzclose(sqzfp); return NULL; } static sqzthread_t *sqz_threadinit(const char *ifile, const char *ofile, uint8_t libfmt, uint8_t nthread) { sqzthread_t *sqzthread = calloc(1, sizeof(sqzthread_t)); if (!sqzthread) return NULL; sqzthread->ifile = ifile; sqzthread->ofile = ofile; sqzthread->libfmt = libfmt; sqzthread->nthread = nthread; pthread_mutex_init(&(sqzthread->mtx), NULL); pthread_cond_init(&(sqzthread->conscond), NULL); pthread_cond_init(&(sqzthread->readcond), NULL); pthread_cond_init(&(sqzthread->intraconscond), NULL); pthread_attr_init(&(sqzthread->thatt)); return sqzthread; } static void sqz_threadkill(sqzthread_t *sqzthread) { if (sqzthread) { if( sqzthread->sqzqueue ) for (int i = 0; i < sqzthread->nthread; i++) if ( sqzthread->sqzqueue[i] ) sqz_fastxkill(sqzthread->sqzqueue[i]); free(sqzthread->sqzqueue); pthread_attr_destroy(&(sqzthread->thatt)); pthread_mutex_destroy(&(sqzthread->mtx)); pthread_cond_destroy(&(sqzthread->conscond)); pthread_cond_destroy(&(sqzthread->readcond)); pthread_cond_destroy(&(sqzthread->intraconscond)); free(sqzthread); } } static uint8_t sqz_inflatefastX(sqzFile sqzfp, FILE *ofp, char fqflag, uint8_t libfmt) { uint8_t ret = 1; uint8_t *outbuff = NULL; uint64_t dsize = 0; uint64_t size = 0; sqzblock_t *blk = sqz_sqzblkinit(LOAD_SIZE); if (!blk) goto exit; size = sqz_filesize(sqzfp); outbuff = malloc(LOAD_SIZE); if (!outbuff) goto exit; sqz_fseek(sqzfp, HEADLEN, SEEK_SET); while ( sqz_getfilepos(sqzfp) < size ) { if (!sqz_readblksize(blk, sqzfp, libfmt)) goto exit; do { dsize = sqz_fastXdecode(blk, outbuff, LOAD_SIZE, fqflag); fwrite(outbuff, 1, dsize, ofp); fflush(ofp); } while (blk->newblk); } ret = 0; exit: sqz_blkkill(blk); free(outbuff); return ret; } uint8_t sqz_threaddecompress(const char *ifile, const char *ofile, uint8_t nthread) { uint8_t ret = 1; sqzthread_t *sqzthread = sqz_threadinit(ifile, ofile, 0, nthread); if (!sqzthread) goto exit; pthread_t rthread; if (pthread_create(&rthread, &(sqzthread->thatt), sqz_decompressor, (void *)sqzthread)) { fprintf(stderr, "[sqz ERROR]: thread launch error.\n"); goto exit; } if (pthread_join(rthread, NULL)) { fprintf(stderr, "\t[sqz ERROR]: thread join failed.\n"); goto exit; } ret = 0; exit: sqz_threadkill(sqzthread); return ret; } uint8_t sqz_threadcompress(const char *ifile, const char *ofile, uint8_t libfmt, uint8_t nthread) { uint8_t ret = 1; sqzthread_t *sqzthread = sqz_threadinit(ifile, ofile, libfmt, nthread); if (!sqzthread) goto exit; pthread_t r; if (pthread_create(&r, &(sqzthread->thatt), sqz_compressor, (void *)sqzthread)) { fprintf(stderr, "[sqz ERROR]: thread launch error.\n"); goto exit; } if (pthread_join(r, NULL)) { fprintf(stderr, "\t[sqz ERROR]: thread join failed.\n"); goto exit; } ret = 0; exit: sqz_threadkill(sqzthread); return ret; }
7PintsOfCherryGarcia/sqzlib
src/sqzlib/sqzlib.h
<gh_stars>1-10 /** \file sqzlib.h <NAME> - <EMAIL> MIT License Copyright (c) 2021 <NAME> 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. */ #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <zlib.h> #define LOAD_SIZE 4L*1024L*1024L //Sequence buffer size #define NAME_SIZE 1L*1024L*1024L //Sequence name buffer size #define HEADLEN 8UL #define B64 8UL //64bits - 8 bytes //TODO These structs will become opaque /* "sqzfastx_t" libsqueezma main data loading structure. Defines the buffers and flags for reading sequencing data into. */ typedef struct { uint8_t nthread; uint8_t endthread; //flags char endflag; //Sequece has not completely been read into a buffer flag char cmpflag; //data members uint64_t size; //Amount of sequence read. uint64_t offset; uint8_t *seq; uint8_t *qlt; uint8_t *namebuffer; uint8_t *readbuffer; uint64_t namesize; uint64_t namepos; //return members uint64_t n; uint64_t bases; uint64_t blks; //Partially loaded sequence uint8_t *pseq; uint8_t *pqlt; uint64_t psize; //Partially decoded sequences uint64_t rem; //Length of sequence remaining to be read uint64_t prevlen; //Size of sequence currently being read } sqzfastx_t; /* Docstring */ typedef struct { //Code data buffer uint8_t *blkbuff; //Buffer to hold encoded fastX data uint64_t blksize; //Size of blkbuff uint64_t mblksize;//Max size of blkbuff uint64_t blkpos; //Position within blkbuff uint64_t namepos; //Position within namebuffer TODO Rethink this memeber uint64_t prevlen; //How much of current sequence had been decoded uint8_t newblk; //flag //Compression members uint8_t *cmpbuff; //Buffer to hold compressed blk data uint64_t cmpsize; uint64_t mcmpsize;//Max size of cmpbuff uint64_t cmppos; } sqzblock_t; /* Docstring */ typedef struct sqzFile_S* sqzFile; /* ############################################################################## kseq compatibility routines ############################################################################## */ /* Read len decoded and decompressed bytes into buff Returns number of bytes written into buff. If returned value is less than len but greater that or equal to 0, end of file has been reached. -1 on error. */ int64_t sqzread(sqzFile file, void *buff, uint64_t len); /* Open sqzFile Returns sqzFile object or NULL on failure */ sqzFile sqzopen(const char *filename, const char *mode); /* Associate an sqzFile with the file descriptor fd */ sqzFile sqzdopen(int fd, const char *mode); /* Rewinds sqzFile. Only suported during reading */ void sqzrewind(sqzFile file); /* Close sqzFile */ void sqzclose(sqzFile file); /* ############################################################################## sqz file routines ############################################################################## */ /* Write an sqz header */ char sqz_filehead(uint8_t fmt, uint8_t libfmt, FILE *ofp); /* Write an sqz tail */ char sqz_filetail(uint64_t numseqs, uint64_t numblks, FILE *ofp); /* Get format of a fastX file */ uint8_t sqz_getformat(sqzFile sqzfp); /* Get size of an sqz file */ uint64_t sqz_filesize(sqzFile sqzfp); /* Get number of blocks in sqz file */ uint8_t sqz_getblocks(sqzFile sqzfp); /* Write entire gz sqzFile to ofile */ void sqz_gzdump(sqzFile sqzfp, const char *ofile); /* Read len uncompressed bytes from gzip sqzfile into buff */ int64_t sqz_gzread(sqzFile sqzfp, void *buff, uint32_t len); /* sqzlib interface to fseek */ int sqz_fseek(sqzFile sqzfp, long offset, int whence); /* sqzlib interface to fread */ uint64_t sqz_fread(void *ptr, uint64_t size, uint64_t nmemb, sqzFile sqzfp); /* sqzlib interface to ftell */ uint64_t sqz_getfilepos(sqzFile sqzfp); /* Returns 1 if sqzfile is fastq format */ uint8_t sqz_sqzisfq(sqzFile sqzfp); /* Get compression library */ uint8_t sqz_sqzgetcmplib(sqzFile sqzfp); /* Get sqzblock structure from sqzfile */ sqzblock_t *sqz_sqzgetblk(sqzFile sqzfp); /* Got to block number in n in sqz file */ uint8_t sqz_go2blockn(sqzFile sqzfp, uint64_t n); /* Get format of sqz file */ uint8_t sqz_format(sqzFile sqzfp); /* ############################################################################## sqz structure routines ############################################################################## */ /* Initialize sqzfastx structure */ sqzfastx_t *sqz_fastxinit(uint8_t fmt, uint64_t size); /* Free sqzfastx structure */ void sqz_fastxkill(sqzfastx_t *sqz); /* Initialize an sqzblock structure */ sqzblock_t *sqz_sqzblkinit(uint64_t size); /* Terminate an sqzblock structure */ void sqz_blkkill(sqzblock_t *blk); /* Get number of sequences in block */ uint64_t sqz_seqsinblk(sqzblock_t *blk); /* ############################################################################## sqz data routines ############################################################################## */ /* Read a data block into an sqz block structure */ uint8_t sqz_readblksize(sqzblock_t *blk, sqzFile sqzfp, uint8_t libfmt); /* Compress encoded data block */ int64_t sqz_blkcompress(sqzblock_t *blk, int level, uint8_t libfmt); /* Encode data from sqz into blk */ char sqz_fastXencode(sqzfastx_t *sqz, sqzblock_t *blk, uint8_t fqflag); /* Decode data in sqz block to memory */ uint64_t sqz_fastXdecode(sqzblock_t *blk, uint8_t *buff, uint64_t size, uint8_t fqflag); uint64_t sqz_loadfastX(sqzfastx_t *sqz, uint8_t fqflag, void *seq); /* Write compressed block to file */ char sqz_blkdump(void *cmpbuff, uint64_t *blksize, uint64_t cmpsize, FILE *ofp); /* Decoad and load sqz block into buff */ uint64_t sqz_loadblk(sqzblock_t *blk, uint8_t **buff, uint64_t s, uint8_t fqflag); #ifdef __cplusplus } #endif
7PintsOfCherryGarcia/sqzlib
src/sqzlib/sqz_kseq.c
<gh_stars>1-10 #include <stdio.h> #include <stdint.h> #include "sqz_data.h" int64_t sqzread(sqzFile file, void *buff, uint64_t len); #include "klib/kseq.h" KSEQ_INIT(sqzFile, sqzread) static uint8_t sqz_checksqz(sqzFile sqzfp) { uint64_t tmp = 0; uint32_t magic = 0; uint8_t fmt = 0; uint8_t sqz = 0; //Read magic tmp += fread(&magic, 1, 4, sqzfp->fp); if (MAGIC ^ magic) { rewind(sqzfp->fp); return 0; } //Set sqz flag fmt |= 4; //Read sequence format tmp += fread(&sqz, 1, 1, sqzfp->fp); fmt |= sqz; //Read compression library tmp += fread(&sqz, 1, 1, sqzfp->fp); fmt |= (sqz << 3); rewind(sqzfp->fp); return fmt; } static uint8_t sqz_remeber(sqzfastx_t *sqz, kseq_t *seq, uint8_t fqflag) { // TODO Pass sequence and length instead of kseq_t struct if (sqz->psize <= seq->seq.l) { if (fqflag) sqz->pqlt = realloc(sqz->pqlt, seq->seq.l*2); sqz->pseq = realloc(sqz->pseq, seq->seq.l*2); if ( ( fqflag && !(sqz->pqlt) ) || !(sqz->pseq)) return 1; sqz->psize = seq->seq.l*2; } memcpy(sqz->pseq, seq->seq.s, seq->seq.l + 1); if (fqflag) memcpy(sqz->pqlt, seq->qual.s, seq->seq.l + 1); return 0; } static uint8_t sqz_loadname(sqzfastx_t *sqz, kseq_t *seq) { uint8_t ret = 0; uint8_t *namebuffer = sqz->namebuffer; uint64_t pos = sqz->namepos; //Check namebuffer is large enough if ( (pos + seq->comment.l + seq->name.l) >= sqz->namesize) { namebuffer = realloc(namebuffer, sqz->namesize*2); if (!(namebuffer)) goto exit; sqz->namebuffer = namebuffer; sqz->namesize *= 2; } memcpy(namebuffer + pos, seq->name.s, seq->name.l + 1); pos += seq->name.l + 1; //If comment exists if (seq->comment.s) { //Substitute terminating null with space namebuffer[pos - 1] = ' '; //Append comment including terminating null memcpy(namebuffer + pos, seq->comment.s, seq->comment.l + 1); pos += seq->comment.l + 1; } ret = 1; exit: sqz->namepos = pos; return ret; } static uint64_t sqz_fastanblock(sqzfastx_t *sqz, kseq_t *kseq) { uint64_t offset = 0; uint64_t n = 0; uint64_t l; uint64_t bases = 0; uint64_t maxlen = sqz->size - B64 - 1; uint8_t *seq = sqz->seq; while ( (kseq_read(kseq) >= 0) ) { l = kseq->seq.l; bases += l; n++; if (!sqz_loadname(sqz, kseq)) { offset = 0; goto exit; } if (l > maxlen) { sqz->endflag = 1; sqz->prevlen = l; sqz_remeber(sqz, kseq, 0); goto exit; } memcpy(seq + offset, &l, B64); offset += B64; memcpy(seq + offset, kseq->seq.s, l + 1); offset += l + 1; if ( maxlen <= (l + 1 + B64) ) break; maxlen -= (l + 1 + B64); } exit: sqz->n += n; sqz->bases = bases; sqz->offset = offset; return n; } static uint64_t sqz_fastqnblock(sqzfastx_t *sqz, kseq_t *kseq) { uint64_t offset = 0; uint64_t n = 0; uint64_t l; uint64_t bases = 0; uint64_t maxlen = sqz->size - B64 - 1; uint8_t *seq = sqz->seq; uint8_t *qlt = sqz->qlt; while ( kseq_read(kseq) >= 0 ) { l = kseq->seq.l; bases += l; n++; if (!sqz_loadname(sqz, kseq)) { offset = 0; goto exit; } if ( l > maxlen ) { sqz->endflag = 1; sqz->prevlen = l; sqz_remeber(sqz, kseq, 1); goto exit; } memcpy(seq + offset, &l, B64); offset += B64; memcpy(seq + offset, kseq->seq.s, l + 1); memcpy(qlt + offset, kseq->qual.s, l + 1); offset += (l + 1); if ( maxlen <= (l + 1 + B64) ) break; maxlen -= (l + 1 + B64); } exit: sqz->n += n; sqz->bases = bases; sqz->offset = offset; return offset; } uint8_t sqz_getformat(sqzFile sqzfp) { uint8_t ret = 0; if ( (ret = sqz_checksqz(sqzfp)) ) return ret; kseq_t *seq = kseq_init(sqzfp); if (!seq) return ret; int l = kseq_read(seq); //ERROR if (l < 0) goto exit; //FASTQ if (seq->qual.l > 0) { ret = 2; goto exit; } //FASTA ret = 1; exit: kseq_destroy(seq); gzrewind(sqzfp->gzfp); return ret; } uint64_t sqz_loadfastX(sqzfastx_t *sqz, uint8_t fqflag, kseq_t *seq) { if (fqflag) return sqz_fastqnblock(sqz, seq); return sqz_fastanblock(sqz, seq); }
7PintsOfCherryGarcia/sqzlib
src/sqzlib/sqz_coding.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <zlib.h> #include <stdint.h> #include "sqz_data.h" #define TWO_BIT_MASK 3 const uint8_t nblk = 255U; const uint8_t qblk = 63U; const uint8_t eblk = 0U; //Table to change "ACGT" to 0123 else to 4 const unsigned char seq_nt4_tableSQZ[128] = { 128, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; //Table to change 01234 to ACGTN const unsigned char seq_dec_tableSQZ[128] = { 'A', 'C','G', 'T', 'N', 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; //Table to change 0,1,2,3,4,5,6,7 to quality values const unsigned char qual_val_table[8] = {33,39,48,55,60,66,70,73}; static inline const uint8_t *sqz_findn(const uint8_t *seq) { while (seq_nt4_tableSQZ[*seq] < 4) seq++; return seq; } static inline uint64_t sqz_bit2encode(const uint8_t *seq, uint8_t seqlen) { uint64_t result = 0; for (uint64_t i = 0; i < seqlen; i++) result = (result << 2) | seq_nt4_tableSQZ[seq[i]]; return result; } static uint64_t sqz_blkcode(uint64_t *buff, const uint8_t *seq, uint64_t len) { if (!len) return 0; uint64_t nblks = ( (len / 32) + ( (len % 32) > 0 ) ) - 1; uint64_t code = 0; uint64_t buffpos; uint64_t nbytes = 0; uint8_t lenleft = 0; //1 less than the total number of iterations needed. for (buffpos = 0; buffpos < nblks; buffpos++) { //Pack 32 mer into 64 bit int code = sqz_bit2encode(seq, 32); memcpy(buff + buffpos, &code, B64); nbytes += B64; seq += 32; } lenleft = ( len - ( nblks * 32) ); code = sqz_bit2encode(seq, lenleft); memcpy(buff + buffpos, &code, B64); nbytes += B64; return nbytes; } static uint64_t sqz_nblkcode(uint8_t *buff, uint64_t len) { if (!len) return 0; //1 less than the total number of iterations needed. uint64_t nblks = ( (len / 127) + ( (len % 127) > 0 ) ) - 1; uint64_t buffpos = 0; for (buffpos = 0; buffpos < nblks; buffpos++) buff[buffpos] = 127; // 127 consecutive non ACGT bases //Last itteration needs special treatment //Set bit 7 if last N block before next base buff[buffpos++] = (len - (nblks * 127)) | NEND; return buffpos; } static uint8_t sqz_8binqual(uint8_t q) { if (q >= 73) return 7<<5; if ( (q < 73) && (q >= 68) ) return 6<<5; if ( (q < 68) && (q >= 63) ) return 5<<5; if ( (q < 63) && (q >= 58) ) return 4<<5; if ( (q < 58) && (q >= 53) ) return 3<<5; if ( (q < 53) && (q >= 43) ) return 2<<5; if ( (q < 43) && (q >= 35) ) return 1<<5; if ( (q < 35) && (q > 0) ) return 1; return 0; } static uint64_t sqz_qualencode(const uint8_t *qlt, uint64_t l, uint8_t *blkbuff) { uint64_t blkpos = 0; uint8_t q = sqz_8binqual(*qlt); uint8_t c = 0; uint8_t code = 0; while(l) { //If next qual val is the same if ( sqz_8binqual(*(qlt + 1)) == q) { //Increase counter c++; //If counter reached if (c == 31) { //Encode qlt++; l--; code = code | (q & 224); code = code | c; memcpy(blkbuff + blkpos, &code, 1); blkpos++; c = 0; code = 0; q = sqz_8binqual(*(qlt + 1)); } qlt++; l--; continue; } //Encode code = code | (q & 224); code = code | c; memcpy(blkbuff + blkpos, &code, 1); blkpos++; qlt++; l--; q = sqz_8binqual(*qlt); c = 0; code = 0; } return blkpos; } static uint64_t sqz_seqencode(const uint8_t *seq, uint64_t l, uint8_t *blkbuff) { uint64_t blkpos = 0; const uint8_t *lstop = seq; const uint8_t *nptr = seq + l; const uint8_t *npos = NULL; uint64_t nn = 0; uint64_t blen = 0; do { //Get position of first non ACGTacgt base npos = sqz_findn(lstop); if (*npos) { //Determine block length up to first non ACGT base blen = npos - lstop; //Determine number of consecutive Ns until next base nn = 0; while ( seq_nt4_tableSQZ[*npos] == 4) { nn++; npos++; } //Write block length memcpy(blkbuff + blkpos, &blen, B64); blkpos += B64; //Encode sequence blkpos += sqz_blkcode((uint64_t *)(blkbuff + blkpos), lstop, blen); //Trace next base after sequence of Ns lstop = npos; //Indicate that a non-ACGT block follows memcpy(blkbuff + blkpos, &nblk, 1); blkpos++; //Encode non-ACGT block blkpos += sqz_nblkcode(blkbuff + blkpos, nn); } } while (*npos); //Detect and encode trailing bases blen = nptr - lstop; if (blen) { memcpy(blkbuff + blkpos, &blen, B64); blkpos += B64; blkpos += sqz_blkcode((uint64_t *)(blkbuff + blkpos), lstop, blen); } return blkpos; } static uint8_t sqz_fastqheadblk(sqzfastx_t *sqz, sqzblock_t *blk) { uint8_t *blkbuff = blk->blkbuff; uint64_t blkpos = 0; uint8_t *seqb = sqz->seq; uint8_t *qltb = sqz->qlt; uint64_t sqzsize = sqz->offset; uint8_t *seq = NULL; uint8_t *qlt = NULL; uint64_t seqlen = 0; uint64_t k = 0; while ( k < sqzsize ) { seqlen = *(uint64_t *)( seqb + k ); k += B64; memcpy(blkbuff + blkpos, &seqlen, B64); blkpos += B64; seq = seqb + k; qlt = qltb + k; blkpos += sqz_seqencode(seq, seqlen, blkbuff + blkpos); memcpy(blkbuff + blkpos, &qblk, 1); blkpos++; blkpos += sqz_qualencode(qlt, seqlen, blkbuff + blkpos); k += seqlen + 1; } //Last sequence, loaded into kseq, but not copied into buffer if (sqz->endflag) { memcpy(blkbuff + blkpos, &sqz->prevlen, B64); blkpos += B64; blkpos += sqz_seqencode(sqz->pseq, sqz->prevlen, blkbuff + blkpos); memcpy(blkbuff + blkpos, &qblk, 1); blkpos++; blkpos += sqz_qualencode(sqz->pqlt, sqz->prevlen, blkbuff + blkpos); } //Copy name data making sure it fits uint64_t blksize = blk->blksize; if ( (blkpos + sqz->namepos) >= blksize ) { blksize += sqz->namepos + B64; blkbuff = realloc(blk->blkbuff, blksize); blk->blkbuff = blkbuff; blk->blksize = blksize; blk->cmpsize = blksize; blk->cmpbuff = realloc(blk->cmpbuff, blk->cmpsize); } memcpy(blkbuff + blkpos, sqz->namebuffer, sqz->namepos); blkpos += sqz->namepos; memcpy(blkbuff + blkpos, &(sqz->namepos), B64); blkpos += B64; sqz->cmpflag = 1; blk->blkpos = blkpos; return 1; } static uint8_t sqz_fastaheadblk(sqzfastx_t *sqz, sqzblock_t *blk) { uint8_t *blkbuff = blk->blkbuff; uint64_t blkpos = blk->blkpos; uint8_t *seqb = sqz->seq; uint64_t sqzsize = sqz->offset; uint8_t *seq = NULL; uint64_t seqlen = 0; uint64_t k = 0; while ( k < sqzsize ) { seqlen = *(uint64_t *)( seqb + k ); k += B64; memcpy(blkbuff + blkpos, &seqlen, B64); blkpos += B64; seq = seqb + k; blkpos += sqz_seqencode(seq, seqlen, blkbuff + blkpos); memcpy(blkbuff + blkpos, &eblk, 1); blkpos++; k += seqlen + 1; } //Last sequence, loaded into kseq, but not copied into buffer if (sqz->endflag) { memcpy(blkbuff + blkpos, &sqz->prevlen, B64); blkpos += B64; blkpos += sqz_seqencode(sqz->pseq, sqz->prevlen, blkbuff + blkpos); memcpy(blkbuff + blkpos, &eblk, 1); blkpos++; } //Copy name data making sure it fits uint64_t blksize = blk->blksize; if ( (blkpos + sqz->namepos) >= blksize ) { blksize += sqz->namepos + B64; blkbuff = realloc(blk->blkbuff, blksize); blk->blkbuff = blkbuff; blk->blksize = blksize; blk->cmpsize = blksize; blk->cmpbuff = realloc(blk->cmpbuff, blk->cmpsize); } memcpy(blkbuff + blkpos, sqz->namebuffer, sqz->namepos); blkpos += sqz->namepos; memcpy(blkbuff + blkpos, &(sqz->namepos), B64); blkpos += B64; sqz->cmpflag = 1; blk->blkpos = blkpos; return 1; } char sqz_fastXencode(sqzfastx_t *sqz, sqzblock_t *blk, uint8_t fqflag) { if (fqflag) return sqz_fastqheadblk(sqz, blk); return sqz_fastaheadblk(sqz, blk); } /* ################################################################################ Decoding functions ################################################################################ */ static inline uint64_t sqz_blksize(uint64_t blklen) { return ( (blklen / 32) + ((blklen % 32) > 0) ) * B64; } static uint64_t sqz_qdecode(const uint8_t *codebuff, uint8_t *outbuff, uint64_t rquals, uint64_t offset) { uint64_t pos = 0; uint64_t nbyte = 0; uint8_t q; uint8_t prevqn; uint8_t i = 0; uint8_t j; //Go to byte of current offset while (pos < offset) { pos += 1 + (*(codebuff + nbyte) & 31); nbyte++; } prevqn = pos - offset; if (prevqn) { q = (*(codebuff - 1) & 224) >> 5; for (i = 0; i < prevqn; i++) *outbuff++ = qual_val_table[q]; rquals -= prevqn; } while (rquals) { i = 1 + (*(codebuff + nbyte) & 31); q = (*(codebuff + nbyte) & 224) >> 5; nbyte++; i = i > rquals ? rquals : i; rquals -= i; for (j = 0; j < i; j++) *outbuff++ = qual_val_table[q]; } return nbyte; } /* Counts number of Ns in an N block Returns number of Ns Modifies pos with number of bytes decoded */ static uint64_t sqz_countnblk(const uint8_t *buff, uint64_t *pos) { uint64_t count = 0; uint64_t i = 0; while ( !(buff[i++] & 128) ) { count += 127; } count += buff[i - 1] & 127; *pos = i; return count; } static uint64_t sqz_qbytes(uint8_t *codebuff, uint64_t bases) { uint64_t rbases = 0; uint64_t nbytes = 0; while (rbases < bases) { rbases += 1 + (*(codebuff++) & 31); nbytes++; } return nbytes; } static uint64_t sqz_gotoqblk(uint8_t *codebuff) { uint64_t codepos = 0; uint64_t blklen; uint8_t nflag; uint64_t bases = 0; uint64_t pos; while (1) { blklen = *(uint64_t *)(codebuff + codepos); codepos += B64; if (blklen) codepos += sqz_blksize(blklen); bases += blklen; nflag = *(codebuff + codepos); codepos++; switch (nflag) { case NBLK: bases += sqz_countnblk(codebuff + codepos, &pos); codepos += pos; continue; case QBLK: goto exit; case EBLK: goto exit; } } exit: return codepos; } static uint64_t sqz_gotoblk(uint8_t *codebuff, uint64_t *retpos, uint64_t offset) { uint64_t bases = 0; uint64_t rbases = 0; uint64_t codepos = 0; uint64_t rpos = 0; uint64_t npos = 0; uint8_t nflag = 0; uint64_t blklen; while (offset >= bases ) { //Store how many bases have been counted rbases = bases; rpos = codepos; //Count block blklen = *(uint64_t *)(codebuff + codepos); codepos += B64; bases += blklen; if (blklen) codepos += sqz_blksize(blklen); //Count N block nflag = *(codebuff + codepos); codepos++; switch (nflag) { case NBLK: bases += sqz_countnblk(codebuff + codepos, &npos); codepos += npos; continue; case QBLK: break; case EBLK: break; } } *retpos += rpos; return rbases; } static void sqz_writens(uint64_t numn, uint8_t *decoded) { while (numn-- > 0) decoded[numn] = 'N'; } static uint64_t sqz_ndecode(uint8_t *codebuff, uint8_t *outbuff, uint64_t offset, uint64_t len, uint64_t *retpos, uint64_t *blkoffset) { uint64_t codepos = 0; uint64_t nlength = 0; uint64_t nbases = 0; //Compute N blk length and number of bytes it needed for encoding nlength = sqz_countnblk(codebuff, &codepos); //Determine how many Ns will fit in buffer nbases = len < ( nlength - offset ) ? len : ( nlength - offset ); sqz_writens(nbases, outbuff); //Move to next block if no more Ns are left to decode if ( !(nlength - offset - nbases) ) { *retpos += codepos; *blkoffset = 0; } return nbases; } static void sqz_merdecode(uint64_t mer, uint8_t *outbuff, uint8_t discard, uint8_t nbases) { mer >>= (discard * 2); uint8_t byte; while(nbases--) { byte = mer & TWO_BIT_MASK; outbuff[nbases] = seq_dec_tableSQZ[byte]; mer >>= 2; } } static void sqz_mblk(const uint64_t *codebuff, uint8_t *outbuff, uint64_t offset, uint64_t len, uint64_t blklen) { uint8_t lb; if ( (len + offset) == blklen ) lb = blklen % 32; else lb = 32; uint64_t codepos = 0; uint64_t outpos = 0; uint64_t blknum = 0; //Compute start position within 32mer uint8_t startpos = offset % 32; //Number of bases to decode from this first 32mer uint8_t nbases = len < (uint64_t)(32 - startpos) ? (uint8_t)len : (32 - startpos); if (nbases) blknum++; //Compute how many blks encode the number of bases requested blknum += ( (len - nbases) / 32) + ( ( (len - nbases) % 32) > 0 ) - 1; //Move to corresponding 32mer const uint64_t *mer = codebuff + (offset / 32); uint64_t blkidx; for (blkidx = 0; blkidx < blknum; blkidx++) { sqz_merdecode(*(mer + blkidx), outbuff + outpos, 0, nbases); codepos += B64; outpos += nbases; startpos = 0; nbases = 32; } len -= outpos; //How large is this last mer? sqz_merdecode(*(mer + blkidx), outbuff + outpos, lb - len, len); codepos += B64; outpos += len; } /* Returns size of a sequence code block */ static uint64_t sqz_codeblksize(uint8_t *codebuff) { uint64_t bases = 0; uint64_t codepos = 0; uint64_t blkpos2 = 0; uint64_t blklen = 0; uint8_t nflag = 0; uint64_t seqlen = *(uint64_t *)codebuff; codepos += B64; while (bases != seqlen) { blklen = *(uint64_t *)(codebuff + codepos); codepos += B64; if (blklen) { bases += blklen; codepos += sqz_blksize(blklen); } //Read N flag nflag = *(codebuff + codepos); codepos++; //Check and account for Ns switch (nflag) { case NBLK: bases += sqz_countnblk(codebuff + codepos, &blkpos2); codepos += blkpos2; if (bases == seqlen) codepos++; //Sequence ends in non-ACGT block continue; case QBLK: codepos += sqz_qbytes(codebuff + codepos, bases); continue; case EBLK: break; } } return codepos; } /* Decodes blklen encoded bases Returns number of bytes decoded Updates wbytes with number of bytes written */ static uint64_t sqz_blkdecode(const uint8_t *codebuff, uint8_t *outbuff, uint64_t *wbytes, uint64_t blklen) { if (!blklen) return 0; //1 less than the total number of iterations needed uint64_t blknum = ( (blklen / 32) + ( (blklen % 32) > 0) ) - 1; uint64_t codepos = 0; uint64_t outpos = 0; uint64_t blkidx = 0; uint64_t blkleft = (blklen % 32) == 0 ? 32 : blklen % 32; uint64_t *mer; mer = (uint64_t *)codebuff; for (blkidx = 0; blkidx < blknum; blkidx++) { sqz_merdecode( *(mer + blkidx), outbuff + outpos, 0, 32); codepos += B64; outpos += 32; } sqz_merdecode( *(mer + blkidx), outbuff + outpos, 0, blkleft); codepos += B64; outpos += blkleft; *wbytes += outpos; return codepos; } static void sqz_pblk(uint8_t *codebuff, uint64_t offset, uint64_t len, uint8_t *outbuff) { uint64_t outpos = 0; uint64_t nnum = 0; uint64_t availbases = len; uint64_t codepos = 0; uint64_t blklen = 0; uint64_t noffset = 0; uint64_t blkbases = 0; //Go to corresponding block (block corresponding to current offset) blkbases = sqz_gotoblk(codebuff, &codepos, offset); offset -= blkbases; while (outpos < len) { //Determine seq blk, n blk, or quality block blklen = *(uint64_t *)(codebuff + codepos); //Offset within N block? if (offset >= blklen) { codepos += (B64 + sqz_blksize(blklen) + 1); noffset = offset - blklen; nnum = sqz_ndecode(codebuff + codepos, outbuff + outpos, noffset, availbases, &codepos, &offset); outpos += nnum; availbases -= nnum; continue; } //How much of the block is available uint64_t blkavail = blklen - offset; uint64_t bases = blkavail < len - outpos ? blkavail : len - outpos; sqz_mblk( (uint64_t*)(codebuff + codepos + B64), outbuff + outpos, offset, bases, blklen); outpos += bases; offset += bases; availbases -= bases; } } /* Given a partially decoded sequence, continue decoding from where it was left Retrns number of decoded bytes */ static uint64_t sqz_rdecode(uint8_t *codebuff, uint8_t *outbuff, uint64_t outsize, uint64_t seqlen, uint64_t decoded, uint8_t fqflag) { uint64_t bleft = 0; uint64_t seq2decode = 0; uint64_t qlt2decode = 0; uint64_t qdecoded = 0; seq2decode = seqlen < decoded ? 0 : seqlen - decoded; seq2decode = seq2decode < outsize ? seq2decode : outsize; qdecoded = seqlen < decoded ? decoded - seqlen - 3 : 0; //Compute how much buffer will be available bleft = outsize - seq2decode; if (seq2decode) { sqz_pblk(codebuff, decoded, seq2decode, outbuff); if (bleft < 3) goto exit; } //In case of fastq, we have to deal with qualities if (fqflag) { if (!qdecoded) { outbuff[seq2decode++] = NL; outbuff[seq2decode++] = '+'; outbuff[seq2decode++] = NL; bleft -= 3; } //How many qualities can be decoded qlt2decode = seqlen - qdecoded < bleft ? (seqlen - qdecoded) : bleft; sqz_qdecode(codebuff + sqz_gotoqblk(codebuff), outbuff + seq2decode, qlt2decode, qdecoded); } exit: return seq2decode + qlt2decode; } /* Decodes outsize bytes from blkbuff Returns number of bytes written */ static uint64_t sqz_pdecode(uint8_t *codebuff, uint8_t *outbuff, uint64_t outsize, uint64_t seqlen, uint8_t fqflag) { uint64_t outpos = 0; //Determine number of bases that fit in buffer uint64_t todecode = (seqlen < outsize) ? seqlen : outsize; sqz_pblk(codebuff, 0, todecode, outbuff); outpos += todecode; outsize -= todecode; //Decode quality if enough space if ( (outsize > 3) && fqflag ) { outbuff[outpos++] = NL; outbuff[outpos++] = '+'; outbuff[outpos++] = NL; outsize -= 3; sqz_qdecode(codebuff + sqz_gotoqblk(codebuff), outbuff + outpos, outsize, 0); outpos += outsize; } return outpos; } /* Loads length bases into decodebuffer Returns number of bytes decoded Updates wbytes with number of bytes written */ static uint64_t sqz_seqdecode(const uint8_t *codebuff, uint8_t *outbuff, uint64_t length, char qflag, uint64_t *wbytes) { uint64_t seqlen = length; uint64_t codepos = 0; uint64_t blklen = 0; uint64_t qltnum = 0; uint64_t outpos = 0; uint64_t nnum = 0; uint64_t nbytes; while (length > 0) { blklen = *(uint64_t *)(codebuff + codepos); qltnum += blklen; codepos += B64; codepos += sqz_blkdecode(codebuff + codepos, outbuff + outpos, &outpos, blklen); length -= blklen; if (length) { codepos++; //nflag byte nnum = sqz_countnblk(codebuff + codepos, &nbytes); qltnum += nnum; codepos += nbytes; sqz_writens(nnum, outbuff + outpos); outpos += nnum; length -= nnum; if (!length) codepos++; //Sequence ends in non-ACGT block continue; } //Flag byte (q or end os seq) codepos++; } //Decode quality strings for fastq data if (qflag) { outbuff[outpos++] = NL; outbuff[outpos++] = '+'; outbuff[outpos++] = NL; codepos += sqz_qdecode(codebuff + codepos, outbuff + outpos, seqlen, 0); outpos += seqlen; } outbuff[outpos++] = NL; *wbytes += outpos; return codepos; } uint64_t sqz_fastXdecode(sqzblock_t *blk, //Data block uint8_t *outbuff, //Array to place decoded data uint64_t outsize, //Size of outbuff char fqflag) //0 - fasta, 1 - fastq { uint8_t *codebuff = blk->blkbuff; uint64_t codepos = blk->blkpos; uint64_t outpos = 0; //Last 8 bytes store size of name buffer uint64_t namesize = *(uint64_t *)( codebuff + ( blk->blksize - B64 ) ); //Size of sequence data in block uint64_t datasize = blk->blksize - B64 - namesize; char *namebuff = (char *)( codebuff + datasize ); uint64_t namepos = blk->namepos; uint64_t prevbytes = blk->prevlen; //Read length of first sequence uint64_t seqlen = *(uint64_t *)( codebuff + codepos );; //Length of name of first sequence uint64_t namelen = strlen(namebuff + namepos); //Extra bytes per seq uint8_t E = fqflag ? 6 : 3; uint64_t buffneed = ( seqlen * (1 + fqflag) ) + (E + namelen); //Check if there is sequence that was not completely decoded if (prevbytes) { uint64_t decoded = prevbytes - namelen - 2; outpos = sqz_rdecode(codebuff + codepos + B64, outbuff, outsize, seqlen, decoded, fqflag); prevbytes += outpos; //Check that no more sequence needs decoding. (Move to next sequence) if (prevbytes < buffneed - 1) goto exit; outbuff[outpos++] = NL; outsize -= outpos; prevbytes = 0; //Update code buffer position to next sequence codepos += sqz_codeblksize(codebuff + codepos); //Get new sequence info namepos += namelen + 1; namelen = strlen(namebuff + namepos); seqlen = *(uint64_t *)( codebuff + codepos ); buffneed = ( seqlen * (1 + fqflag) ) + (E + namelen); } //While there is data to decode while ( codepos < datasize ) { //Test if there is enough space for current sequence if ( outsize < buffneed ) { //Test if at least: ">"|"@" + name length + '\n' + 1 base fits if (outsize < namelen + 3) { //Can't decode this sequence, just return buffer prevbytes = 0; blk->blkpos = codepos; blk->namepos = namepos; goto exit; } outbuff[outpos++] = fqflag ? FQH : FAH; memcpy(outbuff + outpos, namebuff + namepos, namelen); outpos += namelen; outbuff[outpos++] = NL; outsize -= (2 + namelen); prevbytes = sqz_pdecode(codebuff + codepos + B64, outbuff + outpos, outsize, seqlen, fqflag); outpos += prevbytes; prevbytes += (2 + namelen); blk->blkpos = codepos; blk->namepos = namepos; goto exit; } //Sequence fits and there is still space in buffer outbuff[outpos++] = fqflag ? FQH : FAH; memcpy(outbuff + outpos, namebuff + namepos, namelen); outpos += namelen; outbuff[outpos++] = NL; codepos += B64; //fprintf(stderr, "%s\nlen: %lu\n", namebuff + namepos, seqlen); codepos += sqz_seqdecode(codebuff + codepos, outbuff + outpos, seqlen, fqflag, &outpos); outsize -= buffneed; namepos += namelen + 1; //New sequence seqlen = *(uint64_t *)( codebuff + codepos ); namelen = strlen(namebuff + namepos); buffneed = ( seqlen * (1 + fqflag) ) + (E + namelen); } blk->newblk = 0; blk->blkpos = 0; blk->namepos = 0; exit: blk->prevlen = prevbytes; return outpos; }
7PintsOfCherryGarcia/sqzlib
src/sqz.c
<filename>src/sqz.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <getopt.h> #include <unistd.h> typedef struct { char ifile[256]; char ofile[256]; int nthread; char libfmt; } sqzopts_t; uint8_t sqz_threadcompress(const char *ifile, const char *ofile, uint8_t libfmt, uint8_t nthread); uint8_t sqz_threaddecompress(const char *ifile, const char *ofile, uint8_t nthread); char sqz_compress(sqzopts_t opts) { return sqz_threadcompress(opts.ifile, opts.ofile, opts.libfmt, opts.nthread); } char sqz_decompress(sqzopts_t opts) { return sqz_threaddecompress(opts.ifile, opts.ofile, opts.nthread); } void sqz_usage() { fprintf(stderr, "[sqz]: Usage:\n\n"); fprintf(stderr, "\tsqz [options] <file>\n\n"); fprintf(stderr, "\t\tOptions:\n"); fprintf(stderr, "\t\t-d \t\tDecompress previously sqz compressed file.\n"); fprintf(stderr, "\t\t-o <file>\tWrite to outputfile <file>.\n"); fprintf(stderr, "\t\t-t <n>\t\tUse <n> compression/decompression threads.\n"); fprintf(stderr, "\t\t-l <lib>\tUse <lib> compression library."\ "\n\t\t\t\t\tDefault: -l zlib\n"\ "\t\t\t\t\tOptions: zlib, zstd\n"); fprintf(stderr, "\t\t-h \t\tThis help message.\n\n"); } char *sqz_basename(char *namestr) { char *tok = strtok(namestr, "/"); char *ret = tok; while (NULL != (tok = strtok(NULL, "/"))) ret = tok; return ret; } char sqz_ropts(int argc, char **argv, sqzopts_t *opts) { int elem; char ret = 1; //Defaults to encode and compress char dflag = 0; //Decompression flag char oflag = 1; //Output flag char *lib = NULL; //Compression library to use int nthread = 1; int minargs = 2; while (( elem = getopt(argc, argv, "o:t:l:hd") ) >= 0) { switch(elem) { case 'd': dflag = 1; ret = 2; minargs += 1; continue; case 'o': oflag = 0; strcpy(opts->ofile, optarg); minargs += 2; continue; case 't': nthread = atoi(optarg); minargs += 2; continue; case 'l': lib = optarg; minargs += 2; continue; case 'h': ret = 0; sqz_usage(); goto exit; case '?': sqz_usage(); ret = 0; goto exit; } } if (argc < minargs) { fprintf(stderr, "[sqz]: Please provide input file.\n\n"); sqz_usage(); ret = 0; goto exit; } if ( access(argv[argc - 1], F_OK) ) { fprintf(stderr, "[sqz]: %s, file not found.\n\n", argv[argc - 1]); sqz_usage(); ret = 0; goto exit; } strcpy(opts->ifile, argv[argc - 1]); if (dflag) { if (oflag) strcpy(opts->ofile, "/dev/stdout"); } else { if (oflag) { char *bname = sqz_basename( argv[argc - 1] ); strcpy(opts->ofile, bname); strcat(opts->ofile, ".sqz"); } } if (nthread <= 0) opts->nthread = 1; else opts->nthread = nthread; if (!lib) opts->libfmt = 1; else { if (!strcmp(lib, "zlib")) opts->libfmt = 1; else if (!strcmp(lib, "zstd")) opts->libfmt = 2; else { fprintf(stderr, "[sqz]: %s compression lib not supported\n\n", lib); sqz_usage(); ret = 0; } } exit: return ret; } int main(int argc, char *argv[]) { int ret = 1; if (argc < 2) { sqz_usage(); goto exit; } sqzopts_t opts; switch (sqz_ropts(argc, argv, &opts)) { case 0: goto exit; case 1: if ( sqz_compress(opts) ) goto exit; break; case 2: if ( sqz_decompress(opts)) goto exit; break; } ret = 0; exit: return ret; }
7PintsOfCherryGarcia/sqzlib
src/sqzlib/sqz_zstd.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <zstd.h> #include "sqz_data.h" int64_t sqz_zstdcompress(sqzblock_t *blk, int level) { int64_t ret = 0; ret = ZSTD_compress(blk->cmpbuff, blk->cmpsize, blk->blkbuff, blk->blkpos, level); if (ZSTD_isError(ret)) return -1; return ret; } uint64_t sqz_zstddecompress(sqzblock_t *blk) { int64_t ret = 0; ret = ZSTD_decompress(blk->blkbuff, blk->blksize, blk->cmpbuff, blk->cmpsize); if (ZSTD_isError(ret)) return 0; return (uint64_t)ret; }
denizkenankilic/computerVision-basic-hough
hough.h
#ifndef HOUGH_H_ #define HOUGH_H_ #include <vector> namespace keymolen { class Hough { public: Hough(); virtual ~Hough(); public: int Transform(unsigned char* img_data, int w, int h); std::vector< std::pair< std::pair<int, int>, std::pair<int, int> > > GetLines(int threshold); const unsigned int* GetAccu(int *w, int *h); private: unsigned int* _accu; int _accu_w; int _accu_h; int _img_w; int _img_h; }; } #endif /* HOUGH_H_ */
zmichaels11/rcl
rcl/src/rcl/arguments.c
<reponame>zmichaels11/rcl // Copyright 2018 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// \cond INTERNAL // Internal Doxygen documentation #include "rcl/arguments.h" #include <assert.h> #include <string.h> #include "./arguments_impl.h" #include "./remap_impl.h" #include "rcl/error_handling.h" #include "rcl/lexer_lookahead.h" #include "rcl/validate_topic_name.h" #include "rcl_yaml_param_parser/parser.h" #include "rcl_yaml_param_parser/types.h" #include "rcutils/allocator.h" #include "rcutils/error_handling.h" #include "rcutils/format_string.h" #include "rcutils/logging.h" #include "rcutils/logging_macros.h" #include "rcutils/strdup.h" #include "rmw/validate_namespace.h" #include "rmw/validate_node_name.h" #ifdef __cplusplus extern "C" { #endif /// Parse an argument that may or may not be a remap rule. /** * \param[in] arg the argument to parse * \param[in] allocator an allocator to use * \param[in,out] output_rule input a zero intialized rule, output a fully initialized one * \return RCL_RET_OK if a valid rule was parsed, or * \return RCL_RET_INVALID_REMAP_RULE if the argument is not a valid rule, or * \return RCL_RET_BAD_ALLOC if an allocation failed, or * \return RLC_RET_ERROR if an unspecified error occurred. */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_rule( const char * arg, rcl_allocator_t allocator, rcl_remap_t * output_rule); /// Parse an argument that may or may not be a param rule. /** * \param[in] arg the argument to parse * \param[in,out] params param overrides structure to populate. * This structure must have been initialized by the caller. * \return RCL_RET_OK if a valid rule was parsed, or * \return RCL_RET_INVALID_ARGUMENT if an argument is invalid, or * \return RCL_RET_INVALID_PARAM_RULE if the argument is not a valid rule, or * \return RCL_RET_BAD_ALLOC if an allocation failed, or * \return RLC_RET_ERROR if an unspecified error occurred. */ rcl_ret_t _rcl_parse_param_rule( const char * arg, rcl_params_t * params); rcl_ret_t rcl_arguments_get_param_files( const rcl_arguments_t * arguments, rcl_allocator_t allocator, char *** parameter_files) { RCL_CHECK_ALLOCATOR_WITH_MSG(&allocator, "invalid allocator", return RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(arguments, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(arguments->impl, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(parameter_files, RCL_RET_INVALID_ARGUMENT); *(parameter_files) = allocator.allocate( sizeof(char *) * arguments->impl->num_param_files_args, allocator.state); if (NULL == *parameter_files) { return RCL_RET_BAD_ALLOC; } for (int i = 0; i < arguments->impl->num_param_files_args; ++i) { (*parameter_files)[i] = rcutils_strdup(arguments->impl->parameter_files[i], allocator); if (NULL == (*parameter_files)[i]) { // deallocate allocated memory for (int r = i; r >= 0; --r) { if (NULL == (*parameter_files[r])) { break; } allocator.deallocate((*parameter_files[r]), allocator.state); } allocator.deallocate((*parameter_files), allocator.state); (*parameter_files) = NULL; return RCL_RET_BAD_ALLOC; } } return RCL_RET_OK; } int rcl_arguments_get_param_files_count( const rcl_arguments_t * args) { if (NULL == args || NULL == args->impl) { return -1; } return args->impl->num_param_files_args; } rcl_ret_t rcl_arguments_get_param_overrides( const rcl_arguments_t * arguments, rcl_params_t ** parameter_overrides) { RCL_CHECK_ARGUMENT_FOR_NULL(arguments, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(arguments->impl, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(parameter_overrides, RCL_RET_INVALID_ARGUMENT); if (NULL != *parameter_overrides) { RCL_SET_ERROR_MSG("Output parameter override pointer is not null. May leak memory."); return RCL_RET_INVALID_ARGUMENT; } *parameter_overrides = rcl_yaml_node_struct_copy(arguments->impl->parameter_overrides); if (NULL == *parameter_overrides) { return RCL_RET_BAD_ALLOC; } return RCL_RET_OK; } /// Parse an argument that may or may not be a log level rule. /** * \param[in] arg the argument to parse * \param[in] allocator an allocator to use * \param[in,out] log_level parsed log level represented by `RCUTILS_LOG_SEVERITY` enum * \return RCL_RET_OK if a valid log level was parsed, or * \return RCL_RET_INVALID_LOG_LEVEL if the argument is not a valid rule, or * \return RCL_RET_BAD_ALLOC if an allocation failed, or * \return RLC_RET_ERROR if an unspecified error occurred. */ RCL_LOCAL rcl_ret_t _rcl_parse_log_level( const char * arg, rcl_allocator_t allocator, int * log_level); /// Parse an argument that may or may not be a log level rule. /** * \param[in] arg the argument to parse * \param[in] allocator an allocator to use * \param[in,out] log_level parsed log level represented by `RCUTILS_LOG_SEVERITY` enum * \return RCL_RET_OK if a valid log level was parsed, or * \return RCL_RET_INVALID_LOG_LEVEL_RULE if the argument is not a valid rule, or * \return RCL_RET_BAD_ALLOC if an allocation failed, or * \return RLC_RET_ERROR if an unspecified error occurred. * \deprecated to be removed in F-Turtle */ RCL_LOCAL rcl_ret_t _rcl_parse_log_level_rule( const char * arg, rcl_allocator_t allocator, int * log_level); /// Parse an argument that may or may not be a log configuration file. /** * \param[in] arg the argument to parse * \param[in] allocator an allocator to use * \param[in,out] log_config_file parsed log configuration file * \return RCL_RET_OK if a valid log config file was parsed, or * \return RCL_RET_BAD_ALLOC if an allocation failed, or * \return RLC_RET_ERROR if an unspecified error occurred. */ RCL_LOCAL rcl_ret_t _rcl_parse_external_log_config_file( const char * arg, rcl_allocator_t allocator, char ** log_config_file); /// Parse an argument that may or may not be a log file rule. /** * \param[in] arg the argument to parse * \param[in] allocator an allocator to use * \param[in,out] log_config_file parsed log configuration file * \return RCL_RET_OK if a valid log config file was parsed, or * \return RCL_RET_BAD_ALLOC if an allocation failed, or * \return RLC_RET_ERROR if an unspecified error occurred. * \deprecated to be removed in F-Turtle */ RCL_LOCAL rcl_ret_t _rcl_parse_external_log_config_file_rule( const char * arg, rcl_allocator_t allocator, char ** log_config_file); /// Parse an argument that may or may not be a parameter file. /** * The syntax of the file name is not validated. * \param[in] arg the argument to parse * \param[in] allocator an allocator to use * \param[in,out] param_file string that could be a parameter file name * \return RCL_RET_OK if the rule was parsed correctly, or * \return RCL_RET_BAD_ALLOC if an allocation failed, or * \return RLC_RET_ERROR if an unspecified error occurred. */ RCL_LOCAL rcl_ret_t _rcl_parse_param_file( const char * arg, rcl_allocator_t allocator, char ** param_file); /// Parse an argument that may or may not be a parameter file rule. /** * The syntax of the file name is not validated. * \param[in] arg the argument to parse * \param[in] allocator an allocator to use * \param[in,out] param_file string that could be a parameter file name * \return RCL_RET_OK if the rule was parsed correctly, or * \return RCL_RET_INVALID_PARAM_RULE if the argument is not a valid rule, or * \return RCL_RET_BAD_ALLOC if an allocation failed, or * \return RLC_RET_ERROR if an unspecified error occurred. * \deprecated to be removed in F-Turtle */ RCL_LOCAL rcl_ret_t _rcl_parse_param_file_rule( const char * arg, rcl_allocator_t allocator, char ** param_file); #define RCL_ENABLE_FLAG_PREFIX "--enable-" #define RCL_DISABLE_FLAG_PREFIX "--disable-" /// Parse a bool argument that may or may not be for the provided key rule. /** * \param[in] arg the argument to parse * \param[in] key the key for the argument to parse. Should be a null terminated string * \param[in,out] value parsed boolean value * \return RCL_RET_OK if the bool argument was parsed successfully, or * \return RLC_RET_ERROR if an unspecified error occurred. */ RCL_LOCAL rcl_ret_t _rcl_parse_disabling_flag( const char * arg, const char * key, bool * value); /// Parse a bool argument that may or may not be for the provided key rule. /** * \param[in] arg the argument to parse * \param[in] key the key for the argument to parse. Should be a null terminated string * \param[in,out] value parsed boolean value * \return RCL_RET_OK if the bool argument was parsed successfully, or * \return RLC_RET_ERROR if an unspecified error occurred. * \deprecated to be removed in F-Turtle */ RCL_LOCAL rcl_ret_t _rcl_parse_bool_arg( const char * arg, const char * key, bool * value); /// Parse a null terminated string to a boolean value. /** * The case sensitive values: "T", "t", "True", "true", "Y", "y", "Yes", "yes", * and "1" will all map to true. * The case sensitive values: "F", "f", "False", "false", "N", "n", "No", "no", * and "0" will all map to false. * * \param[in] str a null terminated string to be parsed into a boolean * \param[in,out] val the boolean value parsed from the string. * Left unchanged if string cannot be parsed to a valid bool. * \return RCL_RET_OK if a valid boolean parsed, or * \return RLC_RET_ERROR if an unspecified error occurred. * \deprecated to be removed in F-Turtle */ RCL_LOCAL rcl_ret_t _atob( const char * str, bool * val); rcl_ret_t rcl_parse_arguments( int argc, const char * const argv[], rcl_allocator_t allocator, rcl_arguments_t * args_output) { RCL_CHECK_ALLOCATOR_WITH_MSG(&allocator, "invalid allocator", return RCL_RET_INVALID_ARGUMENT); if (argc < 0) { RCL_SET_ERROR_MSG("Argument count cannot be negative"); return RCL_RET_INVALID_ARGUMENT; } else if (argc > 0) { RCL_CHECK_ARGUMENT_FOR_NULL(argv, RCL_RET_INVALID_ARGUMENT); } RCL_CHECK_ARGUMENT_FOR_NULL(args_output, RCL_RET_INVALID_ARGUMENT); if (args_output->impl != NULL) { RCL_SET_ERROR_MSG("Parse output is not zero-initialized"); return RCL_RET_INVALID_ARGUMENT; } rcl_ret_t ret; rcl_ret_t fail_ret; args_output->impl = allocator.allocate(sizeof(rcl_arguments_impl_t), allocator.state); if (NULL == args_output->impl) { return RCL_RET_BAD_ALLOC; } rcl_arguments_impl_t * args_impl = args_output->impl; args_impl->num_remap_rules = 0; args_impl->remap_rules = NULL; args_impl->log_level = -1; args_impl->external_log_config_file = NULL; args_impl->unparsed_args = NULL; args_impl->num_unparsed_args = 0; args_impl->unparsed_ros_args = NULL; args_impl->num_unparsed_ros_args = 0; args_impl->parameter_overrides = NULL; args_impl->parameter_files = NULL; args_impl->num_param_files_args = 0; args_impl->log_stdout_disabled = false; args_impl->log_rosout_disabled = false; args_impl->log_ext_lib_disabled = false; args_impl->allocator = allocator; if (argc == 0) { // there are no arguments to parse return RCL_RET_OK; } // over-allocate arrays to match the number of arguments args_impl->remap_rules = allocator.allocate(sizeof(rcl_remap_t) * argc, allocator.state); if (NULL == args_impl->remap_rules) { ret = RCL_RET_BAD_ALLOC; goto fail; } args_impl->parameter_overrides = rcl_yaml_node_struct_init(allocator); if (NULL == args_impl->parameter_overrides) { ret = RCL_RET_BAD_ALLOC; goto fail; } args_impl->parameter_files = allocator.allocate(sizeof(char *) * argc, allocator.state); if (NULL == args_impl->parameter_files) { ret = RCL_RET_BAD_ALLOC; goto fail; } args_impl->unparsed_ros_args = allocator.allocate(sizeof(int) * argc, allocator.state); if (NULL == args_impl->unparsed_ros_args) { ret = RCL_RET_BAD_ALLOC; goto fail; } args_impl->unparsed_args = allocator.allocate(sizeof(int) * argc, allocator.state); if (NULL == args_impl->unparsed_args) { ret = RCL_RET_BAD_ALLOC; goto fail; } bool parsing_ros_args = false; for (int i = 0; i < argc; ++i) { if (parsing_ros_args) { // Ignore ROS specific arguments flags if (strcmp(RCL_ROS_ARGS_FLAG, argv[i]) == 0) { continue; } // Check for ROS specific arguments explicit end token if (strcmp(RCL_ROS_ARGS_EXPLICIT_END_TOKEN, argv[i]) == 0) { parsing_ros_args = false; continue; } // Attempt to parse argument as parameter override flag if (strcmp(RCL_PARAM_FLAG, argv[i]) == 0 || strcmp(RCL_SHORT_PARAM_FLAG, argv[i]) == 0) { if (i + 1 < argc) { // Attempt to parse next argument as parameter override rule if (RCL_RET_OK == _rcl_parse_param_rule(argv[i + 1], args_impl->parameter_overrides)) { RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Got param override rule : %s\n", argv[i + 1]); ++i; // Skip flag here, for loop will skip rule. continue; } rcl_error_string_t prev_error_string = rcl_get_error_string(); rcl_reset_error(); RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse parameter override rule: '%s %s'. Error: %s", argv[i], argv[i + 1], prev_error_string.str); } else { RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse trailing %s flag. No parameter override rule found.", argv[i]); } ret = RCL_RET_INVALID_ROS_ARGS; goto fail; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Arg %d (%s) is not a %s nor a %s flag.", i, argv[i], RCL_PARAM_FLAG, RCL_SHORT_PARAM_FLAG); // Attempt to parse argument as remap rule flag if (strcmp(RCL_REMAP_FLAG, argv[i]) == 0 || strcmp(RCL_SHORT_REMAP_FLAG, argv[i]) == 0) { if (i + 1 < argc) { // Attempt to parse next argument as remap rule rcl_remap_t * rule = &(args_impl->remap_rules[args_impl->num_remap_rules]); *rule = rcl_get_zero_initialized_remap(); if (RCL_RET_OK == _rcl_parse_remap_rule(argv[i + 1], allocator, rule)) { ++(args_impl->num_remap_rules); RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Got remap rule : %s\n", argv[i + 1]); ++i; // Skip flag here, for loop will skip rule. continue; } rcl_error_string_t prev_error_string = rcl_get_error_string(); rcl_reset_error(); RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse remap rule: '%s %s'. Error: %s", argv[i], argv[i + 1], prev_error_string.str); } else { RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse trailing %s flag. No remap rule found.", argv[i]); } ret = RCL_RET_INVALID_ROS_ARGS; goto fail; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Arg %d (%s) is not a %s nor a %s flag.", i, argv[i], RCL_REMAP_FLAG, RCL_SHORT_REMAP_FLAG); // Attempt to parse argument as parameter file rule if (strcmp(RCL_PARAM_FILE_FLAG, argv[i]) == 0) { if (i + 1 < argc) { // Attempt to parse next argument as remap rule args_impl->parameter_files[args_impl->num_param_files_args] = NULL; if ( RCL_RET_OK == _rcl_parse_param_file( argv[i + 1], allocator, &args_impl->parameter_files[args_impl->num_param_files_args])) { ++(args_impl->num_param_files_args); RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Got params file : %s\ntotal num param files %d", args_impl->parameter_files[args_impl->num_param_files_args - 1], args_impl->num_param_files_args); ++i; // Skip flag here, for loop will skip rule. continue; } rcl_error_string_t prev_error_string = rcl_get_error_string(); rcl_reset_error(); RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse params file: '%s %s'. Error: %s", argv[i], argv[i + 1], prev_error_string.str); } else { RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse trailing %s flag. No file path provided.", argv[i]); } ret = RCL_RET_INVALID_ROS_ARGS; goto fail; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Arg %d (%s) is not a %s flag.", i, argv[i], RCL_PARAM_FILE_FLAG); // Attempt to parse argument as log level configuration if (strcmp(RCL_LOG_LEVEL_FLAG, argv[i]) == 0) { if (i + 1 < argc) { int log_level; if (RCL_RET_OK == _rcl_parse_log_level(argv[i + 1], allocator, &log_level)) { RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Got log level: %s\n", argv[i + 1]); args_impl->log_level = log_level; ++i; // Skip flag here, for loop will skip value. continue; } rcl_error_string_t prev_error_string = rcl_get_error_string(); rcl_reset_error(); RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse log level: '%s %s'. Error: %s", argv[i], argv[i + 1], prev_error_string.str); } else { RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse trailing log level flag: '%s'. No log level provided.", argv[i]); } ret = RCL_RET_INVALID_ROS_ARGS; goto fail; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Arg %d (%s) is not a %s flag.", i, argv[i], RCL_LOG_LEVEL_FLAG); // Attempt to parse argument as log configuration file if (strcmp(RCL_EXTERNAL_LOG_CONFIG_FLAG, argv[i]) == 0) { if (i + 1 < argc) { if (NULL != args_impl->external_log_config_file) { RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Overriding log configuration file : %s\n", args_impl->external_log_config_file); allocator.deallocate(args_impl->external_log_config_file, allocator.state); args_impl->external_log_config_file = NULL; } if (RCL_RET_OK == _rcl_parse_external_log_config_file( argv[i + 1], allocator, &args_impl->external_log_config_file)) { RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Got log configuration file : %s\n", args_impl->external_log_config_file); ++i; // Skip flag here, for loop will skip value. continue; } rcl_error_string_t prev_error_string = rcl_get_error_string(); rcl_reset_error(); RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse log configuration file: '%s %s'. Error: %s", argv[i], argv[i + 1], prev_error_string.str); } else { RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Couldn't parse trailing %s flag. No file path provided.", argv[i]); } ret = RCL_RET_INVALID_ROS_ARGS; goto fail; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Arg %d (%s) is not a %s flag.", i, argv[i], RCL_EXTERNAL_LOG_CONFIG_FLAG); // Attempt to parse --enable/disable-stdout-logs flag ret = _rcl_parse_disabling_flag( argv[i], RCL_LOG_STDOUT_FLAG_SUFFIX, &args_impl->log_stdout_disabled); if (RCL_RET_OK == ret) { RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Disable log stdout ? %s\n", args_impl->log_stdout_disabled ? "true" : "false"); continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as %s%s or %s%s flag. Error: %s", i, argv[i], RCL_ENABLE_FLAG_PREFIX, RCL_LOG_STDOUT_FLAG_SUFFIX, RCL_DISABLE_FLAG_PREFIX, RCL_LOG_STDOUT_FLAG_SUFFIX, rcl_get_error_string().str); rcl_reset_error(); // Attempt to parse --enable/disable-rosout-logs flag ret = _rcl_parse_disabling_flag( argv[i], RCL_LOG_ROSOUT_FLAG_SUFFIX, &args_impl->log_rosout_disabled); if (RCL_RET_OK == ret) { RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Disable log rosout ? %s\n", args_impl->log_rosout_disabled ? "true" : "false"); continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as %s%s or %s%s flag. Error: %s", i, argv[i], RCL_ENABLE_FLAG_PREFIX, RCL_LOG_ROSOUT_FLAG_SUFFIX, RCL_DISABLE_FLAG_PREFIX, RCL_LOG_ROSOUT_FLAG_SUFFIX, rcl_get_error_string().str); rcl_reset_error(); // Attempt to parse --enable/disable-external-lib-logs flag ret = _rcl_parse_disabling_flag( argv[i], RCL_LOG_EXT_LIB_FLAG_SUFFIX, &args_impl->log_ext_lib_disabled); if (RCL_RET_OK == ret) { RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Disable log external lib ? %s\n", args_impl->log_ext_lib_disabled ? "true" : "false"); continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as %s%s or %s%s flag. Error: %s", i, argv[i], RCL_ENABLE_FLAG_PREFIX, RCL_LOG_EXT_LIB_FLAG_SUFFIX, RCL_DISABLE_FLAG_PREFIX, RCL_LOG_EXT_LIB_FLAG_SUFFIX, rcl_get_error_string().str); rcl_reset_error(); // Argument is an unknown ROS specific argument args_impl->unparsed_ros_args[args_impl->num_unparsed_ros_args] = i; ++(args_impl->num_unparsed_ros_args); } else { // Check for ROS specific arguments flags if (strcmp(RCL_ROS_ARGS_FLAG, argv[i]) == 0) { parsing_ros_args = true; continue; } // Attempt to parse argument as remap rule in its deprecated form rcl_remap_t * rule = &(args_impl->remap_rules[args_impl->num_remap_rules]); *rule = rcl_get_zero_initialized_remap(); if (RCL_RET_OK == _rcl_parse_remap_rule(argv[i], allocator, rule)) { RCUTILS_LOG_WARN_NAMED(ROS_PACKAGE_NAME, "Found remap rule '%s'. This syntax is deprecated. Use '%s %s %s' instead.", argv[i], RCL_ROS_ARGS_FLAG, RCL_REMAP_FLAG, argv[i]); RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Got remap rule : %s\n", argv[i + 1]); ++(args_impl->num_remap_rules); continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as a remap rule in its deprecated form. Error: %s", i, argv[i], rcl_get_error_string().str); rcl_reset_error(); // Attempt to parse argument as parameter file rule args_impl->parameter_files[args_impl->num_param_files_args] = NULL; if ( RCL_RET_OK == _rcl_parse_param_file_rule( argv[i], allocator, &(args_impl->parameter_files[args_impl->num_param_files_args]))) { ++(args_impl->num_param_files_args); RCUTILS_LOG_WARN_NAMED(ROS_PACKAGE_NAME, "Found parameter file rule '%s'. This syntax is deprecated. Use '%s %s %s' instead.", argv[i], RCL_ROS_ARGS_FLAG, RCL_PARAM_FILE_FLAG, args_impl->parameter_files[args_impl->num_param_files_args - 1]); RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "params rule : %s\n total num param rules %d", args_impl->parameter_files[args_impl->num_param_files_args - 1], args_impl->num_param_files_args); continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as a deprecated parameter file rule. Error: %s", i, argv[i], rcl_get_error_string().str); rcl_reset_error(); // Attempt to parse argument as log level configuration int log_level; if (RCL_RET_OK == _rcl_parse_log_level_rule(argv[i], allocator, &log_level)) { RCUTILS_LOG_WARN_NAMED(ROS_PACKAGE_NAME, "Found log level rule '%s'. This syntax is deprecated. Use '%s %s %s' instead.", argv[i], RCL_ROS_ARGS_FLAG, RCL_LOG_LEVEL_FLAG, g_rcutils_log_severity_names[log_level]); args_impl->log_level = log_level; continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as a deprecated log level rule. Error: %s", i, argv[i], rcl_get_error_string().str); rcl_reset_error(); // Attempt to parse argument as log configuration file rule rcl_ret_t ret = _rcl_parse_external_log_config_file_rule( argv[i], allocator, &args_impl->external_log_config_file); if (RCL_RET_OK == ret) { RCUTILS_LOG_WARN_NAMED(ROS_PACKAGE_NAME, "Found log config rule '%s'. This syntax is deprecated. Use '%s %s %s' instead.", argv[i], RCL_ROS_ARGS_FLAG, RCL_EXTERNAL_LOG_CONFIG_FLAG, args_impl->external_log_config_file); RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Got log configuration file : %s\n", args_impl->external_log_config_file); continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as a deprecated log config rule. Error: %s", i, argv[i], rcl_get_error_string().str); rcl_reset_error(); // Attempt to parse argument as log_stdout_disabled ret = _rcl_parse_bool_arg( argv[i], RCL_LOG_DISABLE_STDOUT_ARG_RULE, &args_impl->log_stdout_disabled); if (RCL_RET_OK == ret) { const char * flag_prefix = args_impl->log_stdout_disabled ? RCL_DISABLE_FLAG_PREFIX : RCL_ENABLE_FLAG_PREFIX; RCUTILS_LOG_WARN_NAMED(ROS_PACKAGE_NAME, "Found '%s'. This syntax is deprecated. Use '%s %s%s' instead.", argv[i], RCL_ROS_ARGS_FLAG, flag_prefix, RCL_LOG_STDOUT_FLAG_SUFFIX); RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Disable log stdout ? %s\n", args_impl->log_stdout_disabled ? "true" : "false"); continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as a deprecated log_stdout_disabled rule. Error: %s", i, argv[i], rcl_get_error_string().str); rcl_reset_error(); // Attempt to parse argument as log_rosout_disabled ret = _rcl_parse_bool_arg( argv[i], RCL_LOG_DISABLE_ROSOUT_ARG_RULE, &args_impl->log_rosout_disabled); if (RCL_RET_OK == ret) { const char * flag_prefix = args_impl->log_rosout_disabled ? RCL_DISABLE_FLAG_PREFIX : RCL_ENABLE_FLAG_PREFIX; RCUTILS_LOG_WARN_NAMED(ROS_PACKAGE_NAME, "Found '%s'. This syntax is deprecated. Use '%s %s%s' instead.", argv[i], RCL_ROS_ARGS_FLAG, flag_prefix, RCL_LOG_ROSOUT_FLAG_SUFFIX); RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Disable log rosout ? %s\n", args_impl->log_rosout_disabled ? "true" : "false"); continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as a deprecated log_rosout_disabled rule. Error: %s", i, argv[i], rcl_get_error_string().str); rcl_reset_error(); // Attempt to parse argument as log_ext_lib_disabled ret = _rcl_parse_bool_arg( argv[i], RCL_LOG_DISABLE_EXT_LIB_ARG_RULE, &args_impl->log_ext_lib_disabled); if (RCL_RET_OK == ret) { const char * flag_prefix = args_impl->log_ext_lib_disabled ? RCL_DISABLE_FLAG_PREFIX : RCL_ENABLE_FLAG_PREFIX; RCUTILS_LOG_WARN_NAMED(ROS_PACKAGE_NAME, "Found '%s'. This syntax is deprecated. Use '%s %s%s' instead.", argv[i], RCL_ROS_ARGS_FLAG, flag_prefix, RCL_LOG_EXT_LIB_FLAG_SUFFIX); RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Disable log external lib ? %s\n", args_impl->log_ext_lib_disabled ? "true" : "false"); continue; } RCUTILS_LOG_DEBUG_NAMED(ROS_PACKAGE_NAME, "Couldn't parse arg %d (%s) as a deprecated log_ext_lib_disabled rule. Error: %s", i, argv[i], rcl_get_error_string().str); rcl_reset_error(); // Argument is not a ROS specific argument args_impl->unparsed_args[args_impl->num_unparsed_args] = i; ++(args_impl->num_unparsed_args); } } // Shrink remap_rules array to match number of successfully parsed rules if (args_impl->num_remap_rules > 0) { args_impl->remap_rules = rcutils_reallocf( args_impl->remap_rules, sizeof(rcl_remap_t) * args_impl->num_remap_rules, &allocator); if (NULL == args_impl->remap_rules) { ret = RCL_RET_BAD_ALLOC; goto fail; } } else { // No remap rules allocator.deallocate(args_impl->remap_rules, allocator.state); args_impl->remap_rules = NULL; } // Shrink Parameter files if (0 == args_impl->num_param_files_args) { allocator.deallocate(args_impl->parameter_files, allocator.state); args_impl->parameter_files = NULL; } else if (args_impl->num_param_files_args < argc) { args_impl->parameter_files = rcutils_reallocf( args_impl->parameter_files, sizeof(char *) * args_impl->num_param_files_args, &allocator); if (NULL == args_impl->parameter_files) { ret = RCL_RET_BAD_ALLOC; goto fail; } } // Shrink unparsed_ros_args if (0 == args_impl->num_unparsed_ros_args) { // No unparsed ros args allocator.deallocate(args_impl->unparsed_ros_args, allocator.state); args_impl->unparsed_ros_args = NULL; } else if (args_impl->num_unparsed_ros_args < argc) { args_impl->unparsed_ros_args = rcutils_reallocf( args_impl->unparsed_ros_args, sizeof(int) * args_impl->num_unparsed_ros_args, &allocator); if (NULL == args_impl->unparsed_ros_args) { ret = RCL_RET_BAD_ALLOC; goto fail; } } // Shrink unparsed_args if (0 == args_impl->num_unparsed_args) { // No unparsed args allocator.deallocate(args_impl->unparsed_args, allocator.state); args_impl->unparsed_args = NULL; } else if (args_impl->num_unparsed_args < argc) { args_impl->unparsed_args = rcutils_reallocf( args_impl->unparsed_args, sizeof(int) * args_impl->num_unparsed_args, &allocator); if (NULL == args_impl->unparsed_args) { ret = RCL_RET_BAD_ALLOC; goto fail; } } return RCL_RET_OK; fail: fail_ret = ret; if (NULL != args_impl) { ret = rcl_arguments_fini(args_output); if (RCL_RET_OK != ret) { RCUTILS_LOG_ERROR_NAMED(ROS_PACKAGE_NAME, "Failed to fini arguments after earlier failure"); } } return fail_ret; } int rcl_arguments_get_count_unparsed( const rcl_arguments_t * args) { if (NULL == args || NULL == args->impl) { return -1; } return args->impl->num_unparsed_args; } rcl_ret_t rcl_arguments_get_unparsed( const rcl_arguments_t * args, rcl_allocator_t allocator, int ** output_unparsed_indices) { RCL_CHECK_ARGUMENT_FOR_NULL(args, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(args->impl, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ALLOCATOR_WITH_MSG(&allocator, "invalid allocator", return RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(output_unparsed_indices, RCL_RET_INVALID_ARGUMENT); *output_unparsed_indices = NULL; if (args->impl->num_unparsed_args) { *output_unparsed_indices = allocator.allocate( sizeof(int) * args->impl->num_unparsed_args, allocator.state); if (NULL == *output_unparsed_indices) { return RCL_RET_BAD_ALLOC; } for (int i = 0; i < args->impl->num_unparsed_args; ++i) { (*output_unparsed_indices)[i] = args->impl->unparsed_args[i]; } } return RCL_RET_OK; } int rcl_arguments_get_count_unparsed_ros( const rcl_arguments_t * args) { if (NULL == args || NULL == args->impl) { return -1; } return args->impl->num_unparsed_ros_args; } rcl_ret_t rcl_arguments_get_unparsed_ros( const rcl_arguments_t * args, rcl_allocator_t allocator, int ** output_unparsed_ros_indices) { RCL_CHECK_ARGUMENT_FOR_NULL(args, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(args->impl, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ALLOCATOR_WITH_MSG(&allocator, "invalid allocator", return RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(output_unparsed_ros_indices, RCL_RET_INVALID_ARGUMENT); *output_unparsed_ros_indices = NULL; if (args->impl->num_unparsed_ros_args) { *output_unparsed_ros_indices = allocator.allocate( sizeof(int) * args->impl->num_unparsed_ros_args, allocator.state); if (NULL == *output_unparsed_ros_indices) { return RCL_RET_BAD_ALLOC; } for (int i = 0; i < args->impl->num_unparsed_ros_args; ++i) { (*output_unparsed_ros_indices)[i] = args->impl->unparsed_ros_args[i]; } } return RCL_RET_OK; } rcl_arguments_t rcl_get_zero_initialized_arguments(void) { static rcl_arguments_t default_arguments = { .impl = NULL }; return default_arguments; } rcl_ret_t rcl_remove_ros_arguments( char const * const argv[], const rcl_arguments_t * args, rcl_allocator_t allocator, int * nonros_argc, const char ** nonros_argv[]) { RCL_CHECK_ARGUMENT_FOR_NULL(argv, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(nonros_argc, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(args, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ALLOCATOR_WITH_MSG(&allocator, "invalid allocator", return RCL_RET_INVALID_ARGUMENT); *nonros_argc = rcl_arguments_get_count_unparsed(args); *nonros_argv = NULL; if (*nonros_argc <= 0) { return RCL_RET_INVALID_ARGUMENT; } int * unparsed_indices = NULL; rcl_ret_t ret; ret = rcl_arguments_get_unparsed(args, allocator, &unparsed_indices); if (RCL_RET_OK != ret) { return ret; } size_t alloc_size = sizeof(char *) * *nonros_argc; *nonros_argv = allocator.allocate(alloc_size, allocator.state); if (NULL == *nonros_argv) { allocator.deallocate(unparsed_indices, allocator.state); return RCL_RET_BAD_ALLOC; } for (int i = 0; i < *nonros_argc; ++i) { (*nonros_argv)[i] = argv[unparsed_indices[i]]; } allocator.deallocate(unparsed_indices, allocator.state); return RCL_RET_OK; } rcl_ret_t rcl_arguments_copy( const rcl_arguments_t * args, rcl_arguments_t * args_out) { RCL_CHECK_ARGUMENT_FOR_NULL(args, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(args->impl, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(args_out, RCL_RET_INVALID_ARGUMENT); if (NULL != args_out->impl) { RCL_SET_ERROR_MSG("args_out must be zero initialized"); return RCL_RET_INVALID_ARGUMENT; } rcl_allocator_t allocator = args->impl->allocator; args_out->impl = allocator.allocate(sizeof(rcl_arguments_impl_t), allocator.state); if (NULL == args_out->impl) { return RCL_RET_BAD_ALLOC; } args_out->impl->allocator = allocator; // Zero so it's safe to call rcl_arguments_fini() if an error occurrs while copying. args_out->impl->num_remap_rules = 0; args_out->impl->remap_rules = NULL; args_out->impl->unparsed_args = NULL; args_out->impl->num_unparsed_args = 0; args_out->impl->unparsed_ros_args = NULL; args_out->impl->num_unparsed_ros_args = 0; args_out->impl->parameter_overrides = NULL; args_out->impl->parameter_files = NULL; args_out->impl->num_param_files_args = 0; if (args->impl->num_unparsed_args) { // Copy unparsed args args_out->impl->unparsed_args = allocator.allocate( sizeof(int) * args->impl->num_unparsed_args, allocator.state); if (NULL == args_out->impl->unparsed_args) { if (RCL_RET_OK != rcl_arguments_fini(args_out)) { RCL_SET_ERROR_MSG("Error while finalizing arguments due to another error"); } return RCL_RET_BAD_ALLOC; } for (int i = 0; i < args->impl->num_unparsed_args; ++i) { args_out->impl->unparsed_args[i] = args->impl->unparsed_args[i]; } args_out->impl->num_unparsed_args = args->impl->num_unparsed_args; } if (args->impl->num_unparsed_ros_args) { // Copy unparsed ROS args args_out->impl->unparsed_ros_args = allocator.allocate( sizeof(int) * args->impl->num_unparsed_ros_args, allocator.state); if (NULL == args_out->impl->unparsed_ros_args) { if (RCL_RET_OK != rcl_arguments_fini(args_out)) { RCL_SET_ERROR_MSG("Error while finalizing arguments due to another error"); } return RCL_RET_BAD_ALLOC; } for (int i = 0; i < args->impl->num_unparsed_ros_args; ++i) { args_out->impl->unparsed_ros_args[i] = args->impl->unparsed_ros_args[i]; } args_out->impl->num_unparsed_ros_args = args->impl->num_unparsed_ros_args; } if (args->impl->num_remap_rules) { // Copy remap rules args_out->impl->remap_rules = allocator.allocate( sizeof(rcl_remap_t) * args->impl->num_remap_rules, allocator.state); if (NULL == args_out->impl->remap_rules) { if (RCL_RET_OK != rcl_arguments_fini(args_out)) { RCL_SET_ERROR_MSG("Error while finalizing arguments due to another error"); } return RCL_RET_BAD_ALLOC; } args_out->impl->num_remap_rules = args->impl->num_remap_rules; for (int i = 0; i < args->impl->num_remap_rules; ++i) { args_out->impl->remap_rules[i] = rcl_get_zero_initialized_remap(); rcl_ret_t ret = rcl_remap_copy( &(args->impl->remap_rules[i]), &(args_out->impl->remap_rules[i])); if (RCL_RET_OK != ret) { if (RCL_RET_OK != rcl_arguments_fini(args_out)) { RCL_SET_ERROR_MSG("Error while finalizing arguments due to another error"); } return ret; } } } // Copy parameter rules if (args->impl->parameter_overrides) { args_out->impl->parameter_overrides = rcl_yaml_node_struct_copy(args->impl->parameter_overrides); } // Copy parameter files if (args->impl->num_param_files_args) { args_out->impl->parameter_files = allocator.allocate( sizeof(char *) * args->impl->num_param_files_args, allocator.state); if (NULL == args_out->impl->parameter_files) { if (RCL_RET_OK != rcl_arguments_fini(args_out)) { RCL_SET_ERROR_MSG("Error while finalizing arguments due to another error"); } return RCL_RET_BAD_ALLOC; } args_out->impl->num_param_files_args = args->impl->num_param_files_args; for (int i = 0; i < args->impl->num_param_files_args; ++i) { args_out->impl->parameter_files[i] = rcutils_strdup(args->impl->parameter_files[i], allocator); if (NULL == args_out->impl->parameter_files[i]) { if (RCL_RET_OK != rcl_arguments_fini(args_out)) { RCL_SET_ERROR_MSG("Error while finalizing arguments due to another error"); } return RCL_RET_BAD_ALLOC; } } } return RCL_RET_OK; } rcl_ret_t rcl_arguments_fini( rcl_arguments_t * args) { RCL_CHECK_ARGUMENT_FOR_NULL(args, RCL_RET_INVALID_ARGUMENT); if (args->impl) { rcl_ret_t ret = RCL_RET_OK; if (args->impl->remap_rules) { for (int i = 0; i < args->impl->num_remap_rules; ++i) { rcl_ret_t remap_ret = rcl_remap_fini(&(args->impl->remap_rules[i])); if (remap_ret != RCL_RET_OK) { ret = remap_ret; RCUTILS_LOG_ERROR_NAMED( ROS_PACKAGE_NAME, "Failed to finalize remap rule while finalizing arguments. Continuing..."); } } args->impl->allocator.deallocate(args->impl->remap_rules, args->impl->allocator.state); args->impl->remap_rules = NULL; args->impl->num_remap_rules = 0; } args->impl->allocator.deallocate(args->impl->unparsed_args, args->impl->allocator.state); args->impl->num_unparsed_args = 0; args->impl->unparsed_args = NULL; args->impl->allocator.deallocate(args->impl->unparsed_ros_args, args->impl->allocator.state); args->impl->num_unparsed_ros_args = 0; args->impl->unparsed_ros_args = NULL; if (args->impl->parameter_overrides) { rcl_yaml_node_struct_fini(args->impl->parameter_overrides); args->impl->parameter_overrides = NULL; } if (args->impl->parameter_files) { for (int p = 0; p < args->impl->num_param_files_args; ++p) { args->impl->allocator.deallocate( args->impl->parameter_files[p], args->impl->allocator.state); } args->impl->allocator.deallocate(args->impl->parameter_files, args->impl->allocator.state); args->impl->num_param_files_args = 0; args->impl->parameter_files = NULL; } args->impl->allocator.deallocate(args->impl, args->impl->allocator.state); args->impl = NULL; return ret; } RCL_SET_ERROR_MSG("rcl_arguments_t finalized twice"); return RCL_RET_ERROR; } /// Parses a fully qualified namespace for a namespace replacement rule (ex: `/foo/bar`) /** * \sa _rcl_parse_remap_begin_remap_rule() */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_fully_qualified_namespace( rcl_lexer_lookahead2_t * lex_lookahead) { rcl_ret_t ret; // Check arguments sanity assert(NULL != lex_lookahead); // Must have at least one Forward slash / ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_FORWARD_SLASH, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { return RCL_RET_INVALID_REMAP_RULE; } // repeated tokens and slashes (allow trailing slash, but don't require it) while (true) { ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_TOKEN, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { rcl_reset_error(); break; } ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_FORWARD_SLASH, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { rcl_reset_error(); break; } } return RCL_RET_OK; } /// Parse either a token or a backreference (ex: `bar`, or `\7`). /** * \sa _rcl_parse_remap_begin_remap_rule() */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_replacement_token(rcl_lexer_lookahead2_t * lex_lookahead) { rcl_ret_t ret; rcl_lexeme_t lexeme; // Check arguments sanity assert(NULL != lex_lookahead); ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme); if (RCL_RET_OK != ret) { return ret; } if ( RCL_LEXEME_BR1 == lexeme || RCL_LEXEME_BR2 == lexeme || RCL_LEXEME_BR3 == lexeme || RCL_LEXEME_BR4 == lexeme || RCL_LEXEME_BR5 == lexeme || RCL_LEXEME_BR6 == lexeme || RCL_LEXEME_BR7 == lexeme || RCL_LEXEME_BR8 == lexeme || RCL_LEXEME_BR9 == lexeme) { RCL_SET_ERROR_MSG("Backreferences are not implemented"); return RCL_RET_ERROR; } else if (RCL_LEXEME_TOKEN == lexeme) { ret = rcl_lexer_lookahead2_accept(lex_lookahead, NULL, NULL); } else { ret = RCL_RET_INVALID_REMAP_RULE; } return ret; } /// Parse the replacement side of a name remapping rule (ex: `bar/\1/foo`). /** * \sa _rcl_parse_remap_begin_remap_rule() */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_replacement_name( rcl_lexer_lookahead2_t * lex_lookahead, rcl_remap_t * rule) { rcl_ret_t ret; rcl_lexeme_t lexeme; // Check arguments sanity assert(NULL != lex_lookahead); assert(NULL != rule); const char * replacement_start = rcl_lexer_lookahead2_get_text(lex_lookahead); if (NULL == replacement_start) { RCL_SET_ERROR_MSG("failed to get start of replacement"); return RCL_RET_ERROR; } // private name (~/...) or fully qualified name (/...) ? ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme); if (RCL_RET_OK != ret) { return ret; } if (RCL_LEXEME_TILDE_SLASH == lexeme || RCL_LEXEME_FORWARD_SLASH == lexeme) { ret = rcl_lexer_lookahead2_accept(lex_lookahead, NULL, NULL); } if (RCL_RET_OK != ret) { return ret; } // token ( '/' token )* ret = _rcl_parse_remap_replacement_token(lex_lookahead); if (RCL_RET_OK != ret) { return ret; } ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme); if (RCL_RET_OK != ret) { return ret; } while (RCL_LEXEME_EOF != lexeme) { ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_FORWARD_SLASH, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { return RCL_RET_INVALID_REMAP_RULE; } ret = _rcl_parse_remap_replacement_token(lex_lookahead); if (RCL_RET_OK != ret) { return ret; } ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme); if (RCL_RET_OK != ret) { return ret; } } // Copy replacement into rule const char * replacement_end = rcl_lexer_lookahead2_get_text(lex_lookahead); size_t length = (size_t)(replacement_end - replacement_start); rule->impl->replacement = rcutils_strndup( replacement_start, length, rule->impl->allocator); if (NULL == rule->impl->replacement) { RCL_SET_ERROR_MSG("failed to copy replacement"); return RCL_RET_BAD_ALLOC; } return RCL_RET_OK; } /// Parse either a resource name token or a wildcard (ex: `foobar`, or `*`, or `**`). /** * \sa _rcl_parse_resource_match() */ RCL_LOCAL rcl_ret_t _rcl_parse_resource_match_token(rcl_lexer_lookahead2_t * lex_lookahead) { rcl_ret_t ret; rcl_lexeme_t lexeme; // Check arguments sanity assert(NULL != lex_lookahead); ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme); if (RCL_RET_OK != ret) { return ret; } if (RCL_LEXEME_TOKEN == lexeme) { ret = rcl_lexer_lookahead2_accept(lex_lookahead, NULL, NULL); } else if (RCL_LEXEME_WILD_ONE == lexeme) { RCL_SET_ERROR_MSG("Wildcard '*' is not implemented"); return RCL_RET_ERROR; } else if (RCL_LEXEME_WILD_MULTI == lexeme) { RCL_SET_ERROR_MSG("Wildcard '**' is not implemented"); return RCL_RET_ERROR; } else { RCL_SET_ERROR_MSG("Expecting token or wildcard"); ret = RCL_RET_WRONG_LEXEME; } return ret; } /// Parse a resource name match side of a rule (ex: `rostopic://foo`) /** * \sa _rcl_parse_remap_match_name() */ RCL_LOCAL rcl_ret_t _rcl_parse_resource_match( rcl_lexer_lookahead2_t * lex_lookahead, rcl_allocator_t allocator, char ** resource_match) { rcl_ret_t ret; rcl_lexeme_t lexeme; // Check arguments sanity assert(NULL != lex_lookahead); assert(rcutils_allocator_is_valid(&allocator)); assert(NULL != resource_match); assert(NULL == *resource_match); const char * match_start = rcl_lexer_lookahead2_get_text(lex_lookahead); if (NULL == match_start) { RCL_SET_ERROR_MSG("failed to get start of match"); return RCL_RET_ERROR; } // private name (~/...) or fully qualified name (/...) ? ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme); if (RCL_RET_OK != ret) { return ret; } if (RCL_LEXEME_TILDE_SLASH == lexeme || RCL_LEXEME_FORWARD_SLASH == lexeme) { ret = rcl_lexer_lookahead2_accept(lex_lookahead, NULL, NULL); if (RCL_RET_OK != ret) { return ret; } } // token ( '/' token )* ret = _rcl_parse_resource_match_token(lex_lookahead); if (RCL_RET_OK != ret) { return ret; } ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme); if (RCL_RET_OK != ret) { return ret; } while (RCL_LEXEME_SEPARATOR != lexeme) { ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_FORWARD_SLASH, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { return RCL_RET_INVALID_REMAP_RULE; } ret = _rcl_parse_resource_match_token(lex_lookahead); if (RCL_RET_OK != ret) { return ret; } ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme); if (RCL_RET_OK != ret) { return ret; } } // Copy match into rule const char * match_end = rcl_lexer_lookahead2_get_text(lex_lookahead); const size_t length = (size_t)(match_end - match_start); *resource_match = rcutils_strndup(match_start, length, allocator); if (NULL == *resource_match) { RCL_SET_ERROR_MSG("failed to copy match"); return RCL_RET_BAD_ALLOC; } return RCL_RET_OK; } /// Parse the match side of a name remapping rule (ex: `rostopic://foo`) /** * \sa _rcl_parse_remap_begin_remap_rule() */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_match_name( rcl_lexer_lookahead2_t * lex_lookahead, rcl_remap_t * rule) { rcl_ret_t ret; rcl_lexeme_t lexeme; // Check arguments sanity assert(NULL != lex_lookahead); assert(NULL != rule); // rostopic:// rosservice:// ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme); if (RCL_RET_OK != ret) { return ret; } if (RCL_LEXEME_URL_SERVICE == lexeme) { rule->impl->type = RCL_SERVICE_REMAP; ret = rcl_lexer_lookahead2_accept(lex_lookahead, NULL, NULL); } else if (RCL_LEXEME_URL_TOPIC == lexeme) { rule->impl->type = RCL_TOPIC_REMAP; ret = rcl_lexer_lookahead2_accept(lex_lookahead, NULL, NULL); } else { rule->impl->type = (RCL_TOPIC_REMAP | RCL_SERVICE_REMAP); } if (RCL_RET_OK != ret) { return ret; } ret = _rcl_parse_resource_match( lex_lookahead, rule->impl->allocator, &rule->impl->match); if (RCL_RET_WRONG_LEXEME == ret) { ret = RCL_RET_INVALID_REMAP_RULE; } return ret; } /// Parse a name remapping rule (ex: `rostopic:///foo:=bar`). /** * \sa _rcl_parse_remap_begin_remap_rule() */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_name_remap( rcl_lexer_lookahead2_t * lex_lookahead, rcl_remap_t * rule) { rcl_ret_t ret; // Check arguments sanity assert(NULL != lex_lookahead); assert(NULL != rule); // match ret = _rcl_parse_remap_match_name(lex_lookahead, rule); if (RCL_RET_OK != ret) { return ret; } // := ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_SEPARATOR, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { return RCL_RET_INVALID_REMAP_RULE; } // replacement ret = _rcl_parse_remap_replacement_name(lex_lookahead, rule); if (RCL_RET_OK != ret) { return ret; } return RCL_RET_OK; } /// Parse a namespace replacement rule (ex: `__ns:=/new/ns`). /** * \sa _rcl_parse_remap_begin_remap_rule() */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_namespace_replacement( rcl_lexer_lookahead2_t * lex_lookahead, rcl_remap_t * rule) { rcl_ret_t ret; // Check arguments sanity assert(NULL != lex_lookahead); assert(NULL != rule); // __ns ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_NS, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { return RCL_RET_INVALID_REMAP_RULE; } // := ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_SEPARATOR, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { return RCL_RET_INVALID_REMAP_RULE; } // /foo/bar const char * ns_start = rcl_lexer_lookahead2_get_text(lex_lookahead); if (NULL == ns_start) { RCL_SET_ERROR_MSG("failed to get start of namespace"); return RCL_RET_ERROR; } ret = _rcl_parse_remap_fully_qualified_namespace(lex_lookahead); if (RCL_RET_OK != ret) { if (RCL_RET_INVALID_REMAP_RULE == ret) { // The name didn't start with a leading forward slash RCUTILS_LOG_WARN_NAMED( ROS_PACKAGE_NAME, "Namespace not remapped to a fully qualified name (found: %s)", ns_start); } return ret; } // There should be nothing left ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_EOF, NULL, NULL); if (RCL_RET_OK != ret) { // The name must have started with a leading forward slash but had an otherwise invalid format RCUTILS_LOG_WARN_NAMED( ROS_PACKAGE_NAME, "Namespace not remapped to a fully qualified name (found: %s)", ns_start); return ret; } // Copy namespace into rule const char * ns_end = rcl_lexer_lookahead2_get_text(lex_lookahead); size_t length = (size_t)(ns_end - ns_start); rule->impl->replacement = rcutils_strndup(ns_start, length, rule->impl->allocator); if (NULL == rule->impl->replacement) { RCL_SET_ERROR_MSG("failed to copy namespace"); return RCL_RET_BAD_ALLOC; } rule->impl->type = RCL_NAMESPACE_REMAP; return RCL_RET_OK; } /// Parse a nodename replacement rule (ex: `__node:=new_name`). /** * \sa _rcl_parse_remap_begin_remap_rule() */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_nodename_replacement( rcl_lexer_lookahead2_t * lex_lookahead, rcl_remap_t * rule) { rcl_ret_t ret; const char * node_name; size_t length; // Check arguments sanity assert(NULL != lex_lookahead); assert(NULL != rule); // __node ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_NODE, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { return RCL_RET_INVALID_REMAP_RULE; } // := ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_SEPARATOR, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { return RCL_RET_INVALID_REMAP_RULE; } // new_node_name ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_TOKEN, &node_name, &length); if (RCL_RET_WRONG_LEXEME == ret) { node_name = rcl_lexer_lookahead2_get_text(lex_lookahead); RCUTILS_LOG_WARN_NAMED( ROS_PACKAGE_NAME, "Node name not remapped to invalid name: '%s'", node_name); return RCL_RET_INVALID_REMAP_RULE; } if (RCL_RET_OK != ret) { return ret; } // copy the node name into the replacement side of the rule rule->impl->replacement = rcutils_strndup(node_name, length, rule->impl->allocator); if (NULL == rule->impl->replacement) { RCL_SET_ERROR_MSG("failed to allocate node name"); return RCL_RET_BAD_ALLOC; } rule->impl->type = RCL_NODENAME_REMAP; return RCL_RET_OK; } /// Parse a nodename prefix including trailing colon (ex: `node_name:`). RCL_LOCAL rcl_ret_t _rcl_parse_nodename_prefix( rcl_lexer_lookahead2_t * lex_lookahead, rcl_allocator_t allocator, char ** node_name) { size_t length = 0; const char * token = NULL; // Check arguments sanity assert(NULL != lex_lookahead); assert(rcutils_allocator_is_valid(&allocator)); assert(NULL != node_name); assert(NULL == *node_name); // Expect a token and a colon rcl_ret_t ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_TOKEN, &token, &length); if (RCL_RET_OK != ret) { return ret; } ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_COLON, NULL, NULL); if (RCL_RET_OK != ret) { return ret; } // Copy the node name *node_name = rcutils_strndup(token, length, allocator); if (NULL == *node_name) { RCL_SET_ERROR_MSG("failed to allocate node name"); return RCL_RET_BAD_ALLOC; } return RCL_RET_OK; } /// Parse a nodename prefix for a remap rule. /** * \sa _rcl_parse_nodename_prefix() * \sa _rcl_parse_remap_begin_remap_rule() */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_nodename_prefix( rcl_lexer_lookahead2_t * lex_lookahead, rcl_remap_t * rule) { // Check arguments sanity assert(NULL != lex_lookahead); assert(NULL != rule); rcl_ret_t ret = _rcl_parse_nodename_prefix( lex_lookahead, rule->impl->allocator, &rule->impl->node_name); if (RCL_RET_WRONG_LEXEME == ret) { ret = RCL_RET_INVALID_REMAP_RULE; } return ret; } /// Start recursive descent parsing of a remap rule. /** * \param[in] lex_lookahead a lookahead(2) buffer for the parser to use. * \param[in,out] rule input a zero intialized rule, output a fully initialized one. * \return RCL_RET_OK if a valid rule was parsed, or * \return RCL_RET_INVALID_REMAP_RULE if the argument is not a valid rule, or * \return RCL_RET_BAD_ALLOC if an allocation failed, or * \return RLC_RET_ERROR if an unspecified error occurred. */ RCL_LOCAL rcl_ret_t _rcl_parse_remap_begin_remap_rule( rcl_lexer_lookahead2_t * lex_lookahead, rcl_remap_t * rule) { rcl_ret_t ret; rcl_lexeme_t lexeme1; rcl_lexeme_t lexeme2; // Check arguments sanity assert(NULL != lex_lookahead); assert(NULL != rule); // Check for optional nodename prefix ret = rcl_lexer_lookahead2_peek2(lex_lookahead, &lexeme1, &lexeme2); if (RCL_RET_OK != ret) { return ret; } if (RCL_LEXEME_TOKEN == lexeme1 && RCL_LEXEME_COLON == lexeme2) { ret = _rcl_parse_remap_nodename_prefix(lex_lookahead, rule); if (RCL_RET_OK != ret) { return ret; } } ret = rcl_lexer_lookahead2_peek(lex_lookahead, &lexeme1); if (RCL_RET_OK != ret) { return ret; } // What type of rule is this (node name replacement, namespace replacement, or name remap)? if (RCL_LEXEME_NODE == lexeme1) { ret = _rcl_parse_remap_nodename_replacement(lex_lookahead, rule); if (RCL_RET_OK != ret) { return ret; } } else if (RCL_LEXEME_NS == lexeme1) { ret = _rcl_parse_remap_namespace_replacement(lex_lookahead, rule); if (RCL_RET_OK != ret) { return ret; } } else { ret = _rcl_parse_remap_name_remap(lex_lookahead, rule); if (RCL_RET_OK != ret) { return ret; } } // Make sure all characters in string have been consumed ret = rcl_lexer_lookahead2_expect(lex_lookahead, RCL_LEXEME_EOF, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { return RCL_RET_INVALID_REMAP_RULE; } return ret; } rcl_ret_t _rcl_parse_log_level( const char * arg, rcl_allocator_t allocator, int * log_level) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(log_level, RCL_RET_INVALID_ARGUMENT); rcutils_ret_t ret = rcutils_logging_severity_level_from_string(arg, allocator, log_level); if (RCUTILS_RET_OK == ret) { return RCL_RET_OK; } RCL_SET_ERROR_MSG("Argument does not use a valid severity level"); return RCL_RET_ERROR; } rcl_ret_t _rcl_parse_log_level_rule( const char * arg, rcl_allocator_t allocator, int * log_level) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(log_level, RCL_RET_INVALID_ARGUMENT); if (strncmp(RCL_LOG_LEVEL_ARG_RULE, arg, strlen(RCL_LOG_LEVEL_ARG_RULE)) != 0) { RCL_SET_ERROR_MSG("Argument does not start with '" RCL_LOG_LEVEL_ARG_RULE "'"); return RCL_RET_INVALID_LOG_LEVEL_RULE; } rcutils_ret_t ret = rcutils_logging_severity_level_from_string( arg + strlen(RCL_LOG_LEVEL_ARG_RULE), allocator, log_level); if (RCUTILS_RET_OK == ret) { return RCL_RET_OK; } RCL_SET_ERROR_MSG("Argument does not use a valid severity level"); return RCL_RET_INVALID_LOG_LEVEL_RULE; } rcl_ret_t _rcl_parse_remap_rule( const char * arg, rcl_allocator_t allocator, rcl_remap_t * output_rule) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(output_rule, RCL_RET_INVALID_ARGUMENT); rcl_ret_t ret; output_rule->impl = allocator.allocate(sizeof(rcl_remap_impl_t), allocator.state); if (NULL == output_rule->impl) { return RCL_RET_BAD_ALLOC; } output_rule->impl->allocator = allocator; output_rule->impl->type = RCL_UNKNOWN_REMAP; output_rule->impl->node_name = NULL; output_rule->impl->match = NULL; output_rule->impl->replacement = NULL; rcl_lexer_lookahead2_t lex_lookahead = rcl_get_zero_initialized_lexer_lookahead2(); ret = rcl_lexer_lookahead2_init(&lex_lookahead, arg, allocator); if (RCL_RET_OK != ret) { return ret; } ret = _rcl_parse_remap_begin_remap_rule(&lex_lookahead, output_rule); if (RCL_RET_OK != ret) { // cleanup stuff, but return the original error code if (RCL_RET_OK != rcl_remap_fini(output_rule)) { RCUTILS_LOG_ERROR_NAMED(ROS_PACKAGE_NAME, "Failed to fini remap rule after error occurred"); } if (RCL_RET_OK != rcl_lexer_lookahead2_fini(&lex_lookahead)) { RCUTILS_LOG_ERROR_NAMED(ROS_PACKAGE_NAME, "Failed to fini lookahead2 after error occurred"); } } else { ret = rcl_lexer_lookahead2_fini(&lex_lookahead); } return ret; } rcl_ret_t _rcl_parse_param_rule( const char * arg, rcl_params_t * params) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(params, RCL_RET_INVALID_ARGUMENT); rcl_lexer_lookahead2_t lex_lookahead = rcl_get_zero_initialized_lexer_lookahead2(); rcl_ret_t ret = rcl_lexer_lookahead2_init(&lex_lookahead, arg, params->allocator); if (RCL_RET_OK != ret) { return ret; } rcl_lexeme_t lexeme1; rcl_lexeme_t lexeme2; char * node_name = NULL; char * param_name = NULL; // Check for optional nodename prefix ret = rcl_lexer_lookahead2_peek2(&lex_lookahead, &lexeme1, &lexeme2); if (RCL_RET_OK != ret) { goto cleanup; } if (RCL_LEXEME_TOKEN == lexeme1 && RCL_LEXEME_COLON == lexeme2) { ret = _rcl_parse_nodename_prefix(&lex_lookahead, params->allocator, &node_name); if (RCL_RET_OK != ret) { if (RCL_RET_WRONG_LEXEME == ret) { ret = RCL_RET_INVALID_PARAM_RULE; } goto cleanup; } } else { node_name = rcutils_strdup("/**", params->allocator); if (NULL == node_name) { ret = RCL_RET_BAD_ALLOC; goto cleanup; } } ret = _rcl_parse_resource_match(&lex_lookahead, params->allocator, &param_name); if (RCL_RET_OK != ret) { if (RCL_RET_WRONG_LEXEME == ret) { ret = RCL_RET_INVALID_PARAM_RULE; } goto cleanup; } ret = rcl_lexer_lookahead2_expect(&lex_lookahead, RCL_LEXEME_SEPARATOR, NULL, NULL); if (RCL_RET_WRONG_LEXEME == ret) { ret = RCL_RET_INVALID_PARAM_RULE; goto cleanup; } const char * yaml_value = rcl_lexer_lookahead2_get_text(&lex_lookahead); if (!rcl_parse_yaml_value(node_name, param_name, yaml_value, params)) { ret = RCL_RET_INVALID_PARAM_RULE; goto cleanup; } cleanup: params->allocator.deallocate(param_name, params->allocator.state); params->allocator.deallocate(node_name, params->allocator.state); if (RCL_RET_OK != ret) { if (RCL_RET_OK != rcl_lexer_lookahead2_fini(&lex_lookahead)) { RCUTILS_LOG_ERROR_NAMED(ROS_PACKAGE_NAME, "Failed to fini lookahead2 after error occurred"); } } else { ret = rcl_lexer_lookahead2_fini(&lex_lookahead); } return ret; } rcl_ret_t _rcl_parse_param_file( const char * arg, rcl_allocator_t allocator, char ** param_file) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(param_file, RCL_RET_INVALID_ARGUMENT); *param_file = rcutils_strdup(arg, allocator); if (NULL == *param_file) { RCL_SET_ERROR_MSG("Failed to allocate memory for parameters file path"); return RCL_RET_BAD_ALLOC; } return RCL_RET_OK; } rcl_ret_t _rcl_parse_param_file_rule( const char * arg, rcl_allocator_t allocator, char ** param_file) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); const size_t param_prefix_len = strlen(RCL_PARAM_FILE_ARG_RULE); if (strncmp(RCL_PARAM_FILE_ARG_RULE, arg, param_prefix_len) == 0) { size_t outlen = strlen(arg) - param_prefix_len; *param_file = allocator.allocate(sizeof(char) * (outlen + 1), allocator.state); if (NULL == *param_file) { RCL_SET_ERROR_MSG("Failed to allocate memory for parameters file path"); return RCL_RET_BAD_ALLOC; } snprintf(*param_file, outlen + 1, "%s", arg + param_prefix_len); return RCL_RET_OK; } RCL_SET_ERROR_MSG("Argument does not start with '" RCL_PARAM_FILE_ARG_RULE "'"); return RCL_RET_INVALID_PARAM_RULE; } rcl_ret_t _rcl_parse_external_log_config_file( const char * arg, rcl_allocator_t allocator, char ** log_config_file) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(log_config_file, RCL_RET_INVALID_ARGUMENT); *log_config_file = rcutils_strdup(arg, allocator); // TODO(hidmic): add file checks if (NULL == *log_config_file) { RCL_SET_ERROR_MSG("Failed to allocate memory for external log config file"); return RCL_RET_BAD_ALLOC; } return RCL_RET_OK; } rcl_ret_t _rcl_parse_external_log_config_file_rule( const char * arg, rcl_allocator_t allocator, char ** log_config_file) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(log_config_file, RCL_RET_INVALID_ARGUMENT); const size_t param_prefix_len = sizeof(RCL_EXTERNAL_LOG_CONFIG_ARG_RULE) - 1; if (strncmp(RCL_EXTERNAL_LOG_CONFIG_ARG_RULE, arg, param_prefix_len) == 0) { size_t outlen = strlen(arg) - param_prefix_len; *log_config_file = rcutils_format_string_limit(allocator, outlen, "%s", arg + param_prefix_len); if (NULL == *log_config_file) { RCL_SET_ERROR_MSG("Failed to allocate memory for external log config file"); return RCL_RET_BAD_ALLOC; } return RCL_RET_OK; } RCL_SET_ERROR_MSG("Argument does not start with '" RCL_EXTERNAL_LOG_CONFIG_ARG_RULE "'"); return RCL_RET_INVALID_PARAM_RULE; } rcl_ret_t _rcl_parse_disabling_flag( const char * arg, const char * suffix, bool * disable) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(suffix, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(disable, RCL_RET_INVALID_ARGUMENT); const size_t enable_prefix_len = strlen(RCL_ENABLE_FLAG_PREFIX); if ( strncmp(RCL_ENABLE_FLAG_PREFIX, arg, enable_prefix_len) == 0 && strcmp(suffix, arg + enable_prefix_len) == 0) { *disable = false; return RCL_RET_OK; } const size_t disable_prefix_len = strlen(RCL_DISABLE_FLAG_PREFIX); if ( strncmp(RCL_DISABLE_FLAG_PREFIX, arg, disable_prefix_len) == 0 && strcmp(suffix, arg + disable_prefix_len) == 0) { *disable = true; return RCL_RET_OK; } RCL_SET_ERROR_MSG_WITH_FORMAT_STRING( "Argument is not a %s%s nor a %s%s flag.", RCL_ENABLE_FLAG_PREFIX, suffix, RCL_DISABLE_FLAG_PREFIX, suffix); return RCL_RET_ERROR; } rcl_ret_t _rcl_parse_bool_arg( const char * arg, const char * key, bool * value) { RCL_CHECK_ARGUMENT_FOR_NULL(arg, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(key, RCL_RET_INVALID_ARGUMENT); const size_t param_prefix_len = strlen(key); if (strncmp(key, arg, param_prefix_len) == 0) { return _atob(arg + param_prefix_len, value); } RCL_SET_ERROR_MSG("Argument does not start with key"); return RCL_RET_INVALID_PARAM_RULE; } rcl_ret_t _atob( const char * str, bool * val) { RCL_CHECK_ARGUMENT_FOR_NULL(str, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(val, RCL_RET_INVALID_ARGUMENT); const char * true_values[] = {"y", "Y", "yes", "Yes", "t", "T", "true", "True", "1"}; const char * false_values[] = {"n", "N", "no", "No", "f", "F", "false", "False", "0"}; for (size_t idx = 0; idx < sizeof(true_values) / sizeof(char *); idx++) { if (0 == strncmp(true_values[idx], str, strlen(true_values[idx]))) { *val = true; return RCL_RET_OK; } } for (size_t idx = 0; idx < sizeof(false_values) / sizeof(char *); idx++) { if (0 == strncmp(false_values[idx], str, strlen(false_values[idx]))) { *val = false; return RCL_RET_OK; } } return RCL_RET_ERROR; } #ifdef __cplusplus } #endif /// \endcond // Internal Doxygen documentation
zmichaels11/rcl
rcl/src/rcl/common.c
// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifdef __cplusplus extern "C" { #endif #include "./common.h" // NOLINT #include <stdlib.h> #include "rcl/allocator.h" #include "rcl/error_handling.h" #if defined(_WIN32) # define WINDOWS_ENV_BUFFER_SIZE 2048 static char __env_buffer[WINDOWS_ENV_BUFFER_SIZE]; #endif // defined(_WIN32) rcl_ret_t rcl_impl_getenv(const char * env_name, const char ** env_value) { RCL_CHECK_ARGUMENT_FOR_NULL(env_name, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(env_value, RCL_RET_INVALID_ARGUMENT); *env_value = NULL; #if !defined(_WIN32) *env_value = getenv(env_name); if (*env_value == NULL) { *env_value = ""; } #else // !defined(_WIN32) size_t required_size; errno_t ret = getenv_s(&required_size, __env_buffer, sizeof(__env_buffer), env_name); if (ret != 0) { RCL_SET_ERROR_MSG("value in env variable too large to read in"); return RCL_RET_ERROR; } __env_buffer[WINDOWS_ENV_BUFFER_SIZE - 1] = '\0'; *env_value = __env_buffer; #endif // !defined(_WIN32) return RCL_RET_OK; } rcl_ret_t rcl_convert_rmw_ret_to_rcl_ret(rmw_ret_t rmw_ret) { switch (rmw_ret) { case RMW_RET_OK: return RCL_RET_OK; case RMW_RET_INVALID_ARGUMENT: return RCL_RET_INVALID_ARGUMENT; case RMW_RET_BAD_ALLOC: return RCL_RET_BAD_ALLOC; case RMW_RET_UNSUPPORTED: return RCL_RET_UNSUPPORTED; case RMW_RET_NODE_NAME_NON_EXISTENT: return RCL_RET_NODE_NAME_NON_EXISTENT; default: return RCL_RET_ERROR; } } #ifdef __cplusplus } #endif
sjbarigye/CPP_Primer
chap07/Exer07_04_Person.h
<filename>chap07/Exer07_04_Person.h // For subsequent convenience, exercise 7.4 is defined as a header. #ifndef EXER07_04_H #define EXER07_04_H #include <iostream> #include <string> using std::string; using std::istream; using std::ostream; struct Person { // friend declaration required by exercise 7.22 friend istream& read(istream& is, Person& psn); friend ostream& print(ostream& os, const Person &psn); private: string name; string addr; public: // functions required by exercise 7.5 string getName() const { return name; } string getAddr() const { return addr; } // constructors required by exercise 7.15 Person() = default; Person(const string& nm, const string& ad) : name(nm), addr(ad) {} Person(istream &is) { read(is, *this); } }; // functions required by exercise 7.6 istream& read(istream& is, Person &psn) { is >> psn.name >> psn.addr; return is; } ostream& print(ostream& os, const Person &psn) { os << psn.name << " " << psn.addr; return os; } #endif
sjbarigye/CPP_Primer
chap15/Exer15_39/Exer15_39_AndQuery.h
#ifndef AND_QUERY_H #define AND_QUERY_H #include <memory> #include "Exer15_39_TextQuery.h" #include "Exer15_39_BinaryQuery.h" #include "Exer15_39_Query.h" class AndQuery : public BinaryQuery { friend Query operator&(const Query&, const Query&); AndQuery(const Query &left, const Query &right) : BinaryQuery(left, right, "&") {} // concrete class: AndQuery inherits rep and defines the remaining pure virtual QueryResult eval(const TextQuery&) const; }; inline Query operator&(const Query &lhs, const Query &rhs) { return std::shared_ptr<Query_base>(new AndQuery(lhs, rhs)); } #endif
sjbarigye/CPP_Primer
chap13/Page519_542_Message.h
<filename>chap13/Page519_542_Message.h #ifndef MESSAGE_FOLDER_H #define MESSAGE_FOLDER_H #include <iostream> #include <string> #include <set> class Folder; // incomplete class declaration class Message { friend class Folder; friend void swap(Message&, Message&); public: // folders is implicitly initialized to the empty std::set explicit Message(const std::string &str = "") : contents(str) {} // copy control to manage pointers to this Message Message(const Message&); // copy constructor Message(Message&&); // move constructor Message& operator=(const Message&); // copy assignment Message& operator=(Message&&); // move assignment ~Message(); // destructor // add/remove this Message from the specified Folder's std::set of messages void save(Folder&); void remove(Folder&); // insert or remove a given Folder* into folders, required by exercise 13.37 void addFolder(Folder*); void remFolder(Folder*); private: std::string contents; // actual message text std::set<Folder*> folders; // Folders that have this Message // utility functions used by copy constructor, copy-assignment operator and destructor // add this Message to the Folders that point to the parameter void add_to_Folders(const Message&); // remove this Message from every Folder in folders void remove_from_Folders(); // common work: move the Folder pointers from m to this Message void move_Folders(Message*); }; class Folder { friend void swap(Folder&, Folder&); public: explicit Folder(const std::string &s = "") : name(s) {} Folder(const Folder&); Folder& operator=(const Folder&); ~Folder(); void addMsg(Message*); void remMsg(Message*); void show(); private: std::string name; std::set<Message*> messages; void add_messages(const Folder&); void remove_messages(); }; void Folder::addMsg(Message *m) { messages.insert(m); // m->folders.insert(this); } void Folder::remMsg(Message *m) { messages.erase(m); // m->folders.erase(this); } void Folder::show() { for(auto m : messages) std::cout << m->contents << std::endl; } void Message::save(Folder &f) { folders.insert(&f); // add the given Folder to our list of Folders f.addMsg(this); // add this Message to f's std::set of Messages } void Message::remove(Folder &f) { folders.erase(&f); // take the give Folder out of our list of Folders f.remMsg(this); // remove this Message to f's std::set of Messages } // add this Message to Folders that point to m void Message::add_to_Folders(const Message &m) { for(auto f : m.folders) // for each Folder that holds m f->addMsg(this); // add a pointer to this Message to that folders } // remove this message from the corresponding Folders void Message::remove_from_Folders() { for(auto f : folders) // for each pointer in folders f->remMsg(this); // remove this Message from that Folder } void Message::move_Folders(Message *m) { folders = std::move(m->folders); // use std::set move assignment for (auto f : folders) { // for each folder f->remMsg(m); // remove the old Message from the Folder f->addMsg(this); // add this Message to that Folder } m->folders.clear(); // ensure that destroying m is harmless } // copy constructor Message::Message(const Message &m) : contents(m.contents), folders(m.folders) { add_to_Folders(m); // add this Message to the Folders that point to m } // move constructor on page 542 Message::Message(Message &&m) : contents(std::move(m.contents)) { move_Folders(&m); // move folders and updates the folder pointers } // destructor Message::~Message() { remove_from_Folders(); } // move-assignment operator Message& Message::operator=(Message &&rhs) { if(this != &rhs) { // never forget handling self-assignment remove_from_Folders(); // remove this Message from all of the Folders contents = std::move(rhs.contents); // move assignment move_Folders(&rhs); // reset the Folders to point to this Message } return *this; } // copy-assignment operator Message& Message::operator=(const Message &rhs) { // handle self-assignment by removing pointers before inserting them remove_from_Folders(); // update existing Folders contents = rhs.contents; // copy message contents from rhs folders = rhs.folders; // copy Folder pointers from rhs add_to_Folders(rhs); // add this Message to those Folders return *this; } // swap function void swap(Message &lhs, Message &rhs) { using std::swap; // not strictly needed in this case, but good habit for(auto f : lhs.folders) f->remMsg(&lhs); for(auto f : rhs.folders) f->remMsg(&rhs); // swap the contents and Folder pointer sets swap(lhs.folders, rhs.folders); // use swap(std::set&, std::set&) swap(lhs.contents, rhs.contents); // swap(std::string&, std::string&) // add pointer to each Message to their (new) respective Folders for(auto f : lhs.folders) f->addMsg(&lhs); for(auto f : rhs.folders) f->remMsg(&rhs); } void Message::addFolder(Folder *f) { folders.insert(f); } void Message::remFolder(Folder *f) { folders.erase(f); } void Folder::add_messages(const Folder &f) { for(auto m : f.messages) m->save(*this); } void Folder::remove_messages() { for(auto m : messages) m->remove(*this); messages.clear(); // clear the messages because no message points to this folder } Folder::Folder(const Folder &f) : name(f.name), messages(f.messages) { add_messages(f); } Folder& Folder::operator=(const Folder &rhs) { remove_messages(); name = rhs.name; messages = rhs.messages; add_messages(rhs); return *this; } Folder::~Folder() { remove_messages(); } void swap(Folder &lhs, Folder &rhs) { using std::swap; for(auto m : lhs.messages) m->remove(lhs); for(auto m : rhs.messages) m->remove(rhs); swap(lhs.name, rhs.name); swap(lhs.messages, rhs.messages); for(auto m : lhs.messages) m->save(lhs); for(auto m : rhs.messages) m->save(rhs); } #endif // Note: should we add a pointer in folders of Message class in the member // function addMsg of Folder? Practically, this will induce loop call: addMsg // calls save, save calls addMsg. Conceptually, this contrasts to the feature of // each class. Every class just takes response of its own. It shouldn't // interfere with other class' operation. In fact, Folder shouldn't know how // Message processes its data. On the other hand, we cannot only use addMsg // outside both classes. This way a folder has pointed to a message, but a // message doesn't know this. Because we didn't add a record in folder of that // message.
sjbarigye/CPP_Primer
chap06/Page239_inline.h
<gh_stars>10-100 #ifndef INILINE_TEST #define INILINE_TEST #include <string> using std::string; inline const string &shorterString(const string &s1, const string &s2) { return s1.size() <= s2.size() ? s1 : s2; } constexpr int new_sz() { return 42; } #endif
sjbarigye/CPP_Primer
chap19/Exer19_17_Screen.h
// Screen header from exercise 7.23. #ifndef EXER19_17_SCREEN_H #define EXER19_17_SCREEN_H #include <string> class Screen{ // for test, required by exercise 19.12 friend void ptrTest(); public: typedef std::string::size_type pos; // type alias for every kind of member function, required by exercise 19.17 using Action1 = char (Screen::*)() const; using Action2 = char (Screen::*)(pos, pos) const; using Action3 = Screen& (Screen::*)(pos, pos); // return a pointer to data member, required by exercise 19.12 static const std::string Screen::*data() { return &Screen::contents; } Screen() = default; Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) {} char get() const { return contents[cursor]; } char get_cursor() const { return contents[cursor]; } inline char get(pos ht, pos wd) const; Screen &move(pos r, pos c); private: pos cursor = 0; pos height = 0, width = 0; std::string contents; }; char Screen::get(pos r, pos c) const { pos row = r * width; return contents[row + c]; } Screen& Screen::move(pos r, pos c) { pos row = r * width; cursor = row + c; return *this; } #endif
sjbarigye/CPP_Primer
chap06/Chapter6.h
<filename>chap06/Chapter6.h // Exer06_08 #ifndef CHAP06_H #define CHAP06_H int fact(int); void fact(); int abs(int); #endif
sjbarigye/CPP_Primer
chap13/Exer13_28_BinStrTree_value.h
<filename>chap13/Exer13_28_BinStrTree_value.h #ifndef EXER13_28_2_VALUE_H #define EXER13_28_2_VALUE_H #include <cstddef> #include "Exer13_28_TreeNode_value.h" class BinStrTree { public: BinStrTree() : root(new TreeNode()) {} BinStrTree(const BinStrTree &bp); BinStrTree& operator=(const BinStrTree &bp); ~BinStrTree(); private: TreeNode *root; }; BinStrTree::BinStrTree(const BinStrTree &bp) : root(new TreeNode()) { if(bp.root) *root = *bp.root; } BinStrTree& BinStrTree::operator=(const BinStrTree &bp) { auto newp = new TreeNode(*root); delete root; root = newp; return *this; } BinStrTree::~BinStrTree() { delete root; } #endif // Note: because the copy-control members of TreeNode have carefully handled // everything, here we can use it directly without worrying about dereferencing // a null pointer or something else.
sjbarigye/CPP_Primer
chap19/Exer19_02_StrVec.h
// StrVec from chapter 14. #ifndef EXER19_02_STRVEC_H #define EXER19_02_STRVEC_H #include <cstddef> #include <cstdlib> #include <string> #include <utility> #include <memory> #include <initializer_list> #include "Exer19_01_new_delete.h" using std::size_t; using std::string; using std::pair; using std::allocator; using std::initializer_list; class StrVec { // equality operator required by exercise 14.16 friend bool operator==(const StrVec&, const StrVec&); friend bool operator!=(const StrVec&, const StrVec&); // relation operator required by exercise 14.18 friend bool operator<(const StrVec&, const StrVec&); friend bool operator<=(const StrVec&, const StrVec&); friend bool operator>(const StrVec&, const StrVec&); friend bool operator>=(const StrVec&, const StrVec&); public: StrVec(): elements(nullptr), first_free(nullptr), cap(nullptr) {} StrVec(const StrVec&); // move constructor from page 536 StrVec(StrVec&&) noexcept; StrVec& operator=(const StrVec&); // move assignment from page 537 StrVec& operator=(StrVec&&) noexcept; // assignment with an initializer_list parameter from page 563 StrVec& operator=(initializer_list<string>); // constructor that takes a initializer_list as parameter, required by exercise 13.40 StrVec(const initializer_list<string>&); // subscript operator from page 565 // class is not responsible for checking if the subscript is out of range string& operator[](size_t n) // nonconst version of subscript operator { return elements[n]; } string& operator[](size_t n) const // const version of subscript operator { return elements[n]; } ~StrVec(); void push_back(const string&); void push_back(string&&); size_t size() const { return first_free - elements; } size_t capacity() const { return cap - elements; } string *begin() const { return elements; } string *end() const { return first_free; } // both begin() and end() are const // reserve and resize required by exercise 13.39 void reserve(size_t); void resize(size_t); void resize(size_t, const string&); private: static allocator<string> alloc; void chk_n_alloc() { if(size() == capacity()) reallocate(); } pair<string*, string*> alloc_n_copy(const string*, const string*); void free(); void reallocate(); void add_rem(size_t n, const string &s = ""); string *elements; string *first_free; string *cap; }; // Warning: define static member outside the class. Without this the program // using the class wouldn't compile allocator<string> StrVec::alloc; // friend definition bool operator==(const StrVec &lhs, const StrVec &rhs) { if(lhs.size() != rhs.size()) return false; else { for(auto p = lhs.elements, q = rhs.elements; p != lhs.first_free; ++p, ++q) { if(*p != *q) return false; } return true; } } bool operator!=(const StrVec &lhs, const StrVec &rhs) { return !(lhs == rhs); } bool operator<(const StrVec &lhs, const StrVec &rhs) { auto shorter = lhs.size() < rhs.size() ? lhs.size() : rhs.size(); auto p = lhs.begin(), q = rhs.begin(); for(size_t i = 0; p + i != lhs.end(); ++i) { if(*(p + i) == *(q + i)) continue; else if(*(p + i) < *(q + i)) return true; else return false; } return lhs.size() < rhs.size(); } bool operator<=(const StrVec &lhs, const StrVec &rhs) { return lhs < rhs || lhs == rhs; } bool operator>(const StrVec &lhs, const StrVec &rhs) { return !(lhs < rhs || lhs == rhs); } bool operator>=(const StrVec &lhs, const StrVec &rhs) { return !(lhs < rhs); } void StrVec::push_back(const string &s) { chk_n_alloc(); alloc.construct(first_free++, s); } void StrVec::push_back(string &&s) { chk_n_alloc(); alloc.construct(first_free++, std::move(s)); } pair<string*, string*> StrVec::alloc_n_copy(const string *b, const string *e) { auto data = alloc.allocate(e - b); return {data, uninitialized_copy(b, e, data)}; } void StrVec::free() { if (elements) { for(auto p = first_free; p != elements; /*empty*/ ) alloc.destroy(--p); alloc.deallocate(elements, cap - elements); } } StrVec::StrVec(const StrVec &s) { auto newdata = alloc_n_copy(s.begin(), s.end()); elements = newdata.first; first_free = cap = newdata.second; } StrVec::StrVec(StrVec &&s) noexcept : elements(s.elements), first_free(s.first_free), cap(s.cap) { s.elements = s.first_free = s.cap = nullptr; } StrVec::StrVec(const initializer_list<string> &il) { auto newdata = alloc_n_copy(il.begin(), il.end()); elements = newdata.first; first_free = cap = newdata.second; } StrVec::~StrVec() { free(); } StrVec& StrVec::operator=(const StrVec &rhs) { auto data = alloc_n_copy(rhs.begin(), rhs.end()); free(); elements = data.first; first_free = cap = data.second; return *this; } StrVec& StrVec::operator=(StrVec &&rhs) noexcept { if(this != &rhs) { free(); elements = rhs.elements; first_free = rhs.first_free; cap = rhs.cap; rhs.elements = rhs.first_free = rhs.cap = nullptr; } return *this; } StrVec& StrVec::operator=(initializer_list<string> il) { auto data = alloc_n_copy(il.begin(), il.end()); free(); elements = data.first; first_free = cap = data.second; return *this; } void StrVec::reallocate() { // we'll allocate space for twice as many as the current size auto newcapacity = size() ? 2 * size() : 1; // if empty, allocate 1 space, otherwise double // allocate new memory auto newdata = alloc.allocate(newcapacity); // move the data from the old memory to the new auto dest = newdata; // points to the next free position in the new memory auto elem = elements; // points to the next element in the old memory for(size_t i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); // free the old space once we've moved the elements // update our data structure to point to the new elements elements = newdata; first_free = dest; cap = elements + newcapacity; } void StrVec::reserve(size_t n) { if(n > capacity()) { auto newdata = alloc.allocate(n); auto dest = newdata; auto elem = elements; for(size_t i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); elements = newdata; first_free = newdata; cap = elements + n; } } void StrVec::resize(size_t n) { add_rem(n); } void StrVec::resize(size_t n, const string &s) { add_rem(n, s); } void StrVec::add_rem(size_t n, const string &s) { if(n <= size()) { auto p = first_free; while(p != elements + n) alloc.destroy(--p); first_free = p; } else{ auto new_elem_count = n - size(); for(size_t i = 0; i != new_elem_count; ++i) push_back(s); } } #endif
sjbarigye/CPP_Primer
chap15/Exer15_19.h
#ifndef PAGE612_613_ACCESS_H #define PAGE612_613_ACCESS_H class Base { public: void pub_mem(); // public member protected: int prot_mem = 0; // protected member private: char priv_mem = 0; //private member }; struct Pub_Derv : public Base { // ok: derived classes can access protected members int f() { return prot_mem; } // error: private members are inaccessible to derived classes // char g() { return priv_mem; } void memfcn(Base &b) { b = *this; } // legal }; struct Priv_Derv : private Base { // private derivation doesn't affect access in the derived class int f1() { return prot_mem; } void memfcn(Base &b) { b = *this; } // legal }; struct Prot_Derv : protected Base { // protected derivation doesn't affect access in the derived class int f2() { return prot_mem; } void memfcn(Base &b) { b = *this; } // legal }; struct Derived_from_Public : public Pub_Derv { // ok: Base::prot_mem remains protected in Pub_Derv int use_base() { return prot_mem; } void memfcn(Base &b) { b = *this; } // legal }; struct Derived_from_Private: public Priv_Derv { // error: Base::prot_mem is private in Priv_Derv // int use_base() { return prot_mem; } void memfcn(Base &b) { b = *this; } // illegal, Priv_Derv inherits from Base privatele }; struct Derived_from_Protected: public Prot_Derv { // ok: Base::prot_mem is protected in Prot_Derv int use_base() { return prot_mem; } void memfcn(Base &b) { b = *this; } // legal }; #endif // ******compile info of g++****** // Exer15_19.h:3:12: error: 'class Base Base::Base' is inaccessible // class Base { // ^ // Exer15_19.h:36:14: error: within this context // void memfcn(Base &b) { b = *this; } // illegal, Priv_Derv inherits from Base privatele // ^ // Exer15_19.h: In member function 'void Derived_from_Private::memfcn(Base&)': // Exer15_19.h:36:27: error: 'Base' is an inaccessible base of 'Derived_from_Private' // void memfcn(Base &b) { b = *this; } // illegal, Priv_Derv inherits from Base privatele // ^ // ******compile info of clang++****** // Exer15_19.h:36:14: error: 'Base' is a private member of 'Base' // void memfcn(Base &b) { b = *this; } // illegal, Priv_Derv inheri... // ^ // Exer15_19.h:18:20: note: constrained by private inheritance here // struct Priv_Derv : private Base { // ^~~~~~~~~~~~ // Exer15_19.h:3:7: note: member is declared here // class Base { // ^ // Exer15_19.h:36:29: error: cannot cast 'Derived_from_Private' to its private base // // class 'Base' // void memfcn(Base &b) { b = *this; } // illegal, Priv_Derv inheri... // ^ // Exer15_19.h:18:20: note: declared private here // struct Priv_Derv : private Base { // ^~~~~~~~~~~~ // 2 errors generated. // ******compile info of cl****** // 用于 x86 的 Microsoft (R) C/C++ 优化编译器 18.00.40629 版版权所有(C) Microsoft C // orporation。 保留所有权利。 // // Exer15_19.h // Exer15_19.h(36) : error C2247: “Base”不可访问,因为“Priv_Derv”使用“private // ”从“Base”继承 // Exer15_19.h(3) : 参见“Base”的声明 // Exer15_19.h(18) : 参见“Priv_Derv”的声明 // Exer15_19.h(3) : 参见“Base”的声明 // Exer15_19.h(36) : error C2243: “类型转换”: 从“Derived_from_Private *”到“con // st Base &”的转换存在,但无法访问
sjbarigye/CPP_Primer
chap15/Exer15_27_Bulk_quote.h
#ifndef BULK_QUOTE_H #define BULK_QUOTE_H #include <cstddef> #include <iostream> #include <string> #include "Exer15_26_Disc_quote.h" class Bulk_quote : public Disc_quote { // Bulk_quote inherits from Quote public: Bulk_quote() { std::cout << "Bulk_quote()" << std::endl; } // inherited constructor using Disc_quote::Disc_quote; // overrides the base version in order to implement the bulk purchase discount policy double net_price(std::size_t) const override; void debug() const override; // copy-control members Bulk_quote(const Bulk_quote &bq) : Disc_quote(bq) { std::cout << "Bulk_quote(const Bulk_quote&)" << std::endl; } Bulk_quote(Bulk_quote &&bq) noexcept : Disc_quote(std::move(bq)) { std::cout << "Bulk_quote(Bulk_quote&&)" << std::endl; } Bulk_quote& operator=(const Bulk_quote&); Bulk_quote& operator=(Bulk_quote&&) noexcept; ~Bulk_quote() { std::cout << "~Bulk_quote()" << std::endl; } }; // if the specified number of items are purchased, use the discounted price double Bulk_quote::net_price(std::size_t cnt) const { if (cnt >= quantity) return cnt * (1 - discount) * price; else return cnt * price; } inline void Bulk_quote::debug() const { std::cout << "std::string bookNo\n" << "double price\n" << "std::size_t min_qty\n" << "double discount\n" << std::endl; } inline Bulk_quote& Bulk_quote::operator=(const Bulk_quote &rhs) { Disc_quote::operator=(rhs); std::cout << "Bulk_quote& operator=(const Bulk_quote&)" << std::endl; return *this; } inline Bulk_quote& Bulk_quote::operator=(Bulk_quote &&rhs) noexcept { Disc_quote::operator=(std::move(rhs)); std::cout << "Bulk_quote& operator=(Bulk_quote&&)" << std::endl; return *this; } #endif
sjbarigye/CPP_Primer
chap13/Exer13_28_TreeNode_point.h
<reponame>sjbarigye/CPP_Primer #ifndef EXER13_28_1_POINT_H #define EXER13_28_1_POINT_H #include <iostream> #include <string> #include <cstddef> class TreeNode { public: TreeNode() : count(0), left(nullptr), right(nullptr), use(new std::size_t(1)) {} // an empty node TreeNode(const std::string &s) : value(s), count(1), left(nullptr), right(nullptr), use(new std::size_t(1)) {} TreeNode(const TreeNode &tp): value(tp.value), count(tp.count), left(tp.left), right(tp.right), use(tp.use) { ++*use; } TreeNode& operator=(const TreeNode&); std::ostream& read(std::ostream& os) const { os << value << "\t" << count; return os; } void write(const std::string &str) { value = str; } ~TreeNode(); private: std::string value; int count; TreeNode *left; TreeNode *right; std::size_t *use; }; TreeNode& TreeNode::operator=(const TreeNode& tp) { ++*tp.use; if(--*use == 0) { if(left) delete left; if(right) delete right; delete use; } value = tp.value; count = tp.count; left = tp.left; right = tp.right; use = tp.use; return *this; } TreeNode::~TreeNode() { if(--*use == 0) { if(left) { delete left; left = nullptr; } if(right) { delete right; right = nullptr; } delete use; } } #endif // Note: one thing we have to watch out for is that left and child might hold // null. This version is easier to handle than value-like version.
sjbarigye/CPP_Primer
chap19/Exer19_26.c
<gh_stars>10-100 #include "Exer19_26.h" int compute(int *p, int i) { p = &i; return *p; }
sjbarigye/CPP_Primer
chap09/Exer09_51.h
#ifndef EXER09_51_H #define EXER09_51_H #include <iostream> #include <string> #include <vector> #include <stdexcept> using std::cout; using std::endl; using std::string; using std::vector; using std::invalid_argument; static const vector<string> MONALL{ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"}; class Date{ public: Date() = default; Date(const string&); Date& print_date(); private: bool isleap(unsigned); // judge if a year is leap unsigned year = 1900; unsigned month = 1; unsigned day = 1; }; // Date format could be surprisingly complicated. See the wiki page for more info: // https://en.wikipedia.org/wiki/Date_format_by_country // Here, the constructor can only take one argument. So I suppose the order is // month-date-year. Date::Date(const string& date) : Date() { unsigned year_temp = 0, month_temp = 0, day_temp = 0; if(date.empty()) // empty string is invalid throw invalid_argument("Argument shouldn't be empty"); vector<string> split; // put valid strings into a vector string str; // filter white spaces and separators for(const auto &c : date) { if(!(isspace(c) || c == ',' || c == '-' || c == '/' || c == '.')) str.push_back(c); // any separators above (including contiguous white spaces) are okay else { if(!str.empty()) { split.push_back(str); str.clear(); } } } split.push_back(str); // don't forget to push back the last result if(split.size() != 3) throw invalid_argument("Not a valid date."); // if month begins with a letter, it might be a month in English if(isalpha(split[0][0])) { for(auto &c : split[0]) c = toupper(c); // convert month to upper case for(decltype(MONALL.size()) m = 0; m <= MONALL.size(); ++m) { if(MONALL[m].find(split[0]) == 0) // abbreviation or full { if(split[0].size() >= 3 && split[0].size() <= MONALL[m].size()) { month_temp = m + 1; break; } else throw invalid_argument("Not a valid month."); } if(m == 11) throw invalid_argument("Not a valid month."); } } // or month should be a numeric value else if(isdigit(split[0][0])) { month_temp = stoi(split[0]); if(month_temp < 1 || month_temp > 12) throw invalid_argument("Not a valid month."); } // or the input month is wrong else throw invalid_argument("Input is not a month."); day_temp = stoi(split[1]); year_temp = stoi(split[2]); // Judge if a date is legal switch(month_temp){ case 2: if(isleap(year_temp)) { if(day_temp > 29) throw invalid_argument("Date is invalid for leap year."); } else { if(day_temp > 28) throw invalid_argument("Date is invalid for non-leap year."); } break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: if(day_temp > 31) throw invalid_argument("Date is invalid."); break; case 4: case 6: case 9: case 11: default: if(day_temp > 30) throw invalid_argument("Date is out of range."); break; } year = year_temp; month = month_temp; day = day_temp; } Date& Date::print_date() { cout << year << "-" << month << "-" << day << endl; return *this; } inline bool Date::isleap(unsigned y) { return ((y % 400 == 0) || (y % 100 != 0 && y % 4 == 0)); } #endif // Note #1: basic thought is to split the argument into different substrings that // contains no white spaces and then process each substring and verify if a date // is legal. // Note #2: the constructor above tries its best to handle exceptions, thus leading // to throwing many exceptions at different places. This makes the constructor // ugly. So is it appropriate to throw exceptions in a constructor? The answer // seems yes from // https://stackoverflow.com/questions/77639/when-is-it-right-for-a-constructor-to-throw-an-exception // and // https://stackoverflow.com/questions/810839/throwing-exceptions-from-constructors // After all, to get a valid result, we have to judge whether an input that // represents a date is valid. If these exception handlers were not in a // constructor, we have to put them where a date input is required. That means // we have to either write another function or do repeated work. // // On the other hand, throwing exceptions in a constructor won't call destructor, // which might lead to other problems. See the link below. // https://www.byvoid.com/zhs/blog/cpp-constructor-exception // The code above throws too many exceptions, think about other ways to improve // it. // Note #3: should this constructor be declared as explicit? // Consider a situation where we want to get the difference between two dates. // We might want to use a valid date string as a operand. Thus an implicit type // conversion is required. So we shouldn't declare this constructor as explicit.
sjbarigye/CPP_Primer
chap16/Exer16_19_print_container.h
<filename>chap16/Exer16_19_print_container.h<gh_stars>10-100 #ifndef EXER16_19_PRINT_CONTAINER_H #define EXER16_19_PRINT_CONTAINER_H #include <iostream> template <typename C> void print(const C &c) { for(typename C::size_type i = 0; i != c.size(); ++i) std::cout << c[i] << " "; } #endif
sjbarigye/CPP_Primer
chap16/Exer16_62_Sales_data.h
#ifndef EXER16_61_SALES_DATA_H #define EXER16_61_SALES_DATA_H #include <cstddef> #include <iostream> #include <string> #include <functional> using std::cout; using std::cin; using std::cerr; using std::endl; using std::string; using std::istream; using std::ostream; class Sales_data { // friend // overloaded output operator required by exercise 14.6 friend ostream &operator<<(ostream&, const Sales_data&); // overloaded input operator required by exercise 14.9 friend istream &operator>>(istream&, Sales_data&); // overloaded addition operator required by exercise 14.13 friend Sales_data operator+(const Sales_data&, const Sales_data&); // overloaded equality on page 561 friend bool operator==(const Sales_data&, const Sales_data&); friend bool operator!=(const Sales_data&, const Sales_data&); // overloaded addition operator required by exercise 14.20 friend Sales_data operator+(const Sales_data&, const Sales_data&); // hash for Sales_data required by exercise 16.62 friend class std::hash<Sales_data>; public: // constructor Sales_data() = default; Sales_data(const string &s) : bookNo(s) {} Sales_data(const string &s, unsigned n, double p) : bookNo(s), units_sold(n), revenue(p*n) {} explicit Sales_data(istream &is) { is >> *this; } // member string isbn() const { return bookNo; } // overloaded compound-assignment operator required by exercise 14.20 Sales_data& operator+=(const Sales_data&); // takes an ISBN as parameter, required by exercise 14.22 Sales_data& operator=(const string&); private: string bookNo; unsigned units_sold = 0; double revenue = 0.0; double avg_price() const; }; // member functions definition Sales_data& Sales_data::operator+=(const Sales_data& rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } Sales_data& Sales_data::operator=(const string &isbn) { bookNo = isbn; return *this; } // define avg_price as inline, required by exercise 7.26 inline double Sales_data::avg_price() const { if(units_sold != 0) return revenue / units_sold; else return revenue; } // overloaded output operator ostream& operator<<(ostream& os, const Sales_data& item) { os << item.bookNo << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); return os; } // overloaded input operator istream& operator>>(istream &is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; if(is) // check if input invalid item.revenue = item.units_sold * price; else item = Sales_data(); // input failed:given the object default state return is; } bool operator==(const Sales_data &lhs, const Sales_data &rhs) { return lhs.bookNo == rhs.bookNo && lhs.units_sold == rhs.units_sold && lhs.revenue == rhs.revenue; } bool operator!=(const Sales_data &lhs, const Sales_data &rhs) { return !(lhs == rhs); } Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) { Sales_data sum = lhs; sum += rhs; return sum; } // hash specialization for Sales_data required by exercise 16.62 // open the std namespace so we can specialize std::hash namespace std { template <> // we're defining a specialization with the template parameter of Sales_data struct hash<Sales_data> { // the type used to hash an unordered container must define these types typedef size_t result_type; typedef Sales_data argument_type; // by default, this type needs == size_t operator()(const Sales_data&) const; // our class uses synthesized copy control and default constructor }; size_t // here we can use [typename] hash<Sales_data>::result_type to replace size_t hash<Sales_data>::operator()(const Sales_data &s) const { return hash<string>()(s.bookNo) ^ hash<unsigned>()(s.units_sold) ^ hash<double>()(s.revenue); } } // close the std namespace; not: no semicolon after the close curly #endif
sjbarigye/CPP_Primer
chap15/Exer15_11_Limit_quote.h
<gh_stars>10-100 #ifndef LIMIT_QUOTE_H #define LIMIT_QUOTE_H #include <cstddef> #include "Exer15_11_Quote.h" class Limit_quote : public Quote { public: Limit_quote() = default; Limit_quote(const std::string&, double, std::size_t, double); // overrides the base version in order to implement the bulk purchase discount policy double net_price(std::size_t) const override; void debug() const override; private: std::size_t max_qty = 0; // maximum purchase for the discount to apply double discount = 0.0; // fraction discount to apply }; inline Limit_quote::Limit_quote(const std::string &book, double p, std::size_t qty, double disc) : Quote(book, p), max_qty(qty), discount(disc) {} double Limit_quote::net_price(std::size_t cnt) const { if(cnt <= max_qty) return cnt * (1 - discount) * price; else return cnt * price; } inline void Limit_quote::debug() const { std::cout << "std::string bookNo\n" << "double price\n" << "std::size_t max_qty\n" << "double discount\n" << std::endl; } #endif
sjbarigye/CPP_Primer
chap16/Exer16_12_Blob.h
// Note: this header uses contents beyond the section, see section 16.1.3, page 669 // using class members that are types #ifndef EXER16_12_BLOB_H #define EXER16_12_BLOB_H #include <string> #include <vector> #include <initializer_list> #include <memory> #include <utility> #include <stdexcept> template <typename T> class BlobPtr; template <typename T> class ConstBlobPtr; template <typename T> class Blob; template <typename T> bool operator==(const Blob<T>&, const Blob<T>&); template <typename T> bool operator!=(const Blob<T>&, const Blob<T>&); template <typename T> bool operator<(const Blob<T>&, const Blob<T>&); template <typename T> bool operator<=(const Blob<T>&, const Blob<T>&); template <typename T> bool operator>(const Blob<T>&, const Blob<T>&); template <typename T> bool operator>=(const Blob<T>&, const Blob<T>&); template <typename T> class Blob { friend class BlobPtr<T>; friend bool operator==<T>(const Blob<T>&, const Blob<T>&); friend bool operator!=<T>(const Blob<T>&, const Blob<T>&); friend bool operator< <T>(const Blob<T>&, const Blob<T>&); friend bool operator<=<T>(const Blob<T>&, const Blob<T>&); friend bool operator><T>(const Blob<T>&, const Blob<T>&); friend bool operator>=<T>(const Blob<T>&, const Blob<T>&); public: typedef T value_type; typedef typename std::vector<T>::size_type size_type; typedef typename std::vector<T>::difference_type difference_type; // constructors Blob(); Blob(std::initializer_list<T> il); // size size_type size() const { return data->size(); } bool empty() const { return data->empty(); } // elements void push_back(const T &t) { data->push_back(t); } void push_back(T &&t) { data->push_back(std::move(t)); } void pop_back(); T& front(); T& back(); // const version from exercise 12.2 const T& front() const; const T& back() const; T& operator[] (size_type); const T& operator[] (size_type) const; T& at(size_type); const T& at(size_type) const; // use count size_type use_count() const { return data->use_count(); } private: std::shared_ptr<std::vector<T>> data; void check(size_type, const std::string&) const; }; // constructors template <typename T> Blob<T>::Blob(): data(std::make_shared<std::vector<T>>()) {} template <typename T> Blob<T>::Blob(std::initializer_list<T> il): data(std::make_shared<std::vector<T>>(il)) {} // check index template <typename T> void Blob<T>::check(size_type i, const std::string &msg) const { if(i >= data->size()) throw std::out_of_range(msg); } // add and remove elements template <typename T> void Blob<T>::pop_back() { check(0, "pop_back on empty Blob"); data->pop_back(); } // element access template <typename T> T& Blob<T>::front() { check(0, "front on empty Blob"); data->front(); } template <typename T> T& Blob<T>::back() { check(0, "back on empty Blob"); data->back(); } template <typename T> const T& Blob<T>::front() const { check(0, "front on empty Blob"); data->front(); } template <typename T> const T& Blob<T>::back() const { check(0, "back on empty Blob"); data->back(); } template <typename T> T& Blob<T>::operator[](size_type i) { check(i, "index out of range"); return (*data)[i]; } template <typename T> const T& Blob<T>::operator[](size_type i) const { check(i, "index out of range"); return (*data)[i]; } template <typename T> T& Blob<T>::at(size_type i) { check(i, "index out of range"); return data->at(i); } template <typename T> const T& Blob<T>::at(size_type i) const { check(i, "index out of range"); return data->at(i); } // relational operators template <typename T> inline bool operator==(const Blob<T> &lhs, const Blob<T> &rhs) { return *lhs.data == *rhs.data; } template <typename T> inline bool operator!=(const Blob<T> &lhs, const Blob<T> &rhs) { return !(lhs == rhs); } template <typename T> inline bool operator<(const Blob<T> &lhs, const Blob<T> &rhs) { return *lhs.data < *rhs.data; } template <typename T> inline bool operator<=(const Blob<T> &lhs, const Blob<T> &rhs) { return (lhs < rhs || lhs == rhs); } template <typename T> inline bool operator>(const Blob<T> &lhs, const Blob<T> &rhs) { return !(lhs < rhs || lhs == rhs); } template <typename T> inline bool operator>=(const Blob<T> &lhs, const Blob<T> &rhs) { return !(lhs < rhs); } // ****************************** // nonconst version of BlobPtr // ****************************** template <typename T> bool operator==(const BlobPtr<T>&, const BlobPtr<T>&); template <typename T> bool operator!=(const BlobPtr<T>&, const BlobPtr<T>&); template <typename T> bool operator<(const BlobPtr<T>&, const BlobPtr<T>&); template <typename T> bool operator<=(const BlobPtr<T>&, const BlobPtr<T>&); template <typename T> bool operator>(const BlobPtr<T>&, const BlobPtr<T>&); template <typename T> bool operator>=(const BlobPtr<T>&, const BlobPtr<T>&); template <typename T> bool operator+(const BlobPtr<T>&, const BlobPtr<T>&); // using class member that are types, see section 16.1.3, page 669 template <typename T> BlobPtr<T> operator+(const BlobPtr<T>&, typename Blob<T>::difference_type); template <typename T> BlobPtr<T> operator-(const BlobPtr<T>&, typename Blob<T>::difference_type); template <typename T> typename Blob<T>::difference_type operator-(const BlobPtr<T>&, const BlobPtr<T>&); template <typename T> class BlobPtr { friend bool operator==<T>(const BlobPtr<T>&, const BlobPtr<T>&); friend bool operator!=<T>(const BlobPtr<T>&, const BlobPtr<T>&); friend bool operator< <T>(const BlobPtr<T>&, const BlobPtr<T>&); friend bool operator<=<T>(const BlobPtr<T>&, const BlobPtr<T>&); friend bool operator><T>(const BlobPtr<T>&, const BlobPtr<T>&); friend bool operator>=<T>(const BlobPtr<T>&, const BlobPtr<T>&); friend BlobPtr<T> operator+<T>(const BlobPtr<T>&, typename Blob<T>::difference_type); friend BlobPtr<T> operator-<T>(const BlobPtr<T>&, typename Blob<T>::difference_type); friend typename Blob<T>::difference_type operator-<T>(const BlobPtr<T>&, const BlobPtr<T>&); public: typedef typename std::vector<T>::size_type size_type; BlobPtr(); BlobPtr(Blob<T> &a, size_type sz = 0): wptr(a.data), curr(sz) {} // deference T& operator*() const; // subscript T& operator[](size_type); const T& operator[](size_type) const; // increment/decrement BlobPtr& operator++(); BlobPtr& operator--(); BlobPtr& operator++(int); BlobPtr& operator--(int); // compound assignment BlobPtr& operator+=(typename Blob<T>::difference_type); // addition BlobPtr& operator-=(typename Blob<T>::difference_type); // subtraction private: std::shared_ptr<std::vector<T>> check(size_type, const std::string&) const; std::weak_ptr<std::vector<T>> wptr; size_type curr; }; template <typename T> std::shared_ptr<std::vector<T>> BlobPtr<T>::check(size_type i, const std::string& msg) const { auto ret = wptr.lock(); if(!ret) throw std::runtime_error("unbound BlobPtr"); if(i >= ret->size()) throw std::out_of_range(msg); return ret; } // constructors template <typename T> BlobPtr<T>::BlobPtr(): curr(0) {} // deference template <typename T> T& BlobPtr<T>::operator*() const { auto p = check(curr, "deference past end"); return (*p)[curr]; } // subscript template <typename T> T& BlobPtr<T>::operator[](size_type n) { auto p = check(curr + n, "subscript past end"); return (*p)[curr + n]; } template <typename T> const T& BlobPtr<T>::operator[](size_type n) const { auto p = check(curr + n, "subscript past end"); return (*p)[curr + n]; } // relational operator template <typename T> bool operator==(const BlobPtr<T> &lhs, const BlobPtr<T> &rhs) { return lhs.curr == rhs.curr; } template <typename T> bool operator!=(const BlobPtr<T> &lhs, const BlobPtr<T> &rhs) { return !(lhs == rhs); } template <typename T> bool operator<(const BlobPtr<T> &lhs, const BlobPtr<T> &rhs) { return lhs.curr < rhs.curr; } template <typename T> bool operator<=(const BlobPtr<T> &lhs, const BlobPtr<T> &rhs) { return (lhs < rhs || lhs == rhs); } template <typename T> bool operator>(const BlobPtr<T> &lhs, const BlobPtr<T> &rhs) { return !(lhs < rhs || lhs == rhs); } template <typename T> bool operator>=(const BlobPtr<T> &lhs, const BlobPtr<T> &rhs) { return !(lhs < rhs); } // decrement and increment template <typename T> BlobPtr<T>& BlobPtr<T>::operator++() { auto p = check(curr, "increment past end of BlobPtr"); ++curr; return *this; } template <typename T> BlobPtr<T>& BlobPtr<T>::operator--() { --curr; auto p = check(curr, "decrement past begin of BlobPtr"); return *this; } template <typename T> BlobPtr<T>& BlobPtr<T>::operator++(int) { auto ret = *this; --*this; return ret; } template <typename T> BlobPtr<T>& BlobPtr<T>::operator--(int) { auto ret = *this; --*this; return ret; } template <typename T> BlobPtr<T>& BlobPtr<T>::operator+=(typename Blob<T>::difference_type n) { curr += n; check(curr, "pointer addition past end of BlobPtr"); return *this; } template <typename T> BlobPtr<T>& BlobPtr<T>::operator-=(typename Blob<T>::difference_type n) { curr -= n; check(curr, "pointer subtraction past begin of BlobPtr"); return *this; } // addition and subtraction template <typename T> BlobPtr<T> operator+(const BlobPtr<T> &sp, typename Blob<T>::difference_type n) { auto sum = sp; sum += n; return sum; } template <typename T> BlobPtr<T> operator-(const BlobPtr<T> &sp, typename Blob<T>::difference_type n) { auto sum = sp; sum -= n; return sum; } template <typename T> typename Blob<T>::difference_type operator-(const BlobPtr<T> &lhs, const BlobPtr<T> &rhs) { return lhs.curr - rhs.curr; } #endif
sjbarigye/CPP_Primer
chap07/Exer07_32_Screen.h
<reponame>sjbarigye/CPP_Primer #ifndef EXER07_32_H #define EXER07_32_H #include <iostream> #include <string> #include <vector> class Screen; // forward declaration here, or the program won't compile. class Window_mgr { public: using ScreenIndex = std::vector<Screen>::size_type; void clear(ScreenIndex); Window_mgr() = default; Window_mgr(const Screen& s); const Screen& get(ScreenIndex i) const { return screens[i]; } private: std::vector<Screen> screens;//{Screen(24, 80, ' ')}; }; class Screen { // friend function friend void Window_mgr::clear(ScreenIndex); // friend class Window_mgr; public: using pos = std::string::size_type; Screen() = default; Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) {} char get() const { return contents[cursor]; } inline char get(pos ht, pos wd) const; Screen& move(pos r, pos c); Screen& set(pos row, pos col, char c); Screen& set(char c); Screen& display(std::ostream& os); const Screen& display(std::ostream& os) const; private: void do_display(std::ostream& os) const; pos cursor = 0; pos height = 0, width = 0; std::string contents; }; char Screen::get(pos ht, pos wd) const { pos row = wd * width; return contents[row + ht]; } Screen& Screen::move(pos r, pos c) { cursor = r * width + c; return *this; } Screen& Screen::set(pos row, pos col, char c) { contents[row * width + col] = c; return *this; } Screen& Screen::set(char c) { contents[cursor] = c; return *this; } Screen& Screen::display(std::ostream& os) { do_display(os); return *this; } const Screen& Screen::display(std::ostream& os) const { do_display(os); return *this; } inline void Screen::do_display(std::ostream& os) const { os << contents; } Window_mgr::Window_mgr(const Screen& s) { screens = {s}; } // friend function clear() void Window_mgr::clear(ScreenIndex i) { if(i < screens.size()) { Screen &s = screens[i]; s.contents = std::string(s.height * s.width, ' '); } } #endif // Note: let's see line 15: // 15 std::vector<Screen> screens; //{Screen(24, 80, ' ')}; // "{Screen(24, 80, ' ')}" is commented, or else this header won't compile. Why? // Because if we initialize screens with constructor of class Screen, definition // of this constructor must appear before the point where we use it. Thus the // class Screen must be defined in front of class Window_mgr. But if we define // Screen before we define Window_mgr, friend member function clear is unseen at // the point where we declare it as a friend of class Screen. That is to say: // Screen(24, 80, ' ') must appear after the definition of class Screen, while // the declaration of member function clear must appear before the definition of // class Screen! They conflict with each other. As a result, we have to comment // this part to make the program compile. // If we want to initialize screens with one element, we can use a constructor // to resolve conflict. But in-class initializer is not viable here.
sjbarigye/CPP_Primer
chap15/Exer15_39/Exer15_39_Query_base.h
// abstract class acts as a base for concrete query types; all members are private #ifndef QUERY_BASE_H #define QUERY_BASE_H #include <string> #include "Exer15_39_TextQuery.h" class Query_base { friend class Query; protected: using line_no = TextQuery::line_no; // used in eval functions virtual ~Query_base() = default; private: // eval returns the QueryResult that matches this Query virtual QueryResult eval(const TextQuery&) const = 0; // rep is a string representing of the query virtual std::string rep() const = 0; }; #endif
sjbarigye/CPP_Primer
chap19/Exer19_20_TextQuery.h
// TextQuery class from exercise 12.30. #ifndef EXER19_20_TEXT_QUERY_H #define EXER19_20_TEXT_QUERY_H #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <map> #include <set> #include <memory> std::string make_plural(size_t, const std::string&, const std::string&); class TextQuery{ public: class QueryResult; // nested class to be defined later using line_no = std::vector<std::string>::size_type; TextQuery(std::ifstream&); QueryResult query(const std::string&) const; private: std::shared_ptr<std::vector<std::string>> file; std::map<std::string, std::shared_ptr<std::set<line_no>>> wm; }; // we're defining the QueryResult class that is a member of class TextQuery class TextQuery::QueryResult{ // in class scope, we don't have to qualify the name of the QueryResult parameters friend std::ostream& print(std::ostream&, const QueryResult&); public: // no need to define QueryResult::line_no; a nested class can use a member // of its enclosing class without needing to qualify the member's name QueryResult(std::string s, std::shared_ptr<std::set<line_no>> p, std::shared_ptr<std::vector<std::string>> f) : sought(s), lines(p), file(f) { } // members required by exercise 12.33 std::set<line_no>::iterator begin() const { return lines->begin();} std::set<line_no>::iterator end() const { return lines->end();} std::shared_ptr<std::vector<std::string>> get_file() const { return file; } private: std::string sought; std::shared_ptr<std::set<TextQuery::line_no>> lines; std::shared_ptr<std::vector<std::string>> file; }; inline std::string make_plural(size_t ctr, const std::string &word, const std::string &ending) { return (ctr > 1) ? word + ending : word; } #endif
sjbarigye/CPP_Primer
chap15/Exer15_15_Disc_quote.h
<reponame>sjbarigye/CPP_Primer<filename>chap15/Exer15_15_Disc_quote.h #ifndef DISC_QUOTE_H #define DISC_QUOTE_H #include <cstddef> #include <string> #include "Exer15_15_Quote.h" class Disc_quote : public Quote { public: Disc_quote() = default; Disc_quote(const std::string &book, double price, std::size_t qty, double disc): Quote(book, price), quantity(qty), discount(disc) {} double net_price(std::size_t) const = 0; protected: std::size_t quantity = 0; // purchase size for the discount to apply double discount = 0.0; // fractional discount to apply }; #endif
sjbarigye/CPP_Primer
chap14/Exer14_35_ReadString.h
<reponame>sjbarigye/CPP_Primer #ifndef READ_STRING_H #define READ_STRING_H #include <iostream> #include <string> using std::cin; using std::istream; using std::string; class ReadString { public: ReadString(istream &i = cin) : is(i) {} string operator()() const; private: istream &is; }; string ReadString::operator()() const { string s; if(getline(is, s)) return s; else { s = ""; } } #endif
sjbarigye/CPP_Primer
chap12/Exer12_32_TextQuery_StrBlob.h
#ifndef TEXT_QUERY_H #define TEXT_QUERY_H #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <map> #include <set> #include <memory> #include "StrBlob.h" std::string make_plural(size_t, const std::string&, const std::string&); class QueryResult; class TextQuery{ public: using line_no = std::vector<std::string>::size_type; TextQuery(std::ifstream&); QueryResult query(const std::string&) const; private: StrBlob file; std::map<std::string, std::shared_ptr<std::set<line_no>>> wm; }; class QueryResult{ friend std::ostream& print(std::ostream&, const QueryResult&); public: QueryResult(std::string s, std::shared_ptr<std::set<TextQuery::line_no>> p, StrBlob f) : sought(s), lines(p), file(f) { } private: std::string sought; std::shared_ptr<std::set<TextQuery::line_no>> lines; StrBlob file; }; // read the input file and build the std::map of lines to line numbers TextQuery::TextQuery(std::ifstream& is) { std::string text; while(getline(is, text)) //for each line in the file { file.push_back(text); // remember this line of text int n = file.size() - 1; // the current line number std::istringstream line(text); // separate the line into words std::string word; while(line >> word) // for each word in that line { // if word isn't already in wm, subscripting adds a new entry auto &lines = wm[word]; // lines is a std::shared_ptr if(!lines) // that pointer is null the first time we see word lines.reset(new std::set<line_no>); // allocate a new std::set lines->insert(n); // insert this line number } } } QueryResult TextQuery::query(const std::string& sought) const { // we'll return a pointer to this std::set if we don't find sought static std::shared_ptr<std::set<line_no>> nodata(new std::set<line_no>); //use find and not a subscript to avoid adding words to wm! auto loc = wm.find(sought); if(loc == wm.end()) return QueryResult(sought, nodata, file); // not found else return QueryResult(sought, loc->second, file); } std::ostream& print(std::ostream& os, const QueryResult& qr) { // if the word was found, print the count and all occurrences os << qr.sought << " occurs " << qr.lines->size() << " " << make_plural(qr.lines->size(), "time", "s") << std::endl; // print each line in which the word appeared // for now we cannot use overload operator, but a overload function for(auto num : *qr.lines) os << "\t(line " << num + 1 << ") " << qr.file.at(num) << std::endl; return os; } std::string make_plural(size_t ctr, const std::string &word, const std::string &ending) { return (ctr > 1) ? word + ending : word; } #endif
sjbarigye/CPP_Primer
chap15/Exer15_39/Exer15_39_BinaryQuery.h
<filename>chap15/Exer15_39/Exer15_39_BinaryQuery.h #ifndef BINARY_QUERY_H #define BINARY_QUERY_H #include <string> #include "Exer15_39_Query_base.h" #include "Exer15_39_Query.h" class BinaryQuery : public Query_base { protected: BinaryQuery(const Query &l, const Query &r, std::string s) : lhs(l), rhs(r), opSym(s) {} // abstract class: BinaryQuery doesn't define eval std::string rep() const { return "(" + lhs.rep() + " " + opSym + " " + rhs.rep() + ")"; } Query lhs, rhs; // right and left-hand operand std::string opSym; // name of the operator }; #endif
sjbarigye/CPP_Primer
chap07/Exer07_58_example.h
// Exercise 7.58 #include <vector> using std::vector; class Example { public: static double rate; static const int vecSize = 20; static vector<double> vec; };
sjbarigye/CPP_Primer
chap16/Exer16_58_StrVec.h
<reponame>sjbarigye/CPP_Primer #ifndef EXER16_58_STRVEC_H #define EXER16_58_STRVEC_H #include <cstddef> #include <iostream> #include <string> #include <utility> #include <memory> #include <initializer_list> class StrVec { // equality operator required by exercise 14.16 friend bool operator==(const StrVec&, const StrVec&); friend bool operator!=(const StrVec&, const StrVec&); // relation operator required by exercise 14.18 friend bool operator<(const StrVec&, const StrVec&); friend bool operator<=(const StrVec&, const StrVec&); friend bool operator>(const StrVec&, const StrVec&); friend bool operator>=(const StrVec&, const StrVec&); public: using size_type = std::size_t; StrVec(): elements(nullptr), first_free(nullptr), cap(nullptr) {} StrVec(const StrVec&); // move constructor from page 536 StrVec(StrVec&&) noexcept; StrVec& operator=(const StrVec&); // move assignment from page 537 StrVec& operator=(StrVec&&) noexcept; // assignment with an std::initializer_list parameter from page 563 StrVec& operator=(std::initializer_list<std::string>); // constructor that takes a std::initializer_list as parameter, required by exercise 13.40 StrVec(const std::initializer_list<std::string>&); // subscript operator from page 565 // class is not responsible for checking if the subscript is out of range std::string& operator[](size_type n) // nonconst version of subscript operator { return elements[n]; } std::string& operator[](size_type n) const // const version of subscript operator { return elements[n]; } ~StrVec(); void push_back(const std::string&); void push_back(std::string&&); size_type size() const { return first_free - elements; } size_type capacity() const { return cap - elements; } std::string *begin() const { return elements; } std::string *end() const { return first_free; } // both begin() and end() are const // reserve and resize required by exercise 13.39 void reserve(size_type); void resize(size_type); void resize(size_type, const std::string&); // emplace_back required by exercise 16.58 template <typename... Args> void emplace_back(Args&& ...); private: static std::allocator<std::string> alloc; void chk_n_alloc() { if(size() == capacity()) reallocate(); } std::pair<std::string*, std::string*> alloc_n_copy(const std::string*, const std::string*); void free(); void reallocate(); void add_rem(size_type n, const std::string &s = ""); std::string *elements; std::string *first_free; std::string *cap; }; // Warning: define static member outside the class. Without this the program // using the class wouldn't compile std::allocator<std::string> StrVec::alloc; // friend definition bool operator==(const StrVec &lhs, const StrVec &rhs) { if(lhs.size() != rhs.size()) return false; else { for(auto p = lhs.elements, q = rhs.elements; p != lhs.first_free; ++p, ++q) { if(*p != *q) return false; } return true; } } bool operator!=(const StrVec &lhs, const StrVec &rhs) { return !(lhs == rhs); } bool operator<(const StrVec &lhs, const StrVec &rhs) { auto shorter = lhs.size() < rhs.size() ? lhs.size() : rhs.size(); auto p = lhs.begin(), q = rhs.begin(); for(StrVec::size_type i = 0; p + i != lhs.end(); ++i) { if(*(p + i) == *(q + i)) continue; else if(*(p + i) < *(q + i)) return true; else return false; } return lhs.size() < rhs.size(); } bool operator<=(const StrVec &lhs, const StrVec &rhs) { return lhs < rhs || lhs == rhs; } bool operator>(const StrVec &lhs, const StrVec &rhs) { return !(lhs < rhs || lhs == rhs); } bool operator>=(const StrVec &lhs, const StrVec &rhs) { return !(lhs < rhs); } void StrVec::push_back(const std::string &s) { chk_n_alloc(); alloc.construct(first_free++, s); } void StrVec::push_back(std::string &&s) { chk_n_alloc(); alloc.construct(first_free++, std::move(s)); } std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string *b, const std::string *e) { auto data = alloc.allocate(e - b); return {data, uninitialized_copy(b, e, data)}; } void StrVec::free() { if (elements) { for(auto p = first_free; p != elements; /*empty*/ ) alloc.destroy(--p); alloc.deallocate(elements, cap - elements); } } StrVec::StrVec(const StrVec &s) { auto newdata = alloc_n_copy(s.begin(), s.end()); elements = newdata.first; first_free = cap = newdata.second; } StrVec::StrVec(StrVec &&s) noexcept : elements(s.elements), first_free(s.first_free), cap(s.cap) { s.elements = s.first_free = s.cap = nullptr; } StrVec::StrVec(const std::initializer_list<std::string> &il) { auto newdata = alloc_n_copy(il.begin(), il.end()); elements = newdata.first; first_free = cap = newdata.second; } StrVec::~StrVec() { free(); } StrVec& StrVec::operator=(const StrVec &rhs) { auto data = alloc_n_copy(rhs.begin(), rhs.end()); free(); elements = data.first; first_free = cap = data.second; return *this; } StrVec& StrVec::operator=(StrVec &&rhs) noexcept { if(this != &rhs) { free(); elements = rhs.elements; first_free = rhs.first_free; cap = rhs.cap; rhs.elements = rhs.first_free = rhs.cap = nullptr; } return *this; } StrVec& StrVec::operator=(std::initializer_list<std::string> il) { auto data = alloc_n_copy(il.begin(), il.end()); free(); elements = data.first; first_free = cap = data.second; return *this; } void StrVec::reallocate() { // we'll allocate space for twice as many as the current size auto newcapacity = size() ? 2 * size() : 1; // if empty, allocate 1 space, otherwise double // allocate new memory auto newdata = alloc.allocate(newcapacity); // move the data from the old memory to the new auto dest = newdata; // points to the next free position in the new memory auto elem = elements; // points to the next element in the old memory for(size_type i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); // free the old space once we've moved the elements // update our data structure to point to the new elements elements = newdata; first_free = dest; cap = elements + newcapacity; } void StrVec::reserve(size_type n) { if(n > capacity()) { auto newdata = alloc.allocate(n); auto dest = newdata; auto elem = elements; for(size_type i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); elements = newdata; first_free = newdata; cap = elements + n; } } void StrVec::resize(size_type n) { add_rem(n); } void StrVec::resize(size_type n, const std::string &s) { add_rem(n, s); } void StrVec::add_rem(size_type n, const std::string &s) { if(n <= size()) { auto p = first_free; while(p != elements + n) alloc.destroy(--p); first_free = p; } else{ auto new_elem_count = n - size(); for(size_type i = 0; i != new_elem_count; ++i) push_back(s); } } template <typename... Args> void StrVec::emplace_back(Args&&... args) { chk_n_alloc(); alloc.construct(first_free++, std::forward<Args>(args)...); } #endif // Note: in this program we use a static member, never forget to define this // member outside the class(Page 302). We do not need to repeat the static // keyword. We can use default initialization of allocator, so we do not need to // provide an initializer.
sjbarigye/CPP_Primer
chap13/Exer13_55_String.h
// Inheritance: exercise 13.49. // Note: see Exer19_18.cpp for the explanation of the problem issued in note. #ifndef STRING_SIMPLE_H #define STRING_SIMPLE_H #include <iostream> #include <cstddef> #include <cstring> #include <utility> #include <memory> #include <algorithm> class String { public: String(); String(const char*); String(const String&); String(String&&) noexcept; // move constructor String& operator=(const String&); String& operator=(String&&) noexcept; // move assignment ~String(); void push_back(const char&); void push_back(char&&); std::size_t size() const { return first_free - elements;} std::size_t capacity() const { return cap - elements; } char* begin() const { return elements; } char* end() const { return first_free; } bool empty() const { return elements == first_free; } void clear(); private: void chk_n_alloc() { if(size() == capacity()) reallocate(); } std::pair<char*, char*> alloc_n_copy(const char*, const char*); void free(); void reallocate(); private: static std::allocator<char> alloc; static std::size_t ini_size; char *elements; char *first_free; char *cap; }; std::allocator<char> String::alloc; // It seems both gcc and visual studio library allocates 15 space for a default // initialized string. std::size_t String::ini_size = 15; String::String(): elements(nullptr), first_free(nullptr), cap(nullptr) { elements = alloc.allocate(ini_size); first_free = elements; cap = elements + ini_size; } String::String(const char *s) { auto newdata = alloc_n_copy(s, s + strlen(s)); elements = newdata.first; first_free = newdata.second; cap = (strlen(s) > ini_size) ? first_free : (elements + ini_size); } String::String(const String &s) { auto newdata = alloc_n_copy(s.begin(), s.end()); elements = newdata.first; first_free = newdata.second; cap = (s.size() > ini_size) ? first_free : (elements + ini_size); // call identity required by exercise 13.47 std::cout << "String(const String&) is called" << std::endl; } // copy constructor required by exercise 13.49 String::String(String &&s) noexcept : elements(s.elements), first_free(s.first_free), cap(s.cap) { s.elements = s.first_free = s.cap = nullptr; std::cout << "String(String&&) is called" << std::endl; } String& String::operator=(const String& rhs) { auto newdata = alloc_n_copy(rhs.begin(), rhs.end()); free(); elements = newdata.first; first_free = newdata.second; cap = (rhs.size() > ini_size) ? first_free : (elements + ini_size); // call identity required by exercise 13.47 std::cout << "String& operator=(const String&) is called" << std::endl; return *this; } // move assigment required by exercise 13.49 String& String::operator=(String &&rhs) noexcept { if(this != &rhs) { free(); elements = rhs.elements; first_free = rhs.first_free; cap = rhs.cap; rhs.elements = rhs.first_free = rhs.cap = nullptr; } std::cout << "String& operator=(String&&) is called" << std::endl; return *this; } String::~String() { free(); } void String::push_back(const char &c) { chk_n_alloc(); alloc.construct(first_free++, c); } void String::push_back(char &&c) { chk_n_alloc(); alloc.construct(first_free++, std::move(c)); } void String::clear() { for(auto p = first_free; p != elements; /* empty */) alloc.destroy(--p); first_free = elements; } std::pair<char*, char*> String::alloc_n_copy(const char *b, const char *e) { auto newcapacity = (e - b > ini_size) ? (e - b) : ini_size; auto newdata = alloc.allocate(newcapacity); return {newdata, std::uninitialized_copy(b, e, newdata)}; } void String::reallocate() { auto newcapacity = (size() * 2 > ini_size) ? size() * 2 : ini_size; auto newdata = alloc.allocate(newcapacity); auto dest = newdata; auto elem = elements; for(std::size_t i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); elements = newdata; first_free = dest; cap = elements + newcapacity; } void String::free() { // std::for_each(elements, first_free, [](const char &c) {alloc.destroy(&c);}); for(auto p = first_free; p != elements; /* empty */) alloc.destroy(--p); alloc.deallocate(elements, cap - elements); } #endif // Note #1: don't know why, but uninitialized_copy and for_each don't work if std:: // isn't added as prefix. This remains to be solved. // ADDITION: see Exer19_18.cpp for explanation, or see section 18.2.3, page 798 // for the reason. // Note #2: here we can see the advantage of std::allocator compared to new/delete. If // we use new/delete, we might have to use char array instead of raw and uninitialized // memory.
sjbarigye/CPP_Primer
chap15/Exer15_39/Exer15_39_TextQuery.h
<reponame>sjbarigye/CPP_Primer #ifndef TEXT_QUERY_H #define TEXT_QUERY_H #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <map> #include <set> #include <memory> std::string make_plural(size_t, const std::string&, const std::string&); class QueryResult; class TextQuery{ public: using line_no = std::vector<std::string>::size_type; TextQuery(std::ifstream&); QueryResult query(const std::string&) const; private: std::shared_ptr<std::vector<std::string>> file; std::map<std::string, std::shared_ptr<std::set<line_no>>> wm; }; class QueryResult{ friend std::ostream& print(std::ostream&, const QueryResult&); public: QueryResult(std::string s, std::shared_ptr<std::set<TextQuery::line_no>> p, std::shared_ptr<std::vector<std::string>> f) : sought(s), lines(p), file(f) { } // members required by exercise 12.33 std::set<TextQuery::line_no>::iterator begin() const { return lines->begin();} std::set<TextQuery::line_no>::iterator end() const { return lines->end();} std::shared_ptr<std::vector<std::string>> get_file() const { return file; } private: std::string sought; std::shared_ptr<std::set<TextQuery::line_no>> lines; std::shared_ptr<std::vector<std::string>> file; }; #endif
sjbarigye/CPP_Primer
chap18/Exer18_07_Blob.h
<reponame>sjbarigye/CPP_Primer // Blob class template from exercise 16.29 #ifndef EXER18_07_BLOB_H #define EXER18_07_BLOB_H #include <iostream> #include <string> #include <vector> #include <initializer_list> #include <memory> #include <utility> #include <stdexcept> template <typename T> class BlobPtr; template <typename T> class ConstBlobPtr; template <typename T> class Blob; template <typename T> bool operator==(const Blob<T>&, const Blob<T>&); template <typename T> bool operator!=(const Blob<T>&, const Blob<T>&); template <typename T> bool operator<(const Blob<T>&, const Blob<T>&); template <typename T> bool operator<=(const Blob<T>&, const Blob<T>&); template <typename T> bool operator>(const Blob<T>&, const Blob<T>&); template <typename T> bool operator>=(const Blob<T>&, const Blob<T>&); template <typename T> class Blob { friend class BlobPtr<T>; friend bool operator==<T>(const Blob<T>&, const Blob<T>&); friend bool operator!=<T>(const Blob<T>&, const Blob<T>&); friend bool operator< <T>(const Blob<T>&, const Blob<T>&); friend bool operator<=<T>(const Blob<T>&, const Blob<T>&); friend bool operator><T>(const Blob<T>&, const Blob<T>&); friend bool operator>=<T>(const Blob<T>&, const Blob<T>&); public: typedef T value_type; typedef typename std::vector<T>::size_type size_type; typedef typename std::vector<T>::difference_type difference_type; // constructors Blob(); Blob(std::initializer_list<T> il); // template member function required by exercise 16.24 template <typename It> Blob(It b, It e); // size size_type size() const { return data->size(); } bool empty() const { return data->empty(); } // elements void push_back(const T &t) { data->push_back(t); } void push_back(T &&t) { data->push_back(std::move(t)); } void pop_back(); T& front(); T& back(); // const version from exercise 12.2 const T& front() const; const T& back() const; T& operator[] (size_type); const T& operator[] (size_type) const; T& at(size_type); const T& at(size_type) const; // use count size_type use_count() const { return data->use_count(); } private: std::shared_ptr<std::vector<T>> data; void check(size_type, const std::string&) const; }; // constructors template <typename T> Blob<T>::Blob() try : data(std::make_shared<std::vector<T>>()) { } catch(const std::bad_alloc &err) { std::cerr << err.what() << std::endl; } template <typename T> Blob<T>::Blob(std::initializer_list<T> il) try : data(std::make_shared<std::vector<T>>(il)) { } catch(const std::bad_alloc &err) { std::cerr << err.what() << std::endl; } template <typename T> template <typename It> Blob<T>::Blob(It b, It e) try : data(std::make_shared<std::vector<T>>(b, e)) { } catch(const std::bad_alloc &err) { std::cerr << err.what() << std::endl; } // check index template <typename T> void Blob<T>::check(size_type i, const std::string &msg) const { if(i >= data->size()) throw std::out_of_range(msg); } // add and remove elements template <typename T> void Blob<T>::pop_back() { check(0, "pop_back on empty Blob"); data->pop_back(); } // element access template <typename T> T& Blob<T>::front() { check(0, "front on empty Blob"); data->front(); } template <typename T> T& Blob<T>::back() { check(0, "back on empty Blob"); data->back(); } template <typename T> const T& Blob<T>::front() const { check(0, "front on empty Blob"); data->front(); } template <typename T> const T& Blob<T>::back() const { check(0, "back on empty Blob"); data->back(); } template <typename T> T& Blob<T>::operator[](size_type i) { check(i, "index out of range"); return (*data)[i]; } template <typename T> const T& Blob<T>::operator[](size_type i) const { check(i, "index out of range"); return (*data)[i]; } template <typename T> T& Blob<T>::at(size_type i) { check(i, "index out of range"); return data->at(i); } template <typename T> const T& Blob<T>::at(size_type i) const { check(i, "index out of range"); return data->at(i); } // relational operators template <typename T> inline bool operator==(const Blob<T> &lhs, const Blob<T> &rhs) { return *lhs.data == *rhs.data; } template <typename T> inline bool operator!=(const Blob<T> &lhs, const Blob<T> &rhs) { return !(lhs == rhs); } template <typename T> inline bool operator<(const Blob<T> &lhs, const Blob<T> &rhs) { return *lhs.data < *rhs.data; } template <typename T> inline bool operator<=(const Blob<T> &lhs, const Blob<T> &rhs) { return (lhs < rhs || lhs == rhs); } template <typename T> inline bool operator>(const Blob<T> &lhs, const Blob<T> &rhs) { return !(lhs < rhs || lhs == rhs); } template <typename T> inline bool operator>=(const Blob<T> &lhs, const Blob<T> &rhs) { return !(lhs < rhs); } #endif
sjbarigye/CPP_Primer
chap14/Exer14_34.h
<reponame>sjbarigye/CPP_Primer #ifndef FINAL_GRADE_H #define FINAL_GRADE_H #include <string> using std::string; class FinalGrade { public: const string& operator()(bool grade, const string &s1, const string &s2) const { return grade ? s1 : s2; } }; #endif
sjbarigye/CPP_Primer
chap14/Exer14_21_Sales_data.h
<gh_stars>10-100 #ifndef SALES_DATA_H #define SALES_DATA_H #include <iostream> #include <string> class Sales_data { // friend // overloaded output operator required by exercise 14.6 friend std::ostream &operator<<(std::ostream&, const Sales_data&); // overloaded input operator required by exercise 14.9 friend std::istream &operator>>(std::istream&, Sales_data&); // overloaded addition operator required by exercise 14.13 friend Sales_data operator+(const Sales_data&, const Sales_data&); // overloaded equality on page 561 friend bool operator==(const Sales_data&, const Sales_data&); friend bool operator!=(const Sales_data&, const Sales_data&); // overloaded addition operator required by exercise 14.20 friend Sales_data operator+(const Sales_data&, const Sales_data&); public: // constructor Sales_data() = default; Sales_data(const std::string &s) : bookNo(s) {} Sales_data(const std::string &s, unsigned n, double p) : bookNo(s), units_sold(n), revenue(p*n) {} explicit Sales_data(std::istream &is) { is >> *this; } // member std::string isbn() const { return bookNo; } // overloaded compound-assignment operator required by exercise 14.20 Sales_data& operator+=(const Sales_data&); private: std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; double avg_price() const; }; // member functions definition // assumes both objects refer to the same book Sales_data& Sales_data::operator+=(const Sales_data& rhs) { // create temporary object, calls copy constructor, then calls copy-assignment operator. *this = *this + rhs; return *this; } // define avg_price as inline, required by exercise 7.26 inline double Sales_data::avg_price() const { if(units_sold != 0) return revenue / units_sold; else return revenue; } // overloaded output operator std::ostream& operator<<(std::ostream& os, const Sales_data& item) { os << item.bookNo << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); return os; } // overloaded input operator std::istream& operator>>(std::istream &is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; if(is) // check if input invalid item.revenue = item.units_sold * price; else item = Sales_data(); // input failed:given the object default state return is; } bool operator==(const Sales_data &lhs, const Sales_data &rhs) { return lhs.bookNo == rhs.bookNo && lhs.units_sold == rhs.units_sold && lhs.revenue == rhs.revenue; } bool operator!=(const Sales_data &lhs, const Sales_data &rhs) { return !(lhs == rhs); } // assumes both objects refer to the same book Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) { Sales_data sum = lhs; sum.units_sold = sum.units_sold + rhs.units_sold; sum.revenue = sum.revenue + rhs.revenue; return sum; } #endif // Note: compared this with Sales_data.h, we can find that we have to create // temporary objects when adding. For built-in type, this might not be a problem. // But for members of class type, this might cause performance problem.
sjbarigye/CPP_Primer
chap16/Exer16_21_DebugDelete.h
#ifndef EXER16_21_DEBUG_DELETE_H #define EXER16_21_DEBUG_DELETE_H #include <iostream> // function-object class that calls delete on a given pointer class DebugDelete { public: DebugDelete(std::ostream &s = std::cerr) : os(s) {} // as with any function template, the type of T is deduced by the compiler template <typename T> void operator()(T *p) const { os << "deleting shared_ptr" << std::endl; delete p; } private: std::ostream &os; }; #endif
sjbarigye/CPP_Primer
chap07/Exer07_40_Book.h
<reponame>sjbarigye/CPP_Primer // Note: this is a redefinition from chapter 14. It covers contents beyond chapter 7. #ifndef EXER07_40_BOOK_H #define EXER07_40_BOOK_H #include <string> #include <utility> using std::string; class Book { public: Book() = default; Book(string na, string au = "", string no = "") : book_name(na), book_author(au), book_no(no) {} // copy control constructor Book(const Book&) = default; // copy constructor Book(Book &&b) noexcept :// move constructor book_name(std::move(b.book_name)), book_author(std::move(b.book_author)), book_no(std::move(book_no)) {} Book& operator=(const Book&) = default; // copy-assignment operator Book& operator=(Book&&) noexcept; // move assignment operator ~Book() = default; private: string book_name; string book_author; string book_no; }; Book& Book::operator=(Book &&rhs) noexcept { if(this != &rhs) { book_name = std::move(rhs.book_name); book_author = std::move(rhs.book_author); book_no = std::move(rhs.book_no); } return *this; } #endif
sjbarigye/CPP_Primer
chap13/Exer13_27_HasPtr.h
#ifndef EXER13_27_H #define EXER13_27_H #include <cstddef> #include <string> class HasPtr { public: // constructor allocates a new std::string and a new counter, which it sets to 1 HasPtr(const std::string&s = std::string()) : ps(new std::string(s)), i(0), use(new std::size_t(1)) {} // copy constructor copies all three data members and increments the counter HasPtr(const HasPtr &p) : ps(p.ps), i(p.i), use(p.use) { ++*use; } HasPtr& operator=(const HasPtr& p); ~HasPtr(); private: std::string *ps; int i; std::size_t *use; // member to keep track of how many objects share *ps }; HasPtr& HasPtr::operator=(const HasPtr& rhs) { ++*rhs.use; // increments the use count of the right-hand operand if(--*use == 0) // then decrement this object's counter { delete ps; // if no other users delete use; // free this object's allocated members } ps = rhs.ps; i = rhs.i; use = rhs.use; return *this; // return this object } HasPtr::~HasPtr() { if(--*use == 0) // if the reference count goes to 0 { delete ps; // delete the std::string delete use; // and the counter } } #endif
sjbarigye/CPP_Primer
chap15/Exer15_01_Quote.h
<reponame>sjbarigye/CPP_Primer #ifndef QUOTE_H #define QUOTE_H #include <cstddef> #include <iostream> #include <string> class Quote { public: Quote() = default; Quote(const std::string &book, double sales_price) : bookNo(book), price(sales_price) {} std::string isbn() const { return bookNo; } // return the total sales price for the specified number of items // derived class will override and apply different discount algorithms virtual double net_price(std::size_t n) const { return n * price; } virtual ~Quote() = default; // dynamic binding for the destructor private: std::string bookNo; // ISBN number of this item protected: double price = 0.0; // normal, undiscounted price }; // calculate and print the price for the given number of copies, applying any discount double print_total(std::ostream &os, const Quote &item, std::size_t n) { // depending on the type of the object bound to the item parameter // calls either Quote::net_price or Bulk_quote::net_price double ret = item.net_price(n); os << "ISBN: " << item.isbn() // calls Quote::isbn << " # sold: " << n << " total due: " << ret << std::endl; return ret; } #endif
sjbarigye/CPP_Primer
chap19/Sales_data.h
// Warning: this header is used by multiple source files and has special friends for them. Take care if // you want to change the name of this file. #ifndef SALES_DATA_H #define SALES_DATA_H #include <iostream> #include <string> #include <cstddef> // required by exercise 19.19 #include <vector> // required by exercise 19.19 class Sales_data { // friend // overloaded output operator required by exercise 14.6 friend std::ostream &operator<<(std::ostream&, const Sales_data&); // overloaded input operator required by exercise 14.9 friend std::istream &operator>>(std::istream&, Sales_data&); // overloaded addition operator required by exercise 14.13 friend Sales_data operator+(const Sales_data&, const Sales_data&); // overloaded equality on page 561 friend bool operator==(const Sales_data&, const Sales_data&); friend bool operator!=(const Sales_data&, const Sales_data&); // overloaded addition operator required by exercise 14.20 friend Sales_data operator+(const Sales_data&, const Sales_data&); // friend for test, required by exercise 19.16 friend void debug_test(const Sales_data&); // friend for count, required by exercise 19.19 friend auto count_price(const std::vector<Sales_data> &vec, double) -> decltype(vec.begin()); public: // type alias for avg_price, required by exercise 19.16 using Avg = double (Sales_data::*)() const; // constructor Sales_data() = default; Sales_data(const std::string &s) : bookNo(s) {} Sales_data(const std::string &s, unsigned n, double p) : bookNo(s), units_sold(n), revenue(p*n) {} explicit Sales_data(std::istream &is) { is >> *this; } // member std::string isbn() const { return bookNo; } // overloaded compound-assignment operator required by exercise 14.20 Sales_data& operator+=(const Sales_data&); // takes an ISBN as parameter, required by exercise 14.22 Sales_data& operator=(const std::string&); // return a pointer to member, required by exercise 19.13 static const std::string Sales_data::* data() { return &Sales_data::bookNo; } private: std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; double avg_price() const; }; // member functions definition inline Sales_data& Sales_data::operator+=(const Sales_data& rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } inline Sales_data& Sales_data::operator=(const std::string &isbn) { bookNo = isbn; return *this; } // define avg_price as inline, required by exercise 7.26 inline double Sales_data::avg_price() const { if(units_sold != 0) return revenue / units_sold; else return revenue; } // overloaded output operator inline std::ostream& operator<<(std::ostream& os, const Sales_data& item) { os << item.bookNo << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); return os; } // overloaded input operator inline std::istream& operator>>(std::istream &is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; if(is) // check if input invalid item.revenue = item.units_sold * price; else item = Sales_data(); // input failed:given the object default state return is; } inline bool operator==(const Sales_data &lhs, const Sales_data &rhs) { return lhs.bookNo == rhs.bookNo && lhs.units_sold == rhs.units_sold && lhs.revenue == rhs.revenue; } inline bool operator!=(const Sales_data &lhs, const Sales_data &rhs) { return !(lhs == rhs); } inline Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) { Sales_data sum = lhs; sum += rhs; return sum; } #endif
sjbarigye/CPP_Primer
chap15/Exer15_15_Bulk_quote.h
#ifndef BULK_QUOTE_H #define BULK_QUOTE_H #include <cstddef> #include <string> #include "Exer15_15_Disc_quote.h" class Bulk_quote : public Disc_quote { // Bulk_quote inherits from Quote public: Bulk_quote() = default; Bulk_quote(const std::string &book, double price, std::size_t qty, double disc) : Disc_quote(book, price, qty, disc) {} // overrides the base version in order to implement the bulk purchase discount policy double net_price(std::size_t) const override; void debug() const override; }; // if the specified number of items are purchased, use the discounted price double Bulk_quote::net_price(std::size_t cnt) const { if (cnt >= quantity) return cnt * (1 - discount) * price; else return cnt * price; } inline void Bulk_quote::debug() const { std::cout << "std::string bookNo\n" << "double price\n" << "std::size_t min_qty\n" << "double discount\n" << std::endl; } #endif
sjbarigye/CPP_Primer
chap15/Exer15_30_Basket.h
#ifndef BASKET_H #define BASKET_H #include <iostream> #include <set> #include <memory> #include <utility> #include "Exer15_30_Quote.h" #include "Exer15_30_Bulk_quote.h" class Basket { public: // basket uses synthesized default constructor and copy-control members void add_item(const Quote &sale) { items.insert(std::shared_ptr<Quote>(sale.clone()));} void add_item(Quote &&sale) { items.insert(std::shared_ptr<Quote>(std::move(sale).clone())); } // prints the total price for each book and the overall total for items in the basket double total_receipt(std::ostream&) const; private: // function to compare shared_ptrs needed by the multiset member static bool compare(const std::shared_ptr<Quote> &lhs, const std::shared_ptr<Quote> &rhs) { return lhs->isbn() < rhs->isbn(); } // multiset to bold multiple quotes, ordered by the compare member std::multiset<std::shared_ptr<Quote>, decltype(compare)*> items{compare}; }; double Basket::total_receipt(std::ostream &os) const { double sum = 0; // holds the running total // iter refers to the first element in a batch of element with the same ISBN // upper_bound returns an iterator to the element just past the end of that batch for (auto iter = items.cbegin(); iter != items.cend(); iter = items.upper_bound(*iter)) { // we know there's at least one element with this key in the Basket // prints the line item for this book sum += print_total(os, **iter, items.count(*iter)); // **iter is the first object shared_ptr points to with a given ISBN } // print the final overall total os << "Total Sale: " << sum << std::endl; return sum; } #endif
sjbarigye/CPP_Primer
chap16/Exer16_58_Vec.h
#ifndef EXER16_58_VEC_H #define EXER16_58_VEC_H #include <cstddef> #include <utility> #include <memory> #include <initializer_list> template <typename T> class Vec; // equality operator required by exercise 14.16 template <typename T> bool operator==(const Vec<T>&, const Vec<T>&); template <typename T> bool operator!=(const Vec<T>&, const Vec<T>&); // relation operator required by exercise 14.18 template <typename T> bool operator<(const Vec<T>&, const Vec<T>&); template <typename T> bool operator<=(const Vec<T>&, const Vec<T>&); template <typename T> bool operator>(const Vec<T>&, const Vec<T>&); template <typename T> bool operator>=(const Vec<T>&, const Vec<T>&); template <typename T> class Vec { // equality operator required by exercise 14.16 friend bool operator==<T>(const Vec<T>&, const Vec<T>&); friend bool operator!=<T>(const Vec<T>&, const Vec<T>&); // relation operator required by exercise 14.18 friend bool operator< <T>(const Vec<T>&, const Vec<T>&); friend bool operator<=<T>(const Vec<T>&, const Vec<T>&); friend bool operator><T>(const Vec<T>&, const Vec<T>&); friend bool operator>=<T>(const Vec<T>&, const Vec<T>&); public: Vec(): elements(nullptr), first_free(nullptr), cap(nullptr) {} Vec(const Vec&); // move constructor from page 536 Vec(Vec&&) noexcept; Vec& operator=(const Vec&); // move assignment from page 537 Vec& operator=(Vec&&) noexcept; // assignment with an std::initializer_list parameter from page 563 Vec& operator=(std::initializer_list<T>); // constructor that takes a std::initializer_list as parameter, required by exercise 13.40 Vec(const std::initializer_list<T>&); // subscript operator from page 565 // class is not responsible for checking if the subscript is out of range T& operator[](std::size_t n) // nonconst version of subscript operator { return elements[n]; } T& operator[](std::size_t n) const // const version of subscript operator { return elements[n]; } ~Vec(); void push_back(const T&); void push_back(T&&); std::size_t size() const { return first_free - elements; } std::size_t capacity() const { return cap - elements; } T *begin() const { return elements; } T *end() const { return first_free; } // both begin() and end() are const // reserve and resize required by exercise 13.39 void reserve(std::size_t); void resize(std::size_t); void resize(std::size_t, const T&); // emplace_back required by exercise 16.58 template <typename... Args> void emplace_back(Args&&...); private: static std::allocator<T> alloc; void chk_n_alloc() { if(size() == capacity()) reallocate(); } std::pair<T*, T*> alloc_n_copy(const T*, const T*); void free(); void reallocate(); void add_rem(std::size_t n, const T &s = ""); T *elements; T *first_free; T *cap; }; // Warning: define static member outside the class. Without this the program // using the class wouldn't compile template <typename T> std::allocator<T> Vec<T>::alloc; // friend definition template <typename T> bool operator==(const Vec<T> &lhs, const Vec<T> &rhs) { if(lhs.size() != rhs.size()) return false; else { for(auto p = lhs.elements, q = rhs.elements; p != lhs.first_free; ++p, ++q) { if(*p != *q) return false; } return true; } } template <typename T> bool operator!=(const Vec<T> &lhs, const Vec<T> &rhs) { return !(lhs == rhs); } template <typename T> bool operator<(const Vec<T> &lhs, const Vec<T> &rhs) { auto shorter = lhs.size() < rhs.size() ? lhs.size() : rhs.size(); auto p = lhs.begin(), q = rhs.begin(); for(std::size_t i = 0; p + i != lhs.end(); ++i) { if(*(p + i) == *(q + i)) continue; else if(*(p + i) < *(q + i)) return true; else return false; } return lhs.size() < rhs.size(); } template <typename T> bool operator<=(const Vec<T> &lhs, const Vec<T> &rhs) { return lhs < rhs || lhs == rhs; } template <typename T> bool operator>(const Vec<T> &lhs, const Vec<T> &rhs) { return !(lhs < rhs || lhs == rhs); } template <typename T> bool operator>=(const Vec<T> &lhs, const Vec<T> &rhs) { return !(lhs < rhs); } template <typename T> void Vec<T>::push_back(const T &s) { chk_n_alloc(); alloc.construct(first_free++, s); } template <typename T> void Vec<T>::push_back(T &&s) { chk_n_alloc(); alloc.construct(first_free++, std::move(s)); } template <typename T> std::pair<T*, T*> Vec<T>::alloc_n_copy(const T *b, const T *e) { auto data = alloc.allocate(e - b); return {data, std::uninitialized_copy(b, e, data)}; } template <typename T> void Vec<T>::free() { if (elements) { for(auto p = first_free; p != elements; /*empty*/ ) alloc.destroy(--p); alloc.deallocate(elements, cap - elements); } } template <typename T> Vec<T>::Vec(const Vec &s) { auto newdata = alloc_n_copy(s.begin(), s.end()); elements = newdata.first; first_free = cap = newdata.second; } template <typename T> Vec<T>::Vec(Vec &&s) noexcept : elements(s.elements), first_free(s.first_free), cap(s.cap) { s.elements = s.first_free = s.cap = nullptr; } template <typename T> Vec<T>::Vec(const std::initializer_list<T> &il) { auto newdata = alloc_n_copy(il.begin(), il.end()); elements = newdata.first; first_free = cap = newdata.second; } template <typename T> Vec<T>::~Vec() { free(); } template <typename T> Vec<T>& Vec<T>::operator=(const Vec &rhs) { auto data = alloc_n_copy(rhs.begin(), rhs.end()); free(); elements = data.first; first_free = cap = data.second; return *this; } template <typename T> Vec<T>& Vec<T>::operator=(Vec &&rhs) noexcept { if(this != &rhs) { free(); elements = rhs.elements; first_free = rhs.first_free; cap = rhs.cap; rhs.elements = rhs.first_free = rhs.cap = nullptr; } return *this; } template <typename T> Vec<T>& Vec<T>::operator=(std::initializer_list<T> il) { auto data = alloc_n_copy(il.begin(), il.end()); free(); elements = data.first; first_free = cap = data.second; return *this; } template <typename T> void Vec<T>::reallocate() { // we'll allocate space for twice as many as the current size auto newcapacity = size() ? 2 * size() : 1; // if empty, allocate 1 space, otherwise double // allocate new memory auto newdata = alloc.allocate(newcapacity); // move the data from the old memory to the new auto dest = newdata; // points to the next free position in the new memory auto elem = elements; // points to the next element in the old memory for(std::size_t i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); // free the old space once we've moved the elements // update our data structure to point to the new elements elements = newdata; first_free = dest; cap = elements + newcapacity; } template <typename T> void Vec<T>::reserve(std::size_t n) { if(n > capacity()) { auto newdata = alloc.allocate(n); auto dest = newdata; auto elem = elements; for(std::size_t i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); elements = newdata; first_free = newdata; cap = elements + n; } } template <typename T> void Vec<T>::resize(std::size_t n) { add_rem(n); } template <typename T> void Vec<T>::resize(std::size_t n, const T &s) { add_rem(n, s); } template <typename T> void Vec<T>::add_rem(std::size_t n, const T &s) { if(n <= size()) { auto p = first_free; while(p != elements + n) alloc.destroy(--p); first_free = p; } else{ auto new_elem_count = n - size(); for(std::size_t i = 0; i != new_elem_count; ++i) push_back(s); } } template <typename T> template <typename... Args> void Vec<T>::emplace_back(Args&&... args) { chk_n_alloc(); alloc.construct(first_free++, std::forward<Args>(args)...); } #endif
sjbarigye/CPP_Primer
chap13/Page524_536_StrVec.h
#ifndef STRVEC_H #define STRVEC_H #include <cstddef> #include <string> #include <utility> #include <memory> #include <initializer_list> class StrVec { public: StrVec(): elements(nullptr), first_free(nullptr), cap(nullptr) {} StrVec(const StrVec&); // move constructor from page 536 StrVec(StrVec&&) noexcept; StrVec& operator=(const StrVec&); // move assignment from page 537 StrVec& operator=(StrVec&&) noexcept; // constructor that takes a std::initializer_list as parameter, required by exercise 13.40 StrVec(const std::initializer_list<std::string>&); ~StrVec(); void push_back(const std::string&); std::size_t size() const { return first_free - elements; } std::size_t capacity() const { return cap - elements; } std::string *begin() const { return elements; } std::string *end() const { return first_free; } // both begin() and end() are const // reserve and resize required by exercise 13.39 void reserve(std::size_t); void resize(std::size_t); void resize(std::size_t, const std::string&); private: static std::allocator<std::string> alloc; void chk_n_alloc() { if(size() == capacity()) reallocate(); } std::pair<std::string*, std::string*> alloc_n_copy(const std::string*, const std::string*); void free(); void reallocate(); void add_rem(std::size_t n, const std::string &s = ""); std::string *elements; std::string *first_free; std::string *cap; }; // Warning: define static member outside the class, without this the program // using the class won't compile std::allocator<std::string> StrVec::alloc; void StrVec::push_back(const std::string &s) { chk_n_alloc(); alloc.construct(first_free++, s); } std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string *b, const std::string *e) { auto data = alloc.allocate(e - b); return {data, uninitialized_copy(b, e, data)}; } void StrVec::free() { if (elements) { for(auto p = first_free; p != elements; /*empty*/ ) alloc.destroy(--p); alloc.deallocate(elements, cap - elements); } } StrVec::StrVec(const StrVec &s) { auto newdata = alloc_n_copy(s.begin(), s.end()); elements = newdata.first; first_free = cap = newdata.second; } StrVec::StrVec(StrVec &&s) noexcept : elements(s.elements), first_free(s.first_free), cap(s.cap) { s.elements = s.first_free = s.cap = nullptr; } StrVec::StrVec(const std::initializer_list<std::string> &il) { auto newdata = alloc_n_copy(il.begin(), il.end()); elements = newdata.first; first_free = cap = newdata.second; } StrVec::~StrVec() { free(); } StrVec& StrVec::operator=(const StrVec &rhs) { auto data = alloc_n_copy(rhs.begin(), rhs.end()); free(); elements = data.first; first_free = cap = data.second; return *this; } StrVec& StrVec::operator=(StrVec &&rhs) noexcept { if(this != &rhs) { free(); elements = rhs.elements; first_free = rhs.first_free; cap = rhs.cap; rhs.elements = rhs.first_free = rhs.cap = nullptr; } return *this; } void StrVec::reallocate() { // we'll allocate space for twice as many as the current size auto newcapacity = size() ? 2 * size() : 1; // if empty, allocate 1 space, otherwise double // allocate new memory auto newdata = alloc.allocate(newcapacity); // move the data from the old memory to the new auto dest = newdata; // points to the next free position in the new memory auto elem = elements; // points to the next element in the old memory for(std::size_t i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); // free the old space once we've moved the elements // update our data structure to point to the new elements elements = newdata; first_free = dest; cap = elements + newcapacity; } void StrVec::reserve(std::size_t n) { if(n > capacity()) { auto newdata = alloc.allocate(n); auto dest = newdata; auto elem = elements; for(std::size_t i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); elements = newdata; first_free = newdata; cap = elements + n; } } void StrVec::resize(std::size_t n) { add_rem(n); } void StrVec::resize(std::size_t n, const std::string &s) { add_rem(n, s); } void StrVec::add_rem(std::size_t n, const std::string &s) { if(n <= size()) { auto p = first_free; while(p != elements + n) alloc.destroy(--p); first_free = p; } else{ auto new_elem_count = n - size(); for(std::size_t i = 0; i != new_elem_count; ++i) push_back(s); } } #endif // Note: in this program we use a static member, never forget to define this // member outside the class(Page 302). We do not need to repeat the static // keyword. We can use default initialization of std::allocator, so we do not need to // provide an initializer.
sjbarigye/CPP_Primer
chap16/Exer16_65_debug_rep.h
#ifndef EXER16_65_DEBUG_RET_H #define EXER16_65_DEBUG_RET_H #include <iostream> #include <sstream> #include <string> // declare all of the overloaded functions first to avoid silently instantiated template version // print any type we don't otherwise handle template <typename T> std::string debug_rep(const T&); template <typename T> std::string debug_rep(T*); std::string debug_rep(const std::string&); template <typename T> std::string debug_rep(const T &t) { std::cout << "debug_rep(const T&)" << std::endl; std::ostringstream ret; ret << t; // uses T's output operator to print a representation of t return ret.str(); // return a copy of the string to which ret is bound } // print pointers as their pointer value, followed by the object ot which the pointer points // NB: this function will not work properly with char*, because char* has its own version of output operator template <typename T> std::string debug_rep(T *p) { std::cout << "debug_rep(T*)" << std::endl; std::ostringstream ret; // print the pointer's own value ret << "pointer: " << p; if(p) ret << " " << debug_rep(*p); // print the value to which p points else ret << " null pointer"; // or indicate that the p is null return ret.str(); // return a copy of the string to which ret is bound } // print strings include inside double quotes std::string debug_rep(const std::string &s) { std::cout << "debug_rep(const string&)" << std::endl; return '"' + s + '"'; } // convert the character pointers to string and call the string version of debug_rep // use template specialization to to replace overload, required by exercise 65 template <> std::string debug_rep(const char *p) { std::cout << "debug_rep(const char*)" << std::endl; // if the declaration for the version that takes a const string& is not in scope // the return will call debug_rep(const T&) with T instantiated to string return debug_rep(std::string(p)); } template <> std::string debug_rep(char *p) { std::cout << "debug_rep(char*)" << std::endl; return debug_rep(std::string(p)); } #endif
sjbarigye/CPP_Primer
chap15/Exer15_35_Query.h
<reponame>sjbarigye/CPP_Primer // abstract class acts as a base for concrete query types; all members are private #ifndef QUERY_BASE_H #define QUERY_BASE_H #include <iostream> #include <string> #include <memory> #include "Exer15_35_TextQuery.h" class Query_base { friend class Query; protected: Query_base() { #ifndef NDEBUG std::cerr << "Query_base::Query_base()" << std::endl; #endif } using line_no = TextQuery::line_no; // used in eval functions virtual ~Query_base() = default; private: // eval returns the QueryResult that matches this Query // virtual QueryResult eval(const TextQuery&) const = 0; // rep is a string representing of the query virtual std::string rep() const = 0; }; // interface class to manage the Query_base inheritance hierarchy class Query { // these operators access to the shared_ptr constructor friend Query operator~(const Query&); friend Query operator|(const Query&, const Query&); friend Query operator&(const Query&, const Query&); public: Query(const std::string&); // builds a new WordQuery // interface functions: call the corresponding Query_base operations // QueryResult eval(const TextQuery &t) const // { return q->eval(t); } std::string rep() const { #ifndef NDEBUG std::cerr << "Query::rep()" << std::endl; #endif return q->rep(); } private: Query(std::shared_ptr<Query_base> query) : q(query) { #ifndef NDEBUG std::cerr << "Query::Query(shared_ptr<Query_base>)" << std::endl; #endif } std::shared_ptr<Query_base> q; }; // output result std::ostream& operator<<(std::ostream &os, const Query &query) { // Query::rep makes a virtual call through its Query_base pointer to rep() return os << query.rep(); } class WordQuery : public Query_base { friend class Query; // Query uses the WordQuery constructors WordQuery(const std::string &s) : query_word(s) { #ifndef NDEBUG std::cerr << "WordQuery::WordQuery(const string&)" << std::endl; #endif } // concrete class: WordQuery defines all inherited pure virtual functions // QueryResult eval(const TextQuery &t) const // { return t.query(query_word); } std::string rep() const { #ifndef NDEBUG std::cerr << "WordQuery::rep()" << std::endl; #endif return query_word; } std::string query_word; // word for which to search }; // constructor of Query that takes a string parameter inline Query::Query(const std::string &s) : q(new WordQuery(s)) { #ifndef NDEBUG std::cerr << "Query::Query(const string&)" << std::endl; #endif } class NotQuery : public Query_base { friend Query operator~(const Query&); NotQuery(const Query &q) : query(q) { #ifndef NDEBUG std::cerr << "NotQuery::NotQuery(const Query)" << std::endl; #endif } // concrete class: NotQuery defines all inherited pure virtual functoins std::string rep() const { #ifndef NDEBUG std::cerr << "NotQuery::rep()" << std::endl; #endif return "~(" + query.rep() + ")"; } // QueryResult eval(const TextQuery&) const; Query query; }; // allocate a new NotQuery object and bind the resulting NotQuery pointer to a shared_ptr<Query_base> inline Query operator~(const Query &operand) { return std::shared_ptr<Query_base>(new NotQuery(operand)); } class BinaryQuery : public Query_base { protected: BinaryQuery(const Query &l, const Query &r, std::string s) : lhs(l), rhs(r), opSym(s) { #ifndef NDEBUG std::cerr << "BinaryQuery::BinaryQuery(const Query&, const Query&, string)" << std::endl; #endif } // abstract class: BinaryQuery doesn't define eval std::string rep() const { #ifndef NDEBUG std::cerr << "BinaryQuery::rep()" << std::endl; #endif return "(" + lhs.rep() + " " + opSym + " " + rhs.rep() + ")"; } Query lhs, rhs; // right and left-hand operand std::string opSym; // name of the operator }; class AndQuery : public BinaryQuery { friend Query operator&(const Query&, const Query&); AndQuery(const Query &left, const Query &right) : BinaryQuery(left, right, "&") { #ifndef NDEBUG std::cerr << "AndQuery::AndQuery(const Query&, const Query&)" << std::endl; #endif } // concrete class: AndQuery inherits rep and defines the remaining pure virtual // QueryResult eval(const TextQuery&) const; }; inline Query operator&(const Query &lhs, const Query &rhs) { return std::shared_ptr<Query_base>(new AndQuery(lhs, rhs)); } class OrQuery : public BinaryQuery { friend Query operator|(const Query&, const Query&); OrQuery(const Query &left, const Query &right) : BinaryQuery(left, right, "|") { #ifndef NDEBUG std::cerr << "OrQuery::OrQuery(const Query&, const Query&)" << std::endl; #endif } // QueryResult eval(const TextQuery&) const; }; inline Query operator|(const Query &lhs, const Query &rhs) { return std::shared_ptr<Query_base>(new OrQuery(lhs, rhs)); } #endif
sjbarigye/CPP_Primer
chap16/Exer16_14_15_Screen.h
#ifndef EXER16_14_15_SCREEN_H #define EXER16_14_15_SCREEN_H #include <iostream> #include <string> #include <vector> template <unsigned H, unsigned W> class Screen; template <unsigned H, unsigned W> std::ostream& operator<<(std::ostream&, const Screen<H, W>&); template <unsigned H, unsigned W> std::istream& operator>>(std::istream&, Screen<H, W>&); template <unsigned H, unsigned W> class Screen { friend std::ostream& operator<< <H, W>(std::ostream&, const Screen<H, W>&); friend std::istream& operator>> <H, W>(std::istream&, Screen<H, W>&); public: using pos = std::string::size_type; Screen() : contents(H * W, '\0') {} Screen(char c) : contents(H * W, c), cursor(0) {} char get() const { return contents[cursor]; } inline char get(pos ht, pos wd) const; Screen& move(pos r, pos c); Screen& set(pos row, pos col, char c); Screen& set(char c); private: void do_display(std::ostream& os) const; pos cursor = 0; unsigned height = H, width = W; std::string contents; }; template <unsigned H, unsigned W> char Screen<H, W>::get(pos ht, pos wd) const { pos row = wd * width; return contents[row + ht]; } template <unsigned H, unsigned W> Screen<H, W>& Screen<H, W>::move(pos r, pos c) { cursor = r * width + c; return *this; } template <unsigned H, unsigned W> Screen<H, W>& Screen<H, W>::set(pos row, pos col, char c) { contents[row * width + col] = c; return *this; } template <unsigned H, unsigned W> Screen<H, W>& Screen<H, W>::set(char c) { contents[cursor] = c; return *this; } template <unsigned H, unsigned W> inline void Screen<H, W>::do_display(std::ostream& os) const { os << contents; } template <unsigned H, unsigned W> std::ostream& operator<<(std::ostream &os, const Screen<H, W> &s) { s.do_display(os); return os; } template <unsigned H, unsigned W> std::istream& operator>>(std::istream &is, Screen<H, W> &s) { char c; is >> c; s.set(c); return is; } #endif
sjbarigye/CPP_Primer
chap06/Page224_makeplural.h
<filename>chap06/Page224_makeplural.h // This function will be used frequently by subsequent chapters. #include <string> using std::string; string make_plural(size_t ctr, const string &word, const string &ending) { return (ctr > 1) ? word + ending : word; }
sjbarigye/CPP_Primer
chap15/Page612_613_access.h
#ifndef PAGE612_613_ACCESS_H #define PAGE612_613_ACCESS_H class Base { public: void pub_mem(); // public member protected: int prot_mem = 0; // protected member private: char priv_mem = 0; //private member }; struct Pub_Derv : public Base { // ok: derived classes can access protected members int f() { return prot_mem; } // error: private members are inaccessible to derived classes // char g() { return priv_mem; } }; struct Priv_Derv : private Base { // private derivation doesn't affect access in the derived class int f1() { return prot_mem; } }; struct Prot_Derv : protected Base { // protected derivation doesn't affect access in the derived class int f2() { return prot_mem; } }; struct Derived_from_Public : public Pub_Derv { // ok: Base::prot_mem remains protected in Pub_Derv int use_base() { return prot_mem; } }; struct Derived_from_Private: public Priv_Derv { // error: Base::prot_mem is private in Priv_Derv // int use_base() { return prot_mem; } }; struct Derived_from_Protected: public Prot_Derv { // ok: Base::prot_mem is protected in Prot_Derv int use_base() { return prot_mem; } }; #endif
sjbarigye/CPP_Primer
chap15/Exer15_39/Exer15_39_WordQuery.h
<gh_stars>10-100 #ifndef WORD_QUERY_H #define WORD_QUERY_H #include <string> #include "Exer15_39_TextQuery.h" #include "Exer15_39_Query_base.h" class WordQuery : public Query_base { friend class Query; // Query uses the WordQuery constructors WordQuery(const std::string &s) : query_word(s) {} // concrete class: WordQuery defines all inherited pure virtual functions QueryResult eval(const TextQuery &t) const { return t.query(query_word); } std::string rep() const { return query_word; } std::string query_word; // word for which to search }; #endif
sjbarigye/CPP_Primer
chap15/Exer15_39/Exer15_39_Query.h
// interface class to manage the Query_base inheritance hierarchy #ifndef QUERY_H #define QUERY_H #include <iostream> #include <memory> #include <string> #include "Exer15_39_TextQuery.h" #include "Exer15_39_WordQuery.h" class Query { // these operators access to the shared_ptr constructor friend Query operator~(const Query&); friend Query operator|(const Query&, const Query&); friend Query operator&(const Query&, const Query&); public: Query(const std::string &s) : q(new WordQuery(s)) {}; // builds a new WordQuery // interface functions: call the corresponding Query_base operations QueryResult eval(const TextQuery &t) const { return q->eval(t); } std::string rep() const { return q->rep(); } private: Query(std::shared_ptr<Query_base> query) : q(query) {} std::shared_ptr<Query_base> q; }; std::ostream& operator<<(std::ostream&, const Query&); #endif
sjbarigye/CPP_Primer
chap16/Exer16_04_find.h
<gh_stars>10-100 #ifndef EXER16_04_FIND_H #define EXER16_04_FIND_H template <typename TI, typename TV> TI find(TI begin, TI end, const TV &val) { while(begin != end) { if(*begin == val) return begin; ++begin; } return end; } #endif
sjbarigye/CPP_Primer
chap15/Exer15_30_Quote.h
#ifndef QUOTE_H #define QUOTE_H #include <cstddef> #include <iostream> #include <string> #include <utility> class Quote { public: Quote()=default; Quote(const std::string &book, double sales_price) : bookNo(book), price(sales_price) {} std::string isbn() const { return bookNo; } // return the total sales price for the specified number of items // derived class will override and apply different discount algorithms virtual double net_price(std::size_t n) const { return n * price; } virtual void debug() const; // copy control members Quote(const Quote &q) : bookNo(q.bookNo), price(q.price) {} Quote(Quote &&q) noexcept : bookNo(std::move(q.bookNo)), price(std::move(q.price)) {} Quote& operator=(const Quote&); Quote& operator=(Quote&&) noexcept; virtual ~Quote()=default; // dynamic binding for the destructor // virtual function to return a dynamically allocated copy of itself // these members use reference qualifiers virtual Quote* clone() const & { return new Quote(*this); } virtual Quote* clone() && { return new Quote(std::move(*this)); } private: std::string bookNo; // ISBN number of this item protected: double price = 0.0; // normal, undiscounted price }; // calculate and print the price for the given number of copies, applying any discount double print_total(std::ostream &os, const Quote &item, std::size_t n) { // depending on the type of the object bound to the item parameter // calls either Quote::net_price or Bulk_quote::net_price double ret = item.net_price(n); os << "ISBN: " << item.isbn() // calls Quote::isbn << " # sold: " << n << " total due: " << ret << std::endl; return ret; } inline void Quote::debug() const { std::cout << "std::string bookNo\n" << "double price\n" << std::endl; } inline Quote& Quote::operator=(const Quote &rhs) { // self-assignment is safe, we don't need to worry about it bookNo = rhs.bookNo; price = rhs.price; return *this; } inline Quote& Quote::operator=(Quote &&rhs) noexcept { if(this != &rhs) { bookNo = std::move(rhs.bookNo); price = std::move(rhs.price); } return *this; } #endif
sjbarigye/CPP_Primer
chap15/Exer15_16_Limit_quote.h
<gh_stars>10-100 #ifndef LIMIT_QUOTE_H #define LIMIT_QUOTE_H #include <cstddef> #include "Exer15_15_Disc_quote.h" class Limit_quote : public Disc_quote { public: Limit_quote() = default; Limit_quote(const std::string &book, double price, std::size_t qty, double disc) : Disc_quote(book, price, qty, disc) {} // overrides the base version in order to implement the bulk purchase discount policy double net_price(std::size_t) const override; void debug() const override; }; inline double Limit_quote::net_price(std::size_t cnt) const { if(cnt <= quantity) return cnt * (1 - discount) * price; else return cnt * price; } inline void Limit_quote::debug() const { std::cout << "std::string bookNo\n" << "double price\n" << "std::size_t max_qty\n" << "double discount\n" << std::endl; } #endif
sjbarigye/CPP_Primer
chap18/Exer18_09_Sales_data.h
<filename>chap18/Exer18_09_Sales_data.h #ifndef EXER18_09_SALES_DATA_H #define EXER18_09_SALES_DATA_H #include <iostream> #include <string> #include <stdexcept> // exception classes class out_of_stock: public std::runtime_error { public: explicit out_of_stock(const std::string &s): runtime_error(s) {} }; class isbn_mismatch: public std::logic_error { public: explicit isbn_mismatch(const std::string &s): std::logic_error(s) {} isbn_mismatch(const std::string &s, const std::string &lhs, const std::string &rhs): std::logic_error(s), left(lhs), right(rhs) {} const std::string left, right; }; class Sales_data { // friend // overloaded output operator required by exercise 14.6 friend std::ostream &operator<<(std::ostream&, const Sales_data&); // overloaded input operator required by exercise 14.9 friend std::istream &operator>>(std::istream&, Sales_data&); // overloaded addition operator required by exercise 14.13 friend Sales_data operator+(const Sales_data&, const Sales_data&); // overloaded equality on page 561 friend bool operator==(const Sales_data&, const Sales_data&); friend bool operator!=(const Sales_data&, const Sales_data&); // overloaded addition operator required by exercise 14.20 friend Sales_data operator+(const Sales_data&, const Sales_data&); public: // constructor Sales_data() = default; Sales_data(const std::string &s) : bookNo(s) {} Sales_data(const std::string &s, unsigned n, double p) : bookNo(s), units_sold(n), revenue(p*n) {} explicit Sales_data(std::istream &is) { is >> *this; } // member std::string isbn() const { return bookNo; } // overloaded compound-assignment operator required by exercise 14.20 Sales_data& operator+=(const Sales_data&); // takes an ISBN as parameter, required by exercise 14.22 Sales_data& operator=(const std::string&); private: std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; double avg_price() const; }; // member functions definition Sales_data& Sales_data::operator+=(const Sales_data& rhs) { if (isbn() != rhs.isbn()) throw isbn_mismatch("wrong isbns", isbn(), rhs.isbn()); units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } Sales_data& Sales_data::operator=(const std::string &isbn) { bookNo = isbn; return *this; } // define avg_price as inline, required by exercise 7.26 inline double Sales_data::avg_price() const { if(units_sold != 0) return revenue / units_sold; else return revenue; } // overloaded output operator std::ostream& operator<<(std::ostream& os, const Sales_data& item) { os << item.bookNo << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); return os; } // overloaded input operator std::istream& operator>>(std::istream &is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; if(is) // check if input invalid item.revenue = item.units_sold * price; else item = Sales_data(); // input failed:given the object default state return is; } bool operator==(const Sales_data &lhs, const Sales_data &rhs) { return lhs.bookNo == rhs.bookNo && lhs.units_sold == rhs.units_sold && lhs.revenue == rhs.revenue; } bool operator!=(const Sales_data &lhs, const Sales_data &rhs) { return !(lhs == rhs); } Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) { Sales_data sum = lhs; sum += rhs; return sum; } #endif
sjbarigye/CPP_Primer
chap13/Exer13_28_TreeNode_value.h
#ifndef EXER13_28_1_VALUE_H #define EXER13_28_1_VALUE_H #include <iostream> #include <string> #include <cstddef> class TreeNode { public: TreeNode() : count(1), left(nullptr), right(nullptr) {} // an empty node TreeNode(const std::string &s) : value(s), count(1), left(nullptr), right(nullptr) {} TreeNode(const TreeNode &tp); TreeNode& operator=(const TreeNode&); std::ostream& read(std::ostream& os) const { os << value << "\t" << count; return os; } void write(const std::string &str) { value = str; } ~TreeNode(); private: std::string value; int count; TreeNode *left; TreeNode *right; }; TreeNode::TreeNode(const TreeNode &tp) : value(tp.value), count(tp.count), left(new TreeNode()), right(new TreeNode()) { if(tp.left) *left = *tp.left; else left = nullptr; if(tp.right) *right = *tp.right; else right = nullptr; } TreeNode& TreeNode::operator=(const TreeNode& tp) { if(tp.left){ auto newp_left = new TreeNode(*tp.left); delete left; left = newp_left; } else left = nullptr; if(tp.right) { auto newp_right = new TreeNode(*tp.right); delete right; right = newp_right; } else right = nullptr; value = tp.value; count = tp.count; return *this; } TreeNode::~TreeNode() { if(left) { delete left; left = nullptr; } if(right) { delete right; right = nullptr; } } #endif // Note: TreeNode has pointer members of its own type. That implies constructor // and destructor might be called recursively. Thus we have to find out a way to // suspend the recursion. Because the node of a tree can have no child, the value // of left and right might be null. We can use this as the condition to judge if // the recursion should stop. First we write copy constructor and destructor, then // combine them to copy-assignment operator.
sjbarigye/CPP_Primer
chap15/Exer15_30_Disc_quote.h
#ifndef DISC_QUOTE_H #define DISC_QUOTE_H #include <cstddef> #include <iostream> #include <string> #include <utility> #include "Exer15_30_Quote.h" class Disc_quote : public Quote { public: Disc_quote()=default; Disc_quote(const std::string &book, double price, std::size_t qty, double disc): Quote(book, price), quantity(qty), discount(disc) {} double net_price(std::size_t) const = 0; // copy-control members Disc_quote(const Disc_quote &dq) : Quote(dq), quantity(dq.quantity), discount(dq.discount) {} Disc_quote(Disc_quote &&dq) noexcept : Quote(std::move(dq)), quantity(std::move(dq.quantity)), discount(std::move(dq.discount)) {} Disc_quote& operator=(const Disc_quote&); Disc_quote& operator=(Disc_quote&&) noexcept; ~Disc_quote()=default; // virtual by inheritance protected: std::size_t quantity = 0; // purchase size for the discount to apply double discount = 0.0; // fractional discount to apply }; inline Disc_quote& Disc_quote::operator=(const Disc_quote &rhs) { Quote::operator=(rhs); quantity = rhs.quantity; discount = rhs.discount; return *this; } inline Disc_quote& Disc_quote::operator=(Disc_quote &&rhs) noexcept { if(this != &rhs) { Quote::operator=(std::move(rhs)); quantity = std::move(rhs.quantity); discount = std::move(rhs.discount); } return *this; } #endif
sjbarigye/CPP_Primer
chap15/Exer15_39/Exer15_39_NotQuery.h
<gh_stars>10-100 #ifndef NOT_QUERY_H #define NOT_QUERY_H #include <string> #include <memory> #include "Exer15_39_TextQuery.h" #include "Exer15_39_Query_base.h" #include "Exer15_39_Query.h" class NotQuery : public Query_base { friend Query operator~(const Query&); NotQuery(const Query &q) : query(q) {} // concrete class: NotQuery defines all inherited pure virtual functoins std::string rep() const {} QueryResult eval(const TextQuery&) const; Query query; }; inline Query operator~(const Query &operand) { return std::shared_ptr<Query_base>(new NotQuery(operand)); } #endif
sjbarigye/CPP_Primer
chap14/Book.h
<reponame>sjbarigye/CPP_Primer<gh_stars>10-100 #ifndef BOOK_H #define BOOK_H #include <iostream> #include <string> #include <utility> using std::ostream; using std::istream; using std::string; class Book { // overloaded output operator required by exercise 14.8 friend ostream &operator<<(ostream&, const Book&); // overloaded input operator required by exercise 14.12 friend istream &operator>>(istream&, Book&); // overloaded equality operator required by exercise 14.17 friend bool operator==(const Book&, const Book&); friend bool operator!=(const Book&, const Book&); public: Book() = default; Book(string na, string au = "", string no = "") : book_name(na), book_author(au), book_no(no) {} // copy control constructor Book(const Book&) = default; // copy constructor Book(Book &&b) noexcept :// move constructor book_name(std::move(b.book_name)), book_author(std::move(b.book_author)), book_no(std::move(book_no)) {} Book& operator=(const Book&) = default; // copy-assignment operator Book& operator=(Book&&) noexcept; // move assignment operator Book& operator=(const string&); // take an ISBN as parameter, required by exercise 14.25 ~Book() = default; private: string book_name; string book_author; string book_no; }; Book& Book::operator=(Book &&rhs) noexcept { if(this != &rhs) { book_name = std::move(rhs.book_name); book_author = std::move(rhs.book_author); book_no = std::move(rhs.book_no); } return *this; } Book& Book::operator=(const string &isbn) { book_no = isbn; return *this; } // friend definition ostream& operator<<(ostream& os, const Book &b) { os << b.book_name << " " << b.book_author << " " << b.book_no; return os; } istream& operator>>(istream& is, Book &b) { is >> b.book_name >> b.book_author >> b.book_no; if(is) b = Book(); return is; }bool operator==(const Book &lhs, const Book &rhs) { return lhs.book_name == rhs.book_name && lhs.book_author == rhs.book_name && lhs.book_no == rhs.book_no; } bool operator!=(const Book &lhs, const Book &rhs) { return !(lhs == rhs); } #endif
sjbarigye/CPP_Primer
chap15/Exer15_39/Exer15_39_OrQuery.h
<reponame>sjbarigye/CPP_Primer<filename>chap15/Exer15_39/Exer15_39_OrQuery.h #ifndef OR_QUERY_H #define OR_QUERY_H #include <memory> #include "Exer15_39_TextQuery.h" #include "Exer15_39_BinaryQuery.h" #include "Exer15_39_Query.h" class OrQuery : public BinaryQuery { friend Query operator|(const Query&, const Query&); OrQuery(const Query &left, const Query &right) : BinaryQuery(left, right, "|") {} QueryResult eval(const TextQuery&) const; }; inline Query operator|(const Query &lhs, const Query &rhs) { return std::shared_ptr<Query_base>(new OrQuery(lhs, rhs)); } #endif
sjbarigye/CPP_Primer
chap07/Exer07_49_Sales_data.h
#ifndef SALES_DATA_H #define SALES_DATA_H #include <iostream> #include <string> // substitute class for struct class Sales_data { // friend friend std::istream& read(std::istream&, Sales_data&); friend std::ostream& print(std::ostream& os, const Sales_data& item); friend Sales_data add(const Sales_data& item1, const Sales_data& item2); public: // constructor Sales_data() : Sales_data("", 0, 0) { std::cout << "Sales_data()" << std::endl; } Sales_data(const std::string &s) : Sales_data(s, 0, 0) { std::cout << "Sales_data(const std::string &s)" << std::endl; } Sales_data(const std::string &s, unsigned n, double p) : bookNo(s), units_sold(n), revenue(p*n) { std::cout << "Sales_data(const std::string &s, unsigned n, double p)" << std::endl; } Sales_data(std::istream &is) : Sales_data() { std::cout << "Sales_data(std::istream &is)" << std::endl; read(is, *this); } // member // Sales_data& combine(Sales_data); // combine #(a) // Sales_data& combine(Sales_data&); // combine #(b) Sales_data& combine(const Sales_data& rhs); // combine #(c) std::string isbn() const { return bookNo; } private: std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; double avg_price() const; }; // declare friend functions outside class std::istream& read(std::istream&, Sales_data&); std::ostream& print(std::ostream& os, const Sales_data& item); Sales_data add(const Sales_data& item1, const Sales_data& item2); // member functions definition Sales_data& Sales_data::combine(const Sales_data& rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } // define avg_price as inline, required by exercise 7.26 inline double Sales_data::avg_price() const { if(units_sold != 0) return revenue / units_sold; else return revenue; } // friend functions definition std::istream& read(std::istream &is, Sales_data& item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; item.revenue = item.units_sold * price; return is; } // Why does the book use an std::ostream reference as return value rather than void? // 'Cause only in this way can user have a better manipulation of the format. std::ostream& print(std::ostream& os, const Sales_data& item) { os << item.bookNo << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); return os; } Sales_data add(const Sales_data& item1, const Sales_data& item2) { Sales_data sum = item1; sum.combine(item2); return sum; } #endif
sjbarigye/CPP_Primer
chap13/Exer13_15.h
<gh_stars>10-100 #ifndef EXER13_14_H #define EXER13_14_H #include <iostream> #include <cstdlib> struct numbered { numbered() : mysn(rand()) {} numbered(const numbered&) : mysn(rand()) {} int mysn = 0; }; void f(numbered s) { std::cout << s.mysn << std::endl; } // copy constructor always generates a new value #endif
sjbarigye/CPP_Primer
chap16/Exer16_29_Blob.h
// Note: this header has an unsolved problem. See notes below. #ifndef EXER16_29_BLOB_H #define EXER16_29_BLOB_H #include <string> #include <vector> #include <initializer_list> #include <utility> #include <stdexcept> #include "Exer16_28_shared_ptr.h" // #include <memory> // must be excluded, see notes below. template <typename T> class BlobPtr; template <typename T> class ConstBlobPtr; template <typename T> class Blob; template <typename T> bool operator==(const Blob<T>&, const Blob<T>&); template <typename T> bool operator!=(const Blob<T>&, const Blob<T>&); template <typename T> bool operator<(const Blob<T>&, const Blob<T>&); template <typename T> bool operator<=(const Blob<T>&, const Blob<T>&); template <typename T> bool operator>(const Blob<T>&, const Blob<T>&); template <typename T> bool operator>=(const Blob<T>&, const Blob<T>&); template <typename T> class Blob { friend class BlobPtr<T>; friend bool operator==<T>(const Blob<T>&, const Blob<T>&); friend bool operator!=<T>(const Blob<T>&, const Blob<T>&); friend bool operator< <T>(const Blob<T>&, const Blob<T>&); friend bool operator<=<T>(const Blob<T>&, const Blob<T>&); friend bool operator><T>(const Blob<T>&, const Blob<T>&); friend bool operator>=<T>(const Blob<T>&, const Blob<T>&); public: typedef T value_type; typedef typename std::vector<T>::size_type size_type; typedef typename std::vector<T>::difference_type difference_type; // constructors Blob(); Blob(std::initializer_list<T> il); // template member function required by exercise 16.24 template <typename It> Blob(It b, It e); // size size_type size() const { return data->size(); } bool empty() const { return data->empty(); } // elements void push_back(const T &t) { data->push_back(t); } void push_back(T &&t) { data->push_back(std::move(t)); } void pop_back(); T& front(); T& back(); // const version from exercise 12.2 const T& front() const; const T& back() const; T& operator[] (size_type); const T& operator[] (size_type) const; T& at(size_type); const T& at(size_type) const; // use count size_type use_count() const { return data->use_count(); } private: shared_ptr<std::vector<T>> data; void check(size_type, const std::string&) const; }; // constructors template <typename T> Blob<T>::Blob(): data(make_shared<std::vector<T>>()) {} template <typename T> Blob<T>::Blob(std::initializer_list<T> il): data(make_shared<std::vector<T>>(il)) {} template <typename T> template <typename It> Blob<T>::Blob(It b, It e) : data(make_shared<std::vector<T>>(b, e)) {} // check index template <typename T> void Blob<T>::check(size_type i, const std::string &msg) const { if(i >= data->size()) throw std::out_of_range(msg); } // add and remove elements template <typename T> void Blob<T>::pop_back() { check(0, "pop_back on empty Blob"); data->pop_back(); } // element access template <typename T> T& Blob<T>::front() { check(0, "front on empty Blob"); data->front(); } template <typename T> T& Blob<T>::back() { check(0, "back on empty Blob"); data->back(); } template <typename T> const T& Blob<T>::front() const { check(0, "front on empty Blob"); data->front(); } template <typename T> const T& Blob<T>::back() const { check(0, "back on empty Blob"); data->back(); } template <typename T> T& Blob<T>::operator[](size_type i) { check(i, "index out of range"); return (*data)[i]; } template <typename T> const T& Blob<T>::operator[](size_type i) const { check(i, "index out of range"); return (*data)[i]; } template <typename T> T& Blob<T>::at(size_type i) { check(i, "index out of range"); return data->at(i); } template <typename T> const T& Blob<T>::at(size_type i) const { check(i, "index out of range"); return data->at(i); } // relational operators template <typename T> inline bool operator==(const Blob<T> &lhs, const Blob<T> &rhs) { return *lhs.data == *rhs.data; } template <typename T> inline bool operator!=(const Blob<T> &lhs, const Blob<T> &rhs) { return !(lhs == rhs); } template <typename T> inline bool operator<(const Blob<T> &lhs, const Blob<T> &rhs) { return *lhs.data < *rhs.data; } template <typename T> inline bool operator<=(const Blob<T> &lhs, const Blob<T> &rhs) { return (lhs < rhs || lhs == rhs); } template <typename T> inline bool operator>(const Blob<T> &lhs, const Blob<T> &rhs) { return !(lhs < rhs || lhs == rhs); } template <typename T> inline bool operator>=(const Blob<T> &lhs, const Blob<T> &rhs) { return !(lhs < rhs); } #endif // Note: the header <memory> must be excluded, or even if we don't use std:: before // make_shared, the program still uses standard library version of it. THE REASON // IS NOT KNOWN FOR NOW. // The result is that even if <memory> is after "Exer16_28_shared_ptr.h", still // the standard library version of make_shared is used. But shared_ptr must // follow std:: if we want to use the standard library version. Here we don't want // to use the standard library version so we don't use std::; now the problem // emerges: (std::)make_shared can only work with std::shared_ptr, but we provide // a custom version of shared_ptr. As a result, the program won't compile. So we // had better not include memory here.
sjbarigye/CPP_Primer
chap19/Exer19_01_new_delete.h
#ifndef EXER19_01_MEMORY_H #define EXER19_01_MEMORY_H #include <iostream> #include <cstddef> #include <cstdlib> #include <new> inline void *operator new(std::size_t size) { std::cout << "You are using self-defined version of new!" << std::endl; if(void* mem = std::malloc(size)) return mem; else throw std::bad_alloc(); } inline void operator delete(void* mem) noexcept { std::cout << "You are using self-defined version of delete!" << std::endl; free(mem); } #endif
sjbarigye/CPP_Primer
chap16/Exer16_05_print.h
#ifndef EXER16_05_PRINT_H #define EXER16_05_PRINT_H #include <iostream> template <typename V, unsigned N> void print(const V (&arr)[N]) { for(auto elem : arr) { std::cout << elem << " "; } std::cout << std::endl; } #endif
sjbarigye/CPP_Primer
chap13/Exer13_28_BinStrTree_point.h
<reponame>sjbarigye/CPP_Primer<gh_stars>10-100 #ifndef EXER13_28_2_POINT_H #define EXER13_28_2_POINT_H #include <cstddef> #include "Exer13_28_TreeNode_point.h" class BinStrTree { public: BinStrTree() : root(new TreeNode()), use(new std::size_t(1)) {} BinStrTree(const BinStrTree &bp) : root(bp.root), use(bp.use) { ++*use; } BinStrTree& operator=(const BinStrTree &bp); ~BinStrTree(); private: TreeNode *root; std::size_t *use; }; BinStrTree& BinStrTree::operator=(const BinStrTree &bp) { ++*bp.use; if(--*use == 0) { delete root; delete use; } root = bp.root; use = bp.use; return *this; } BinStrTree::~BinStrTree() { if(--*use == 0) { delete root; delete use; } } #endif
sjbarigye/CPP_Primer
chap19/Exer19_21_25_Token.h
<filename>chap19/Exer19_21_25_Token.h // Warning: Visual Studio 2013 doesn't support union with class type member that has copy-control // operations. Use higher version or other compilers. #ifndef EXER19_21_TOKEN_H #define EXER19_21_TOKEN_H #include <iostream> #include <string> #include <utility> #include "Sales_data.h" // required by exercise 19.25 class Token { // overloaded output operator friend std::ostream& operator<<(std::ostream&, const Token&); public: // copy control needed because our class has a union with a string member Token() : tok(INT), ival{0} {} Token(const Token &t) : tok(t.tok) { copyUnion(t); } // move constructor, required by exercise 19.23 Token(Token &&t) noexcept : tok(std::move(t.tok)) { moveUnion(std::move(t)); } Token& operator=(const Token&); // move assignment operator, required by exercise 19.23 Token& operator=(Token&&) noexcept; // if the union holds a string, we must destroy it ~Token() { freeUnion(); } // assignment operators to set the differing members of the union Token& operator=(const std::string&); Token& operator=(char); Token& operator=(int); Token& operator=(double); Token& operator=(const Sales_data&); // required by exercise 19.25 private: enum { INT, CHAR, DBL, STR, SALE } tok; // discriminant union { // anonymous union char cval; int ival; double dval; std::string sval; Sales_data sdata; // Sales_data member, required by exercise 19.22 }; // each Token object has an unnamed member of this unnamed union type // check the discriminant and copy the union member as appropriate void copyUnion(const Token&); void moveUnion(Token &&t); void freeUnion(); // free class type member of union }; inline void Token::freeUnion() { if(tok == STR) sval.std::string::~string(); if(tok == SALE) sdata.~Sales_data(); } #endif