Added rate averager test.

Added rate averager test.

--- cpp/tests/test-util.cpp
+++ cpp/tests/test-util.cpp
@@ -13,6 +13,7 @@
 #include "db/util/Date.h"
 #include "db/util/PathFormatter.h"
 #include "db/util/Random.h"
+#include "db/util/RateAverager.h"
 #include "db/util/StringTools.h"
 #include "db/util/StringTokenizer.h"
 #include "db/util/UniqueList.h"
@@ -779,6 +780,38 @@
       string s1 = "abcABC123!@#$%^&()~,. ?/\\*:|\"<>+[]";
       string s2 = "abcABC123!@#$%^&()~,. ____________";
       assertStrCmp(PathFormatter::formatFilename(s1).c_str(), s2.c_str());
+   }
+   tr.passIfNoException();
+}
+
+void runRateAveragerTest(TestRunner& tr)
+{
+   tr.test("RateAverager 10 items/sec");
+   {
+      RateAverager ra;
+      uint64_t start = System::getCurrentMilliseconds();
+      Thread::sleep(900);
+      ra.addItems(5, start);
+      Thread::sleep(100);
+      ra.addItems(5, start);
+      printf("cur=%1.4f i/s,tot=%1.4f i/s ... ",
+         ra.getItemsPerSecond(),
+         ra.getTotalItemsPerSecond());
+   }
+   tr.passIfNoException();
+
+   tr.test("RateAverager 10 items/sec again");
+   {
+      RateAverager ra;
+      uint64_t start = System::getCurrentMilliseconds();
+      ra.addItems(5, start);
+      Thread::sleep(900);
+      start = System::getCurrentMilliseconds();
+      Thread::sleep(100);
+      ra.addItems(5, start);
+      printf("cur=%1.4f i/s,tot=%1.4f i/s ... ",
+         ra.getItemsPerSecond(),
+         ra.getTotalItemsPerSecond());
    }
    tr.passIfNoException();
 }
@@ -926,6 +959,7 @@
    {
       runAnsiEscapeCodeTest(tr);
       //runRandomTest(tr);
+      //runRateAveragerTest(tr);
       return 0;
    }
 };


Revert r336100

Revert r336100

This was a bad change. .word == 2byte on x86.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@336103 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Target/X86/AsmParser/X86AsmParser.cpp
+++ lib/Target/X86/AsmParser/X86AsmParser.cpp
@@ -846,6 +846,7 @@
                         const InlineAsmIdentifierInfo &Info);

   bool parseDirectiveEven(SMLoc L);
+  bool ParseDirectiveWord(unsigned Size, SMLoc L);
   bool ParseDirectiveCode(StringRef IDVal, SMLoc L);

   /// CodeView FPO data directives.
@@ -943,8 +944,6 @@
                const MCInstrInfo &mii, const MCTargetOptions &Options)
       : MCTargetAsmParser(Options, sti, mii),  InstInfo(nullptr),
         Code16GCC(false) {
-
-    Parser.addAliasForDirective(".word", ".4byte");

     // Initialize the set of available features.
     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
@@ -3265,7 +3264,9 @@
 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
   MCAsmParser &Parser = getParser();
   StringRef IDVal = DirectiveID.getIdentifier();
-  if (IDVal.startswith(".code"))
+  if (IDVal == ".word")
+    return ParseDirectiveWord(2, DirectiveID.getLoc());
+  else if (IDVal.startswith(".code"))
     return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
   else if (IDVal.startswith(".att_syntax")) {
     getParser().setParsingInlineAsm(false);
@@ -3326,6 +3327,27 @@
     getStreamer().EmitValueToAlignment(2, 0, 1, 0);
   return false;
 }
+/// ParseDirectiveWord
+///  ::= .word [ expression (, expression)* ]
+bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
+  auto parseOp = [&]() -> bool {
+    const MCExpr *Value;
+    SMLoc ExprLoc = getLexer().getLoc();
+    if (getParser().parseExpression(Value))
+      return true;
+    if (const auto *MCE = dyn_cast<MCConstantExpr>(Value)) {
+      assert(Size <= 8 && "Invalid size");
+      uint64_t IntValue = MCE->getValue();
+      if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
+        return Error(ExprLoc, "literal value out of range for directive");
+      getStreamer().EmitIntValue(IntValue, Size);
+    } else
+      getStreamer().EmitValue(Value, Size, ExprLoc);
+    return false;
+  };
+  parseMany(parseOp);
+  return false;
+}

 /// ParseDirectiveCode
 ///  ::= .code16 | .code32 | .code64


zotero_harvester: fix condition

zotero_harvester: fix condition

