Search Results

Search found 16 results on 1 pages for 'streambuf'.

Page 1/1 | 1 

  • Deriving streambuf or basic_ostringstream?

    - by Helltone
    Hi, I want to derive a stringstream so that I can use the operator<< to construct a message which will then be thrown. The API would look like: error("some text") << " more text " << 42 << std::endl; This should do a throw "some text more text 42" So what I did is make an errorbuf (inheriting from streambuf) which overloads the 'overflow' method and then create an ostream(&errorbuf). I wonder if I shouldn't instead inherit from basic_ostringstream or something...

    Read the article

  • Can't insert a number into a C++ custom streambuf/ostream

    - by 0xbe5077ed
    I have written a custom std::basic_streambuf and std::basic_ostream because I want an output stream that I can get a JNI string from in a manner similar to how you can call std::ostringstream::str(). These classes are quite simple. namespace myns { class jni_utf16_streambuf : public std::basic_streambuf<char16_t> { JNIEnv * d_env; std::vector<char16_t> d_buf; virtual int_type overflow(int_type); public: jni_utf16_streambuf(JNIEnv *); jstring jstr() const; }; typedef std::basic_ostream<char16_t, std::char_traits<char16_t>> utf16_ostream; class jni_utf16_ostream : public utf16_ostream { jni_utf16_streambuf d_buf; public: jni_utf16_ostream(JNIEnv *); jstring jstr() const; }; // ... } // namespace myns In addition, I have made four overloads of operator<<, all in the same namespace: namespace myns { // ... utf16_ostream& operator<<(utf16_ostream&, jstring) throw(std::bad_cast); utf16_ostream& operator<<(utf16_ostream&, const char *); utf16_ostream& operator<<(utf16_ostream&, const jni_utf16_string_region&); jni_utf16_ostream& operator<<(jni_utf16_ostream&, jstring); // ... } // namespace myns The implementation of jni_utf16_streambuf::overflow(int_type) is trivial. It just doubles the buffer width, puts the requested character, and sets the base, put, and end pointers correctly. It is tested and I am quite sure it works. The jni_utf16_ostream works fine inserting unicode characters. For example, this works fine and results in the stream containing "hello, world": myns::jni_utf16_ostream o(env); o << u"hello, wor" << u'l' << u'd'; My problem is as soon as I try to insert an integer value, the stream's bad bit gets set, for example: myns::jni_utf16_ostream o(env); if (o.badbit()) throw "bad bit before"; // does not throw int32_t x(5); o << x; if (o.badbit()) throw "bad bit after"; // throws :( I don't understand why this is happening! Is there some other method on std::basic_streambuf I need to be implementing????

    Read the article

  • How do I build a filtered_streambuf based on basic_streambuf?

    - by swestrup
    I have a project that requires me to insert a filter into a stream so that outgoing data will be modified according to the filter. After some research, it seems that what I want to do is create a filtered_streambuf like this: template <class StreamBuf class filtered_streambuf: public StreamBuf { ... } And then insert a filtered_streambuf<> into whichever stream I need to be filtered. My problem is that I don't know what invariants I need to maintain while filtering a stream, in order to ensure that Derived classes can work as expected. In particular, I may find I have filtered_streambufs built over other filtered_streambufs. All the various stream inserters, extractors and manipulators work as expected. The trouble is that I just can't seem to work out what the minimal interface is that I need to supply in order to guarantee that an iostream will have what it needs to work correctly. In particular, do I need to fake the movement of the protected pointer variables, or not? Do I need a fake data buffer, or not? Can I just override the public functions, rewriting them in terms of the base streambuf, or is that too simplistic?

    Read the article

  • C++: Best text accumulator

    - by MInner
    Text gets accumulates piecemeal before being sent to client. Now we use own class that allocates memory for each piece as char massive. (Anyway, works like char[][] + std::list<char*>). Then we build the whole string, convert it into std::sting and then create boost::asio::streambuf using it. That's slow enough, I assume. Correct me if I'm wrong. I know, in many cases simple FILE type from stdio.h is used. How does it works? Allocates memory at every write into it. So, is it faster and is there any way to read into boost::asio::streambuf from FILE?

    Read the article

  • Reading from serial port with Boost Asio?

    - by trikri
    Hi! I'm going to check for incoming messages (data packages) on the serial port, using Boost Asio. Each message will start with a header that is one byte long, and will specify which type of the message has been sent. Each different type of message has an own length. The function I'm about to write should check for new incoming messages continually, and when it finds one it should read it, and then some other function should parse it. I thought that the code might look something like this: void check_for_incoming_messages() { boost::asio::streambuf response; boost::system::error_code error; std::string s1, s2; if (boost::asio::read(port, response, boost::asio::transfer_at_least(0), error)) { s1 = streambuf_to_string(response); int msg_code = s1[0]; if (msg_code < 0 || msg_code >= NUM_MESSAGES) { // Handle error, invalid message header } if (boost::asio::read(port, response, boost::asio::transfer_at_least(message_lengths[msg_code]-s1.length()), error)) { s2 = streambuf_to_string(response); // Handle the content of s1 and s2 } else if (error != boost::asio::error::eof) { throw boost::system::system_error(error); } } else if (error != boost::asio::error::eof) { throw boost::system::system_error(error); } } Is boost::asio::streambuf is the right thing to use? And how do I extract the data from it so I can parse the message? I also want to know if I need to have a separate thread which only calls this function, so that it get called more often? Isn't there a risk for loosing data in between two calls to the function otherwise, because so much data comes in that it can't be stored in the serial ports memory? I'm using Qt as a widget toolkit and I don't really know how long time it needs to process all it's events.

    Read the article

  • std::ostream interface to an OLE IStream

    - by PaulH
    I have a Visual Studio 2008 C++ application using IStreams. I would like to use the IStream connection in a std::ostream. Something like this: IStream* stream = /*create valid IStream instance...*/; IStreamBuf< WIN32_FIND_DATA > sb( stream ); std::ostream os( &sb ); WIN32_FIND_DATA d = { 0 }; // send the structure along the IStream os << d; To accomplish this, I've implemented the following code: template< class _CharT, class _Traits > inline std::basic_ostream< _CharT, _Traits >& operator<<( std::basic_ostream< _CharT, _Traits >& os, const WIN32_FIND_DATA& i ) { const _CharT* c = reinterpret_cast< const _CharT* >( &i ); const _CharT* const end = c + sizeof( WIN32_FIND_DATA ) / sizeof( _CharT ); for( c; c < end; ++c ) os << *c; return os; } template< typename T > class IStreamBuf : public std::streambuf { public: IStreamBuf( IStream* stream ) : stream_( stream ) { setp( reinterpret_cast< char* >( &buffer_ ), reinterpret_cast< char* >( &buffer_ ) + sizeof( buffer_ ) ); }; virtual ~IStreamBuf() { sync(); }; protected: traits_type::int_type FlushBuffer() { int bytes = std::min< int >( pptr() - pbase(), sizeof( buffer_ ) ); DWORD written = 0; HRESULT hr = stream_->Write( &buffer_, bytes, &written ); if( FAILED( hr ) ) { return traits_type::eof(); } pbump( -bytes ); return bytes; }; virtual int sync() { if( FlushBuffer() == traits_type::eof() ) return -1; return 0; }; traits_type::int_type overflow( traits_type::int_type ch ) { if( FlushBuffer() == traits_type::eof() ) return traits_type::eof(); if( ch != traits_type::eof() ) { *pptr() = ch; pbump( 1 ); } return ch; }; private: /// data queued up to be sent T buffer_; /// output stream IStream* stream_; }; // class IStreamBuf Yes, the code compiles and seems to work, but I've not had the pleasure of implementing a std::streambuf before. So, I'd just like to know if it's correct and complete. Thanks, PaulH

    Read the article

  • Convert C++Builder AnsiString to std::string via boost::lexical_cast

    - by David Klein
    For a school assignment I have to implement a project in C++ using Borland C++ Builder. As the VCL uses AnsiString for all GUI Components I have to convert all of my std::strings to AnsiString for the sake of displaying. std::string inp = "Hello world!"; AnsiString outp(inp.c_str()); works of course but is a bit tedious to write and code duplication I want to avoid. As we use Boost in other contexts I decided to provide some helper functions go get boost::lexical_cast to work with AnsiString. Here is my implementation so far: std::istream& operator>>(std::istream& istr, AnsiString& str) { istr.exceptions(std::ios::badbit | std::ios::failbit | std::ios::eofbit); std::string s; std::getline(istr,s); str = AnsiString(s.c_str()); return istr; } In the beginning I got Access Violation after Access Violation but since I added the .exceptions() stuff the picture gets clearer. When the conversion is performed I get the following Exception: ios_base::eofbit set [Runtime Error/std::ios_base::failure] Does anyone have an idea how to fix it and can explain why the error occurs? My C++ experience is very limited. The conversion routine the other way round would be: std::ostream& operator<<(std::ostream& ostr,const AnsiString& str) { ostr << (str.c_str()); return ostr; } Maybe someone will spot an error here too :) With best regards! Edit: At the moment I'm using the edited version of Jem, it works in the beginning. After a while of using the programm the Borland Codeguard mentions some pointer arithmetic in already freed regions. Any ideas how this could be related? The Codeguard log (I'm using the german version, translations marked with stars): ------------------------------------------ Fehler 00080. 0x104230 (r) (Thread 0x07A4): Zeigerarithmetik in freigegebenem Speicher: 0x0241A238-0x0241A258. **(pointer arithmetic in freed region)** | d:\program files\borland\bds\4.0\include\dinkumware\sstream Zeile 126: | { // not first growth, adjust pointers | _Seekhigh = _Seekhigh - _Mysb::eback() + _Ptr; |> _Mysb::setp(_Mysb::pbase() - _Mysb::eback() + _Ptr, | _Mysb::pptr() - _Mysb::eback() + _Ptr, _Ptr + _Newsize); | if (_Mystate & _Noread) Aufrufhierarchie: **(stack-trace)** 0x00411731(=FOSChampion.exe:0x01:010731) d:\program files\borland\bds\4.0\include\dinkumware\sstream#126 0x00411183(=FOSChampion.exe:0x01:010183) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#465 0x0040933D(=FOSChampion.exe:0x01:00833D) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#151 0x00405988(=FOSChampion.exe:0x01:004988) d:\program files\borland\bds\4.0\include\dinkumware\ostream#679 0x00405759(=FOSChampion.exe:0x01:004759) D:\Projekte\Schule\foschamp\src\Server\Ansistringkonverter.h#31 0x004080C9(=FOSChampion.exe:0x01:0070C9) D:\Projekte\Schule\foschamp\lib\boost_1_34_1\boost/lexical_cast.hpp#151 Objekt (0x0241A238) [Größe: 32 Byte] war erstellt mit new **(Object was created with new)** | d:\program files\borland\bds\4.0\include\dinkumware\xmemory Zeile 28: | _Ty _FARQ *_Allocate(_SIZT _Count, _Ty _FARQ *) | { // allocate storage for _Count elements of type _Ty |> return ((_Ty _FARQ *)::operator new(_Count * sizeof (_Ty))); | } | Aufrufhierarchie: **(stack-trace)** 0x0040ED90(=FOSChampion.exe:0x01:00DD90) d:\program files\borland\bds\4.0\include\dinkumware\xmemory#28 0x0040E194(=FOSChampion.exe:0x01:00D194) d:\program files\borland\bds\4.0\include\dinkumware\xmemory#143 0x004115CF(=FOSChampion.exe:0x01:0105CF) d:\program files\borland\bds\4.0\include\dinkumware\sstream#105 0x00411183(=FOSChampion.exe:0x01:010183) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#465 0x0040933D(=FOSChampion.exe:0x01:00833D) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#151 0x00405988(=FOSChampion.exe:0x01:004988) d:\program files\borland\bds\4.0\include\dinkumware\ostream#679 Objekt (0x0241A238) war Gelöscht mit delete **(Object was deleted with delete)** | d:\program files\borland\bds\4.0\include\dinkumware\xmemory Zeile 138: | void deallocate(pointer _Ptr, size_type) | { // deallocate object at _Ptr, ignore size |> ::operator delete(_Ptr); | } | Aufrufhierarchie: **(stack-trace)** 0x004044C6(=FOSChampion.exe:0x01:0034C6) d:\program files\borland\bds\4.0\include\dinkumware\xmemory#138 0x00411628(=FOSChampion.exe:0x01:010628) d:\program files\borland\bds\4.0\include\dinkumware\sstream#111 0x00411183(=FOSChampion.exe:0x01:010183) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#465 0x0040933D(=FOSChampion.exe:0x01:00833D) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#151 0x00405988(=FOSChampion.exe:0x01:004988) d:\program files\borland\bds\4.0\include\dinkumware\ostream#679 0x00405759(=FOSChampion.exe:0x01:004759) D:\Projekte\Schule\foschamp\src\Server\Ansistringkonverter.h#31 ------------------------------------------ Ansistringkonverter.h is the file with the posted operators and line 31 is: std::ostream& operator<<(std::ostream& ostr,const AnsiString& str) { ostr << (str.c_str()); **(31)** return ostr; } Thanks for your help :)

    Read the article

  • CodePlex Daily Summary for Wednesday, June 16, 2010

    CodePlex Daily Summary for Wednesday, June 16, 2010New ProjectsAtomFeedBuilder: Simple and lightweight Atom feed builder. Developed in VB.Net.Cable and Wire harness tester: If you build lots of cable/wire harness' you know that testing them is a pain. I have wanted an automated cable tester for a while now but commerci...Carmenta Engine Power Pack: The target of Carmenta Engine Power Pack is to provide extensions, utilities and wrapper classes that allows developers to work more efficiently w...Customer Book: Customer Book, its like address book with facility for generating quotation for a business or a supplier to the clients.Dialector: Using this program, you can convert pure Turkish texts into different dialects; such as: Emmi, Kufurbaz, Kusdili, Laz, Peltek, Tiki, and many more....Downline Commision Generator: Analyze the compensations plan of the organizations in multi-level marketing or network marketing. Check with this tool the commision plan of the c...EmbeddedSpark 2010 Project M: Project M is a system for seamlessly interfacing a tabletop interface to portable devices placed upon it. Using image recognition and projectors, P...Event Log Creator by eVestment Alliance: Provides a simple utility to create a new source and log in the Windows event log. The utility checks if the current user is an administrator, and...ExchangeHog: Desktop/daemon application that aggregates emails from multiple pop3-accounts into single Microsoft Exchange 2010 account. For users receiving ema...Extra Time Calculator: Extra Time Calculator allows exam end times to be easily calculated for students receiving an extra time accommodation.Generic WCF Hosting Service: The Generic Host Service provides a simple, reusable, and reliable mechanism for hosting WCF services. Google Storage for .NET: Google Storage for .NET (GSN) is an open source library that provides .NET developers with easy access to the Google Storage API. The library allo...Helium: The Helium XNA game engine is a light portable game engine designed to work on many platforms and soon to be expanded on more. Currently the helium...IconizedButton Control Set: ASP.NET WebForms IconizedButton Custom Control Set. Replaces the dull Button/LinkButton/HyperLink controls with styling and left and right aligned...Jedi Council PM List: Allows for users to process Private Message Lists on the Jedi Council forums for TheForce.Net.JetPumpDesign: 本软件为蒸气喷射泵设计计算软件 作者:申阳 单位:西安交通大学过程装备与控制工程61班log4Nez: An high personalized implementation of a logging libraryMutantFramework: Provides a common set of building blocks for building enterprise applicationsNUnit Add-in for Growl Notifications: NUnit add-in which allows to send notifications to Growl when test run is started or finished, when a first test failure occurs and so on.Object Reports: Object Reports is a "proof of concept" application which provides users the ability to visualy build queries based on data stored in the relational...openTrionyx: openTrionyx is a set of tools to make easier web application development. Includes Data, Web and plain text documents tools. Developed in C#, compl...Partial Rendering control for MVC 2: This project shows a web custom control that allow to have partial rendering using async post-back (through JQuery) in a MVC 2 web application.PowerGUI Visual Studio Extension: The PowerGUI Visual Studio Extension exposes PowerGUI as an editor in Visual Studio. PowerShell developers can now write scripts directly in Visual...PowerShell Script Provider: Write your own PowerShell provider using only script, no C# required. Module definition is provided by a Windows PowerShell 2.0 Module, which may b...Scholar: Scholar is a solution/framework for .Net developers to help with the creation of distributed data processing (think SETI@home style apps). It is in...scrabb: Scrabb help people play scrabble over net.SharePointNuke: A DotNetNuke module that connects to a SharePoint server using web services API and displays the content of a specified list. SolidWorksBackConverter: a Project to Convert a solidwork file to an older version Soma - Sql Oriented MApping framework: Sql Oriented MApping framework.SPCreate: SPCreate auto store procedure creator. It's developed in c#. SpCreate as output ADO.NET Class (C# or VB.Net) and SQL Server or MS Access Store pro...std::streambuf wrapper for COM IStream: This provides a subclass of std::streambuf that wraps a COM IStream, so you can use an IStream with any C++ code that uses iostreams or the STL alg...VACID solutions: Solutions of verification problems posed in paper "Verification of Ample Correctness of Invariants of Data-structures". Developed with various tool...Viewer: Our Goal is to create a C# project that will centeralize Image and Movie Viewing in a forms application, It will also have a Specialized Webbrowser...vsXPathTester: vsXPathTester is a utility for Developer. This help them load XML file and the run their XPath Query. The Resultant is shown in window. It save the...New Releases.Net Max Framework: Version 1.0.0: Version 1.0.0 - EstableAndrew's XNA Helpers: V1.2: Features upgraded features based off of the V1.1 code for both X86 and XBOX Additions/Changes Reworked the Texture2D and Rectangle extender namesp...BaseCalendar: BaseControls 1.2: BaseControls 1.2 contains the BaseCalendar ASP.NET control. Changes: 1.2 Exposed EffectiveVisibleDate and FirstVisibleDay methods 1.1 Rendering ...Customer Book: Customer Book Code: Bronze Release PostgreSQL database dump for Customer Book. Open PgAdmin III and restore the database dump into your server. Notice User Name for t...Data Connection Suite: Data Connections Suite v1.0.0.0: This is the first release of this incomplete component, but good enought to use in a production environment (it's what we do).DigitArchive: Build 8: Now the software works on .NET 3.5 and above. So if you have Windows 7 it installs without any pre-requisites. Changes: -Works on .NET 3.5 -Now t...Doom 64 Ex (SVN Builds): Doom 64 Ex r-738: Finally a new build after so many months. There are way to many updates to even begin to write about here just download and frag away. There is a s...DotNetNuke® Media: 03.03.00a: This release is Beta!! There is no guaranteed upgrade path to the 03.03.00 release version! Please use this to help us and test what we have. Repor...Downline Commision Generator: Downline Commision Generator: Downline Commision GeneratorElmah2 : An extensable error logger for ASP.net: 1.0 Beta 1: This is a beta release be sure to report any errors etc. Be sure to check out the documentation tab on information on how to install and configure...EPiServer Template Foundation: First compiled release: First compiled release for experimenting only! :) An introductory post will be published shortly on the blog.Helium: Initial Release: This is the initial release of the Helium Engine. Please check out the documentation link for information on how to use the engine. To see a ful...IconizedButton Control Set: IconizedButton Control Set: Taking a line from Google's play book - marking everything as Beta. Seriously, I'd like to hear some feedback before moving the Development Status...JetPumpDesign: JetPumpDesign 1.0: 当前的软件可以设计5级以内的蒸汽喷射泵。Microsoft Silverlight Analytics Framework: Version 1.4.4 Installer: Tools TargetingVisual Studio 2010 Expression Blend 4 (part of Expression Studio 4) Analytics Services Included Vendor Behavior Silverlight 3...NHibernate Sidekick Library: 0.7.0: Added a few methods for use with the NHibernate 2nd level cache (EvictAllObjectsFromCache and EvictPersistentClass). I also added the boolean optio...NHibernate Sidekick Library: 0.7.5: Fix for http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactionsNito.KitchenSink: Version 9: Dependencies Nito.Linq 0.6 Beta (released 2010-06-14) Rx 1.0.2563.0 (released 2010-06-09) Supported Platforms .NET 4.0 Client Profile, with Rx. ...NQueue: Version 1.0.0.0: Version 1.0.0.0NUnit Add-in for Growl Notifications: NUnit Add-in for Growl Notifications 1.0 build 0: The very first stable releasePartial Rendering control for MVC 2: Partial Rendering control for MVC 2: Here there is the source code and a MVC 2 web site as testPowerShell Script Provider: PSProvider 0.1: Requires PowerShell 2.0 RTM The functions in the attached ps1 script are the bare minimum for a working container-style provider (no subfolders.) ...Quick Performance Monitor: Version 1.4.3: Fixed issue where if an instance name contains backslash characters (\) the program would not load the performance counter properly. Also added sta...SharePointNuke: SharePointNuke 2.00.08: SharePointNuke 2.00.08 - Binary DotNetNuke 5.x module.Skype Voice Changer: 1.0 Updated Sample Code: This updated release is the accompanying code for the Skype Voice Changer article on Coding4Fun. Changes in this release: Added support for PreEmp...std::streambuf wrapper for COM IStream: Beta release (tested in a commercial project): This code has been tested in a custom Windows Search filter and property handler I wrote for a proprietary binary format. There may be some bugs, b...Sunlit World Scheme: Sunlit World Scheme - 20100615 - source and binary: This is the result of building the current source code in Debug mode. The source code is included. The binaries are in the SchemeCode folder along...Timo-Design / 40FINGERS DotNetNuke® Skinning Extensions: Style Helper Skin Object Beta: The 40FINGERS Style Helper Skin object allows you to add CSS and Javascript links and meta tags to the head of your page. It can also remove CSS l...Umbraco CMS: Umbraco 4.1 RC: This is the final test version of Umbraco 4.1 before the final release. PLEASE BE AWARE THAT UMBRACO 4.1 RC IS A .NET 4.0 RELEASE AND WON'T WORK O...VCC: Latest build, v2.1.30615.0: Automatic drop of latest buildWCF 4 Templates for Visual Studio 2010: UserNameForCertificate Template: Produces a WCF service application supporting username and password authentication, relying on message security to protect messages en route. Suppl...WCF 4 Templates for Visual Studio 2010: UserNameOverHttps Template: Produces a WCF service application supporting username and password authentication over HTTPS/SSL, relying on transport security to protect message...xUnit.net Contrib: xunitcontrib 0.4.1 alpha (ReSharper 5.1.1709 only): xunitcontrib release 0.4.1 (ReSharper runner) This release targets the current nightly build of ReSharper 5.1's Early Access Programme (build 1709)...Most Popular ProjectsCommunity Forums NNTP bridgeRIA Services EssentialsNeatUploadBxf (Basic XAML Framework).NET Transactional File ManagerSOLID by exampleSSIS Expression Editor & TesterWEI ShareChirpy - VS Add In For Handling Js, Css, and DotLess FilesASP.NET MVC Time PlannerMost Active ProjectsdotSpatialRhyduino - Arduino and Managed CodeCassandraemonpatterns & practices – Enterprise LibraryCommunity Forums NNTP bridgeLightweight Fluent Workflowpatterns & practices: Enterprise Library ContribNB_Store - Free DotNetNuke Ecommerce Catalog ModuleBlogEngine.NETjQuery Library for SharePoint Web Services

    Read the article

  • Recommendations for a C++ polymorphic, seekable, binary I/O interface

    - by Trevor Robinson
    I've been using std::istream and ostream as a polymorphic interface for random-access binary I/O in C++, but it seems suboptimal in numerous ways: 64-bit seeks are non-portable and error-prone due to streampos/streamoff limitations; currently using boost/iostreams/positioning.hpp as a workaround, but it requires vigilance Missing operations such as truncating or extending a file (ala POSIX ftruncate) Inconsistency between concrete implementations; e.g. stringstream has independent get/put positions whereas filestream does not Inconsistency between platform implementations; e.g. behavior of seeking pass the end of a file or usage of failbit/badbit on errors Don't need all the formatting facilities of stream or possibly even the buffering of streambuf streambuf error reporting (i.e. exceptions vs. returning an error indicator) is supposedly implementation-dependent in practice I like the simplified interface provided by the Boost.Iostreams Device concept, but it's provided as function templates rather than a polymorphic class. (There is a device class, but it's not polymorphic and is just an implementation helper class not necessarily used by the supplied device implementations.) I'm primarily using large disk files, but I really want polymorphism so I can easily substitute alternate implementations (e.g. use stringstream instead of fstream for unit tests) without all the complexity and compile-time coupling of deep template instantiation. Does anyone have any recommendations of a standard approach to this? It seems like a common situation, so I don't want to invent my own interfaces unnecessarily. As an example, something like java.nio.FileChannel seems ideal. My best solution so far is to put a thin polymorphic layer on top of Boost.Iostreams devices. For example: class my_istream { public: virtual std::streampos seek(stream_offset off, std::ios_base::seekdir way) = 0; virtual std::streamsize read(char* s, std::streamsize n) = 0; virtual void close() = 0; }; template <class T> class boost_istream : public my_istream { public: boost_istream(const T& device) : m_device(device) { } virtual std::streampos seek(stream_offset off, std::ios_base::seekdir way) { return boost::iostreams::seek(m_device, off, way); } virtual std::streamsize read(char* s, std::streamsize n) { return boost::iostreams::read(m_device, s, n); } virtual void close() { boost::iostreams::close(m_device); } private: T m_device; };

    Read the article

  • Serializing network messages

    - by mtsvetkov
    I am writing a network wrapper around boost::asio and was wondering what is a good and simple way to serialize my messages. I have a message factory which can take care of dispatching the data to the correct builder, but I want to know if there are any established solutions for getting the binary data on the sender side and consequently passing the data for deserialization on the receiver end. Some options I've explored are: passing a pointer to a char[] to the serialize/deserialize functions (for serialize to write to, and deserialize to read from), but it's difficult to enforce buffer size this way; building on that, I decided to have the serialize function return a boost::asio::mutable_buffer, however ownership of the memory gets blurred between multiple classes, as the network wrapper needs to clean up the memory allocated by the message builder. I have also seen solutions involving streambuf's and stringstream's, but manipulating binary data in terms of its string representation is something I want to avoid. Is there some sort of binary stream I can use instead? What I am looking for is a solution (preferrably using boost libs) that lets the message builder dictate the amount of memory allocated during serialization and what that would look like in terms of passing the data around between the wrapper and message factory/message builders. PS. Messages contain almost exclusively built-in types and PODs and form a shallow but wide hierarchy for the sake of going through a factory. Note: a link to examples of using boost::serialization for something like this would be appreciated as I'm having difficulties figuring out the relation between it and buffers.

    Read the article

  • CodePlex Daily Summary for Wednesday, November 02, 2011

    CodePlex Daily Summary for Wednesday, November 02, 2011Popular ReleasesWYGIWYS Driver: 1.1.2.0 release: Win32, x86, kernel mode driver.Reset IPv6: 1.0.0.0: First release. Only works for Spanish and English operating system editions.BExplorer (Better Explorer): Better Explorer 2.0.0.631 Alpha: Changelog: Added: Some new functions in ribbon Added: Possibility to choose displayed columns Added: Basic Search Fixed: Some bugs after navigation Fixed: Attempt to fix slow navigation and slow start Known issues: - BreadcrumbBar fails on some situations - Basic search not work quite well in some situations Please if anyone find bugs be kind and report them at the Issue Tracker! Thanks!DotNetNuke® Community Edition: 05.06.04: Major Highlights Fixed issue with upgrades on systems that had upgraded the Telerik library to 6.0.0 Fixed issue with Razor Host upgrade to 5.6.3 The logic for module administration checks contains incorrect logic in 1 place, opening the possibility of a user with edit permissions gaining access to functionality they should not have through a particularly crafted url Security FixesBrowsers support the ability to remember common strings such as usernames/addresses etc. Code was adde...Terminals: Version 2.0 - Beta 2 Release: The team has finally put the nail into the official release date for version 2.0. As bugs are winding down on the 2.0 Roadmap we decided to push out another build - the first 2.0 Beta build. Please take time to use and abuse this release. We left logging in place, and this is a debug build so be sure to submit your logs on each bug reported, and please do report all bugs! Check the source code page on the site, this beta includes all commits since (and including) the 90428 check-in back i...iTuner - The iTunes Companion: iTuner 1.4.4322: Added German (unverified, apologies if incorrect) Properly source invariant resources with correct resIDs Replaced obsolete lyric providers with working providers Fix Pseudolater to correctly morph every third char Fix null reference in CatalogBaseTrack Folder Changes: Track Folder Changes 1.0: Track Folder Changes 1.0 (binary)Windows Workflow Foundation on Codeplex: Microsoft.Activities v1.8.8: Microsoft.Activities Overview How do I install Microsoft.Activities? Updates in this release9318Technical Analysis Engine for .NET: Technical Analysis Engine 1.25: What's new in the 1.25 release (2011-11-01): - Added Williams %R indicator - Added Moving Average Envelopes indicatorBF3Rcon.NET: BF3Rcon 3.0: This release is targeted for RCON documentation based on R3. Everything should be beta stable, but it's alpha because I haven't been able to fully test it. When a stable release is ready, a proper changelog will be kept. Important Edit: There's one method that will keep this from working in Mono. GeneratePasswordHash uses void HashAlgorithm.Dispose(), which isn't in Mono. This will have to be changed to Clear() in the next release. If anyone needs a Mono version of this immediately, you can...BoxWorld: BoxWorld_2011.10.30: BoxWorld - 8.0.1110.30 This is the initial release of BoxWorld. I'd recommend downloading the installer as it contains the compiled code and everything all nicely contained. By default, you end up with this directory structure: C:\Program Files\ViperWorks\BoxWorld C:\Program Files\ViperWorks\BoxWorld\Data C:\Program Files\ViperWorks\BoxWorld\Interface C:\Program Files\ViperWorks\BoxWorld\Source In the root you have the compiled EXE files, one for the main release, one for the LITE release ...VidCoder: 1.2.1: Fixed a couple regressions: video encoder was blank in queue and crashes with the High Profile preset when opening the Settings window. Fixed problem with auto-update introduced in 1.2.0. If you have 1.2.0 you will need to update manually to get this.Koober: Koober - The Ebook Creator 0.2: The official release of Koober as Open source. Koober is a ebook creator for Windows, and Koob Reader is the reader.patterns & practices: Enterprise Library Contrib: Enterprise Library Contrib - 5.0 (Oct 2011): This release of Enterprise Library Contrib is based on the Microsoft patterns & practices Enterprise Library 5.0 core and contains the following: Common extensionsTypeConfigurationElement<T> - A Polymorphic Configuration Element without having to be part of a PolymorphicConfigurationElementCollection. AnonymousConfigurationElement - A Configuration element that can be uniquely identified without having to define its name explicitly. Data Access Application Block extensionsMySql Provider - ...Network Monitor Open Source Parsers: Network Monitor Parsers 3.4.2748: The Network Monitor Parsers packages contain parsers for more than 400 network protocols, including RFC based public protocols and protocols for Microsoft products defined in the Microsoft Open Specifications for Windows and SQL Server. NetworkMonitor_Parsers.msi is the base parser package which defines parsers for commonly used public protocols and protocols for Microsoft Windows. In this release, NetowrkMonitor_Parsers.msi continues to improve quality and fix bugs. It has included the fo...Media Companion: MC 3.420b Weekly: Ensure .NET 4.0 Full Framework is installed. (Available from http://www.microsoft.com/download/en/details.aspx?id=17718) Ensure the NFO ID fix is applied when transitioning from versions prior to 3.416b. (Details here) Movies Fixed: Fanart and poster scraping issues TV Shows (Re)Added: Rebuild single show Fixed: Issue when shows are moved from original location Ability to handle " for actor nicknames Crash when episode name contains "<" (does not scrape yet) Clears fanart when switch...patterns & practices - Unity: Unity 3.0 for .NET4.5 Preview: The Unity 3.0.1026.0 Preview enables Unity to work on .NET 4.5 with both the WinRT and desktop profiles. The major changes include: Unity projects updated to target .NET 4.5. Dynamic build plans modified to use compiled lambda expressions instead of Reflection.Emit Converting reflection to use the new TypeInfo for reflection. Projects updated to work with the Microsoft Visual Studio 2011 Preview Notes/Known Issues: The Microsoft.Practices.Unity.UnityServiceLocator class cannot be use...Managed Extensibility Framework: MEF 2 Preview 4: Detailed information on this release is available on the BCL team blog.AcDown????? - Anime&Comic Downloader: AcDown????? v3.6: ?? ● AcDown??????????、??????,??????????????????????,???????Acfun、Bilibili、???、???、???、Tucao.cc、SF???、?????80????,???????????、?????????。 ● AcDown???????????????????????????,???,???????????????????。 ● AcDown???????C#??,????.NET Framework 2.0??。?????"Acfun?????"。 ????32??64? Windows XP/Vista/7 ????????????? ??:????????Windows XP???,?????????.NET Framework 2.0???(x86)?.NET Framework 2.0???(x64),?????"?????????"??? ??????????????,??????????: ??"AcDown?????"????????? ?? v3.6?? ??“????”...Microsoft Ajax Minifier: Microsoft Ajax Minifier 4.33: Add JSParser.ParseExpression method to parse JavaScript expressions rather than source-elements. Add -strict switch (CodeSettings.StrictMode) to force input code to ECMA5 Strict-mode (extra error-checking, "use strict" at top). Fixed bug when MinifyCode setting was set to false but RemoveUnneededCode was left it's default value of true.New ProjectsAlgorithms: algorithms, ACM C++ programs, Electronic design automation algorithmsAll-In-One: Ein Programm - Alle Funktionen Einfach Komponente erstellen - und schon gibt es eine Funktion mehr!Bar Code File Copy: Bar Code File Copy is a mobile app that allows user to initiate file transfer from a PC to another with the help of barcodes and Windows Phone 7.BlekBoox: Google Books API CF-Soft: this is my workspace to study C# programming.CodePaste.NET Tray Application: A simple tray application to create snippets on CodePaste.NET. Right click the app and select New Snippet. A snippet will be created, the contents of your clipboard will be pasted and your clipboard will be replaced with the URL after the code snippet is successfully posted.Common libs of fanthos: Fanthos.Libs.Controls provides panel and button with special draw and special events. Fanthos.Libs.Network provides class that you can use the method likes Async WCF in dotNet 2.0.Database Filesystem: The DBFS project implements a filesystem paradigm to the storage of objects in a database. The primary development language is Visual Basic .NET.Destructible Texture2D: The project shows how to create a destructible texture2D in XNA. This project is developed using the XNA framework and C# programming languageEject and Close CD Tray: For some reason i cannot seem to find any command line program to eject or close the cd tray. So i've created my own version and sharing it for everyone to use. It is an extremely simplistic program with the sole aim of ejecting or closing the cd tray and nothing else.Excel add-in for pricing options: Price options using various distributions.FDFToolkit .NET: FDFToolkit .NET makes it easier to read, write, create, populate, merge FDF, XDP, XFDF, and XML data with Acrobat and LiveCycle PDF forms. FDFToolkit.net utilizes iTextSharp 4.x technologies, under MPL license.Fiction Catalog: A catalog project designed to store information about fictional literature.Gangbee Software: This is customized version of Nopcommerce 1.9Guess Number: This simple program is letting you to guess number from 1 to 20. H? th?ng Khách s?n: H? th?ng qu?n lí khách s?nHelloTipi Photo Downloader: Permet de télécharger les photos en qualité original de votre site de famille [url:HelloTipi|http://www.hellotipi.com].Image Tagger & Resizer: Resize, and text in the lower right of picture with i.e. copyright information.Kinect Sensor Controller: A project using kinect sensor to control objectsKJFramework.Dynamic ??????: KJFramework.Dynamic ???????? KJFramework????????????????????,?????????: KJFramework.Dynamic(??????). ???????????????????????,???????????????,?????????, ????????????????????,????,???????????????,??????????(??,???????)。 ????,?????????????????????(Component), ??????DynamicDomainComponent??。 ??,????????????,???????????DynamicDomainService??。 ??????,???????????? ???????DynamicDomainService。 ??DynamicDomainService??,????????????????。 ?????, ????????????(Tunnel)???,??????(Tunnel)...Lan ETS Player Registration Software: This is the custom software that the Lan ETS staff uses to register people when they arrive at the LAN party.LINQ to Calil: LINQ to Calil ????? (http://calil.jp/) ???????? API ? LINQ ????????。???????????? LINQ ???????????????。.NET Framework 4 ???????、Silverlight ??????????。 LINQ to Calil ??????????????????????????????????????。Login Form in VB: <project name> makes it easier for <target user group> to <activity>. You'll no longer have to <activity>. It's developed in <programming language>.MbpGpsTester: MbpGpsTester is a gps test tool.Mi proyecto: Mi proyectoMy NuGET Packages: This project contains a custom program that allows you to quickly update NuGET packages from multiple sources and package feeds. It also contains set-up of some packages that are used by HydroDesktop.MyyoutubeforWp7: MyyoutubeforWp7 is a youtube application where users can search and view the videoNERO'S TOOLS: NEROS TOOLS will be an area of programming tools and resources for the automation control industry and the everyday usage of major control systems software.NetWebScript: NetWebScript is a IL to JavaScript compiler. It allow to write complex web application in C# or any other .Net language. It provide Visual Studio integration to debug into orginial sources. It allow to share code with server.Northern Lights WP7 Toolkit: Northern Lights WP7 Toolkit contains some common tools for WP7 Developers.SccmBoundaryHealthTool: .NET application that will search the AD forest for SCCM boundary configurations and report the following: * Overlapping boundaries, including those inter-boundary type, e.g. IP subnet overlaps with AD site. * Unassigned AD sites * Orphaned AD sites in SCCMSeven: Seven is a set of tools for programs development using the Oberon 07 language. SOAP Test Application (with EWS Tools): Application that allows testing of SOAP implementations, in particular Exchange Web Services.SocialCastDotNet: C# library for accessing the SocialCast APISosyal: Sosyal as.sqlce_perfDemo: just a bit of code to demonstrate sqlce insert performance on the desktop. I'm using sqlce on the desktop to persist data as its the fastest thing I can find. Insert perfromance seems to top out at around 65,000records/sec on my laptop but it also seems to limited at this point by my hard drive speeds. The sample code should be able to accept a dataTable, dataReader or dataset and persit to a sqlce database. Also in the code is a small wrapper on the sqlce connectionstring (localconne...SqlMon for OracleClient: This is a project to doing a tool just like Quest SQL Monitor that capture sql sentence in client side.So it's so cool that juect join in and user it. It's developed in C# and Visual Studio 2010 and bases on the EasyHook that is a powerfull .NET hook library.It injects in oci.dll and hook the "OCIStmtPrepare" function which excute before sql excuting,through the parameter "stms" we can get the sqltext and display itStackOverflow Offline Reader using a pdf reader: Using one or more keywords and number of questions to download, the app creates and displays a single pdf file of the questions and answers pertaining to the keyword(s). This enables the user to read questions in an offline manner or to read in a top/down fashion. std::streambuf wrapper for COM IStream: This provides a subclass of std::streambuf that wraps a COM IStream, so you can use an IStream with any C++ code that uses iostreams or the STL algorithms with a streambuf_iterator. It does no internal buffering whatsoever (I'd be happy to change this if someone needs it).step out ring signatures .net: Simple program to demonstrate how srs works in real world of .net.System Center Service Manager 2010 SP1 WCF and Web Service: Simple WCF Service and Web Service for SCSM 2010 SP1.System32 - SDK de componentes y acceso a datos para .NET: System32 - SDK de componentes y acceso a datos para .NET Taha Mail: A Java Web Based MailTest TDS: Test TFS - 1Track Folder Changes: Displays in real time a tree with the list of created/deleted/changed files in a specific directory and its subdirectoriesumbTrafficCentral: A plugin for Umbraco that adds robust and scalable handling of redirects, storing the data in the media library. WebDAV Test Application: Application to test WebDAV functionality.XnaXaml: XnaXaml allows you to add a XAML file to your Content Pipeline in XNA and edit straight from Visual Studio. It then takes the XAML file and parses through it to create mock objects that can be used to render controls to the screen in XNA. These mock objects can also be used to pass data to any GUI system you choose.???-?????????? ?? ????????????? ????????? ??????????? ??????? ???: Under construction

    Read the article

  • Can anyone explain why my crypto++ decrypted file 16 bytes short?

    - by Tom Williams
    I suspect it might be too much to hope for, but can anyone with experience with crypto++ explain why the "decrypted.out" file created by main() is 16 characters short (which probably not coincidentally is the block size)? I think the issue must be in CryptStreamBuffer::GetNextChar(), but I've been staring at it and the crypto++ documentation for hours. Any other comments about how crummy or naive my std::streambuf implementation are also welcome ;-) And I've just noticed I'm missing some calls to delete so you don't have to tell me about those. Thanks, Tom // Runtime Includes #include <iostream> // Crypto++ Includes #include "aes.h" #include "modes.h" // xxx_Mode< > #include "filters.h" // StringSource and // StreamTransformation #include "files.h" using namespace std; class CryptStreamBuffer: public std::streambuf { public: CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c); CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c); protected: virtual int_type overflow(int_type ch = traits_type::eof()); virtual int_type uflow(); virtual int_type underflow(); virtual int_type pbackfail(int_type ch); virtual int sync(); private: int GetNextChar(); int m_NextChar; // Buffered character CryptoPP::StreamTransformationFilter* m_StreamTransformationFilter; CryptoPP::FileSource* m_Source; CryptoPP::FileSink* m_Sink; }; // class CryptStreamBuffer CryptStreamBuffer::CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c) : m_NextChar(traits_type::eof()), m_StreamTransformationFilter(0), m_Source(0), m_Sink(0) { m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c); m_Source = new CryptoPP::FileSource(encryptedInput, false, m_StreamTransformationFilter); } CryptStreamBuffer::CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c) : m_NextChar(traits_type::eof()), m_StreamTransformationFilter(0), m_Source(0), m_Sink(0) { m_Sink = new CryptoPP::FileSink(encryptedOutput); m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c, m_Sink); } CryptStreamBuffer::int_type CryptStreamBuffer::overflow(int_type ch) { return m_StreamTransformationFilter->Put((byte)ch); } CryptStreamBuffer::int_type CryptStreamBuffer::uflow() { int_type result = GetNextChar(); // Reset the buffered character m_NextChar = traits_type::eof(); return result; } CryptStreamBuffer::int_type CryptStreamBuffer::underflow() { return GetNextChar(); } CryptStreamBuffer::int_type CryptStreamBuffer::pbackfail(int_type ch) { return traits_type::eof(); } int CryptStreamBuffer::sync() { if (m_Sink) { m_StreamTransformationFilter->MessageEnd(); } } int CryptStreamBuffer::GetNextChar() { // If we have a buffered character do nothing if (m_NextChar != traits_type::eof()) { return m_NextChar; } // If there are no more bytes currently available then pump the source // *** I SUSPECT THE PROBLEM IS HERE *** if (m_StreamTransformationFilter->MaxRetrievable() == 0) { m_Source->Pump(1024); } // Retrieve the next byte byte nextByte; size_t noBytes = m_StreamTransformationFilter->Get(nextByte); if (0 == noBytes) { return traits_type::eof(); } // Buffer up the next character m_NextChar = nextByte; return m_NextChar; } void InitKey(byte key[]) { key[0] = -62; key[1] = 102; key[2] = 78; key[3] = 75; key[4] = -96; key[5] = 125; key[6] = 66; key[7] = 125; key[8] = -95; key[9] = -66; key[10] = 114; key[11] = 22; key[12] = 48; key[13] = 111; key[14] = -51; key[15] = 112; } void DecryptFile(const char* sourceFileName, const char* destFileName) { ifstream ifs(sourceFileName, ios::in | ios::binary); ofstream ofs(destFileName, ios::out | ios::binary); byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; InitKey(key); CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption decryptor(key, sizeof(key)); if (ifs) { if (ofs) { CryptStreamBuffer cryptBuf(ifs, decryptor); std::istream decrypt(&cryptBuf); int c; while (EOF != (c = decrypt.get())) { ofs << (char)c; } ofs.flush(); } else { std::cerr << "Failed to open file '" << destFileName << "'." << endl; } } else { std::cerr << "Failed to open file '" << sourceFileName << "'." << endl; } } void EncryptFile(const char* sourceFileName, const char* destFileName) { ifstream ifs(sourceFileName, ios::in | ios::binary); ofstream ofs(destFileName, ios::out | ios::binary); byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; InitKey(key); CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption encryptor(key, sizeof(key)); if (ifs) { if (ofs) { CryptStreamBuffer cryptBuf(ofs, encryptor); std::ostream encrypt(&cryptBuf); int c; while (EOF != (c = ifs.get())) { encrypt << (char)c; } encrypt.flush(); } else { std::cerr << "Failed to open file '" << destFileName << "'." << endl; } } else { std::cerr << "Failed to open file '" << sourceFileName << "'." << endl; } } int main(int argc, char* argv[]) { EncryptFile(argv[1], "encrypted.out"); DecryptFile("encrypted.out", "decrypted.out"); return 0; }

    Read the article

  • Can anyone explain why my crypto++ decrypted file is 16 bytes short?

    - by Tom Williams
    I suspect it might be too much to hope for, but can anyone with experience with crypto++ explain why the "decrypted.out" file created by main() is 16 characters short (which probably not coincidentally is the block size)? I think the issue must be in CryptStreamBuffer::GetNextChar(), but I've been staring at it and the crypto++ documentation for hours. Any other comments about how crummy or naive my std::streambuf implementation are also welcome ;-) And I've just noticed I'm missing some calls to delete so you don't have to tell me about those. Thanks, Tom // Runtime Includes #include <iostream> // Crypto++ Includes #include "aes.h" #include "modes.h" // xxx_Mode< > #include "filters.h" // StringSource and // StreamTransformation #include "files.h" using namespace std; class CryptStreamBuffer: public std::streambuf { public: CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c); CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c); protected: virtual int_type overflow(int_type ch = traits_type::eof()); virtual int_type uflow(); virtual int_type underflow(); virtual int_type pbackfail(int_type ch); virtual int sync(); private: int GetNextChar(); int m_NextChar; // Buffered character CryptoPP::StreamTransformationFilter* m_StreamTransformationFilter; CryptoPP::FileSource* m_Source; CryptoPP::FileSink* m_Sink; }; // class CryptStreamBuffer CryptStreamBuffer::CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c) : m_NextChar(traits_type::eof()), m_StreamTransformationFilter(0), m_Source(0), m_Sink(0) { m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c); m_Source = new CryptoPP::FileSource(encryptedInput, false, m_StreamTransformationFilter); } CryptStreamBuffer::CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c) : m_NextChar(traits_type::eof()), m_StreamTransformationFilter(0), m_Source(0), m_Sink(0) { m_Sink = new CryptoPP::FileSink(encryptedOutput); m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c, m_Sink); } CryptStreamBuffer::int_type CryptStreamBuffer::overflow(int_type ch) { return m_StreamTransformationFilter->Put((byte)ch); } CryptStreamBuffer::int_type CryptStreamBuffer::uflow() { int_type result = GetNextChar(); // Reset the buffered character m_NextChar = traits_type::eof(); return result; } CryptStreamBuffer::int_type CryptStreamBuffer::underflow() { return GetNextChar(); } CryptStreamBuffer::int_type CryptStreamBuffer::pbackfail(int_type ch) { return traits_type::eof(); } int CryptStreamBuffer::sync() { if (m_Sink) { m_StreamTransformationFilter->MessageEnd(); } } int CryptStreamBuffer::GetNextChar() { // If we have a buffered character do nothing if (m_NextChar != traits_type::eof()) { return m_NextChar; } // If there are no more bytes currently available then pump the source // *** I SUSPECT THE PROBLEM IS HERE *** if (m_StreamTransformationFilter->MaxRetrievable() == 0) { m_Source->Pump(1024); } // Retrieve the next byte byte nextByte; size_t noBytes = m_StreamTransformationFilter->Get(nextByte); if (0 == noBytes) { return traits_type::eof(); } // Buffer up the next character m_NextChar = nextByte; return m_NextChar; } void InitKey(byte key[]) { key[0] = -62; key[1] = 102; key[2] = 78; key[3] = 75; key[4] = -96; key[5] = 125; key[6] = 66; key[7] = 125; key[8] = -95; key[9] = -66; key[10] = 114; key[11] = 22; key[12] = 48; key[13] = 111; key[14] = -51; key[15] = 112; } void DecryptFile(const char* sourceFileName, const char* destFileName) { ifstream ifs(sourceFileName, ios::in | ios::binary); ofstream ofs(destFileName, ios::out | ios::binary); byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; InitKey(key); CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption decryptor(key, sizeof(key)); if (ifs) { if (ofs) { CryptStreamBuffer cryptBuf(ifs, decryptor); std::istream decrypt(&cryptBuf); int c; while (EOF != (c = decrypt.get())) { ofs << (char)c; } ofs.flush(); } else { std::cerr << "Failed to open file '" << destFileName << "'." << endl; } } else { std::cerr << "Failed to open file '" << sourceFileName << "'." << endl; } } void EncryptFile(const char* sourceFileName, const char* destFileName) { ifstream ifs(sourceFileName, ios::in | ios::binary); ofstream ofs(destFileName, ios::out | ios::binary); byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; InitKey(key); CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption encryptor(key, sizeof(key)); if (ifs) { if (ofs) { CryptStreamBuffer cryptBuf(ofs, encryptor); std::ostream encrypt(&cryptBuf); int c; while (EOF != (c = ifs.get())) { encrypt << (char)c; } encrypt.flush(); } else { std::cerr << "Failed to open file '" << destFileName << "'." << endl; } } else { std::cerr << "Failed to open file '" << sourceFileName << "'." << endl; } } int main(int argc, char* argv[]) { EncryptFile(argv[1], "encrypted.out"); DecryptFile("encrypted.out", "decrypted.out"); return 0; }

    Read the article

  • Thread Local Memory, Using std::string's internal buffer for c-style Scratch Memory.

    - by Hassan Syed
    I am using Protocol Buffers and OpensSSL to generate, HMACs and then CBC encrypt the two fields to obfuscate the session cookies -- similar Kerberos tokens. Protocol Buffers' API communicates with std::strings and has a buffer caching mechanism; I exploit the caching mechanism, for successive calls in the the same thread, by placing it in thread local memory; additionally the OpenSSL HMAC and EVP CTX's are also placed in the same thread local memory structure ( see this question for some detail on why I use thread local memory and the massive amount of speedup it enables even with a single thread). The generation and deserialization, "my algorithms", of these cookie strings uses intermediary void *s and std::strings and since Protocol Buffers has an internal memory retention mechanism I want these characteristics for "my algorithms". So how do I implement a common scratch memory ? I don't know much about the rdbuf(streambuf - strinbuf ??) of the std::string object. I would presumeably need to grow it to the lowest common size ever encountered during the execution of "my algorithms". Thoughts ? My question I guess would be: " is the internal buffer of a string re-usable, and if so, how ?" Edit: See comments to Vlad's answer please.

    Read the article

  • boost::asio::async_read_until problem

    - by user368831
    Hi again, I'm modify the boost asio echo example to use async_read_until to read the input word by word. Even though I am using async_read_until all the data sent seems to be read from the socket. Could someone please advise: #include <cstdlib> #include <iostream> #include <boost/bind.hpp> #include <boost/asio.hpp> using boost::asio::ip::tcp; class session { public: session(boost::asio::io_service& io_service) : socket_(io_service) { } tcp::socket& socket() { return socket_; } void start() { std::cout<<"starting"<<std::endl; boost::asio::async_read_until(socket_, buffer, ' ', boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_read(const boost::system::error_code& error, size_t bytes_transferred) { std::ostringstream ss; ss<<&buffer; std::string s = ss.str(); std::cout<<s<<std::endl; if (!error) { boost::asio::async_write(socket_, boost::asio::buffer(s), boost::bind(&session::handle_write, this, boost::asio::placeholders::error)); } else { delete this; } } void handle_write(const boost::system::error_code& error) { std::cout<<"handling write"<<std::endl; if (!error) { } else { delete this; } } private: tcp::socket socket_; boost::asio::streambuf buffer; }; class server { public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), port)) { session* new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error)); } void handle_accept(session* new_session, const boost::system::error_code& error) { if (!error) { new_session->start(); new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error)); } else { delete new_session; } } private: boost::asio::io_service& io_service_; tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_tcp_echo_server <port>\n"; return 1; } boost::asio::io_service io_service; using namespace std; // For atoi. server s(io_service, atoi(argv[1])); io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } Thanks!

    Read the article

  • boost::asio::async_write problem

    - by user368831
    Hi, I'm trying to figure out how asynchronous reads and writes work in boost asio by manipulating the echo example. Currently, I have a server that should, when sent a sentence, respond with only the first word. However, the boost::asio::async_write never seems to complete even though the write handler is being called. Can someone please explain what's going on? Here's the code: #include <cstdlib> #include <iostream> #include <boost/bind.hpp> #include <boost/asio.hpp> using boost::asio::ip::tcp; class session { public: session(boost::asio::io_service& io_service) : socket_(io_service) { } tcp::socket& socket() { return socket_; } void start() { std::cout<<"starting"<<std::endl; boost::asio::async_read_until(socket_, buffer, ' ', boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_read(const boost::system::error_code& error, size_t bytes_transferred) { // std::ostringstream ss; // ss<<&buffer; char* c = new char[bytes_transferred]; //std::string s; buffer.sgetn(c,bytes_transferred); std::cout<<"data: "<< c<<" bytes: "<<bytes_transferred<<std::endl; if (!error) { boost::asio::async_write(socket_, boost::asio::buffer(c,bytes_transferred), boost::bind(&session::handle_write, this, boost::asio::placeholders::error)); } else { delete this; } } void handle_write(const boost::system::error_code& error) { std::cout<<"handling write"<<std::endl; if (!error) { } else { delete this; } } private: tcp::socket socket_; boost::asio::streambuf buffer; }; class server { public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), port)) { session* new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error)); } void handle_accept(session* new_session, const boost::system::error_code& error) { if (!error) { new_session->start(); new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error)); } else { delete new_session; } } private: boost::asio::io_service& io_service_; tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_tcp_echo_server <port>\n"; return 1; } boost::asio::io_service io_service; using namespace std; // For atoi. server s(io_service, atoi(argv[1])); io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } Thanks!

    Read the article

1