--- cpp/zotero_harvester.cc
+++ cpp/zotero_harvester.cc
@@ -646,7 +646,7 @@
         break;
     case CommandLineArgs::SelectionMode::URL: {
         const auto parent_journal(harvester_config.lookupJournal(commandline_args.selected_url_parent_journal_));
-        if (parent_journal != nullptr) {
+        if (parent_journal == nullptr) {
             harvester_config.default_journal_params_->entry_point_url_ = commandline_args.selected_url_;
             auto current_journal_datastore(QueueDownloadsForJournal(*harvester_config.default_journal_params_,
                                                                     harvester_config, &harvestable_manager,


Comment

Comment

--- minicourse/exercises.hpp
+++ minicourse/exercises.hpp
@@ -22,7 +22,10 @@
 void map_incr(const value_type* source, value_type* dest) {
   // todo: fill in
 }
-
+
+// source: pointer to the first item of the source array
+// n: number of items in the source array
+// seed: value to return in the case where `n` == 0
 value_type max(value_type* source, long n, value_type seed) {
   return seed; // todo: fill in
 }


GVN-hoist: enable by default

GVN-hoist: enable by default

As we addressed all compilation time problems with GVN-hoist
https://llvm.org/bugs/show_bug.cgi?id=28670
this patch turns GVN-hoist back by default.

Differential Revision: https://reviews.llvm.org/D23136

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@277685 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Transforms/IPO/PassManagerBuilder.cpp
+++ lib/Transforms/IPO/PassManagerBuilder.cpp
@@ -138,8 +138,8 @@
              "(default = 75)"));

 static cl::opt<bool> EnableGVNHoist(
-    "enable-gvn-hoist", cl::init(false), cl::Hidden,
-    cl::desc("Enable the experimental GVN Hoisting pass"));
+    "enable-gvn-hoist", cl::init(true), cl::Hidden,
+    cl::desc("Enable the GVN hoisting pass (default = on)"));

 PassManagerBuilder::PassManagerBuilder() {
     OptLevel = 2;


Build fix for older ffmpeg.

Build fix for older ffmpeg.

svn path=/trunk/libavg/; revision=7969

--- src/video/FFMpegDecoder.cpp
+++ src/video/FFMpegDecoder.cpp
@@ -996,9 +996,9 @@
 bool FFMpegDecoder::isImageCodec(const AVCodecContext* pContext) const
 {
     int imageCodecIDs[] = {CODEC_ID_PNG, CODEC_ID_PPM, CODEC_ID_PBM, CODEC_ID_PGM,
-            CODEC_ID_PGMYUV, CODEC_ID_BMP, CODEC_ID_DPX,
+            CODEC_ID_PGMYUV, CODEC_ID_BMP,
             CODEC_ID_JPEG2000, CODEC_ID_PAM, CODEC_ID_PCX,
-            CODEC_ID_PICTOR, CODEC_ID_PTX, CODEC_ID_SGI, CODEC_ID_SUNRAST, CODEC_ID_TIFF,
+            CODEC_ID_PTX, CODEC_ID_SGI, CODEC_ID_SUNRAST, CODEC_ID_TIFF,
             CODEC_ID_TARGA, -1};

     int i = 0;


Fix some bugs i created while removing mgStrToString

Everything works now

--- cpp_utils/WebServer.cpp
+++ cpp_utils/WebServer.cpp
@@ -18,14 +18,13 @@
 #include <mongoose.h>
 #include <string>

-
 static char tag[] = "WebServer";

 struct WebServerUserData {
-	WebServer *pWebServer;
-	WebServer::HTTPMultiPart *pMultiPart;
-	WebServer::WebSocketHandler *pWebSocketHandler;
-	void *originalUserData;
+    WebServer *pWebServer;
+    WebServer::HTTPMultiPart *pMultiPart;
+    WebServer::WebSocketHandler *pWebSocketHandler;
+    void *originalUserData;
 };

 /**
@@ -34,98 +33,89 @@
  * @return The string representation of the event.
  */
 static std::string mongoose_eventToString(int event) {
-	switch (event) {
-	case MG_EV_CONNECT:
-		return "MG_EV_CONNECT";
-	case MG_EV_ACCEPT:
-		return "MG_EV_ACCEPT";
-	case MG_EV_CLOSE:
-		return "MG_EV_CLOSE";
-	case MG_EV_SEND:
-		return "MG_EV_SEND";
-	case MG_EV_RECV:
-		return "MG_EV_RECV";
-	case MG_EV_POLL:
-		return "MG_EV_POLL";
-	case MG_EV_TIMER:
-		return "MG_EV_TIMER";
-	case MG_EV_HTTP_PART_DATA:
-		return "MG_EV_HTTP_PART_DATA";
-	case MG_EV_HTTP_MULTIPART_REQUEST:
-		return "MG_EV_HTTP_MULTIPART_REQUEST";
-	case MG_EV_HTTP_PART_BEGIN:
-		return "MG_EV_HTTP_PART_BEGIN";
-	case MG_EV_HTTP_PART_END:
-		return "MG_EV_HTTP_PART_END";
-	case MG_EV_HTTP_MULTIPART_REQUEST_END:
-		return "MG_EV_HTTP_MULTIPART_REQUEST_END";
-	case MG_EV_HTTP_REQUEST:
-		return "MG_EV_HTTP_REQUEST";
-	case MG_EV_HTTP_REPLY:
-		return "MG_EV_HTTP_REPLY";
-	case MG_EV_HTTP_CHUNK:
-		return "MG_EV_HTTP_CHUNK";
-	case MG_EV_MQTT_CONNACK:
-		return "MG_EV_MQTT_CONNACK";
-	case MG_EV_MQTT_CONNECT:
-		return "MG_EV_MQTT_CONNECT";
-	case MG_EV_MQTT_DISCONNECT:
-		return "MG_EV_MQTT_DISCONNECT";
-	case MG_EV_MQTT_PINGREQ:
-		return "MG_EV_MQTT_PINGREQ";
-	case MG_EV_MQTT_PINGRESP:
-		return "MG_EV_MQTT_PINGRESP";
-	case MG_EV_MQTT_PUBACK:
-		return "MG_EV_MQTT_PUBACK";
-	case MG_EV_MQTT_PUBCOMP:
-		return "MG_EV_MQTT_PUBCOMP";
-	case MG_EV_MQTT_PUBLISH:
-		return "MG_EV_MQTT_PUBLISH";
-	case MG_EV_MQTT_PUBREC:
-		return "MG_EV_MQTT_PUBREC";
-	case MG_EV_MQTT_PUBREL:
-		return "MG_EV_MQTT_PUBREL";
-	case MG_EV_MQTT_SUBACK:
-		return "MG_EV_MQTT_SUBACK";
-	case MG_EV_MQTT_SUBSCRIBE:
-		return "MG_EV_MQTT_SUBSCRIBE";
-	case MG_EV_MQTT_UNSUBACK:
-		return "MG_EV_MQTT_UNSUBACK";
-	case MG_EV_MQTT_UNSUBSCRIBE:
-		return "MG_EV_MQTT_UNSUBSCRIBE";
-	case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST:
-		return "MG_EV_WEBSOCKET_HANDSHAKE_REQUEST";
-	case MG_EV_WEBSOCKET_HANDSHAKE_DONE:
-		return "MG_EV_WEBSOCKET_HANDSHAKE_DONE";
-	case MG_EV_WEBSOCKET_FRAME:
-		return "MG_EV_WEBSOCKET_FRAME";
-	case MG_EV_WEBSOCKET_CONTROL_FRAME:
-		return "MG_EV_WEBSOCKET_CONTROL_FRAME";
-	}
-	std::ostringstream s;
-	s << "Unknown event: " << event;
-	return s.str();
+    switch (event) {
+    case MG_EV_CONNECT:
+        return "MG_EV_CONNECT";
+    case MG_EV_ACCEPT:
+        return "MG_EV_ACCEPT";
+    case MG_EV_CLOSE:
+        return "MG_EV_CLOSE";
+    case MG_EV_SEND:
+        return "MG_EV_SEND";
+    case MG_EV_RECV:
+        return "MG_EV_RECV";
+    case MG_EV_POLL:
+        return "MG_EV_POLL";
+    case MG_EV_TIMER:
+        return "MG_EV_TIMER";
+    case MG_EV_HTTP_PART_DATA:
+        return "MG_EV_HTTP_PART_DATA";
+    case MG_EV_HTTP_MULTIPART_REQUEST:
+        return "MG_EV_HTTP_MULTIPART_REQUEST";
+    case MG_EV_HTTP_PART_BEGIN:
+        return "MG_EV_HTTP_PART_BEGIN";
+    case MG_EV_HTTP_PART_END:
+        return "MG_EV_HTTP_PART_END";
+    case MG_EV_HTTP_MULTIPART_REQUEST_END:
+        return "MG_EV_HTTP_MULTIPART_REQUEST_END";
+    case MG_EV_HTTP_REQUEST:
+        return "MG_EV_HTTP_REQUEST";
+    case MG_EV_HTTP_REPLY:
+        return "MG_EV_HTTP_REPLY";
+    case MG_EV_HTTP_CHUNK:
+        return "MG_EV_HTTP_CHUNK";
+    case MG_EV_MQTT_CONNACK:
+        return "MG_EV_MQTT_CONNACK";
+    case MG_EV_MQTT_CONNECT:
+        return "MG_EV_MQTT_CONNECT";
+    case MG_EV_MQTT_DISCONNECT:
+        return "MG_EV_MQTT_DISCONNECT";
+    case MG_EV_MQTT_PINGREQ:
+        return "MG_EV_MQTT_PINGREQ";
+    case MG_EV_MQTT_PINGRESP:
+        return "MG_EV_MQTT_PINGRESP";
+    case MG_EV_MQTT_PUBACK:
+        return "MG_EV_MQTT_PUBACK";
+    case MG_EV_MQTT_PUBCOMP:
+        return "MG_EV_MQTT_PUBCOMP";
+    case MG_EV_MQTT_PUBLISH:
+        return "MG_EV_MQTT_PUBLISH";
+    case MG_EV_MQTT_PUBREC:
+        return "MG_EV_MQTT_PUBREC";
+    case MG_EV_MQTT_PUBREL:
+        return "MG_EV_MQTT_PUBREL";
+    case MG_EV_MQTT_SUBACK:
+        return "MG_EV_MQTT_SUBACK";
+    case MG_EV_MQTT_SUBSCRIBE:
+        return "MG_EV_MQTT_SUBSCRIBE";
+    case MG_EV_MQTT_UNSUBACK:
+        return "MG_EV_MQTT_UNSUBACK";
+    case MG_EV_MQTT_UNSUBSCRIBE:
+        return "MG_EV_MQTT_UNSUBSCRIBE";
+    case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST:
+        return "MG_EV_WEBSOCKET_HANDSHAKE_REQUEST";
+    case MG_EV_WEBSOCKET_HANDSHAKE_DONE:
+        return "MG_EV_WEBSOCKET_HANDSHAKE_DONE";
+    case MG_EV_WEBSOCKET_FRAME:
+        return "MG_EV_WEBSOCKET_FRAME";
+    case MG_EV_WEBSOCKET_CONTROL_FRAME:
+        return "MG_EV_WEBSOCKET_CONTROL_FRAME";
+    }
+    std::string s;
+    s += "Unknown event: ";
+    s += event;
+    return s;
 } //eventToString

-/**
- * @brief Convert a Mongoose string type to a string.
- * @param [in] mgStr The Mongoose string.
- * @return A std::string representation of the Mongoose string.
- */
-static std::string mgStrToString(struct mg_str mgStr) {
-	return std::string(mgStr.p, mgStr.len);
-} // mgStrToStr
-
 static void dumpHttpMessage(struct http_message *pHttpMessage) {
-	ESP_LOGD(tag, "HTTP Message");
-	ESP_LOGD(tag, "Message: %s", mgStrToString(pHttpMessage->message).c_str());
-	ESP_LOGD(tag, "URI: %s", mgStrToString(pHttpMessage->uri).c_str());
+    ESP_LOGD(tag, "HTTP Message");
+    ESP_LOGD(tag, "Message: %.*s", (int)pHttpMessage->uri.len, pHttpMessage->message.p);
 }

 /*
 static struct mg_str uploadFileNameHandler(struct mg_connection *mgConnection, struct mg_str fname) {
-	ESP_LOGD(tag, "uploadFileNameHandler: %s", mgStrToString(fname).c_str());
-	return fname;
+    ESP_LOGD(tag, "uploadFileNameHandler: %s", mgStrToString(fname).c_str());
+    return fname;
 }
 */

@@ -140,139 +130,139 @@
  * @return N/A.
  */
 static void mongoose_event_handler_web_server(
-	struct mg_connection *mgConnection, // The network connection associated with the event.
-	int event, // The type of event.
-	void *eventData // Data associated with the event.
+    struct mg_connection *mgConnection, // The network connection associated with the event.
+    int event, // The type of event.
+    void *eventData // Data associated with the event.
 ) {
-	if (event == MG_EV_POLL) {
-		return;
-	}
-	ESP_LOGD(tag, "Event: %s [%d]", mongoose_eventToString(event).c_str(), mgConnection->sock);
-	switch (event) {
-		case MG_EV_HTTP_REQUEST: {
-			struct http_message *message = (struct http_message *) eventData;
-			dumpHttpMessage(message);
-
-			struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
-			WebServer *pWebServer = pWebServerUserData->pWebServer;
-			pWebServer->processRequest(mgConnection, message);
-			break;
-		} // MG_EV_HTTP_REQUEST
-
-		case MG_EV_HTTP_MULTIPART_REQUEST: {
-			struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
-			ESP_LOGD(tag, "User_data address 0x%d", (uint32_t)pWebServerUserData);
-			WebServer *pWebServer = pWebServerUserData->pWebServer;
-			if (pWebServer->m_pMultiPartFactory == nullptr) {
-				return;
-			}
-			WebServer::HTTPMultiPart *pMultiPart = pWebServer->m_pMultiPartFactory->newInstance();
-			struct WebServerUserData *p2 = new WebServerUserData();
-			ESP_LOGD(tag, "New User_data address 0x%d", (uint32_t)p2);
-			p2->originalUserData    = pWebServerUserData;
-			p2->pWebServer          = pWebServerUserData->pWebServer;
-			p2->pMultiPart          = pMultiPart;
-			p2->pWebSocketHandler   = nullptr;
-			mgConnection->user_data = p2;
-			//struct http_message *message = (struct http_message *) eventData;
-			//dumpHttpMessage(message);
-			break;
-		} // MG_EV_HTTP_MULTIPART_REQUEST
-
-		case MG_EV_HTTP_MULTIPART_REQUEST_END: {
-			struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
-			if (pWebServerUserData->pMultiPart != nullptr) {
-				delete pWebServerUserData->pMultiPart;
-				pWebServerUserData->pMultiPart = nullptr;
-			}
-			mgConnection->user_data = pWebServerUserData->originalUserData;
-			delete pWebServerUserData;
-			WebServer::HTTPResponse httpResponse = WebServer::HTTPResponse(mgConnection);
-			httpResponse.setStatus(200);
-			httpResponse.sendData("");
-			break;
-		} // MG_EV_HTTP_MULTIPART_REQUEST_END
-
-		case MG_EV_HTTP_PART_BEGIN: {
-			struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
-			struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData;
-			ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d",
-					part->file_name, part->var_name, part->status, (uint32_t)part->user_data);
-			if (pWebServerUserData->pMultiPart != nullptr) {
-				pWebServerUserData->pMultiPart->begin(std::string(part->var_name), std::string(part->file_name));
-			}
-			break;
-		} // MG_EV_HTTP_PART_BEGIN
-
-		case MG_EV_HTTP_PART_DATA: {
-			struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
-			struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData;
-			ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d",
-					part->file_name, part->var_name, part->status, (uint32_t)part->user_data);
-			if (pWebServerUserData->pMultiPart != nullptr) {
-				pWebServerUserData->pMultiPart->data(mgStrToString(part->data));
-			}
-			break;
-		} // MG_EV_HTTP_PART_DATA
-
-		case MG_EV_HTTP_PART_END: {
-			struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
-			struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData;
-			ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d",
-					part->file_name, part->var_name, part->status, (uint32_t)part->user_data);
-			if (pWebServerUserData->pMultiPart != nullptr) {
-				pWebServerUserData->pMultiPart->end();
-			}
-			break;
-		} // MG_EV_HTTP_PART_END
-
-		case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: {
-			struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
-			WebServer *pWebServer = pWebServerUserData->pWebServer;
-			if (pWebServer->m_pWebSocketHandlerFactory != nullptr) {
-				if (pWebServerUserData->pWebSocketHandler != nullptr) {
-					ESP_LOGD(tag, "Warning: MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: pWebSocketHandler was NOT null");
-				}
-				struct WebServerUserData *p2 = new WebServerUserData();
-				ESP_LOGD(tag, "New User_data address 0x%d", (uint32_t)p2);
-				p2->originalUserData    = pWebServerUserData;
-				p2->pWebServer          = pWebServerUserData->pWebServer;
-				p2->pWebSocketHandler = pWebServer->m_pWebSocketHandlerFactory->newInstance();
-				mgConnection->user_data = p2;
-			} else {
-				ESP_LOGD(tag, "We received a WebSocket request but we have no handler factory!");
-			}
-			break;
-		} // MG_EV_WEBSOCKET_HANDSHAKE_REQUEST
-
-		case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
-			struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
-			if (pWebServerUserData->pWebSocketHandler == nullptr) {
-				ESP_LOGE(tag, "Error: MG_EV_WEBSOCKET_FRAME: pWebSocketHandler is null");
-				return;
-			}
-			pWebServerUserData->pWebSocketHandler->onCreated();
-			break;
-		} // MG_EV_WEBSOCKET_HANDSHAKE_DONE
-
-
-		/*
-		 * When we receive a MG_EV_WEBSOCKET_FRAME then we have received a chunk of data over the network.
-		 * Our goal will be to send this to the web socket handler (if one exists).
-		 */
-		case MG_EV_WEBSOCKET_FRAME: {
-			struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
-			if (pWebServerUserData->pWebSocketHandler == nullptr) {
-				ESP_LOGE(tag, "Error: MG_EV_WEBSOCKET_FRAME: pWebSocketHandler is null");
-				return;
-			}
-			struct websocket_message *ws_message = (websocket_message *)eventData;
-			ESP_LOGD(tag, "Received data length: %d", ws_message->size);
-			pWebServerUserData->pWebSocketHandler->onMessage(std::string((char *)ws_message->data, ws_message->size));
-			break;
-		} // MG_EV_WEBSOCKET_FRAME
-
-	} // End of switch
+    if (event == MG_EV_POLL) {
+        return;
+    }
+    ESP_LOGD(tag, "Event: %s [%d]", mongoose_eventToString(event).c_str(), mgConnection->sock);
+    switch (event) {
+        case MG_EV_HTTP_REQUEST: {
+            struct http_message *message = (struct http_message *) eventData;
+            dumpHttpMessage(message);
+
+            struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
+            WebServer *pWebServer = pWebServerUserData->pWebServer;
+            pWebServer->processRequest(mgConnection, message);
+            break;
+        } // MG_EV_HTTP_REQUEST
+
+        case MG_EV_HTTP_MULTIPART_REQUEST: {
+            struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
+            ESP_LOGD(tag, "User_data address 0x%d", (uint32_t)pWebServerUserData);
+            WebServer *pWebServer = pWebServerUserData->pWebServer;
+            if (pWebServer->m_pMultiPartFactory == nullptr) {
+                return;
+            }
+            WebServer::HTTPMultiPart *pMultiPart = pWebServer->m_pMultiPartFactory->newInstance();
+            struct WebServerUserData *p2 = new WebServerUserData();
+            ESP_LOGD(tag, "New User_data address 0x%d", (uint32_t)p2);
+            p2->originalUserData    = pWebServerUserData;
+            p2->pWebServer          = pWebServerUserData->pWebServer;
+            p2->pMultiPart          = pMultiPart;
+            p2->pWebSocketHandler   = nullptr;
+            mgConnection->user_data = p2;
+            //struct http_message *message = (struct http_message *) eventData;
+            //dumpHttpMessage(message);
+            break;
+        } // MG_EV_HTTP_MULTIPART_REQUEST
+
+        case MG_EV_HTTP_MULTIPART_REQUEST_END: {
+            struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
+            if (pWebServerUserData->pMultiPart != nullptr) {
+                delete pWebServerUserData->pMultiPart;
+                pWebServerUserData->pMultiPart = nullptr;
+            }
+            mgConnection->user_data = pWebServerUserData->originalUserData;
+            delete pWebServerUserData;
+            WebServer::HTTPResponse httpResponse = WebServer::HTTPResponse(mgConnection);
+            httpResponse.setStatus(200);
+            httpResponse.sendData("");
+            break;
+        } // MG_EV_HTTP_MULTIPART_REQUEST_END
+
+        case MG_EV_HTTP_PART_BEGIN: {
+            struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
+            struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData;
+            ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d",
+                    part->file_name, part->var_name, part->status, (uint32_t)part->user_data);
+            if (pWebServerUserData->pMultiPart != nullptr) {
+                pWebServerUserData->pMultiPart->begin(std::string(part->var_name), std::string(part->file_name));
+            }
+            break;
+        } // MG_EV_HTTP_PART_BEGIN
+
+        case MG_EV_HTTP_PART_DATA: {
+            struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
+            struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData;
+            ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d",
+                    part->file_name, part->var_name, part->status, (uint32_t)part->user_data);
+            if (pWebServerUserData->pMultiPart != nullptr) {
+                pWebServerUserData->pMultiPart->data(std::string(part->data.p, part->data.len));
+            }
+            break;
+        } // MG_EV_HTTP_PART_DATA
+
+        case MG_EV_HTTP_PART_END: {
+            struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
+            struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData;
+            ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d",
+                    part->file_name, part->var_name, part->status, (uint32_t)part->user_data);
+            if (pWebServerUserData->pMultiPart != nullptr) {
+                pWebServerUserData->pMultiPart->end();
+            }
+            break;
+        } // MG_EV_HTTP_PART_END
+
+        case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: {
+            struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
+            WebServer *pWebServer = pWebServerUserData->pWebServer;
+            if (pWebServer->m_pWebSocketHandlerFactory != nullptr) {
+                if (pWebServerUserData->pWebSocketHandler != nullptr) {
+                    ESP_LOGD(tag, "Warning: MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: pWebSocketHandler was NOT null");
+                }
+                struct WebServerUserData *p2 = new WebServerUserData();
+                ESP_LOGD(tag, "New User_data address 0x%d", (uint32_t)p2);
+                p2->originalUserData    = pWebServerUserData;
+                p2->pWebServer          = pWebServerUserData->pWebServer;
+                p2->pWebSocketHandler = pWebServer->m_pWebSocketHandlerFactory->newInstance();
+                mgConnection->user_data = p2;
+            } else {
+                ESP_LOGD(tag, "We received a WebSocket request but we have no handler factory!");
+            }
+            break;
+        } // MG_EV_WEBSOCKET_HANDSHAKE_REQUEST
+
+        case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
+            struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
+            if (pWebServerUserData->pWebSocketHandler == nullptr) {
+                ESP_LOGE(tag, "Error: MG_EV_WEBSOCKET_FRAME: pWebSocketHandler is null");
+                return;
+            }
+            pWebServerUserData->pWebSocketHandler->onCreated();
+            break;
+        } // MG_EV_WEBSOCKET_HANDSHAKE_DONE
+
+
+        /*
+         * When we receive a MG_EV_WEBSOCKET_FRAME then we have received a chunk of data over the network.
+         * Our goal will be to send this to the web socket handler (if one exists).
+         */
+        case MG_EV_WEBSOCKET_FRAME: {
+            struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
+            if (pWebServerUserData->pWebSocketHandler == nullptr) {
+                ESP_LOGE(tag, "Error: MG_EV_WEBSOCKET_FRAME: pWebSocketHandler is null");
+                return;
+            }
+            struct websocket_message *ws_message = (websocket_message *)eventData;
+            ESP_LOGD(tag, "Received data length: %d", ws_message->size);
+            pWebServerUserData->pWebSocketHandler->onMessage(std::string((char *)ws_message->data, ws_message->size));
+            break;
+        } // MG_EV_WEBSOCKET_FRAME
+
+    } // End of switch
 } // End of mongoose_event_handler

@@ -280,9 +270,9 @@
  * @brief Constructor.
  */
 WebServer::WebServer() {
-	m_rootPath                 = "";
-	m_pMultiPartFactory        = nullptr;
-	m_pWebSocketHandlerFactory = nullptr;
+    m_rootPath                 = "";
+    m_pMultiPartFactory        = nullptr;
+    m_pWebSocketHandlerFactory = nullptr;
 } // WebServer

@@ -295,7 +285,7 @@
  * @return The current root path.
  */
 const std::string& WebServer::getRootPath() {
-	return m_rootPath;
+    return m_rootPath;
 } // getRootPath

@@ -322,7 +312,7 @@
 void WebServer::addPathHandler(const std::string& method, const std::string& pathExpr,
                                void (* handler)(WebServer::HTTPRequest* pHttpRequest,
                                                 WebServer::HTTPResponse* pHttpResponse)) {
-	m_pathHandlers.push_back(PathHandler(method, pathExpr, handler));
+    m_pathHandlers.push_back(PathHandler(method, pathExpr, handler));
 } // addPathHandler

 void WebServer::addPathHandler(std::string&& method, const std::string& pathExpr,
@@ -340,31 +330,31 @@
  * @return N/A.
  */
 void WebServer::start(uint16_t port) {
-	ESP_LOGD(tag, "WebServer task starting");
-	struct mg_mgr mgr;
-	mg_mgr_init(&mgr, NULL);
-
-	std::stringstream stringStream;
-	stringStream << ':' << port;
-	struct mg_connection *mgConnection = mg_bind(&mgr, stringStream.str().c_str(), mongoose_event_handler_web_server);
-
-	if (mgConnection == NULL) {
-		ESP_LOGE(tag, "No connection from the mg_bind()");
-		vTaskDelete(NULL);
-		return;
-	}
-
-	struct WebServerUserData *pWebServerUserData = new WebServerUserData();
-	pWebServerUserData->pWebServer = this;
-	pWebServerUserData->pMultiPart = nullptr;
-	mgConnection->user_data        = pWebServerUserData; // Save the WebServer instance reference in user_data.
-	ESP_LOGD(tag, "start: User_data address 0x%d", (uint32_t)pWebServerUserData);
-	mg_set_protocol_http_websocket(mgConnection);
-
-	ESP_LOGD(tag, "WebServer listening on port %d", port);
-	while (1) {
-		mg_mgr_poll(&mgr, 2000);
-	}
+    ESP_LOGD(tag, "WebServer task starting");
+    struct mg_mgr mgr;
+    mg_mgr_init(&mgr, NULL);
+
+    std::stringstream stringStream;
+    stringStream << ':' << port;
+    struct mg_connection *mgConnection = mg_bind(&mgr, stringStream.str().c_str(), mongoose_event_handler_web_server);
+
+    if (mgConnection == NULL) {
+        ESP_LOGE(tag, "No connection from the mg_bind()");
+        vTaskDelete(NULL);
+        return;
+    }
+
+    struct WebServerUserData *pWebServerUserData = new WebServerUserData();
+    pWebServerUserData->pWebServer = this;
+    pWebServerUserData->pMultiPart = nullptr;
+    mgConnection->user_data        = pWebServerUserData; // Save the WebServer instance reference in user_data.
+    ESP_LOGD(tag, "start: User_data address 0x%d", (uint32_t)pWebServerUserData);
+    mg_set_protocol_http_websocket(mgConnection);
+
+    ESP_LOGD(tag, "WebServer listening on port %d", port);
+    while (1) {
+        mg_mgr_poll(&mgr, 2000);
+    }
 } // run

@@ -373,7 +363,7 @@
  * @param [in] pMultiPart A pointer to the multi part factory.
  */
 void WebServer::setMultiPartFactory(HTTPMultiPartFactory *pMultiPartFactory) {
-	m_pMultiPartFactory = pMultiPartFactory;
+    m_pMultiPartFactory = pMultiPartFactory;
 }

@@ -395,9 +385,13 @@
  * @return N/A.
  */
 void WebServer::setRootPath(const std::string& path) {
-	m_rootPath = path;
+    m_rootPath = path;
 } // setRootPath

+void WebServer::setRootPath(std::string&& path) {
+    m_rootPath = std::move(path);
+} // setRootPath
+

 /**
  * @brief Register the factory for creating web socket handlers.
@@ -406,7 +400,7 @@
  * @return N/A.
  */
 void WebServer::setWebSocketHandlerFactory(WebSocketHandlerFactory* pWebSocketHandlerFactory) {
-	m_pWebSocketHandlerFactory = pWebSocketHandlerFactory;
+    m_pWebSocketHandlerFactory = pWebSocketHandlerFactory;
 } // setWebSocketHandlerFactory

@@ -415,9 +409,9 @@
  * @param [in] nc The network connection for the response.
  */
 WebServer::HTTPResponse::HTTPResponse(struct mg_connection* nc) {
-	m_nc = nc;
-	m_status = 200;
-	m_dataSent = false;
+    m_nc = nc;
+    m_status = 200;
+    m_dataSent = false;
 } // HTTPResponse

@@ -427,7 +421,7 @@
  * @param [in] value The value of the header.
  */
 void WebServer::HTTPResponse::addHeader(const std::string& name, const std::string& value) {
-	m_headers[name] = value;
+    m_headers[name] = value;
 } // addHeader

 void WebServer::HTTPResponse::addHeader(std::string&& name, std::string&& value) {
@@ -441,7 +435,7 @@
  * @return N/A.
  */
 void WebServer::HTTPResponse::sendData(const std::string& data) {
-	sendData((uint8_t *)data.data(), data.length());
+    sendData((uint8_t *)data.data(), data.length());
 } // sendData

@@ -453,24 +447,35 @@
  * @return N/A.
  */
 void WebServer::HTTPResponse::sendData(const uint8_t* pData, size_t length) {
-	if (m_dataSent) {
-		ESP_LOGE(tag, "HTTPResponse: Data already sent!  Attempt to send again/more.");
-		return;
-	}
-	m_dataSent = true;
-
-	std::string headers;
-
-	for (auto iter = m_headers.begin(); iter != m_headers.end(); iter++) {
+    if (m_dataSent) {
+        ESP_LOGE(tag, "HTTPResponse: Data already sent!  Attempt to send again/more.");
+        return;
+    }
+    m_dataSent = true;
+
+    std::string headers;
+    unsigned long headers_len = 0;
+
+    for(auto iter = m_headers.begin(); iter != m_headers.end(); iter++) {
+        if(iter != m_headers.begin())
+            headers_len += 2;
+        headers_len += iter->first.length();
+        headers_len += 2;
+        headers_len += iter->second.length();
+    }
+    headers_len += 1;
+    headers.resize(headers_len); // Will not have to resize and recopy during the next loop, we have 2 loops but it still ends up being faster
+
+    for (auto iter = m_headers.begin(); iter != m_headers.end(); iter++) {
         if(iter != m_headers.begin())
             headers += "\r\n";
         headers += iter->first;
         headers += ": ";
         headers += iter->second;
-	}
-	mg_send_head(m_nc, m_status, length, headers.c_str());
-	mg_send(m_nc, pData, length);
-	m_nc->flags |= MG_F_SEND_AND_CLOSE;
+    }
+    mg_send_head(m_nc, m_status, length, headers.c_str());
+    mg_send(m_nc, pData, length);
+    m_nc->flags |= MG_F_SEND_AND_CLOSE;
 } // sendData

@@ -480,7 +485,7 @@
  * @return N/A.
  */
 void WebServer::HTTPResponse::setHeaders(const std::map<std::string, std::string>& headers) {
-	m_headers = headers;
+    m_headers = headers;
 } // setHeaders

 void WebServer::HTTPResponse::setHeaders(std::map<std::string, std::string>&& headers) {
@@ -492,8 +497,8 @@
  * @brief Get the current root path.
  * @return The current root path.
  */
-std::string WebServer::HTTPResponse::getRootPath() {
-	return m_rootPath;
+const std::string& WebServer::HTTPResponse::getRootPath() const {
+    return m_rootPath;
 } // getRootPath

@@ -503,7 +508,11 @@
  * @return N/A.
  */
 void WebServer::HTTPResponse::setRootPath(const std::string& path) {
-	m_rootPath = path;
+    m_rootPath = path;
+} // setRootPath
+
+void WebServer::HTTPResponse::setRootPath(std::string&& path) {
+    m_rootPath = std::move(path);
 } // setRootPath

 /**
@@ -514,7 +523,7 @@
  * @return N/A.
  */
 void WebServer::HTTPResponse::setStatus(int status) {
-	m_status = status;
+    m_status = status;
 } // setStatus

@@ -529,44 +538,43 @@
  * @param [in] message The message representing the request.
  */
 void WebServer::processRequest(struct mg_connection *mgConnection, struct http_message* message) {
-	std::string uri = mgStrToString(message->uri);
-	ESP_LOGD(tag, "WebServer::processRequest: Matching: %s", uri.c_str());
-	HTTPResponse httpResponse = HTTPResponse(mgConnection);
-	httpResponse.setRootPath(getRootPath());
-
-	/*
-	 * Iterate through each of the path handlers looking for a match with the method and specified path.
-	 */
-	std::vector<PathHandler>::iterator it;
-	for (it = m_pathHandlers.begin(); it != m_pathHandlers.end(); ++it) {
-		if ((*it).match(mgStrToString(message->method), uri)) {
-			HTTPRequest httpRequest(message);
-			(*it).invoke(&httpRequest, &httpResponse);
-			ESP_LOGD(tag, "Found a match!!");
-			return;
-		}
-	} // End of examine path handlers.
-
-	// Because we reached here, it means that we did NOT match a handler.  Now we want to attempt
-	// to retrieve the corresponding file content.
-	std::string filePath = httpResponse.getRootPath();
-    filePath += uri;
-	ESP_LOGD(tag, "Opening file: %s", filePath.c_str());
-	FILE *file = fopen(filePath.c_str(), "r");
-	if (file != nullptr) {
-		fseek(file, 0L, SEEK_END);
-		size_t length = ftell(file);
-		fseek(file, 0L, SEEK_SET);
-		uint8_t *pData = (uint8_t *)malloc(length);
-		fread(pData, length, 1, file);
-		fclose(file);
-		httpResponse.sendData(pData, length);
-		free(pData);
-	} else {
-		// Handle unable to open file
-		httpResponse.setStatus(404); // Not found
-		httpResponse.sendData("");
-	}
+    ESP_LOGD(tag, "WebServer::processRequest: Matching: %.*s", (int)message->uri.len, message->uri.p);
+    HTTPResponse httpResponse = HTTPResponse(mgConnection);
+    httpResponse.setRootPath(getRootPath());
+
+    /*
+     * Iterate through each of the path handlers looking for a match with the method and specified path.
+     */
+    std::vector<PathHandler>::iterator it;
+    for (it = m_pathHandlers.begin(); it != m_pathHandlers.end(); ++it) {
+        if ((*it).match(message->method.p, message->method.len, message->uri.p)) {
+            HTTPRequest httpRequest(message);
+            (*it).invoke(&httpRequest, &httpResponse);
+            ESP_LOGD(tag, "Found a match!!");
+            return;
+        }
+    } // End of examine path handlers.
+
+    // Because we reached here, it means that we did NOT match a handler.  Now we want to attempt
+    // to retrieve the corresponding file content.
+    std::string filePath = httpResponse.getRootPath();
+    filePath.append(message->uri.p, message->uri.len);
+    ESP_LOGD(tag, "Opening file: %s", filePath.c_str());
+    FILE *file = fopen(filePath.c_str(), "r");
+    if (file != nullptr) {
+        fseek(file, 0L, SEEK_END);
+        size_t length = ftell(file);
+        fseek(file, 0L, SEEK_SET);
+        uint8_t *pData = (uint8_t *)malloc(length);
+        fread(pData, length, 1, file);
+        fclose(file);
+        httpResponse.sendData(pData, length);
+        free(pData);
+    } else {
+        // Handle unable to open file
+        httpResponse.setStatus(404); // Not found
+        httpResponse.sendData("");
+    }
 } // processRequest

@@ -577,17 +585,13 @@
  * @param [in] pathPattern The path pattern to be matched.
  * @param [in] webServerRequestHandler The request handler to be called.
  */
-WebServer::PathHandler::PathHandler(const std::string& method, const std::string& pathPattern,
-                                    void (* webServerRequestHandler)(WebServer::HTTPRequest* pHttpRequest,
-                                                                     WebServer::HTTPResponse* pHttpResponse)) {
-	m_method         = method;
-	m_pattern        = std::regex(pathPattern);
-	m_requestHandler = webServerRequestHandler;
+WebServer::PathHandler::PathHandler(const std::string& method, const std::string& pathPattern, void (* webServerRequestHandler)(WebServer::HTTPRequest* pHttpRequest, WebServer::HTTPResponse* pHttpResponse)) {
+    m_method         = method;
+    m_pattern        = std::regex(pathPattern);
+    m_requestHandler = webServerRequestHandler;
 } // PathHandler

-WebServer::PathHandler::PathHandler(std::string&& method, const std::string& pathPattern,
-                                    void (* webServerRequestHandler)(WebServer::HTTPRequest* pHttpRequest,
-                                                                     WebServer::HTTPResponse* pHttpResponse)) {
+WebServer::PathHandler::PathHandler(std::string&& method, const std::string& pathPattern, void (* webServerRequestHandler)(WebServer::HTTPRequest* pHttpRequest, WebServer::HTTPResponse* pHttpResponse)) {
     m_method         = std::move(method);
     m_pattern        = std::regex(pathPattern);
     m_requestHandler = webServerRequestHandler;
@@ -598,15 +602,17 @@
  * @brief Determine if the path matches.
  *
  * @param [in] method The method to be matched.
+ * @param [in] method_len The method's length
  * @param [in] path The path to be matched.
  * @return True if the path matches.
  */
-bool WebServer::PathHandler::match(const std::string& method, const std::string& path) {
-	//ESP_LOGD(tag, "match: %s with %s", m_pattern.c_str(), path.c_str());
-	if (method != m_method) {
-		return false;
-	}
-	return std::regex_search(path, m_pattern);
+
+bool WebServer::PathHandler::match(const char* method, size_t method_len, const char* path) {
+    //ESP_LOGD(tag, "match: %s with %s", m_pattern.c_str(), path.c_str());
+    if (method_len != m_method.length() || strncmp(method, m_method.c_str(), method_len) != 0) {
+        return false;
+    }
+    return std::regex_search(path, m_pattern);
 } // match

@@ -617,7 +623,7 @@
  * @return N/A.
  */
 void WebServer::PathHandler::invoke(WebServer::HTTPRequest* request, WebServer::HTTPResponse *response) {
-	m_requestHandler(request, response);
+    m_requestHandler(request, response);
 } // invoke

@@ -628,30 +634,64 @@
  * @param [in] message The description of the underlying Mongoose message.
  */
 WebServer::HTTPRequest::HTTPRequest(struct http_message* message) {
-	m_message = message;
+    m_message = message;
 } // HTTPRequest

 /**
  * @brief Get the body of the request.
  * When an HTTP request is either PUT or POST then it may contain a payload that is also
+ * known as the body.  This method returns that payload (if it exists). Careful, because it's not a standard string
+ * that is terminated by a null character, use the getBodyLen() function to determine the body length
+ * @return The body of the request.
+ */
+const char* WebServer::HTTPRequest::getBody() const {
+    return m_message->body.p;
+} // getBody
+
+/**
+ * @brief Get the length of the body of the request.
+ * When an HTTP request is either PUT or POST then it may contain a payload that is also
  * known as the body.  This method returns that payload (if it exists).
- * @return The body of the request.
- */
-std::string WebServer::HTTPRequest::getBody() const {
-	return mgStrToString(m_message->body);
-} // getBody
+ * @return The length of the body of the request.
+ */
+size_t WebServer::HTTPRequest::getBodyLen() const {
+    return m_message->body.len;
+} // getBodyLen

 /**
  * @brief Get the method of the request.
  * An HTTP request contains a request method which is one of GET, PUT, POST, etc.
- * @return The method of the request.
- */
-std::string WebServer::HTTPRequest::getMethod() const {
-	return mgStrToString(m_message->method);
+ * @return The method of the request. Careful, because it's not a standard string
+ * that is terminated by a null character, use the getMethodLen() function to determine the method length
+ * @return The body of the request.
+ */
+const char* WebServer::HTTPRequest::getMethod() const {
+    return m_message->method.p;
 } // getMethod

+/**
+ * @brief Get the length of the method of the request.
+ * An HTTP request contains a request method which is one of GET, PUT, POST, etc.
+ * @return The length of the method of the request.
+ */
+size_t WebServer::HTTPRequest::getMethodLen() const {
+    return m_message->method.len;
+} // getMethodLen
+
+
+/**
+ * @brief Get the path of the request.
+ * The path of an HTTP request is the portion of the URL that follows the hostname/port pair
+ * but does not include any query parameters. Careful, because it's not a standard string
+ * that is terminated by a null character, use the getPathLen() function to determine the path length
+ * @return The body of the request.
+ * @return The path of the request.
+ */
+const char* WebServer::HTTPRequest::getPath() const {
+    return m_message->uri.p;
+} // getPath

 /**
  * @brief Get the path of the request.
@@ -659,8 +699,8 @@
  * but does not include any query parameters.
  * @return The path of the request.
  */
-std::string WebServer::HTTPRequest::getPath() const {
-	return mgStrToString(m_message->uri);
+size_t WebServer::HTTPRequest::getPathLen() const {
+    return m_message->uri.len;
 } // getPath

 #define STATE_NAME 0
@@ -672,47 +712,48 @@
  * @return The query part of the request.
  */
 std::map<std::string, std::string> WebServer::HTTPRequest::getQuery() const {
-	// Walk through all the characters in the query string maintaining a simple state machine
-	// that lets us know what we are parsing.
-	std::map<std::string, std::string> queryMap;
-	std::string queryString = mgStrToString(m_message->query_string);
-	int i=0;
-
-	/*
-	 * We maintain a simple state machine with states of:
-	 * * STATE_NAME - We are parsing a name.
-	 * * STATE_VALUE - We are parsing a value.
-	 */
-	int state = STATE_NAME;
-	std::string name = "";
-	std::string value;
-	// Loop through each character in the query string.
-	for (i=0; i<queryString.length(); i++) {
-		char currentChar = queryString[i];
-		if (state == STATE_NAME) {
-			if (currentChar != '=') {
-				name += currentChar;
-			} else {
-				state = STATE_VALUE;
-				value = "";
-			}
-		} // End state = STATE_NAME
-		else if (state == STATE_VALUE) {
-			if (currentChar != '&') {
-				value += currentChar;
-			} else {
-				//ESP_LOGD(tag, "name=%s, value=%s", name.c_str(), value.c_str());
-				queryMap[name] = value;
-				state = STATE_NAME;
-				name = "";
-			}
-		} // End state = STATE_VALUE
-	} // End for loop
-	if (state == STATE_VALUE) {
-		//ESP_LOGD(tag, "name=%s, value=%s", name.c_str(), value.c_str());
-		queryMap[name] = value;
-	}
-	return queryMap;
+    // Walk through all the characters in the query string maintaining a simple state machine
+    // that lets us know what we are parsing.
+    std::map<std::string, std::string> queryMap;
+    const char* queryString = m_message->query_string.p;
+    size_t queryStringLen = m_message->query_string.len;
+    int i=0;
+
+    /*
+     * We maintain a simple state machine with states of:
+     * * STATE_NAME - We are parsing a name.
+     * * STATE_VALUE - We are parsing a value.
+     */
+    int state = STATE_NAME;
+    std::string name = "";
+    std::string value;
+    // Loop through each character in the query string.
+    for (i=0; i<queryStringLen; i++) {
+        char currentChar = queryString[i];
+        if (state == STATE_NAME) {
+            if (currentChar != '=') {
+                name += currentChar;
+            } else {
+                state = STATE_VALUE;
+                value = "";
+            }
+        } // End state = STATE_NAME
+        else if (state == STATE_VALUE) {
+            if (currentChar != '&') {
+                value += currentChar;
+            } else {
+                //ESP_LOGD(tag, "name=%s, value=%s", name.c_str(), value.c_str());
+                queryMap[name] = value;
+                state = STATE_NAME;
+                name = "";
+            }
+        } // End state = STATE_VALUE
+    } // End for loop
+    if (state == STATE_VALUE) {
+        //ESP_LOGD(tag, "name=%s, value=%s", name.c_str(), value.c_str());
+        queryMap[name] = value;
+    }
+    return queryMap;
 } // getQuery

@@ -736,17 +777,17 @@
  * @return A vector of the constituent parts of the path.
  */
 std::vector<std::string> WebServer::HTTPRequest::pathSplit() const {
-	std::istringstream stream(getPath());
-	std::vector<std::string> ret;
-	std::string pathPart;
-	while(std::getline(stream, pathPart, '/')) {
-		ret.push_back(pathPart);
-	}
-	// Debug
-	for (int i=0; i<ret.size(); i++) {
-		ESP_LOGD(tag, "part[%d]: %s", i, ret[i].c_str());
-	}
-	return ret;
+    std::istringstream stream(std::string(getPath(), getPathLen())); // I don't know if there's a better istringstream constructor for this
+    std::vector<std::string> ret;
+    std::string pathPart;
+    while(std::getline(stream, pathPart, '/')) {
+        ret.push_back(pathPart);
+    }
+    // Debug
+    for (int i=0; i<ret.size(); i++) {
+        ESP_LOGD(tag, "part[%d]: %s", i, ret[i].c_str());
+    }
+    return ret;
 } // pathSplit

 /**
@@ -758,8 +799,8 @@
  * @return N/A.
  */
 void WebServer::HTTPMultiPart::begin(const std::string& varName, const std::string& fileName) {
-	ESP_LOGD(tag, "WebServer::HTTPMultiPart::begin(varName=\"%s\", fileName=\"%s\")",
-		varName.c_str(), fileName.c_str());
+    ESP_LOGD(tag, "WebServer::HTTPMultiPart::begin(varName=\"%s\", fileName=\"%s\")",
+        varName.c_str(), fileName.c_str());
 } // WebServer::HTTPMultiPart::begin

@@ -769,7 +810,7 @@
  * @return N/A.
  */
 void WebServer::HTTPMultiPart::end() {
-	ESP_LOGD(tag, "WebServer::HTTPMultiPart::end()");
+    ESP_LOGD(tag, "WebServer::HTTPMultiPart::end()");
 } // WebServer::HTTPMultiPart::end

@@ -781,7 +822,7 @@
  * @return N/A.
  */
 void WebServer::HTTPMultiPart::data(const std::string& data) {
-	ESP_LOGD(tag, "WebServer::HTTPMultiPart::data(), length=%d", data.length());
+    ESP_LOGD(tag, "WebServer::HTTPMultiPart::data(), length=%d", data.length());
 } // WebServer::HTTPMultiPart::data

@@ -790,7 +831,7 @@
  * @return N/A.
  */
 void WebServer::HTTPMultiPart::multipartEnd() {
-	ESP_LOGD(tag, "WebServer::HTTPMultiPart::multipartEnd()");
+    ESP_LOGD(tag, "WebServer::HTTPMultiPart::multipartEnd()");
 } // WebServer::HTTPMultiPart::multipartEnd

@@ -799,7 +840,7 @@
  * @return N/A.
  */
 void WebServer::HTTPMultiPart::multipartStart() {
-	ESP_LOGD(tag, "WebServer::HTTPMultiPart::multipartStart()");
+    ESP_LOGD(tag, "WebServer::HTTPMultiPart::multipartStart()");
 } // WebServer::HTTPMultiPart::multipartStart

@@ -836,10 +877,10 @@
  * @return N/A.
  */
 void WebServer::WebSocketHandler::sendData(const std::string& message) {
-	ESP_LOGD(tag, "WebSocketHandler::sendData(length=%d)", message.length());
-	mg_send_websocket_frame(m_mgConnection,
-	   WEBSOCKET_OP_BINARY | WEBSOCKET_OP_CONTINUE,
-	   message.data(), message.length());
+    ESP_LOGD(tag, "WebSocketHandler::sendData(length=%d)", message.length());
+    mg_send_websocket_frame(m_mgConnection,
+       WEBSOCKET_OP_BINARY | WEBSOCKET_OP_CONTINUE,
+       message.data(), message.length());
 } // sendData

 /**
@@ -849,9 +890,9 @@
  * @return N/A.
  */
 void WebServer::WebSocketHandler::sendData(const uint8_t* data, uint32_t size) {
-	mg_send_websocket_frame(m_mgConnection,
-	   WEBSOCKET_OP_BINARY | WEBSOCKET_OP_CONTINUE,
-	   data, size);
+    mg_send_websocket_frame(m_mgConnection,
+       WEBSOCKET_OP_BINARY | WEBSOCKET_OP_CONTINUE,
+       data, size);
 } // sendData

@@ -862,7 +903,7 @@
  * @return N/A.
  */
 void WebServer::WebSocketHandler::close() {
-	mg_send_websocket_frame(m_mgConnection, WEBSOCKET_OP_CLOSE, nullptr, 0);
+    mg_send_websocket_frame(m_mgConnection, WEBSOCKET_OP_CLOSE, nullptr, 0);
 } // close


[LoopPred] Rename a variable to simply a future patch [NFC]

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@357433 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Transforms/Scalar/LoopPredication.cpp
+++ lib/Transforms/Scalar/LoopPredication.cpp
@@ -654,17 +654,17 @@
 }

 bool LoopPredication::widenWidenableBranchGuardConditions(
-    BranchInst *Guard, SCEVExpander &Expander) {
-  assert(isGuardAsWidenableBranch(Guard) && "Must be!");
+    BranchInst *BI, SCEVExpander &Expander) {
+  assert(isGuardAsWidenableBranch(BI) && "Must be!");
   LLVM_DEBUG(dbgs() << "Processing guard:\n");
-  LLVM_DEBUG(Guard->dump());
+  LLVM_DEBUG(BI->dump());

   TotalConsidered++;
   SmallVector<Value *, 4> Checks;
   IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
   Value *Condition = nullptr, *WidenableCondition = nullptr;
   BasicBlock *GBB = nullptr, *DBB = nullptr;
-  parseWidenableBranch(Guard, Condition, WidenableCondition, GBB, DBB);
+  parseWidenableBranch(BI, Condition, WidenableCondition, GBB, DBB);
   unsigned NumWidened = collectChecks(Checks, Condition, Expander, Builder);
   if (NumWidened == 0)
     return false;
@@ -672,7 +672,7 @@
   TotalWidened += NumWidened;

   // Emit the new guard condition
-  Builder.SetInsertPoint(Guard);
+  Builder.SetInsertPoint(BI);
   Value *LastCheck = nullptr;
   for (auto *Check : Checks)
     if (!LastCheck)
@@ -682,9 +682,9 @@
   // Make sure that the check contains widenable condition and therefore can be
   // further widened.
   LastCheck = Builder.CreateAnd(LastCheck, WidenableCondition);
-  auto *OldCond = Guard->getOperand(0);
-  Guard->setOperand(0, LastCheck);
-  assert(isGuardAsWidenableBranch(Guard) &&
+  auto *OldCond = BI->getOperand(0);
+  BI->setOperand(0, LastCheck);
+  assert(isGuardAsWidenableBranch(BI) &&
          "Stopped being a guard after transform?");
   RecursivelyDeleteTriviallyDeadInstructions(OldCond);


Set memory properly.

Set memory properly.

--- cpu/cpu_exec_context.cc
+++ cpu/cpu_exec_context.cc
@@ -94,7 +94,7 @@

 CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num,
                          FunctionalMemory *_mem, int _asid)
-    : cpu(_cpu), thread_num(_thread_num), process(0), mem(NULL), asid(_asid),
+    : cpu(_cpu), thread_num(_thread_num), process(0), mem(_mem), asid(_asid),
       func_exe_inst(0), storeCondFailures(0)
 {
     memset(&regs, 0, sizeof(RegFile));


[PlaceSafepoints] Reduce dominator tree recalculation

Reduce recalculation of the dominator tree by identifying all sites that will need a safepoint poll before doing any of the insertion. This allows us to invalidate the dominator info once, rather than once per safepoint poll inserted.

While I'm at it, update findLocationForEntrySafepoint to properly update the dom tree now that the interface has been made easy. When first written, it wasn't per comment in the code.

Differential Revision: http://reviews.llvm.org/D9727

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@237220 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Transforms/Scalar/PlaceSafepoints.cpp
+++ lib/Transforms/Scalar/PlaceSafepoints.cpp
@@ -185,8 +185,8 @@
 // Insert a safepoint poll immediately before the given instruction.  Does
 // not handle the parsability of state at the runtime call, that's the
 // callers job.
-static void
-InsertSafepointPoll(DominatorTree &DT, Instruction *after,
+static void
+InsertSafepointPoll(Instruction *after,
                     std::vector<CallSite> &ParsePointsNeeded /*rval*/);

 static bool isGCLeafFunction(const CallSite &CS);
@@ -450,11 +450,7 @@
   }

   BasicBlock *BB = cursor->getParent();
-  SplitBlock(BB, cursor, nullptr);
-
-  // Note: SplitBlock modifies the DT.  Simply passing a Pass (which is a
-  // module pass) is not enough.
-  DT.recalculate(F);
+  SplitBlock(BB, cursor, &DT);

   // SplitBlock updates the DT
   DEBUG(DT.verifyDomTree());
@@ -567,10 +563,10 @@
   // actually insert parse points yet.  That will be done for all polls and
   // calls in a single pass.

-  // Note: With the migration, we need to recompute this for each 'pass'.  Once
-  // we merge these, we'll do it once before the analysis
   DominatorTree DT;
-
+  DT.recalculate(F);
+
+  SmallVector<Instruction *, 16> PollsNeeded;
   std::vector<CallSite> ParsePointNeeded;

   if (enableBackedgeSafepoints(F)) {
@@ -611,7 +607,6 @@
       // We are inserting a poll, the function is modified
       modified = true;

-      std::vector<CallSite> ParsePoints;
       if (SplitBackedge) {
         // Split the backedge of the loop and insert the poll within that new
         // basic block.  This creates a loop with two latches per original
@@ -638,46 +633,42 @@
         SetVector<BasicBlock *> SplitBackedges;
         for (BasicBlock *Header : Headers) {
           BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
-
-          std::vector<CallSite> RuntimeCalls;
-          InsertSafepointPoll(DT, NewBB->getTerminator(), RuntimeCalls);
+          PollsNeeded.push_back(NewBB->getTerminator());
           NumBackedgeSafepoints++;
-          ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
-                                  RuntimeCalls.end());
         }
-
       } else {
         // Split the latch block itself, right before the terminator.
-        std::vector<CallSite> RuntimeCalls;
-        InsertSafepointPoll(DT, Term, RuntimeCalls);
+        PollsNeeded.push_back(Term);
         NumBackedgeSafepoints++;
-        ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
-                                RuntimeCalls.end());
       }
-
-      // Record the parse points for later use
-      ParsePointNeeded.insert(ParsePointNeeded.end(), ParsePoints.begin(),
-                              ParsePoints.end());
     }
   }

   if (enableEntrySafepoints(F)) {
-    DT.recalculate(F);
-    Instruction *term = findLocationForEntrySafepoint(F, DT);
-    if (!term) {
+    Instruction *Location = findLocationForEntrySafepoint(F, DT);
+    if (!Location) {
       // policy choice not to insert?
     } else {
-      std::vector<CallSite> RuntimeCalls;
-      InsertSafepointPoll(DT, term, RuntimeCalls);
+      PollsNeeded.push_back(Location);
       modified = true;
       NumEntrySafepoints++;
-      ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
-                              RuntimeCalls.end());
-    }
-  }
-
+    }
+  }
+
+  // Now that we've identified all the needed safepoint poll locations, insert
+  // safepoint polls themselves.
+  for (Instruction *PollLocation : PollsNeeded) {
+    std::vector<CallSite> RuntimeCalls;
+    InsertSafepointPoll(PollLocation, RuntimeCalls);
+    ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
+                            RuntimeCalls.end());
+  }
+  PollsNeeded.clear(); // make sure we don't accidentally use
+  // The dominator tree has been invalidated by the inlining performed in the
+  // above loop.  TODO: Teach the inliner how to update the dom tree?
+  DT.recalculate(F);
+
   if (enableCallSafepoints(F)) {
-    DT.recalculate(F);
     std::vector<CallSite> Calls;
     findCallSafepoints(F, Calls);
     NumCallSafepoints += Calls.size();
@@ -692,7 +683,6 @@
   unique_unsorted(ParsePointNeeded);

   // Any parse point (no matter what source) will be handled here
-  DT.recalculate(F); // Needed?

   // We're about to start modifying the function
   if (!ParsePointNeeded.empty())
@@ -788,7 +778,7 @@
 }

 static void
-InsertSafepointPoll(DominatorTree &DT, Instruction *term,
+InsertSafepointPoll(Instruction *term,
                     std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
   Module *M = term->getParent()->getParent()->getParent();
   assert(M);
@@ -818,7 +808,6 @@
   }
   after++;
   assert(after != poll->getParent()->end() && "must have successor");
-  assert(DT.dominates(before, after) && "trivially true");

   // do the actual inlining
   InlineFunctionInfo IFI;
@@ -847,13 +836,6 @@
          "malformed poll function");

   scanInlinedCode(&*(start), &*(after), calls, BBs);
-
-  // Recompute since we've invalidated cached data.  Conceptually we
-  // shouldn't need to do this, but implementation wise we appear to.  Needed
-  // so we can insert safepoints correctly.
-  // TODO: update more cheaply
-  DT.recalculate(*after->getParent()->getParent());
-
   assert(!calls.empty() && "slow path not found for safepoint poll");

   // Record the fact we need a parsable state at the runtime call contained in


cql3: expression: update find_atom, count_if for function_call, cast, field_selection

The combination of the new types and these functions cannot happen yet,
but as they are generic functions it is better to implement them in
case it becomes possible later.

--- cql3/expr/expression.hh
+++ cql3/expr/expression.hh
@@ -268,9 +268,20 @@
             [] (const token&) -> const binary_operator* { return nullptr; },
             [] (const unresolved_identifier&) -> const binary_operator* { return nullptr; },
             [] (const column_mutation_attribute&) -> const binary_operator* { return nullptr; },
-            [] (const function_call&) -> const binary_operator* { return nullptr; },
-            [] (const cast&) -> const binary_operator* { return nullptr; },
-            [] (const field_selection&) -> const binary_operator* { return nullptr; },
+            [&] (const function_call& fc) -> const binary_operator* {
+                for (auto& arg : fc.args) {
+                    if (auto found = find_atom(arg, f)) {
+                        return found;
+                    }
+                }
+                return nullptr;
+            },
+            [&] (const cast& c) -> const binary_operator* {
+                return find_atom(*c.arg, f);
+            },
+            [&] (const field_selection& fs) -> const binary_operator* {
+                return find_atom(*fs.structure, f);
+            },
         }, e);
 }

@@ -290,9 +301,15 @@
             [] (const token&) -> size_t { return 0; },
             [] (const unresolved_identifier&) -> size_t { return 0; },
             [] (const column_mutation_attribute&) -> size_t { return 0; },
-            [] (const function_call&) -> size_t { return 0; },
-            [] (const cast&) -> size_t { return 0; },
-            [] (const field_selection&) -> size_t { return 0; },
+            [&] (const function_call& fc) -> size_t {
+                return std::accumulate(fc.args.cbegin(), fc.args.cend(), size_t{0},
+                                       [&] (size_t acc, const expression& c) { return acc + count_if(c, f); });
+            },
+            [&] (const cast& c) -> size_t {
+                return count_if(*c.arg, f); },
+            [&] (const field_selection& fs) -> size_t {
+                return count_if(*fs.structure, f);
+            },
         }, e);
 }


[PlaceSafepoints] Use DEBUG() instead of TraceLSP

DEBUG() is the more idiomatic LLVM style.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@259121 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Transforms/Scalar/PlaceSafepoints.cpp
+++ lib/Transforms/Scalar/PlaceSafepoints.cpp
@@ -94,9 +94,6 @@
 // optimizes better.
 static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
                                    cl::init(false));
-
-// Print tracing output
-static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));

 namespace {

@@ -320,8 +317,7 @@
     // avoiding the runtime cost of the actual safepoint.
     if (!AllBackedges) {
       if (mustBeFiniteCountedLoop(L, SE, Pred)) {
-        if (TraceLSP)
-          errs() << "skipping safepoint placement in finite loop\n";
+        DEBUG(dbgs() << "skipping safepoint placement in finite loop\n");
         FiniteExecution++;
         continue;
       }
@@ -330,8 +326,7 @@
         // Note: This is only semantically legal since we won't do any further
         // IPO or inlining before the actual call insertion..  If we hadn't, we
         // might latter loose this call safepoint.
-        if (TraceLSP)
-          errs() << "skipping safepoint placement due to unconditional call\n";
+        DEBUG(dbgs() << "skipping safepoint placement due to unconditional call\n");
         CallInLoop++;
         continue;
       }
@@ -347,10 +342,7 @@
     // variables) and branches to the true header
     TerminatorInst *Term = Pred->getTerminator();

-    if (TraceLSP) {
-      errs() << "[LSP] terminator instruction: ";
-      Term->dump();
-    }
+    DEBUG(dbgs() << "[LSP] terminator instruction: " << *Term);

     PollLocations.push_back(Term);
   }


cql3/query_processor: Clean up code formatting

Currently, query_processor.cc code formatting is all over the place,
which makes the file hard to read. Apply some formatting magic to make
it prettier.

Message-Id: <5731209a5b6817b76a8cf45098cab36af0eaceb9@scylladb.com>

--- cql3/query_processor.cc
+++ cql3/query_processor.cc
@@ -64,8 +64,8 @@
     service::query_state _qs;
 public:
     internal_state()
-            : _qs(service::client_state{service::client_state::internal_tag()}) {
-    }
+        : _qs(service::client_state{service::client_state::internal_tag()})
+    { }
     operator service::query_state&() {
         return _qs;
     }
@@ -88,7 +88,7 @@
 }

 query_processor::query_processor(distributed<service::storage_proxy>& proxy,
-        distributed<database>& db)
+                                 distributed<database>& db)
     : _migration_subscriber{std::make_unique<migration_subscriber>(this)}
     , _proxy(proxy)
     , _db(db)
@@ -133,8 +133,9 @@
 }

 future<::shared_ptr<result_message>>
-query_processor::process_statement(::shared_ptr<cql_statement> statement, service::query_state& query_state,
-        const query_options& options)
+query_processor::process_statement(::shared_ptr<cql_statement> statement,
+                                   service::query_state& query_state,
+                                   const query_options& options)
 {
 #if 0
         logger.trace("Process {} @CL.{}", statement, options.getConsistency());
@@ -170,7 +171,9 @@
 }

 future<::shared_ptr<transport::messages::result_message::prepared>>
-query_processor::prepare(const std::experimental::string_view& query_string, const service::client_state& client_state, bool for_thrift)
+query_processor::prepare(const std::experimental::string_view& query_string,
+                         const service::client_state& client_state,
+                         bool for_thrift)
 {
     auto existing = get_stored_prepared_statement(query_string, client_state.get_raw_keyspace(), for_thrift);
     if (existing) {
@@ -186,7 +189,9 @@
 }

 ::shared_ptr<transport::messages::result_message::prepared>
-query_processor::get_stored_prepared_statement(const std::experimental::string_view& query_string, const sstring& keyspace, bool for_thrift)
+query_processor::get_stored_prepared_statement(const std::experimental::string_view& query_string,
+                                               const sstring& keyspace,
+                                               bool for_thrift)
 {
     if (for_thrift) {
         auto statement_id = compute_thrift_id(query_string, keyspace);
@@ -206,8 +211,10 @@
 }

 future<::shared_ptr<transport::messages::result_message::prepared>>
-query_processor::store_prepared_statement(const std::experimental::string_view& query_string, const sstring& keyspace,
-        ::shared_ptr<statements::prepared_statement> prepared, bool for_thrift)
+query_processor::store_prepared_statement(const std::experimental::string_view& query_string,
+                                          const sstring& keyspace,
+                                          ::shared_ptr<statements::prepared_statement> prepared,
+                                          bool for_thrift)
 {
 #if 0
     // Concatenate the current keyspace so we don't mix prepared statements between keyspace (#5352).
@@ -301,7 +308,7 @@

         if (!statement) {
             throw exceptions::syntax_exception("Parsing failed");
-        };
+        }
         return std::move(statement);
     } catch (const exceptions::recognition_exception& e) {
         throw exceptions::syntax_exception(sprint("Invalid or malformed CQL query string: %s", e.what()));
@@ -313,10 +320,10 @@
     }
 }

-query_options query_processor::make_internal_options(
-                ::shared_ptr<statements::prepared_statement> p,
-                const std::initializer_list<data_value>& values,
-                db::consistency_level cl) {
+query_options query_processor::make_internal_options(::shared_ptr<statements::prepared_statement> p,
+                                                     const std::initializer_list<data_value>& values,
+                                                     db::consistency_level cl)
+{
     if (p->bound_names.size() != values.size()) {
         throw std::invalid_argument(sprint("Invalid number of values. Expecting %d but got %d", p->bound_names.size(), values.size()));
     }
@@ -335,8 +342,8 @@
     return query_options(cl, bound_values);
 }

-::shared_ptr<statements::prepared_statement> query_processor::prepare_internal(
-        const sstring& query_string) {
+::shared_ptr<statements::prepared_statement> query_processor::prepare_internal(const sstring& query_string)
+{
     auto& p = _internal_statements[query_string];
     if (p == nullptr) {
         auto np = parse_statement(query_string)->prepare(_db.local());
@@ -346,9 +353,10 @@
     return p;
 }

-future<::shared_ptr<untyped_result_set>> query_processor::execute_internal(
-        const sstring& query_string,
-        const std::initializer_list<data_value>& values) {
+future<::shared_ptr<untyped_result_set>>
+query_processor::execute_internal(const sstring& query_string,
+                                  const std::initializer_list<data_value>& values)
+{
     if (log.is_enabled(logging::log_level::trace)) {
         log.trace("execute_internal: \"{}\" ({})", query_string, ::join(", ", values));
     }
@@ -356,22 +364,23 @@
     return execute_internal(p, values);
 }

-future<::shared_ptr<untyped_result_set>> query_processor::execute_internal(
-        ::shared_ptr<statements::prepared_statement> p,
-        const std::initializer_list<data_value>& values) {
+future<::shared_ptr<untyped_result_set>>
+query_processor::execute_internal(::shared_ptr<statements::prepared_statement> p,
+                                  const std::initializer_list<data_value>& values)
+{
     auto opts = make_internal_options(p, values);
-    return do_with(std::move(opts),
-            [this, p = std::move(p)](auto& opts) {
-                return p->statement->execute_internal(_proxy, *_internal_state, opts).then(
-                        [p](auto msg) {
-                            return make_ready_future<::shared_ptr<untyped_result_set>>(::make_shared<untyped_result_set>(msg));
-                        });
-            });
-}
-
-future<::shared_ptr<untyped_result_set>> query_processor::process(
-                const sstring& query_string,
-                db::consistency_level cl, const std::initializer_list<data_value>& values, bool cache)
+    return do_with(std::move(opts), [this, p = std::move(p)](auto& opts) {
+        return p->statement->execute_internal(_proxy, *_internal_state, opts).then([p](auto msg) {
+            return make_ready_future<::shared_ptr<untyped_result_set>>(::make_shared<untyped_result_set>(msg));
+        });
+    });
+}
+
+future<::shared_ptr<untyped_result_set>>
+query_processor::process(const sstring& query_string,
+                         db::consistency_level cl,
+                         const std::initializer_list<data_value>& values,
+                         bool cache)
 {
     auto p = cache ? prepare_internal(query_string) : parse_statement(query_string)->prepare(_db.local());
     if (!cache) {
@@ -380,23 +389,24 @@
     return process(p, cl, values);
 }

-future<::shared_ptr<untyped_result_set>> query_processor::process(
-                ::shared_ptr<statements::prepared_statement> p,
-                db::consistency_level cl, const std::initializer_list<data_value>& values)
+future<::shared_ptr<untyped_result_set>>
+query_processor::process(::shared_ptr<statements::prepared_statement> p,
+                         db::consistency_level cl,
+                         const std::initializer_list<data_value>& values)
 {
     auto opts = make_internal_options(p, values, cl);
-    return do_with(std::move(opts),
-            [this, p = std::move(p)](auto & opts) {
-                return p->statement->execute(_proxy, *_internal_state, opts).then(
-                        [p](auto msg) {
-                            return make_ready_future<::shared_ptr<untyped_result_set>>(::make_shared<untyped_result_set>(msg));
-                        });
-            });
-}
-
+    return do_with(std::move(opts), [this, p = std::move(p)](auto & opts) {
+        return p->statement->execute(_proxy, *_internal_state, opts).then([p](auto msg) {
+            return make_ready_future<::shared_ptr<untyped_result_set>>(::make_shared<untyped_result_set>(msg));
+        });
+    });
+}

 future<::shared_ptr<transport::messages::result_message>>
-query_processor::process_batch(::shared_ptr<statements::batch_statement> batch, service::query_state& query_state, query_options& options) {
+query_processor::process_batch(::shared_ptr<statements::batch_statement> batch,
+                               service::query_state& query_state,
+                               query_options& options)
+{
     return batch->check_access(query_state.get_client_state()).then([this, &query_state, &options, batch] {
         batch->validate();
         batch->validate(_proxy, query_state.get_client_state());


Changed call for WvPipe to fit new WvPipe Signature

git-svn-id: 4a4e6d3f3969003d0af9593019da3e8c357e24a8@574 6619c942-59fa-0310-bf43-a07aaa81d9ac

--- wvdialer.cc
+++ wvdialer.cc
@@ -1057,11 +1057,11 @@
     };

     /* Filter out NULL holes in the raw argv list: */
-    char const *argv[sizeof(argv_raw)];
+    char * argv[sizeof(argv_raw)];
     int argv_index = 0;
     for (unsigned int i = 0; i < sizeof(argv_raw)/sizeof(char *); i++) {
 	if (argv_raw[i])
-            argv[argv_index++] = argv_raw[i];
+            argv[argv_index++] = (char *)argv_raw[i];
     }
     argv[argv_index] = NULL;

@@ -1098,7 +1098,8 @@
 //    }
 //    log("pppd args: %s\n", pppd_args);

-    ppp_pipe = new WvPipe( argv[0], argv, false, false, false,
+    // ugly cast however without it the argv list can't be init'd
+    ppp_pipe = new WvPipe( argv[0], (const char * const *)argv, false, false, false,
 			   modem, modem, modem );

     log( WvLog::Notice, "pid of pppd: %s\n", ppp_pipe->getpid() );


bug #399: Added test for no arch and no default provided

--- src/vmm/LibVirtDriverKVM.cc
+++ src/vmm/LibVirtDriverKVM.cc
@@ -168,6 +168,11 @@
     if ( arch.empty() )
     {
         get_default("OS","ARCH",arch);
+
+        if ( arch.empty() )
+        {
+            goto error_arch;
+        }
     }

     if (emulator == "kvm")
@@ -628,6 +633,11 @@
     file.close();
     return -1;

+error_arch:
+    vm->log("VMM", Log::ERROR, "No ARCH defined and no default provided.");
+    file.close();
+    return -1;
+
 error_boot:
     vm->log("VMM", Log::ERROR, "No BOOT device defined and no default provided.");
     file.close();


try more

try more

--- testing/adios2/engine/ssc/TestSscBaseUnlocked.cpp
+++ testing/adios2/engine/ssc/TestSscBaseUnlocked.cpp
@@ -192,10 +192,6 @@
             ASSERT_EQ(stringVar.Max(),
                       "sample string sample string sample string");

-            int i;
-            engine.Get(scalarInt, i);
-            ASSERT_EQ(i, currentStep);
-
             VerifyData(myChars.data(), currentStep, start, count, shape,
                        mpiRank);
             VerifyData(myUChars.data(), currentStep, start, count, shape,


Remove redundant code.
As per Doug’s review of r6356.

Swift SVN r6391

--- lib/SIL/TypeLowering.cpp
+++ lib/SIL/TypeLowering.cpp
@@ -142,8 +142,8 @@

   AnyFunctionType::ExtInfo outerInfo = t->getExtInfo();
   AbstractCC outerCC = outerInfo.getCC();
-  assert(!t->isAutoClosure() && "auto_closures cannot be curried");
-  assert(!t->isBlock() && "objc blocks cannot be curried");
+  assert(!outerInfo.isAutoClosure() && "auto_closures cannot be curried");
+  assert(!outerInfo.isBlock() && "objc blocks cannot be curried");

   // The uncurried input types.
   SmallVector<TupleTypeElt, 4> inputs;
@@ -226,15 +226,11 @@
     curriedGenericParams->setAllArchetypes(C.AllocateCopy(allArchetypes));
     curriedGenericParams->setOuterParameters(outerParameters);

-    outerInfo.withIsAutoClosure(false);
-    outerInfo.withIsBlock(false);
     return CanPolymorphicFunctionType(
            PolymorphicFunctionType::get(inputType, resultType,
                                         curriedGenericParams,
                                         outerInfo, C));
   } else {
-    outerInfo.withIsAutoClosure(false);
-    outerInfo.withIsBlock(false);
     return CanFunctionType(FunctionType::get(inputType, resultType,
                                              outerInfo, C));
   }


Fixed bug with expiration of leases.

Fixed bug with expiration of leases.

--- backend.cpp
+++ backend.cpp
@@ -131,7 +131,7 @@
 		query = format (
 			"SELECT ip_addr FROM dhcp_host "
 				"WHERE ( mac_addr=x'{0,B16,f0,w2}' OR mac_addr=x'000000000000' ) "
-				"AND ip_addr NOT IN ( SELECT ip_addr FROM dhcp_lease WHERE mac_addr <> x'{0,B16,f0,w2}' ) "
+				"AND ip_addr NOT IN ( SELECT ip_addr FROM dhcp_lease WHERE mac_addr <> x'{0,B16,f0,w2} AND expiration > NOW()' ) "
 				"ORDER BY mac_addr DESC, dhcp_host.ip_addr ASC",
 			as_hex<uint8_t>( hwaddr, 6 ) );
 	}
@@ -284,8 +284,10 @@
 		return false;
 	}

-	query = format( "UPDATE dhcp_lease SET expiration=TIMESTAMPADD( SECOND, {2}, NOW() )"
-			"WHERE ip_addr={0} AND mac_addr = x'{1,B16,f0,w2}'",
+	query = format( "UPDATE dhcp_lease "
+			"SET expiration=TIMESTAMPADD( SECOND, {2}, NOW() ),"
+			"SET mac_addr=x'{1,B16,f0,w2}' "
+			"WHERE ip_addr = {0} AND ( mac_addr = x'{1,B16,f0,w2}' OR expiration <= NOW() )",
 		ntohl( ip ), as_hex<uint8_t>(hwaddr,6), time );

 	if ( mysql_query( db, query.c_str() ) != 0 )


after an epic refactoring fest, finally implement ivar/method lookup in methods, resolving rdar://10682135.

There are still problems in the field of name lookup, but this is progress at least.

Swift SVN r1235

--- lib/Sema/NameBinding.cpp
+++ lib/Sema/NameBinding.cpp
@@ -15,6 +15,7 @@
 //===----------------------------------------------------------------------===//

 #include "swift/Subsystems.h"
+#include "NameLookup.h"
 #include "swift/AST/AST.h"
 #include "swift/AST/Component.h"
 #include "swift/AST/Diagnostics.h"
@@ -270,23 +271,22 @@
   Type ExtendedType = CurFD->getExtensionType();
   if (ExtendedType.isNull()) return 0;

-  // This should find methods even in plus functions.
-
-
-  // FIXME: This is going to have to find properties as well some day, which
-  // requires doing full extension lookup.
-
-
-
-  //ExtendedType.dump();
-  // This is happening after name binding types.
-
-  //(tuple_element_expr type='[byref(implicit)] CGSize' field #1
-  //  (look_through_oneof_expr type='[byref(implicit)] (origin : CGPoint, size : CGSize)'
-  //    (declref_expr type='[byref(implicit)] oneof { CGRect : (origin : CGPoint, size : CGSize)}' decl=t
-
-
-  return 0;
+  // Do a full "dot syntax" name lookup with the implicit 'this' base.
+  MemberLookup Lookup(ExtendedType, UDRE->getName(), *Binder.TU);
+
+  // On failure, this isn't an ivar or method reference.
+  if (!Lookup.isSuccess()) return 0;
+
+
+  // On success, this is a member reference.  Build a VarDecl around the
+  // implicit 'this' VarDecl.
+  VarDecl *ThisDecl = CurFD->getImplicitThisDecl();
+  assert(ThisDecl && "Couldn't find decl for 'this'");
+  Expr *ThisExpr = new (Binder.Context) DeclRefExpr(ThisDecl, SourceLoc(),
+                                                    CurFD->computeThisType());
+
+  return Lookup.createResultAST(ThisExpr, SourceLoc(), UDRE->getLoc(),
+                                Binder.Context);
 }

 /// BindName - Bind an UnresolvedDeclRefExpr by performing name lookup and


Refactor special member function deletion. No functionality change.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@153673 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Sema/SemaDeclCXX.cpp
+++ lib/Sema/SemaDeclCXX.cpp
@@ -4416,7 +4416,8 @@
   }

   // C++11 [class.ctor]p5:
-  // -- any direct or virtual base class [...] has class type M [...] and
+  // -- any direct or virtual base class, or non-static data member with no
+  //    brace-or-equal-initializer, has class type M (or array thereof) and
   //    either M has no default constructor or overload resolution as applied
   //    to M's default constructor results in an ambiguity or in a function
   //    that is deleted or inaccessible
@@ -4425,8 +4426,9 @@
   //    overload resolution, as applied to B's corresponding special member,
   //    results in an ambiguity or a function that is deleted or inaccessible
   //    from the defaulted special member
-  // FIXME: in-class initializers should be handled here
-  if (CSM != Sema::CXXDestructor) {
+  if (CSM != Sema::CXXDestructor &&
+      !(CSM == Sema::CXXDefaultConstructor &&
+        Field && Field->hasInClassInitializer())) {
     Sema::SpecialMemberOverloadResult *SMOR = lookupIn(Class);
     if (!SMOR->hasSuccess())
       return true;
@@ -4521,6 +4523,7 @@
         FieldRecord->isAnonymousStructOrUnion()) {
       bool AllVariantFieldsAreConst = true;

+      // FIXME: Handle anonymous unions declared within anonymous unions.
       for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
                                          UE = FieldRecord->field_end();
            UI != UE; ++UI) {
@@ -4540,70 +4543,13 @@
           FieldRecord->field_begin() != FieldRecord->field_end())
         return true;

-      // Don't try to initialize the anonymous union
+      // Don't check the implicit member of the anonymous union type.
       // This is technically non-conformant, but sanity demands it.
       return false;
     }

-    // When checking a constructor, the field's destructor must be accessible
-    // and not deleted.
-    if (IsConstructor) {
-      CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
-      if (FieldDtor->isDeleted())
-        return true;
-      if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
-          Sema::AR_accessible)
-        return true;
-    }
-
-    // Check that the corresponding member of the field is accessible,
-    // unique, and non-deleted. We don't do this if it has an explicit
-    // initialization when default-constructing.
-    if (!(CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())) {
-      Sema::SpecialMemberOverloadResult *SMOR = lookupIn(FieldRecord);
-      if (!SMOR->hasSuccess())
-        return true;
-
-      CXXMethodDecl *FieldMember = SMOR->getMethod();
-
-      // We need the corresponding member of a union to be trivial so that
-      // we can safely process all members simultaneously.
-      if (inUnion() && !FieldMember->isTrivial())
-        return true;
-
-      if (IsConstructor) {
-        CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
-        if (S.CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
-                                     S.PDiag()) != Sema::AR_accessible)
-        return true;
-
-        // For a move operation, the corresponding operation must actually
-        // be a move operation (and not a copy selected by overload
-        // resolution) unless we are working on a trivially copyable class.
-        if (IsMove && !FieldCtor->isMoveConstructor() &&
-            !FieldRecord->isTriviallyCopyable())
-          return true;
-      } else if (CSM == Sema::CXXDestructor) {
-        CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
-        if (FieldDtor->isDeleted())
-          return true;
-        if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
-            Sema::AR_accessible)
-          return true;
-      } else {
-        assert(IsAssignment && "unexpected kind of special member");
-        if (S.CheckDirectMemberAccess(Loc, FieldMember, S.PDiag())
-              != Sema::AR_accessible)
-          return true;
-
-        // -- for the move assignment operator, a non-static data member with a
-        //    type that does not have a move assignment operator and is not
-        //    trivially copyable.
-        if (IsMove && !FieldMember->isMoveAssignmentOperator() &&
-            !FieldRecord->isTriviallyCopyable())
-          return true;
-      }
-    }
+    if (shouldDeleteForClassSubobject(FieldRecord, FD))
+      return true;
   } else if (IsAssignment && FieldType.isConstQualified()) {
     // C++11 [class.copy]p23:
     // -- a non-static data member of const non-class type (or array thereof)


Point2D: throw out_of_range instead of range_error (so boost can translate it to an IndexError instead of RuntimeError

git-svn-id: f4e1a40f847802203273bde8e26df4d11611876a@3132 44470bb9-56e9-0310-a0f8-c586564d3dc6

--- src/wrapper/bitmap_wrap.cpp
+++ src/wrapper/bitmap_wrap.cpp
@@ -49,7 +49,7 @@
             case 1:
                 return pt.y;
             default:
-                throw std::range_error("Index out of range for Point2D. Must be 0 or 1.");
+                throw std::out_of_range("Index out of range for Point2D. Must be 0 or 1.");
         }
     }


MB-100 Don't backfill temp items into the TAP stream

Change-Id: I175f102944355f962b8c5745b468b6fb2a6dd94c
Reviewed-on: http://review.couchbase.org/19170
Reviewed-by: Michael Wiederhold <a17fed27eaa842282862ff7c1b9c8395a26ac320@couchbase.com>
Tested-by: Chiyoung Seo <8b279095f11c26cc21045fda5a3e51debb005aa9@gmail.com>

--- backfill.cc
+++ backfill.cc
@@ -135,6 +135,11 @@
     if (efficientVBDump && residentRatioBelowThreshold && !v->isResident()) {
         return;
     }
+
+    if (v->isTempItem()) {
+        return;
+    }
+
     queued_item qi(new QueuedItem(v->getKey(), currentBucket->getId(), queue_op_set,
                                   v->getId()));
     queue->push_back(qi);


[ms-inline asm] Rewrite the symbol references as wildcard MCParsedAsmOperands.
A Sema lookup is used to determine the size of the variable, which is in turn
used during wildcard matching.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@165058 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Sema/SemaStmtAsm.cpp
+++ lib/Sema/SemaStmtAsm.cpp
@@ -575,6 +575,43 @@
     // If we had an error parsing the operands, fail gracefully.
     if (HadError) { DEF_SIMPLE_MSASM(EmptyAsmStr); return Owned(NS); }

+    // Rewrite the symbol references as wildcard MCParsedAsmOperands.
+    for (unsigned i = 1, e = Operands.size(); i != e; ++i)
+      if (Operands[i]->isMem()) {
+        StringRef Name = getMSInlineAsmExprName(Pieces[StrIdx][i]);
+
+        // The expr may be a register.  E.g., DWORD PTR [eax]
+        if (Context.getTargetInfo().isValidGCCRegisterName(Name))
+          continue;
+
+        IdentifierInfo *II = getIdentifierInfo(Name, AsmToks,
+                                               AsmTokRanges[StrIdx].first,
+                                               AsmTokRanges[StrIdx].second);
+        // Lookup the identifier.
+        // TODO: Someone with more experience with clang should verify this the
+        // proper way of doing a symbol lookup.
+        DeclarationName DeclName(II);
+        Scope *CurScope = getCurScope();
+        LookupResult R(*this, DeclName, AsmLoc, Sema::LookupOrdinaryName);
+        if (!this->LookupName(R, CurScope, false/*AllowBuiltinCreation*/))
+          assert(0 && "Sema::LookupName failed!");
+        assert (R.isSingleResult() && "Expected a single result?!");
+        NamedDecl *Decl = R.getFoundDecl();
+        switch (Decl->getKind()) {
+        default:
+          assert(0 && "Unknown decl kind.");
+          break;
+        case Decl::Var: {
+        case Decl::ParmVar:
+          VarDecl *Var = cast<VarDecl>(Decl);
+          QualType Ty = Var->getType();
+          // Set the expected operand size.
+          Operands[i]->setMSAsmWildcard(Context.getTypeInfo(Ty).first);
+          break;
+        }
+        }
+      }
+
     // Match the MCInstr.
     unsigned Kind;
     unsigned Opcode;
@@ -619,8 +656,7 @@
       // Expr/Input or Output.
       StringRef Name = getMSInlineAsmExprName(Pieces[StrIdx][i]);

-      // The expr may be a register.
-      // E.g., DWORD PTR [eax]
+      // The expr may be a register.  E.g., DWORD PTR [eax]
       if (Context.getTargetInfo().isValidGCCRegisterName(Name))
         continue;


messages when starting/stopping playback

--- backlog.cpp
+++ backlog.cpp
@@ -155,6 +155,15 @@

 	bool isInChan = CBacklogMod::inChan(Channel);

+	if(printedLines == 0) {
+		PutModule("No log files found for window " + Channel + " in " + DirPath + "/");
+		return;
+	} else if (isInChan) {
+		m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + Channel + " :" + "Backlog playback...", GetClient());
+	} else {
+		PutModule("*** Backlog playback...");
+	}
+
 	// now actually print
 	for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) {
 		 if(isInChan) {
@@ -169,8 +178,10 @@
 		 }
 	}

-	if(printedLines == 0) {
-		PutModule("No log files found for window " + Channel + " in " + DirPath + "/");
+	if (isInChan) {
+		m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + Channel + " :" + "Playback complete.", GetClient());
+	} else {
+		PutModule("*** Playback complete.");
 	}
 }


Performance: check for null string directly isntead of calling XMLString::stringLen

git-svn-id: 95233098a850bdf68e142cb551b6b3e756f38fc7@174243 13f79535-47bb-0310-9956-ffa450edef68

--- src/xercesc/util/XMLUri.cpp
+++ src/xercesc/util/XMLUri.cpp
@@ -438,7 +438,7 @@
         // string or a fragment (e.g. "?y" or "#s") -
         // see <http://www.ics.uci.edu/~fielding/url/test1.html> which
         // identified this as a bug in the RFC
-        if ((!fPath || XMLString::stringLen(fPath) == 0) &&
+        if ((!fPath || !*fPath) &&
             fScheme == 0 &&
             fHost == 0)
         {
@@ -483,7 +483,7 @@
         }

         // check for absolute path - RFC 2396 5.2 #5
-        if (XMLString::stringLen(fPath) > 0 &&
+        if ((fPath && *fPath) &&
             XMLString::startsWith(fPath, SINGLE_SLASH))
         {
             return;
@@ -654,13 +654,13 @@
     ArrayJanitor<XMLCh> portName(portStr);
     int port = -1;

-    if ((XMLString::stringLen(host) > 0) &&   // non empty host
+    if ((host && *host) &&   // non empty host
         (index != -1)                    &&   // ":" found
         (start < end)                     )   // ":" is not the last
     {
         XMLString::subString(portStr, &(uriSpec[start]), 0, end-start);

-        if (XMLString::stringLen(portStr) > 0)
+        if (portStr && *portStr)
         {
             try
             {
@@ -936,7 +936,7 @@

     //sometimes we get passed a empty string rather than a null.
     //Other procedures rely on it being null
-    if(XMLString::stringLen(newUserInfo) > 0) {
+    if(newUserInfo && *newUserInfo) {
         fUserInfo = XMLString::replicate(newUserInfo);
     }

@@ -1246,7 +1246,7 @@
     XMLCh* tmpAddr = XMLString::replicate(addrString);
     ArrayJanitor<XMLCh>  janName(tmpAddr);
     XMLString::trim(tmpAddr);
-    if ((XMLString::stringLen(tmpAddr) == 0) ||
+    if ((!tmpAddr || !*tmpAddr) ||
         (XMLString::stringLen(tmpAddr) > 255) )
         return false;


Remove dead code introduced in r165751.

Remove dead code introduced in r165751.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@165772 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Sema/SemaStmtAsm.cpp
+++ lib/Sema/SemaStmtAsm.cpp
@@ -407,8 +407,7 @@
 static bool buildMSAsmStrings(Sema &SemaRef,
                               SourceLocation AsmLoc,
                               ArrayRef<Token> AsmToks,
-                              std::vector<std::string> &AsmStrings,
-                     std::vector<std::pair<unsigned,unsigned> > &AsmTokRanges) {
+                              std::vector<std::string> &AsmStrings) {
   assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");

   SmallString<512> Asm;
@@ -421,7 +420,6 @@
     if (isNewAsm) {
       if (i) {
         AsmStrings.push_back(Asm.str());
-        AsmTokRanges.push_back(std::make_pair(startTok, i-1));
         startTok = i;
         Asm.clear();
       }
@@ -441,7 +439,6 @@
     Asm += Spelling;
   }
   AsmStrings.push_back(Asm.str());
-  AsmTokRanges.push_back(std::make_pair(startTok, AsmToks.size()-1));

   return false;
 }
@@ -476,8 +473,7 @@
   if (AsmToks.empty()) { DEF_SIMPLE_MSASM(EmptyAsmStr); return Owned(NS); }

   std::vector<std::string> AsmStrings;
-  std::vector<std::pair<unsigned,unsigned> > AsmTokRanges;
-  if (buildMSAsmStrings(*this, AsmLoc, AsmToks, AsmStrings, AsmTokRanges))
+  if (buildMSAsmStrings(*this, AsmLoc, AsmToks, AsmStrings))
     return StmtError();

   std::vector<std::vector<StringRef> > Pieces(AsmStrings.size());


added super+ in xlinkwrapper mapping usb speed vector

--- src/xlink/xlink_wrapper.cpp
+++ src/xlink/xlink_wrapper.cpp
@@ -342,7 +342,7 @@

 std::string XLinkWrapper::getUSBSpeed(){
     assert(_device_link_id != -1);
-    std::vector<std::string> speed_str = {"Unknown", "Low/1.5Mbps", "Full/12Mbps", "High/480Mbps", "Super/5000Mbps"};
+    std::vector<std::string> speed_str = {"Unknown", "Low/1.5Mbps", "Full/12Mbps", "High/480Mbps", "Super/5000Mbps", "Super+/10000Mbps"};
     return speed_str[XLinkGetUSBSpeed(_device_link_id)];
 }


draw multiseries horizontal bars

draw multiseries horizontal bars

--- barchart.cc
+++ barchart.cc
@@ -238,25 +238,21 @@

     /* multi series unstacked */
     else {
-      /*
-      auto num_series = getSeries().size();
       auto draw_y_multi = draw_y;
-      auto draw_height_multi = draw_height / num_series;
+      auto draw_height_multi = draw_height / num_series_;
       for (int i = 0; i < bar.ys.size(); i++) {
-        auto& y_val = bar.ys[i];
-        auto y_min = y_val.first;
-        auto y_max = y_val.second;
-        auto draw_x = padding_left_ + y_min * inner_width_;
-        auto draw_width = (y_max - y_min) * inner_width_;
+      auto y_min = y_domain->scale(bar.ys[i].first);
+      auto y_max = y_domain->scale(bar.ys[i].second);
+        auto draw_x = padding_left + y_min * inner_width;
+        auto draw_width = (y_max - y_min) * inner_width;
         target->drawRect(
             draw_x,
             draw_y_multi,
             draw_width,
             draw_height_multi * (1.0f - kBarPadding * 0.5f),
-            colorName(i));
+            "color0");
         draw_y_multi += (draw_height_multi * (1.0f + kBarPadding * 0.5f));
       }
-      */
     }

     draw_y += bar_height + bar_padding;


Support opaque type printing a little bit at least

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@2748 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/VMCore/AsmWriter.cpp
+++ lib/VMCore/AsmWriter.cpp
@@ -481,6 +481,8 @@
   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
     Out << "[" << ATy->getNumElements() << " x ";
     printType(ATy->getElementType()) << "]";
+  } else if (OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
+    Out << OTy->getDescription();
   } else {
     assert(Ty->isPrimitiveType() && "Unknown derived type!");
     printType(Ty);


Make printing of metadata more robust when function is not found (which is the normal situation for non function-local metadata)

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@93748 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/VMCore/AsmWriter.cpp
+++ lib/VMCore/AsmWriter.cpp
@@ -2064,7 +2064,7 @@
   } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
     Function *F = N->getFunction();
     SlotTracker SlotTable(F);
-    AssemblyWriter W(OS, SlotTable, getModuleFromVal(F), AAW);
+    AssemblyWriter W(OS, SlotTable, F ? getModuleFromVal(F) : 0, AAW);
     W.printMDNodeBody(N);
   } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
     SlotTracker SlotTable(N->getParent());


Reuse PrintEscapedString for printing names in .ll
 - One functionality change, '\\' in a name is now printed as a hex
   escape instead of "\\\\". This is consistent with other users of
   PrintEscapedString.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@58343 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/VMCore/AsmWriter.cpp
+++ lib/VMCore/AsmWriter.cpp
@@ -60,6 +60,25 @@
   return 0;
 }

+// PrintEscapedString - Print each character of the specified string, escaping
+// it if it is not printable or if it is an escape char.
+static void PrintEscapedString(const char *Str, unsigned Length,
+                               raw_ostream &Out) {
+  for (unsigned i = 0; i != Length; ++i) {
+    unsigned char C = Str[i];
+    if (isprint(C) && C != '\\' && C != '"' && isprint(C))
+      Out << C;
+    else
+      Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
+  }
+}
+
+// PrintEscapedString - Print each character of the specified string, escaping
+// it if it is not printable or if it is an escape char.
+static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
+  PrintEscapedString(Str.c_str(), Str.size(), Out);
+}
+
 enum PrefixType {
   GlobalPrefix,
   LabelPrefix,
@@ -82,7 +101,7 @@
   }

   // Scan the name to see if it needs quotes first.
-  bool NeedsQuotes = NameStr[0] >= '0' && NameStr[0] <= '9';
+  bool NeedsQuotes = isdigit(NameStr[0]);
   if (!NeedsQuotes) {
     for (unsigned i = 0; i != NameLen; ++i) {
       char C = NameStr[i];
@@ -102,18 +121,7 @@
   // Okay, we need quotes.  Output the quotes and escape any scary characters as
   // needed.
   OS << '"';
-  for (unsigned i = 0; i != NameLen; ++i) {
-    char C = NameStr[i];
-    if (C == '\\') {
-      OS << "\\\\";
-    } else if (C != '"' && isprint(C)) {
-      OS << C;
-    } else {
-      OS << '\\';
-      OS << hexdigit((C >> 4) & 0x0F);
-      OS << hexdigit((C >> 0) & 0x0F);
-    }
-  }
+  PrintEscapedString(NameStr, NameLen, OS);
   OS << '"';
 }

@@ -576,21 +584,6 @@
     std::map<const Type *, std::string> TypeNames;
     fillTypeNameTable(M, TypeNames);
     printTypeInt(Out, Ty, TypeNames);
-  }
-}
-
-// PrintEscapedString - Print each character of the specified string, escaping
-// it if it is not printable or if it is an escape char.
-static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
-  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
-    unsigned char C = Str[i];
-    if (isprint(C) && C != '"' && C != '\\') {
-      Out << C;
-    } else {
-      Out << '\\'
-          << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
-          << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
-    }
   }
 }


Eliminate nightmarish API

Eliminate nightmarish API

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@12214 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/VMCore/Constants.cpp
+++ lib/VMCore/Constants.cpp
@@ -1119,26 +1119,3 @@
 const char *ConstantExpr::getOpcodeName() const {
   return Instruction::getOpcodeName(getOpcode());
 }
-
-unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
-  // Uses of constant pointer refs are global values, not constants!
-  if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
-    GlobalValue *NewGV = cast<GlobalValue>(NewV);
-    GlobalValue *OldGV = CPR->getValue();
-
-    assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
-    Operands[0] = NewGV;
-    OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
-    return 1;
-  } else {
-    Constant *NewC = cast<Constant>(NewV);
-    unsigned NumReplaced = 0;
-    for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
-      if (Operands[i] == OldV) {
-        ++NumReplaced;
-        Operands[i] = NewC;
-      }
-    return NumReplaced;
-  }
-}
-