Index: src/libchcore/CommonDataTypes.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/CommonDataTypes.h (.../CommonDataTypes.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/CommonDataTypes.h (.../CommonDataTypes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,11 +19,10 @@ #ifndef __COMMONDATATYPES_H__ #define __COMMONDATATYPES_H__ -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + typedef unsigned long file_count_t; + typedef unsigned long long file_size_t; +} -typedef unsigned long file_count_t; -typedef unsigned long long file_size_t; - -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ConfigNode.cpp =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ConfigNode.cpp (.../ConfigNode.cpp) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/ConfigNode.cpp (.../ConfigNode.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,51 +19,50 @@ #include "stdafx.h" #include "ConfigNode.h" -BEGIN_CHCORE_NAMESPACE - -namespace details +namespace chcore { - ConfigNode::ConfigNode(object_id_t oidObjectID, const TString& strNodeName, int iOrder, const TString& strValue) : - m_oidObjectID(oidObjectID), - m_iOrder(m_setModifications, iOrder), - m_strNodeName(m_setModifications, strNodeName), - m_strValue(m_setModifications, strValue) + namespace details { - m_setModifications[eMod_Added] = true; - } + ConfigNode::ConfigNode(object_id_t oidObjectID, const TString& strNodeName, int iOrder, const TString& strValue) : + m_oidObjectID(oidObjectID), + m_iOrder(m_setModifications, iOrder), + m_strNodeName(m_setModifications, strNodeName), + m_strValue(m_setModifications, strValue) + { + m_setModifications[eMod_Added] = true; + } - ConfigNode::ConfigNode(const ConfigNode& rSrc) : - m_oidObjectID(rSrc.m_oidObjectID), - m_iOrder(m_setModifications, rSrc.m_iOrder), - m_strNodeName(m_setModifications, rSrc.m_strNodeName), - m_strValue(m_setModifications, rSrc.m_strValue) - { - m_setModifications = rSrc.m_setModifications; - } - - ConfigNode& ConfigNode::operator=(const ConfigNode& rSrc) - { - if(this != &rSrc) + ConfigNode::ConfigNode(const ConfigNode& rSrc) : + m_oidObjectID(rSrc.m_oidObjectID), + m_iOrder(m_setModifications, rSrc.m_iOrder), + m_strNodeName(m_setModifications, rSrc.m_strNodeName), + m_strValue(m_setModifications, rSrc.m_strValue) { - m_oidObjectID = rSrc.m_oidObjectID; - m_iOrder = rSrc.m_iOrder; - m_strNodeName = rSrc.m_strNodeName; - m_strValue = rSrc.m_strValue; m_setModifications = rSrc.m_setModifications; } - return *this; - } + ConfigNode& ConfigNode::operator=(const ConfigNode& rSrc) + { + if (this != &rSrc) + { + m_oidObjectID = rSrc.m_oidObjectID; + m_iOrder = rSrc.m_iOrder; + m_strNodeName = rSrc.m_strNodeName; + m_strValue = rSrc.m_strValue; + m_setModifications = rSrc.m_setModifications; + } - TString ConfigNode::GetNodeName() const - { - return m_strNodeName; - } + return *this; + } - int ConfigNode::GetOrder() const - { - return m_iOrder; + TString ConfigNode::GetNodeName() const + { + return m_strNodeName; + } + + int ConfigNode::GetOrder() const + { + return m_iOrder; + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/ConfigNode.h =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ConfigNode.h (.../ConfigNode.h) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/ConfigNode.h (.../ConfigNode.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,43 +25,42 @@ #include "TSharedModificationTracker.h" #include "SerializerDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -namespace details +namespace chcore { - class ConfigNode + namespace details { - public: - ConfigNode(object_id_t oidObjectID, const TString& strNodeName, int iOrder, const TString& strValue); - ConfigNode(const ConfigNode& rSrc); + class ConfigNode + { + public: + ConfigNode(object_id_t oidObjectID, const TString& strNodeName, int iOrder, const TString& strValue); + ConfigNode(const ConfigNode& rSrc); - ConfigNode& operator=(const ConfigNode& rSrc); + ConfigNode& operator=(const ConfigNode& rSrc); - TString GetNodeName() const; - int GetOrder() const; + TString GetNodeName() const; + int GetOrder() const; - public: - enum EModifications - { - eMod_None = 0, - eMod_Added = 1, - eMod_NodeName, - eMod_Value, - eMod_Order, + public: + enum EModifications + { + eMod_None = 0, + eMod_Added = 1, + eMod_NodeName, + eMod_Value, + eMod_Order, - eMod_Last - }; + eMod_Last + }; - typedef std::bitset Bitset; - mutable Bitset m_setModifications; + typedef std::bitset Bitset; + mutable Bitset m_setModifications; - object_id_t m_oidObjectID; - TSharedModificationTracker m_iOrder; - TSharedModificationTracker m_strNodeName; - TSharedModificationTracker m_strValue; - }; + object_id_t m_oidObjectID; + TSharedModificationTracker m_iOrder; + TSharedModificationTracker m_strNodeName; + TSharedModificationTracker m_strValue; + }; + } } -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ConfigNodeContainer.cpp =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ConfigNodeContainer.cpp (.../ConfigNodeContainer.cpp) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/ConfigNodeContainer.cpp (.../ConfigNodeContainer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,453 +24,453 @@ #include "ErrorCodes.h" #include -BEGIN_CHCORE_NAMESPACE - -namespace details +namespace chcore { - /////////////////////////////////////////////////////////////////////// - ChangeValue::ChangeValue(const TString& strNewValue) : m_strNewValue(strNewValue) + namespace details { - } + /////////////////////////////////////////////////////////////////////// + ChangeValue::ChangeValue(const TString& strNewValue) : m_strNewValue(strNewValue) + { + } - void ChangeValue::operator()(ConfigNode& rNode) - { - m_bWasModified = false; - if(rNode.m_strValue.Get() != m_strNewValue) + void ChangeValue::operator()(ConfigNode& rNode) { - rNode.m_strValue.Modify() = m_strNewValue; - m_bWasModified = true; + m_bWasModified = false; + if (rNode.m_strValue.Get() != m_strNewValue) + { + rNode.m_strValue.Modify() = m_strNewValue; + m_bWasModified = true; + } } - } - bool ChangeValue::WasModified() const - { - return m_bWasModified; - } + bool ChangeValue::WasModified() const + { + return m_bWasModified; + } - /////////////////////////////////////////////////////////////////////// - ChangeOrderAndValue::ChangeOrderAndValue(const TString& tNewValue, int iOrder) : - m_strNewValue(tNewValue), - m_iOrder(iOrder) - { - } + /////////////////////////////////////////////////////////////////////// + ChangeOrderAndValue::ChangeOrderAndValue(const TString& tNewValue, int iOrder) : + m_strNewValue(tNewValue), + m_iOrder(iOrder) + { + } - void ChangeOrderAndValue::operator()(ConfigNode& rNode) - { - m_bWasModified = false; - if(rNode.m_strValue.Get() != m_strNewValue || rNode.m_iOrder != m_iOrder) + void ChangeOrderAndValue::operator()(ConfigNode& rNode) { - rNode.m_strValue = m_strNewValue; - rNode.m_iOrder = m_iOrder; + m_bWasModified = false; + if (rNode.m_strValue.Get() != m_strNewValue || rNode.m_iOrder != m_iOrder) + { + rNode.m_strValue = m_strNewValue; + rNode.m_iOrder = m_iOrder; - m_bWasModified = true; + m_bWasModified = true; + } } - } - bool ChangeOrderAndValue::WasModified() const - { - return m_bWasModified; - } + bool ChangeOrderAndValue::WasModified() const + { + return m_bWasModified; + } - /////////////////////////////////////////////////////////////////////// - ConfigNodeContainer::ConfigNodeContainer() : - m_bDelayedEnabled(false), - m_oidLastObjectID(0) - { - } + /////////////////////////////////////////////////////////////////////// + ConfigNodeContainer::ConfigNodeContainer() : + m_bDelayedEnabled(false), + m_oidLastObjectID(0) + { + } - ConfigNodeContainer::ConfigNodeContainer(const ConfigNodeContainer& rSrc) - { - boost::shared_lock lock(rSrc.m_lock); - m_mic = rSrc.m_mic; - m_strFilePath = rSrc.m_strFilePath; - m_setDelayedNotifications.Clear(); - m_bDelayedEnabled = false; - m_oidLastObjectID = rSrc.m_oidLastObjectID; - } - - ConfigNodeContainer& ConfigNodeContainer::operator=(const ConfigNodeContainer& rSrc) - { - if(this != &rSrc) + ConfigNodeContainer::ConfigNodeContainer(const ConfigNodeContainer& rSrc) { - boost::unique_lock lock2(m_lock); boost::shared_lock lock(rSrc.m_lock); - m_mic = rSrc.m_mic; m_strFilePath = rSrc.m_strFilePath; + m_setDelayedNotifications.Clear(); m_bDelayedEnabled = false; m_oidLastObjectID = rSrc.m_oidLastObjectID; - - m_setDelayedNotifications.Clear(); } - return *this; - } + ConfigNodeContainer& ConfigNodeContainer::operator=(const ConfigNodeContainer& rSrc) + { + if (this != &rSrc) + { + boost::unique_lock lock2(m_lock); + boost::shared_lock lock(rSrc.m_lock); - TStringArray ConfigNodeContainer::GetArrayValue(PCTSTR pszPropName, const TStringArray& rDefaultValue) const - { - TStringArray tArray; + m_mic = rSrc.m_mic; + m_strFilePath = rSrc.m_strFilePath; + m_bDelayedEnabled = false; + m_oidLastObjectID = rSrc.m_oidLastObjectID; - boost::shared_lock lock(m_lock); + m_setDelayedNotifications.Clear(); + } - std::pair pairFnd - = m_mic.equal_range(boost::make_tuple(pszPropName)); + return *this; + } - if(pairFnd.first == m_mic.end()) - return rDefaultValue; - - while(pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) + TStringArray ConfigNodeContainer::GetArrayValue(PCTSTR pszPropName, const TStringArray& rDefaultValue) const { - tArray.Add((*pairFnd.first).m_strValue); - ++pairFnd.first; - } + TStringArray tArray; - return tArray; - } + boost::shared_lock lock(m_lock); - bool ConfigNodeContainer::GetArrayValueNoDefault(PCTSTR pszPropName, TStringArray& rValue) const - { - boost::shared_lock lock(m_lock); + std::pair pairFnd + = m_mic.equal_range(boost::make_tuple(pszPropName)); - rValue.Clear(); + if (pairFnd.first == m_mic.end()) + return rDefaultValue; - std::pair pairFnd - = m_mic.equal_range(boost::make_tuple(pszPropName)); + while (pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) + { + tArray.Add((*pairFnd.first).m_strValue); + ++pairFnd.first; + } - if(pairFnd.first == m_mic.end()) - return false; + return tArray; + } - while(pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) + bool ConfigNodeContainer::GetArrayValueNoDefault(PCTSTR pszPropName, TStringArray& rValue) const { - rValue.Add((*pairFnd.first).m_strValue); - ++pairFnd.first; - } + boost::shared_lock lock(m_lock); - return true; - } + rValue.Clear(); - bool ConfigNodeContainer::SetArrayValue(PCTSTR pszPropName, const TStringArray& rValue) - { - bool bResult = false; + std::pair pairFnd + = m_mic.equal_range(boost::make_tuple(pszPropName)); - boost::unique_lock lock(m_lock); + if (pairFnd.first == m_mic.end()) + return false; - std::pair pairFnd - = m_mic.equal_range(boost::make_tuple(pszPropName)); - - if(pairFnd.first == m_mic.end()) - { - // insert new items - for(size_t stIndex = 0; stIndex < rValue.GetCount(); ++stIndex) + while (pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) { - m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, boost::numeric_cast(stIndex), rValue.GetAt(stIndex))); + rValue.Add((*pairFnd.first).m_strValue); + ++pairFnd.first; } - return false; + return true; } - else + + bool ConfigNodeContainer::SetArrayValue(PCTSTR pszPropName, const TStringArray& rValue) { - // insert/modify/delete items (diff mode) - size_t stIndex = 0; - while(pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) + bool bResult = false; + + boost::unique_lock lock(m_lock); + + std::pair pairFnd + = m_mic.equal_range(boost::make_tuple(pszPropName)); + + if (pairFnd.first == m_mic.end()) { - if(stIndex < rValue.GetCount()) + // insert new items + for (size_t stIndex = 0; stIndex < rValue.GetCount(); ++stIndex) { - // update existing item - ChangeOrderAndValue tChange(rValue.GetAt(stIndex), boost::numeric_cast(stIndex)); - m_mic.modify(pairFnd.first, tChange); - bResult |= tChange.WasModified(); + m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, boost::numeric_cast(stIndex), rValue.GetAt(stIndex))); + } - ++pairFnd.first; + return false; + } + else + { + // insert/modify/delete items (diff mode) + size_t stIndex = 0; + while (pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) + { + if (stIndex < rValue.GetCount()) + { + // update existing item + ChangeOrderAndValue tChange(rValue.GetAt(stIndex), boost::numeric_cast(stIndex)); + m_mic.modify(pairFnd.first, tChange); + bResult |= tChange.WasModified(); + + ++pairFnd.first; + } + else + { + // delete this item + m_setRemovedObjects.Add(pairFnd.first->m_oidObjectID); + pairFnd.first = m_mic.erase(pairFnd.first); + } + + ++stIndex; } - else + + while (stIndex < rValue.GetCount()) { - // delete this item - m_setRemovedObjects.Add(pairFnd.first->m_oidObjectID); - pairFnd.first = m_mic.erase(pairFnd.first); + // add items not added before (with new oids) + m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, boost::numeric_cast(stIndex), rValue.GetAt(stIndex))); + ++stIndex; } - ++stIndex; + return true; } - - while(stIndex < rValue.GetCount()) - { - // add items not added before (with new oids) - m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, boost::numeric_cast(stIndex), rValue.GetAt(stIndex))); - ++stIndex; - } - - return true; } - } - namespace - { - struct PredIsPrefixedWith + namespace { - private: - PredIsPrefixedWith& operator=(const PredIsPrefixedWith&); - PredIsPrefixedWith(); + struct PredIsPrefixedWith + { + private: + PredIsPrefixedWith& operator=(const PredIsPrefixedWith&); + PredIsPrefixedWith(); - public: - PredIsPrefixedWith(PCTSTR pszPrefix, TRemovedObjects& rRemovedObjects) : m_strPrefix(pszPrefix), m_rRemovedObjects(rRemovedObjects) {} - PredIsPrefixedWith(const PredIsPrefixedWith& rSrc) : m_strPrefix(rSrc.m_strPrefix), m_rRemovedObjects(rSrc.m_rRemovedObjects) {} + public: + PredIsPrefixedWith(PCTSTR pszPrefix, TRemovedObjects& rRemovedObjects) : m_strPrefix(pszPrefix), m_rRemovedObjects(rRemovedObjects) {} + PredIsPrefixedWith(const PredIsPrefixedWith& rSrc) : m_strPrefix(rSrc.m_strPrefix), m_rRemovedObjects(rSrc.m_rRemovedObjects) {} - bool operator()(const ConfigNode& rNode) const - { - if(rNode.m_strNodeName.Get().StartsWith(m_strPrefix.c_str())) + bool operator()(const ConfigNode& rNode) const { - m_rRemovedObjects.Add(rNode.m_oidObjectID); - return true; + if (rNode.m_strNodeName.Get().StartsWith(m_strPrefix.c_str())) + { + m_rRemovedObjects.Add(rNode.m_oidObjectID); + return true; + } + return false; } - return false; - } - TString m_strPrefix; - TRemovedObjects& m_rRemovedObjects; - }; - } + TString m_strPrefix; + TRemovedObjects& m_rRemovedObjects; + }; + } - void ConfigNodeContainer::DeleteNode(PCTSTR pszPropName) - { - boost::unique_lock lock(m_lock); + void ConfigNodeContainer::DeleteNode(PCTSTR pszPropName) + { + boost::unique_lock lock(m_lock); - PredIsPrefixedWith pred(pszPropName, m_setRemovedObjects); + PredIsPrefixedWith pred(pszPropName, m_setRemovedObjects); - bool bWasFoundBefore = false; - ConfigNodeContainer::NodeContainer::iterator iterCurrent = m_mic.begin(); - while(iterCurrent != m_mic.end()) - { - // NOTE: PredIsPrefixedWith registers the object IDs as deleted in m_setRemovedObjects (for change management purposes) - if(pred(*iterCurrent)) - iterCurrent = m_mic.erase(iterCurrent); - else if(bWasFoundBefore) - break; // as the elements are sorted, when we matched something earlier and now we don't - it means that there are no more matching elements - else - ++iterCurrent; + bool bWasFoundBefore = false; + ConfigNodeContainer::NodeContainer::iterator iterCurrent = m_mic.begin(); + while (iterCurrent != m_mic.end()) + { + // NOTE: PredIsPrefixedWith registers the object IDs as deleted in m_setRemovedObjects (for change management purposes) + if (pred(*iterCurrent)) + iterCurrent = m_mic.erase(iterCurrent); + else if (bWasFoundBefore) + break; // as the elements are sorted, when we matched something earlier and now we don't - it means that there are no more matching elements + else + ++iterCurrent; + } } - } - bool ConfigNodeContainer::ExtractNodes(PCTSTR pszNode, ConfigNodeContainer& tNewContainer) const - { - bool bFound = false; - TString strReplace(pszNode); - strReplace += _T("."); + bool ConfigNodeContainer::ExtractNodes(PCTSTR pszNode, ConfigNodeContainer& tNewContainer) const + { + bool bFound = false; + TString strReplace(pszNode); + strReplace += _T("."); - boost::unique_lock dst_lock(tNewContainer.m_lock); - tNewContainer.m_mic.clear(); + boost::unique_lock dst_lock(tNewContainer.m_lock); + tNewContainer.m_mic.clear(); - boost::shared_lock lock(m_lock); + boost::shared_lock lock(m_lock); - for(NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - if(iter->m_strNodeName.Get().StartsWith(strReplace.c_str())) + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) { - bFound = true; + if (iter->m_strNodeName.Get().StartsWith(strReplace.c_str())) + { + bFound = true; - TString strName = iter->m_strNodeName.Get(); - strName.MidSelf(strReplace.GetLength()); + TString strName = iter->m_strNodeName.Get(); + strName.MidSelf(strReplace.GetLength()); - tNewContainer.m_mic.insert(ConfigNode(++tNewContainer.m_oidLastObjectID, strName, iter->GetOrder(), iter->m_strValue)); + tNewContainer.m_mic.insert(ConfigNode(++tNewContainer.m_oidLastObjectID, strName, iter->GetOrder(), iter->m_strValue)); + } } + + return bFound; } - return bFound; - } + bool ConfigNodeContainer::ExtractMultipleNodes(PCTSTR pszNode, std::vector& tNewContainers) const + { + bool bFound = false; + TString strReplace(pszNode); + strReplace += _T("["); - bool ConfigNodeContainer::ExtractMultipleNodes(PCTSTR pszNode, std::vector& tNewContainers) const - { - bool bFound = false; - TString strReplace(pszNode); - strReplace += _T("["); + boost::shared_lock lock(m_lock); - boost::shared_lock lock(m_lock); + size_t stLastIndex = std::numeric_limits::max(); + ConfigNodeContainer* pCurrentContainer = NULL; - size_t stLastIndex = std::numeric_limits::max(); - ConfigNodeContainer* pCurrentContainer = NULL; - - for(NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - if(iter->m_strNodeName.Get().StartsWith(strReplace.c_str())) + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) { - bFound = true; + if (iter->m_strNodeName.Get().StartsWith(strReplace.c_str())) + { + bFound = true; - TString strName = iter->m_strNodeName.Get(); - strName.MidSelf(strReplace.GetLength()); - size_t stPos = strName.Find(_T("]")); - if(stPos == std::numeric_limits::max()) - THROW_CORE_EXCEPTION(eErr_InvalidData); - if(strName.GetAt(stPos + 1) != _T('.')) - THROW_CORE_EXCEPTION(eErr_InvalidData); + TString strName = iter->m_strNodeName.Get(); + strName.MidSelf(strReplace.GetLength()); + size_t stPos = strName.Find(_T("]")); + if (stPos == std::numeric_limits::max()) + THROW_CORE_EXCEPTION(eErr_InvalidData); + if (strName.GetAt(stPos + 1) != _T('.')) + THROW_CORE_EXCEPTION(eErr_InvalidData); - size_t stNodeIndex = boost::lexical_cast(strName.Left(stPos)); - if(stNodeIndex != stLastIndex) - { - tNewContainers.push_back(ConfigNodeContainer()); - pCurrentContainer = &tNewContainers.back(); + size_t stNodeIndex = boost::lexical_cast(strName.Left(stPos)); + if (stNodeIndex != stLastIndex) + { + tNewContainers.push_back(ConfigNodeContainer()); + pCurrentContainer = &tNewContainers.back(); - stLastIndex = stNodeIndex; - } + stLastIndex = stNodeIndex; + } - strName.Delete(0, stPos + 2); // skip "]." at the beginning - if (!pCurrentContainer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + strName.Delete(0, stPos + 2); // skip "]." at the beginning + if (!pCurrentContainer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); - pCurrentContainer->m_mic.insert(ConfigNode(++pCurrentContainer->m_oidLastObjectID, strName, iter->GetOrder(), iter->m_strValue)); + pCurrentContainer->m_mic.insert(ConfigNode(++pCurrentContainer->m_oidLastObjectID, strName, iter->GetOrder(), iter->m_strValue)); + } } + + return bFound; } - return bFound; - } + void ConfigNodeContainer::ImportNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer) + { + boost::shared_lock src_lock(tContainer.m_lock); + boost::unique_lock lock(m_lock); - void ConfigNodeContainer::ImportNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer) - { - boost::shared_lock src_lock(tContainer.m_lock); - boost::unique_lock lock(m_lock); + // search for nodes in this container that starts with pszNode + TString strSearch(pszNode); + strSearch += _T("."); - // search for nodes in this container that starts with pszNode - TString strSearch(pszNode); - strSearch += _T("."); + typedef std::pair PairInfo; + std::set setExistingNames; - typedef std::pair PairInfo; - std::set setExistingNames; - - for(NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - if(iter->m_strNodeName.Get().StartsWith(strSearch.c_str())) + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) { - setExistingNames.insert(std::make_pair(iter->m_strNodeName.Get(), iter->m_iOrder.Get())); + if (iter->m_strNodeName.Get().StartsWith(strSearch.c_str())) + { + setExistingNames.insert(std::make_pair(iter->m_strNodeName.Get(), iter->m_iOrder.Get())); + } } - } - NodeContainer::const_iterator iter = tContainer.m_mic.begin(); - for(; iter != tContainer.m_mic.end(); ++iter) - { - TString strNodeName = pszNode; - strNodeName += _T(".") + iter->m_strNodeName; - - std::set::iterator iterExisting = setExistingNames.find(std::make_pair(strNodeName, iter->m_iOrder.Get())); - if(iterExisting != setExistingNames.end()) + NodeContainer::const_iterator iter = tContainer.m_mic.begin(); + for (; iter != tContainer.m_mic.end(); ++iter) { - // node already exists - modify instead of delete+add - m_mic.modify(iter, ChangeValue(iter->m_strValue)); + TString strNodeName = pszNode; + strNodeName += _T(".") + iter->m_strNodeName; - setExistingNames.erase(iterExisting); - } - else - { - // node does not exist - need to add new one - m_mic.insert(ConfigNode(++m_oidLastObjectID, strNodeName, iter->GetOrder(), iter->m_strValue)); - } + std::set::iterator iterExisting = setExistingNames.find(std::make_pair(strNodeName, iter->m_iOrder.Get())); + if (iterExisting != setExistingNames.end()) + { + // node already exists - modify instead of delete+add + m_mic.modify(iter, ChangeValue(iter->m_strValue)); - // remove all nodes with names from setExisting - BOOST_FOREACH(const PairInfo& pairNode, setExistingNames) - { - NodeContainer::iterator iterToRemove = m_mic.find(boost::make_tuple(pairNode.first, pairNode.second)); - if(iterToRemove != m_mic.end()) - m_setRemovedObjects.Add(iterToRemove->m_oidObjectID); + setExistingNames.erase(iterExisting); + } + else + { + // node does not exist - need to add new one + m_mic.insert(ConfigNode(++m_oidLastObjectID, strNodeName, iter->GetOrder(), iter->m_strValue)); + } - m_mic.erase(iterToRemove); + // remove all nodes with names from setExisting + BOOST_FOREACH(const PairInfo& pairNode, setExistingNames) + { + NodeContainer::iterator iterToRemove = m_mic.find(boost::make_tuple(pairNode.first, pairNode.second)); + if (iterToRemove != m_mic.end()) + m_setRemovedObjects.Add(iterToRemove->m_oidObjectID); + + m_mic.erase(iterToRemove); + } } } - } - void ConfigNodeContainer::AddNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer) - { - boost::shared_lock src_lock(tContainer.m_lock); - boost::unique_lock lock(m_lock); + void ConfigNodeContainer::AddNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer) + { + boost::shared_lock src_lock(tContainer.m_lock); + boost::unique_lock lock(m_lock); - // determine the current (max) number associated with the node name - TString strSearch(pszNode); - strSearch += _T("["); + // determine the current (max) number associated with the node name + TString strSearch(pszNode); + strSearch += _T("["); - size_t stMaxNodeNumber = 0; + size_t stMaxNodeNumber = 0; - for(NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - TString strCurrentNode = iter->m_strNodeName.Get(); - if(strCurrentNode.StartsWith(strSearch.c_str())) + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) { - strCurrentNode.MidSelf(strSearch.GetLength()); - size_t stPos = strCurrentNode.Find(_T("]")); - if(stPos == std::numeric_limits::max()) - THROW_CORE_EXCEPTION(eErr_InvalidData); + TString strCurrentNode = iter->m_strNodeName.Get(); + if (strCurrentNode.StartsWith(strSearch.c_str())) + { + strCurrentNode.MidSelf(strSearch.GetLength()); + size_t stPos = strCurrentNode.Find(_T("]")); + if (stPos == std::numeric_limits::max()) + THROW_CORE_EXCEPTION(eErr_InvalidData); - size_t stNumber = boost::lexical_cast(strCurrentNode.Left(stPos).c_str()); - stMaxNodeNumber = std::max(stMaxNodeNumber, stNumber + 1); + size_t stNumber = boost::lexical_cast(strCurrentNode.Left(stPos).c_str()); + stMaxNodeNumber = std::max(stMaxNodeNumber, stNumber + 1); + } } - } - TString strNodePrefix = pszNode; - strNodePrefix += TString(_T("[")) + boost::lexical_cast(stMaxNodeNumber).c_str() + _T("]."); + TString strNodePrefix = pszNode; + strNodePrefix += TString(_T("[")) + boost::lexical_cast(stMaxNodeNumber).c_str() + _T("]."); - NodeContainer::const_iterator iter = tContainer.m_mic.begin(); - for(; iter != tContainer.m_mic.end(); ++iter) - { - TString strNodeName = strNodePrefix + iter->m_strNodeName; + NodeContainer::const_iterator iter = tContainer.m_mic.begin(); + for (; iter != tContainer.m_mic.end(); ++iter) + { + TString strNodeName = strNodePrefix + iter->m_strNodeName; - m_mic.insert(ConfigNode(++m_oidLastObjectID, strNodeName, iter->GetOrder(), iter->m_strValue)); + m_mic.insert(ConfigNode(++m_oidLastObjectID, strNodeName, iter->GetOrder(), iter->m_strValue)); + } } - } - void ConfigNodeContainer::ImportNode(TString strCurrentPath, const boost::property_tree::wiptree& rTree) - { - if(rTree.empty()) - return; + void ConfigNodeContainer::ImportNode(TString strCurrentPath, const boost::property_tree::wiptree& rTree) + { + if (rTree.empty()) + return; - // append separator for non-empty nodes - if(!strCurrentPath.IsEmpty()) - strCurrentPath += _T("."); + // append separator for non-empty nodes + if (!strCurrentPath.IsEmpty()) + strCurrentPath += _T("."); - TString strNewPath; + TString strNewPath; - // analyze subnodes (has only leaf-node(s), multiple non-leaf subnodes with same name, multiple subnodes with different names) - std::set setNodeNames; - bool bAllLeafNodes = true; - size_t stChildCount = 0; - BOOST_FOREACH(const boost::property_tree::wiptree::value_type& rNode, rTree) - { - setNodeNames.insert(rNode.first.c_str()); + // analyze subnodes (has only leaf-node(s), multiple non-leaf subnodes with same name, multiple subnodes with different names) + std::set setNodeNames; + bool bAllLeafNodes = true; + size_t stChildCount = 0; + BOOST_FOREACH(const boost::property_tree::wiptree::value_type& rNode, rTree) + { + setNodeNames.insert(rNode.first.c_str()); - if(!rNode.second.empty()) - bAllLeafNodes = false; + if (!rNode.second.empty()) + bAllLeafNodes = false; - ++stChildCount; - } + ++stChildCount; + } - // sanity check (either unique names or empty or an array with single name - size_t stNodeNamesCount = setNodeNames.size(); - if(stChildCount != stNodeNamesCount && stNodeNamesCount != 1) - THROW_CORE_EXCEPTION(eErr_InvalidData); + // sanity check (either unique names or empty or an array with single name + size_t stNodeNamesCount = setNodeNames.size(); + if (stChildCount != stNodeNamesCount && stNodeNamesCount != 1) + THROW_CORE_EXCEPTION(eErr_InvalidData); - enum EMode { eMode_LeafStringArrayEntries, eMode_LeafOrContainer, eMode_ContainerSplit, eMode_ContainerPassThrough }; - EMode eMode = eMode_LeafStringArrayEntries; + enum EMode { eMode_LeafStringArrayEntries, eMode_LeafOrContainer, eMode_ContainerSplit, eMode_ContainerPassThrough }; + EMode eMode = eMode_LeafStringArrayEntries; - if(stNodeNamesCount == 1 && stChildCount > 1) - { - if(bAllLeafNodes) - eMode = eMode_LeafStringArrayEntries; + if (stNodeNamesCount == 1 && stChildCount > 1) + { + if (bAllLeafNodes) + eMode = eMode_LeafStringArrayEntries; + else + eMode = eMode_ContainerSplit; + } else - eMode = eMode_ContainerSplit; - } - else - eMode = eMode_LeafOrContainer; + eMode = eMode_LeafOrContainer; - int iIndex = 0; - BOOST_FOREACH(const boost::property_tree::wiptree::value_type& rNode, rTree) - { - switch(eMode) + int iIndex = 0; + BOOST_FOREACH(const boost::property_tree::wiptree::value_type& rNode, rTree) { - case eMode_LeafStringArrayEntries: + switch (eMode) { + case eMode_LeafStringArrayEntries: + { strNewPath = strCurrentPath + rNode.first.c_str(); m_mic.insert(ConfigNode(++m_oidLastObjectID, strNewPath, iIndex++, rNode.second.get_value().c_str())); break; } - case eMode_LeafOrContainer: + case eMode_LeafOrContainer: { strNewPath = strCurrentPath + rNode.first.c_str(); - if(rNode.second.empty()) + if (rNode.second.empty()) { // get leaf info m_mic.insert(ConfigNode(++m_oidLastObjectID, strNewPath, 0, rNode.second.get_value().c_str())); @@ -483,129 +483,128 @@ break; } - case eMode_ContainerSplit: + case eMode_ContainerSplit: { strNewPath = strCurrentPath + rNode.first.c_str() + _T("[") + boost::lexical_cast(iIndex++).c_str() + _T("]"); ImportNode(strNewPath, rNode.second); break; } - case eMode_ContainerPassThrough: + case eMode_ContainerPassThrough: { break; } + } } } - } - void ConfigNodeContainer::ImportFromPropertyTree(const boost::property_tree::wiptree& rTree, boost::unique_lock&) - { -// boost::unique_lock lock(m_lock); // do not lock - locking is done outside - m_mic.clear(); + void ConfigNodeContainer::ImportFromPropertyTree(const boost::property_tree::wiptree& rTree, boost::unique_lock&) + { + // boost::unique_lock lock(m_lock); // do not lock - locking is done outside + m_mic.clear(); - // iterate through property tree - ImportNode(_T(""), rTree); + // iterate through property tree + ImportNode(_T(""), rTree); #ifdef _DEBUG - Dump(); + Dump(); #endif - } + } - void ConfigNodeContainer::ExportToPropertyTree(boost::property_tree::wiptree& rTree) const - { - rTree.clear(); + void ConfigNodeContainer::ExportToPropertyTree(boost::property_tree::wiptree& rTree) const + { + rTree.clear(); - size_t stLastBracketID = std::numeric_limits::max(); - TString strGroupNode; + size_t stLastBracketID = std::numeric_limits::max(); + TString strGroupNode; - boost::property_tree::wiptree treeSubnodes; + boost::property_tree::wiptree treeSubnodes; - boost::shared_lock lock(m_lock); - for(NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - const TString& rNodeName = iter->m_strNodeName.Get(); + boost::shared_lock lock(m_lock); + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) + { + const TString& rNodeName = iter->m_strNodeName.Get(); - TString strNodeName = rNodeName; + TString strNodeName = rNodeName; - size_t stBracketPos = strNodeName.Find(_T("[")); - if(stBracketPos != TString::npos) - { - // there is a bracket in the node name - this element is a part of a hierarchy of similar nodes - size_t stSecondBracketPos = strNodeName.Find(_T("]"), stBracketPos + 1); - if(stSecondBracketPos == TString::npos) - THROW_CORE_EXCEPTION(eErr_InvalidData); + size_t stBracketPos = strNodeName.Find(_T("[")); + if (stBracketPos != TString::npos) + { + // there is a bracket in the node name - this element is a part of a hierarchy of similar nodes + size_t stSecondBracketPos = strNodeName.Find(_T("]"), stBracketPos + 1); + if (stSecondBracketPos == TString::npos) + THROW_CORE_EXCEPTION(eErr_InvalidData); - strGroupNode = strNodeName.Left(stBracketPos); - TString strSubnodeName = strNodeName.Mid(stSecondBracketPos + 1); - wchar_t chDot = 0; - if(!strSubnodeName.GetAt(0, chDot) || chDot != L'.') - THROW_CORE_EXCEPTION(eErr_InvalidData); - strSubnodeName.Delete(0, 1); + strGroupNode = strNodeName.Left(stBracketPos); + TString strSubnodeName = strNodeName.Mid(stSecondBracketPos + 1); + wchar_t chDot = 0; + if (!strSubnodeName.GetAt(0, chDot) || chDot != L'.') + THROW_CORE_EXCEPTION(eErr_InvalidData); + strSubnodeName.Delete(0, 1); - size_t stBracketID = boost::lexical_cast(strNodeName.Mid(stBracketPos + 1, stSecondBracketPos - stBracketPos - 1)); - if(stBracketID != stLastBracketID) + size_t stBracketID = boost::lexical_cast(strNodeName.Mid(stBracketPos + 1, stSecondBracketPos - stBracketPos - 1)); + if (stBracketID != stLastBracketID) + { + // new ID - add new property tree node + if (!treeSubnodes.empty()) + { + rTree.add_child(strGroupNode.c_str(), treeSubnodes); + treeSubnodes.clear(); + } + } + + // same ID - add new element to existing property tree node + treeSubnodes.put(strSubnodeName.c_str(), iter->m_strValue.Get()); + stLastBracketID = stBracketID; + } + else { - // new ID - add new property tree node - if(!treeSubnodes.empty()) + // add the subnodes from previous bracket-based entries + if (!treeSubnodes.empty()) { rTree.add_child(strGroupNode.c_str(), treeSubnodes); treeSubnodes.clear(); } - } - // same ID - add new element to existing property tree node - treeSubnodes.put(strSubnodeName.c_str(), iter->m_strValue.Get()); - stLastBracketID = stBracketID; - } - else - { - // add the subnodes from previous bracket-based entries - if(!treeSubnodes.empty()) - { - rTree.add_child(strGroupNode.c_str(), treeSubnodes); - treeSubnodes.clear(); + // no bracket in the node name - this is just a standard entry + rTree.add(strNodeName.c_str(), iter->m_strValue.Get()); } - - // no bracket in the node name - this is just a standard entry - rTree.add(strNodeName.c_str(), iter->m_strValue.Get()); } + + // add the last subnode if not empty + if (!treeSubnodes.empty()) + rTree.add_child(strGroupNode.c_str(), treeSubnodes); } - // add the last subnode if not empty - if(!treeSubnodes.empty()) - rTree.add_child(strGroupNode.c_str(), treeSubnodes); - } - #ifdef _DEBUG - void ConfigNodeContainer::Dump() - { - const size_t stBufferSize = 1024; - TCHAR szBuffer[stBufferSize]; - - for(NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) + void ConfigNodeContainer::Dump() { - unsigned long long ullID = iter->m_oidObjectID; - int iNodeNameModified = iter->m_strNodeName.IsModified() ? 1 : 0; - int iNodeNameModified2 = iter->m_setModifications[ConfigNode::eMod_NodeName]; - int iOrderModified = iter->m_iOrder.IsModified() ? 1 : 0; - int iOrderModified2 = iter->m_setModifications[ConfigNode::eMod_Order]; - int iValueModified = iter->m_strValue.IsModified() ? 1 : 0; - int iValueModified2 = iter->m_setModifications[ConfigNode::eMod_Value]; - bool bAdded = iter->m_setModifications[ConfigNode::eMod_Added]; + const size_t stBufferSize = 1024; + TCHAR szBuffer[stBufferSize]; - _sntprintf_s(szBuffer, stBufferSize, _TRUNCATE, _T("Node (oid %I64u): %s(%ld/%ld).%ld(%ld/%ld) = %s(%ld/%ld)%s\n"), ullID, - iter->m_strNodeName.Get().c_str(), iNodeNameModified, iNodeNameModified2, - iter->m_iOrder.Get(), iOrderModified, iOrderModified2, - iter->m_strValue.Get().c_str(), iValueModified, iValueModified2, - bAdded ? L" [added]" : L""); - OutputDebugString(szBuffer); + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) + { + unsigned long long ullID = iter->m_oidObjectID; + int iNodeNameModified = iter->m_strNodeName.IsModified() ? 1 : 0; + int iNodeNameModified2 = iter->m_setModifications[ConfigNode::eMod_NodeName]; + int iOrderModified = iter->m_iOrder.IsModified() ? 1 : 0; + int iOrderModified2 = iter->m_setModifications[ConfigNode::eMod_Order]; + int iValueModified = iter->m_strValue.IsModified() ? 1 : 0; + int iValueModified2 = iter->m_setModifications[ConfigNode::eMod_Value]; + bool bAdded = iter->m_setModifications[ConfigNode::eMod_Added]; + + _sntprintf_s(szBuffer, stBufferSize, _TRUNCATE, _T("Node (oid %I64u): %s(%ld/%ld).%ld(%ld/%ld) = %s(%ld/%ld)%s\n"), ullID, + iter->m_strNodeName.Get().c_str(), iNodeNameModified, iNodeNameModified2, + iter->m_iOrder.Get(), iOrderModified, iOrderModified2, + iter->m_strValue.Get().c_str(), iValueModified, iValueModified2, + bAdded ? L" [added]" : L""); + OutputDebugString(szBuffer); + } } - } #endif - void ConfigNodeContainer::AddEntry(PCTSTR pszPropName, int iIndex, const TString& strValue) - { - std::pair pairInsert = m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, iIndex, strValue)); - pairInsert.first->m_setModifications.reset(); + void ConfigNodeContainer::AddEntry(PCTSTR pszPropName, int iIndex, const TString& strValue) + { + std::pair pairInsert = m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, iIndex, strValue)); + pairInsert.first->m_setModifications.reset(); + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/ConfigNodeContainer.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ConfigNodeContainer.h (.../ConfigNodeContainer.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/ConfigNodeContainer.h (.../ConfigNodeContainer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -38,233 +38,232 @@ #include #include -BEGIN_CHCORE_NAMESPACE - -namespace details +namespace chcore { - struct ChangeValue + namespace details { - ChangeValue(const TString& strNewValue); + struct ChangeValue + { + ChangeValue(const TString& strNewValue); - void operator()(ConfigNode& rNode); + void operator()(ConfigNode& rNode); - bool WasModified() const; + bool WasModified() const; - private: - TString m_strNewValue; - bool m_bWasModified; - }; + private: + TString m_strNewValue; + bool m_bWasModified; + }; - struct ChangeOrderAndValue - { - ChangeOrderAndValue(const TString& tNewValue, int iOrder); + struct ChangeOrderAndValue + { + ChangeOrderAndValue(const TString& tNewValue, int iOrder); - void operator()(ConfigNode& rNode); + void operator()(ConfigNode& rNode); - bool WasModified() const; + bool WasModified() const; - private: - TString m_strNewValue; - int m_iOrder; - bool m_bWasModified; - }; + private: + TString m_strNewValue; + int m_iOrder; + bool m_bWasModified; + }; - struct ConfigNodeContainer - { - public: - ConfigNodeContainer(); - ConfigNodeContainer(const ConfigNodeContainer& rSrc); - - ConfigNodeContainer& operator=(const ConfigNodeContainer& rSrc); - - void AddEntry(PCTSTR pszPropName, int iIndex, const TString& strValue); - - // get/set single values - template - T GetValue(PCTSTR pszPropName, const T& rDefaultValue) const + struct ConfigNodeContainer { - boost::shared_lock lock(m_lock); - T tResult = rDefaultValue; + public: + ConfigNodeContainer(); + ConfigNodeContainer(const ConfigNodeContainer& rSrc); - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if(iterFnd != m_mic.end()) - tResult = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); + ConfigNodeContainer& operator=(const ConfigNodeContainer& rSrc); - return tResult; - } + void AddEntry(PCTSTR pszPropName, int iIndex, const TString& strValue); - template<> - TString GetValue(PCTSTR pszPropName, const TString& rDefaultValue) const - { - boost::shared_lock lock(m_lock); - TString tResult = rDefaultValue; + // get/set single values + template + T GetValue(PCTSTR pszPropName, const T& rDefaultValue) const + { + boost::shared_lock lock(m_lock); + T tResult = rDefaultValue; - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if(iterFnd != m_mic.end()) - tResult = (*iterFnd).m_strValue; + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + tResult = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); - return tResult; - } + return tResult; + } - template<> - bool GetValue(PCTSTR pszPropName, const bool& bDefaultValue) const - { - boost::shared_lock lock(m_lock); - bool bResult = bDefaultValue; - - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if(iterFnd != m_mic.end()) + template<> + TString GetValue(PCTSTR pszPropName, const TString& rDefaultValue) const { - if((*iterFnd).m_strValue.Get().CompareNoCase(_T("false")) == 0) - bResult = false; - else if((*iterFnd).m_strValue.Get().CompareNoCase(_T("true")) == 0) - bResult = true; - else - bResult = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); - } + boost::shared_lock lock(m_lock); + TString tResult = rDefaultValue; - return bResult; - } + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + tResult = (*iterFnd).m_strValue; - template - bool GetValueNoDefault(PCTSTR pszPropName, T& rValue) const - { - boost::shared_lock lock(m_lock); - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if(iterFnd != m_mic.end()) - { - rValue = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); - return true; + return tResult; } - return false; - } - - template<> - bool GetValueNoDefault(PCTSTR pszPropName, TString& rValue) const - { - boost::shared_lock lock(m_lock); - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if(iterFnd != m_mic.end()) + template<> + bool GetValue(PCTSTR pszPropName, const bool& bDefaultValue) const { - rValue = (*iterFnd).m_strValue; - return true; - } + boost::shared_lock lock(m_lock); + bool bResult = bDefaultValue; - return false; - } + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + if ((*iterFnd).m_strValue.Get().CompareNoCase(_T("false")) == 0) + bResult = false; + else if ((*iterFnd).m_strValue.Get().CompareNoCase(_T("true")) == 0) + bResult = true; + else + bResult = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); + } - template<> - bool GetValueNoDefault(PCTSTR pszPropName, bool& rValue) const - { - boost::shared_lock lock(m_lock); - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if(iterFnd != m_mic.end()) - { - const TString& strValue = (*iterFnd).m_strValue.Get(); - if(strValue.CompareNoCase(_T("false")) == 0) - rValue = false; - else if(strValue.CompareNoCase(_T("true")) == 0) - rValue = true; - else - rValue = boost::lexical_cast(strValue.c_str()); - return true; + return bResult; } - return false; - } + template + bool GetValueNoDefault(PCTSTR pszPropName, T& rValue) const + { + boost::shared_lock lock(m_lock); + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + rValue = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); + return true; + } - template - bool SetValue(PCTSTR pszPropName, const T& rValue) - { - boost::unique_lock lock(m_lock); + return false; + } - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if(iterFnd != m_mic.end()) + template<> + bool GetValueNoDefault(PCTSTR pszPropName, TString& rValue) const { - ChangeValue tChange(boost::lexical_cast(rValue).c_str()); - m_mic.modify(iterFnd, tChange); - return tChange.WasModified(); + boost::shared_lock lock(m_lock); + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + rValue = (*iterFnd).m_strValue; + return true; + } + + return false; } - else + + template<> + bool GetValueNoDefault(PCTSTR pszPropName, bool& rValue) const { - m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, 0, boost::lexical_cast(rValue).c_str())); - return true; + boost::shared_lock lock(m_lock); + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + const TString& strValue = (*iterFnd).m_strValue.Get(); + if (strValue.CompareNoCase(_T("false")) == 0) + rValue = false; + else if (strValue.CompareNoCase(_T("true")) == 0) + rValue = true; + else + rValue = boost::lexical_cast(strValue.c_str()); + return true; + } + + return false; } - } - template<> - bool SetValue(PCTSTR pszPropName, const bool& bValue) - { - boost::unique_lock lock(m_lock); - - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if(iterFnd != m_mic.end()) + template + bool SetValue(PCTSTR pszPropName, const T& rValue) { - ChangeValue tChange(boost::lexical_cast(bValue ? _T("true") : _T("false")).c_str()); - m_mic.modify(iterFnd, tChange); - return tChange.WasModified(); + boost::unique_lock lock(m_lock); + + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + ChangeValue tChange(boost::lexical_cast(rValue).c_str()); + m_mic.modify(iterFnd, tChange); + return tChange.WasModified(); + } + else + { + m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, 0, boost::lexical_cast(rValue).c_str())); + return true; + } } - else + + template<> + bool SetValue(PCTSTR pszPropName, const bool& bValue) { - m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, 0, bValue ? _T("true") : _T("false"))); - return true; + boost::unique_lock lock(m_lock); + + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + ChangeValue tChange(boost::lexical_cast(bValue ? _T("true") : _T("false")).c_str()); + m_mic.modify(iterFnd, tChange); + return tChange.WasModified(); + } + else + { + m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, 0, bValue ? _T("true") : _T("false"))); + return true; + } } - } - // vector-based values - TStringArray GetArrayValue(PCTSTR pszPropName, const TStringArray& rDefaultValue) const; - bool GetArrayValueNoDefault(PCTSTR pszPropName, TStringArray& rValue) const; - bool SetArrayValue(PCTSTR pszPropName, const TStringArray& rValue); + // vector-based values + TStringArray GetArrayValue(PCTSTR pszPropName, const TStringArray& rDefaultValue) const; + bool GetArrayValueNoDefault(PCTSTR pszPropName, TStringArray& rValue) const; + bool SetArrayValue(PCTSTR pszPropName, const TStringArray& rValue); - // deletion - void DeleteNode(PCTSTR pszPropName); + // deletion + void DeleteNode(PCTSTR pszPropName); - // extracting nodes - bool ExtractNodes(PCTSTR pszNode, ConfigNodeContainer& tNewContainer) const; - bool ExtractMultipleNodes(PCTSTR pszNode, std::vector& tNewContainers) const; + // extracting nodes + bool ExtractNodes(PCTSTR pszNode, ConfigNodeContainer& tNewContainer) const; + bool ExtractMultipleNodes(PCTSTR pszNode, std::vector& tNewContainers) const; - void ImportNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer); // replaces specified node with data from tContainer - void AddNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer); // adds specified config as a newly numbered node in this container + void ImportNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer); // replaces specified node with data from tContainer + void AddNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer); // adds specified config as a newly numbered node in this container - void ImportFromPropertyTree(const boost::property_tree::wiptree& rTree, boost::unique_lock&); - void ExportToPropertyTree(boost::property_tree::wiptree& rTree) const; + void ImportFromPropertyTree(const boost::property_tree::wiptree& rTree, boost::unique_lock&); + void ExportToPropertyTree(boost::property_tree::wiptree& rTree) const; #ifdef _DEBUG - // debugging - void Dump(); + // debugging + void Dump(); #endif - private: - void ImportNode(TString strCurrentPath, const boost::property_tree::wiptree& rTree); + private: + void ImportNode(TString strCurrentPath, const boost::property_tree::wiptree& rTree); - public: - typedef boost::multi_index_container, - boost::multi_index::const_mem_fun - > + boost::multi_index::composite_key, + boost::multi_index::const_mem_fun > - > - > NodeContainer; - - NodeContainer m_mic; + > + > + > NodeContainer; - TString m_strFilePath; + NodeContainer m_mic; - boost::signals2::signal m_notifier; - TStringSet m_setDelayedNotifications; - bool m_bDelayedEnabled; - object_id_t m_oidLastObjectID; + TString m_strFilePath; - TRemovedObjects m_setRemovedObjects; + boost::signals2::signal m_notifier; + TStringSet m_setDelayedNotifications; + bool m_bDelayedEnabled; + object_id_t m_oidLastObjectID; - mutable boost::shared_mutex m_lock; - }; + TRemovedObjects m_setRemovedObjects; + + mutable boost::shared_mutex m_lock; + }; + } } -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/EFeedbackResult.h =================================================================== diff -u -N -r671f4b1792a20d98b186f4e0a9cc6a620dede019 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/EFeedbackResult.h (.../EFeedbackResult.h) (revision 671f4b1792a20d98b186f4e0a9cc6a620dede019) +++ src/libchcore/EFeedbackResult.h (.../EFeedbackResult.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,20 +21,19 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -enum EFeedbackResult +namespace chcore { - eResult_Unknown = 0, - eResult_Overwrite, - eResult_CopyRest, - eResult_Skip, - eResult_Cancel, - eResult_Pause, - eResult_Retry, - eResult_Ignore -}; + enum EFeedbackResult + { + eResult_Unknown = 0, + eResult_Overwrite, + eResult_CopyRest, + eResult_Skip, + eResult_Cancel, + eResult_Pause, + eResult_Retry, + eResult_Ignore + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/EFileError.h =================================================================== diff -u -N -rf7314a3065ebf529a998aa0f98072049d06d192f -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/EFileError.h (.../EFileError.h) (revision f7314a3065ebf529a998aa0f98072049d06d192f) +++ src/libchcore/EFileError.h (.../EFileError.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,20 +21,19 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -enum class EFileError +namespace chcore { - eDeleteError, ///< Problem occurred when tried to delete the fs object - eSeekError, ///< Problem occurred when tried to set file pointer - eResizeError, ///< Problem occurred when tried to change size of the fs object - eReadError, ///< Problem occurred when tried to read data from file - eWriteError, ///< Problem occurred when tried to write data to a file - eFinalizeError, ///< Problem occurred when tried to finalize file - eFastMoveError, ///< Problem occurred when tried to perform fast move operation (that does not involve copying contents) - eCreateError ///< Problem occurred when tried to create the fs object -}; + enum class EFileError + { + eDeleteError, ///< Problem occurred when tried to delete the fs object + eSeekError, ///< Problem occurred when tried to set file pointer + eResizeError, ///< Problem occurred when tried to change size of the fs object + eReadError, ///< Problem occurred when tried to read data from file + eWriteError, ///< Problem occurred when tried to write data to a file + eFinalizeError, ///< Problem occurred when tried to finalize file + eFastMoveError, ///< Problem occurred when tried to perform fast move operation (that does not involve copying contents) + eCreateError ///< Problem occurred when tried to create the fs object + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/EOperationTypes.h =================================================================== diff -u -N -r633a533cb6e741d44fe28aa56339e1d2709b1b27 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/EOperationTypes.h (.../EOperationTypes.h) (revision 633a533cb6e741d44fe28aa56339e1d2709b1b27) +++ src/libchcore/EOperationTypes.h (.../EOperationTypes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,19 +25,18 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -// enum represents type of the operation handled by the task -enum EOperationType +namespace chcore { - eOperation_None, - eOperation_Copy, - eOperation_Move, + // enum represents type of the operation handled by the task + enum EOperationType + { + eOperation_None, + eOperation_Copy, + eOperation_Move, - // add new operation types before this enum value - eOperation_Max -}; + // add new operation types before this enum value + eOperation_Max + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ESubTaskTypes.h =================================================================== diff -u -N -rd88274a4bbfd4ef005d44c4d179b7596cb627486 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ESubTaskTypes.h (.../ESubTaskTypes.h) (revision d88274a4bbfd4ef005d44c4d179b7596cb627486) +++ src/libchcore/ESubTaskTypes.h (.../ESubTaskTypes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,20 +25,19 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -enum ESubOperationType +namespace chcore { - eSubOperation_None, - eSubOperation_FastMove, - eSubOperation_Scanning, - eSubOperation_Copying, - eSubOperation_Deleting, + enum ESubOperationType + { + eSubOperation_None, + eSubOperation_FastMove, + eSubOperation_Scanning, + eSubOperation_Copying, + eSubOperation_Deleting, - // add new operation types before this one - eSubOperation_Max -}; + // add new operation types before this one + eSubOperation_Max + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ETaskCurrentState.h =================================================================== diff -u -N -rc9092a6f41bed1c132d5d5ddfe430e8b3ddd70ca -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ETaskCurrentState.h (.../ETaskCurrentState.h) (revision c9092a6f41bed1c132d5d5ddfe430e8b3ddd70ca) +++ src/libchcore/ETaskCurrentState.h (.../ETaskCurrentState.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,24 +21,23 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -// enum representing current processing state of the task -enum ETaskCurrentState +namespace chcore { - eTaskState_None, - eTaskState_Waiting, - eTaskState_Processing, - eTaskState_Paused, - eTaskState_Cancelled, - eTaskState_Error, - eTaskState_Finished, - eTaskState_LoadError, + // enum representing current processing state of the task + enum ETaskCurrentState + { + eTaskState_None, + eTaskState_Waiting, + eTaskState_Processing, + eTaskState_Paused, + eTaskState_Cancelled, + eTaskState_Error, + eTaskState_Finished, + eTaskState_LoadError, - // insert new values before this one - eTaskState_Max -}; + // insert new values before this one + eTaskState_Max + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ErrorCodes.h =================================================================== diff -u -N -re4005a958c9412d890eeff1e8087c8298aa7bcf7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ErrorCodes.h (.../ErrorCodes.h) (revision e4005a958c9412d890eeff1e8087c8298aa7bcf7) +++ src/libchcore/ErrorCodes.h (.../ErrorCodes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,86 +21,85 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -enum EGeneralErrors +namespace chcore { - // general errors - eErr_Success = 0, - eErr_BoundsExceeded = 1, - eErr_InvalidArgument = 2, - eErr_UnhandledCase = 3, - eErr_InternalProblem = 4, - eErr_UseOfUninitializedObject = 5, - eErr_InvalidData = 6, - eErr_InvalidPointer = 7, + enum EGeneralErrors + { + // general errors + eErr_Success = 0, + eErr_BoundsExceeded = 1, + eErr_InvalidArgument = 2, + eErr_UnhandledCase = 3, + eErr_InternalProblem = 4, + eErr_UseOfUninitializedObject = 5, + eErr_InvalidData = 6, + eErr_InvalidPointer = 7, - // shared memory (500+) - eErr_CannotOpenSharedMemory = 500, - eErr_SharedMemoryNotOpen = 501, - eErr_SharedMemoryInvalidFormat = 502, - eErr_SharedMemoryAlreadyExists = 503, + // shared memory (500+) + eErr_CannotOpenSharedMemory = 500, + eErr_SharedMemoryNotOpen = 501, + eErr_SharedMemoryInvalidFormat = 502, + eErr_SharedMemoryAlreadyExists = 503, - // threading (1000+) - eErr_MutexTimedOut = 1000, - eErr_CannotCreateEvent = 1001, - eErr_ThreadAlreadyStarted = 1002, - eErr_CannotResetEvent = 1003, - eErr_CannotCreateThread = 1004, - eErr_CannotChangeThreadPriority = 1005, - eErr_CannotResumeThread = 1006, - eErr_WaitingFailed = 1007, - eErr_CannotSuspendThread = 1008, - eErr_CannotSetEvent = 1009, + // threading (1000+) + eErr_MutexTimedOut = 1000, + eErr_CannotCreateEvent = 1001, + eErr_ThreadAlreadyStarted = 1002, + eErr_CannotResetEvent = 1003, + eErr_CannotCreateThread = 1004, + eErr_CannotChangeThreadPriority = 1005, + eErr_CannotResumeThread = 1006, + eErr_WaitingFailed = 1007, + eErr_CannotSuspendThread = 1008, + eErr_CannotSetEvent = 1009, - // string errors (1500+) + // string errors (1500+) - // Task definition errors (2000+) - eErr_UnsupportedVersion = 2000, - eErr_MissingXmlData = 2001, - eErr_TaskAlreadyExists = 2002, + // Task definition errors (2000+) + eErr_UnsupportedVersion = 2000, + eErr_MissingXmlData = 2001, + eErr_TaskAlreadyExists = 2002, - // Serialization errors (2500+) - eErr_CannotReadArchive = 2500, - eErr_SerializeLoadError = 2501, - eErr_SerializeStoreError = 2502, - eErr_ContainerObjectMismatch = 2503, - eErr_NodeDoesNotExist = 2504, - eErr_UnsupportedMultipleSubnodesLevels = 2505, - eErr_CannotWriteArchive = 2506, - eErr_InvalidSerializationData = 2507, - eErr_CannotSetDatabaseOptions = 2508, - eErr_InvalidSerializer = 2509, + // Serialization errors (2500+) + eErr_CannotReadArchive = 2500, + eErr_SerializeLoadError = 2501, + eErr_SerializeStoreError = 2502, + eErr_ContainerObjectMismatch = 2503, + eErr_NodeDoesNotExist = 2504, + eErr_UnsupportedMultipleSubnodesLevels = 2505, + eErr_CannotWriteArchive = 2506, + eErr_InvalidSerializationData = 2507, + eErr_CannotSetDatabaseOptions = 2508, + eErr_InvalidSerializer = 2509, - // Filesystem errors (3000+) - eErr_FixedDriveWithoutDriveLetter = 3000, - eErr_CannotGetFileInfo = 3001, - eErr_CannotDeleteFile = 3002, - eErr_CannotReadFile = 3003, - eErr_CannotWriteFile = 3004, - eErr_InvalidOverlappedPosition = 3005, + // Filesystem errors (3000+) + eErr_FixedDriveWithoutDriveLetter = 3000, + eErr_CannotGetFileInfo = 3001, + eErr_CannotDeleteFile = 3002, + eErr_CannotReadFile = 3003, + eErr_CannotWriteFile = 3004, + eErr_InvalidOverlappedPosition = 3005, - // Task handling errors (4000+) - eErr_MissingTaskSerializationPath = 4000, - eErr_UndefinedOperation = 4001, + // Task handling errors (4000+) + eErr_MissingTaskSerializationPath = 4000, + eErr_UndefinedOperation = 4001, - // Memory allocation/deallocation (4500+) - eErr_CannotAllocateMemory = 4500, + // Memory allocation/deallocation (4500+) + eErr_CannotAllocateMemory = 4500, - // database errors (5000+) - eErr_SQLiteCannotOpenDatabase = 5000, - eErr_SQLiteFinalizeError = 5001, - eErr_SQLitePrepareError = 5002, - eErr_SQLiteStatementNotPrepared = 5003, - eErr_SQLiteStepError = 5004, - eErr_SQLiteBindError = 5005, - eErr_SQLiteNoRowAvailable = 5006, - eErr_SQLiteCannotBeginTransaction = 5007, - eErr_SQLiteCannotRollbackTransaction = 5008, - eErr_SQLiteCannotCommitTransaction = 5009, - eErr_SQLiteReset = 5010, -}; + // database errors (5000+) + eErr_SQLiteCannotOpenDatabase = 5000, + eErr_SQLiteFinalizeError = 5001, + eErr_SQLitePrepareError = 5002, + eErr_SQLiteStatementNotPrepared = 5003, + eErr_SQLiteStepError = 5004, + eErr_SQLiteBindError = 5005, + eErr_SQLiteNoRowAvailable = 5006, + eErr_SQLiteCannotBeginTransaction = 5007, + eErr_SQLiteCannotRollbackTransaction = 5008, + eErr_SQLiteCannotCommitTransaction = 5009, + eErr_SQLiteReset = 5010, + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/IColumnsDefinition.cpp =================================================================== diff -u -N -r9479911a096555a7504c5c8a8eaee83ecb63440c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IColumnsDefinition.cpp (.../IColumnsDefinition.cpp) (revision 9479911a096555a7504c5c8a8eaee83ecb63440c) +++ src/libchcore/IColumnsDefinition.cpp (.../IColumnsDefinition.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "IColumnsDefinition.h" -BEGIN_CHCORE_NAMESPACE - -IColumnsDefinition::~IColumnsDefinition() +namespace chcore { + IColumnsDefinition::~IColumnsDefinition() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/IColumnsDefinition.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IColumnsDefinition.h (.../IColumnsDefinition.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/IColumnsDefinition.h (.../IColumnsDefinition.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,61 +24,60 @@ #include #include "TPath.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API IColumnsDefinition +namespace chcore { -public: - enum ETypes + class LIBCHCORE_API IColumnsDefinition { - eType_bool, - eType_short, - eType_ushort, - eType_int, - eType_uint, - eType_long, - eType_ulong, - eType_longlong, - eType_ulonglong, - eType_double, - eType_string, - eType_path, + public: + enum ETypes + { + eType_bool, + eType_short, + eType_ushort, + eType_int, + eType_uint, + eType_long, + eType_ulong, + eType_longlong, + eType_ulonglong, + eType_double, + eType_string, + eType_path, - eType_Last - }; + eType_Last + }; -public: - virtual ~IColumnsDefinition(); + public: + virtual ~IColumnsDefinition(); - virtual size_t AddColumn(const TString& strColumnName, ETypes eColType) = 0; - virtual void Clear() = 0; + virtual size_t AddColumn(const TString& strColumnName, ETypes eColType) = 0; + virtual void Clear() = 0; - virtual size_t GetColumnIndex(const wchar_t* strColumnName) = 0; - virtual const TString& GetColumnName(size_t stIndex) const = 0; - virtual size_t GetCount() const = 0; - virtual bool IsEmpty() const = 0; -}; + virtual size_t GetColumnIndex(const wchar_t* strColumnName) = 0; + virtual const TString& GetColumnName(size_t stIndex) const = 0; + virtual size_t GetCount() const = 0; + virtual bool IsEmpty() const = 0; + }; -template struct ColumnType {}; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_bool; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_short; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ushort; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_int; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_uint; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_long; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ulong; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_longlong; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ulonglong; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_double; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_string; }; -template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_path; }; + template struct ColumnType {}; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_bool; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_short; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ushort; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_int; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_uint; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_long; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ulong; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_longlong; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ulonglong; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_double; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_string; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_path; }; -template -IColumnsDefinition::ETypes GetColumnType(const T&) -{ - return ColumnType::value; + template + IColumnsDefinition::ETypes GetColumnType(const T&) + { + return ColumnType::value; + } } -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/IFeedbackHandler.cpp =================================================================== diff -u -N -r458af7bf8c35950fdeb4b906950437596324aea1 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IFeedbackHandler.cpp (.../IFeedbackHandler.cpp) (revision 458af7bf8c35950fdeb4b906950437596324aea1) +++ src/libchcore/IFeedbackHandler.cpp (.../IFeedbackHandler.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "IFeedbackHandler.h" -BEGIN_CHCORE_NAMESPACE - -IFeedbackHandler::~IFeedbackHandler() +namespace chcore { + IFeedbackHandler::~IFeedbackHandler() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/IFeedbackHandler.h =================================================================== diff -u -N -r2755e12daeccb1935f569e7235e685e566b0b098 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IFeedbackHandler.h (.../IFeedbackHandler.h) (revision 2755e12daeccb1935f569e7235e685e566b0b098) +++ src/libchcore/IFeedbackHandler.h (.../IFeedbackHandler.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -27,32 +27,31 @@ #include "ISerializerRowData.h" #include "EFileError.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API IFeedbackHandler +namespace chcore { -public: - virtual ~IFeedbackHandler(); + class LIBCHCORE_API IFeedbackHandler + { + public: + virtual ~IFeedbackHandler(); - // requests with some processing data - virtual EFeedbackResult FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) = 0; - virtual EFeedbackResult FileAlreadyExists(const TFileInfoPtr& spSrcFileInfo, const TFileInfoPtr& spDstFileInfo) = 0; - virtual EFeedbackResult NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) = 0; + // requests with some processing data + virtual EFeedbackResult FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) = 0; + virtual EFeedbackResult FileAlreadyExists(const TFileInfoPtr& spSrcFileInfo, const TFileInfoPtr& spDstFileInfo) = 0; + virtual EFeedbackResult NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) = 0; - // no-data requests - virtual EFeedbackResult OperationFinished() = 0; - virtual EFeedbackResult OperationError() = 0; + // no-data requests + virtual EFeedbackResult OperationFinished() = 0; + virtual EFeedbackResult OperationError() = 0; - // reset permanent states - virtual void RestoreDefaults() = 0; + // reset permanent states + virtual void RestoreDefaults() = 0; - //serialization - virtual void Store(const ISerializerContainerPtr& spContainer) const = 0; - virtual void Load(const ISerializerContainerPtr& spContainer) = 0; -}; + //serialization + virtual void Store(const ISerializerContainerPtr& spContainer) const = 0; + virtual void Load(const ISerializerContainerPtr& spContainer) = 0; + }; -typedef boost::shared_ptr IFeedbackHandlerPtr; + typedef boost::shared_ptr IFeedbackHandlerPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/IFeedbackHandlerFactory.cpp =================================================================== diff -u -N -r458af7bf8c35950fdeb4b906950437596324aea1 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IFeedbackHandlerFactory.cpp (.../IFeedbackHandlerFactory.cpp) (revision 458af7bf8c35950fdeb4b906950437596324aea1) +++ src/libchcore/IFeedbackHandlerFactory.cpp (.../IFeedbackHandlerFactory.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "IFeedbackHandlerFactory.h" -BEGIN_CHCORE_NAMESPACE - -IFeedbackHandlerFactory::~IFeedbackHandlerFactory() +namespace chcore { + IFeedbackHandlerFactory::~IFeedbackHandlerFactory() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/IFeedbackHandlerFactory.h =================================================================== diff -u -N -r671f4b1792a20d98b186f4e0a9cc6a620dede019 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IFeedbackHandlerFactory.h (.../IFeedbackHandlerFactory.h) (revision 671f4b1792a20d98b186f4e0a9cc6a620dede019) +++ src/libchcore/IFeedbackHandlerFactory.h (.../IFeedbackHandlerFactory.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,17 +22,16 @@ #include "libchcore.h" #include "IFeedbackHandler.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API IFeedbackHandlerFactory +namespace chcore { -public: - virtual ~IFeedbackHandlerFactory(); - virtual IFeedbackHandlerPtr Create() = 0; -}; + class LIBCHCORE_API IFeedbackHandlerFactory + { + public: + virtual ~IFeedbackHandlerFactory(); + virtual IFeedbackHandlerPtr Create() = 0; + }; -typedef boost::shared_ptr IFeedbackHandlerFactoryPtr; + typedef boost::shared_ptr IFeedbackHandlerFactoryPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/IFilesystem.cpp =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IFilesystem.cpp (.../IFilesystem.cpp) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/IFilesystem.cpp (.../IFilesystem.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "IFilesystem.h" -BEGIN_CHCORE_NAMESPACE - -IFilesystem::~IFilesystem() +namespace chcore { + IFilesystem::~IFilesystem() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/IFilesystem.h =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IFilesystem.h (.../IFilesystem.h) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/IFilesystem.h (.../IFilesystem.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -27,45 +27,44 @@ #include "IFilesystemFind.h" #include "IFilesystemFile.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API IFilesystem +namespace chcore { -public: - enum EPathsRelation + class LIBCHCORE_API IFilesystem { - eRelation_Network, // at least one of the paths is network one - eRelation_CDRom, // at least one of the paths relates to cd/dvd drive - eRelation_TwoPhysicalDisks, // paths lies on two separate physical disks - eRelation_SinglePhysicalDisk, // paths lies on the same physical disk - eRelation_Other // other type of relation - }; + public: + enum EPathsRelation + { + eRelation_Network, // at least one of the paths is network one + eRelation_CDRom, // at least one of the paths relates to cd/dvd drive + eRelation_TwoPhysicalDisks, // paths lies on two separate physical disks + eRelation_SinglePhysicalDisk, // paths lies on the same physical disk + eRelation_Other // other type of relation + }; -public: - virtual ~IFilesystem(); + public: + virtual ~IFilesystem(); - virtual bool PathExist(const TSmartPath& strPath) = 0; + virtual bool PathExist(const TSmartPath& strPath) = 0; - virtual bool SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) = 0; - virtual bool SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) = 0; + virtual bool SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) = 0; + virtual bool SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) = 0; - virtual bool CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) = 0; - virtual bool RemoveDirectory(const TSmartPath& pathFile) = 0; - virtual bool DeleteFile(const TSmartPath& pathFile) = 0; + virtual bool CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) = 0; + virtual bool RemoveDirectory(const TSmartPath& pathFile) = 0; + virtual bool DeleteFile(const TSmartPath& pathFile) = 0; - virtual bool GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData = TBasePathDataPtr()) = 0; - virtual bool FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) = 0; + virtual bool GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData = TBasePathDataPtr()) = 0; + virtual bool FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) = 0; - virtual IFilesystemFindPtr CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) = 0; - virtual IFilesystemFilePtr CreateFileObject(const TSmartPath& pathFile) = 0; + virtual IFilesystemFindPtr CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) = 0; + virtual IFilesystemFilePtr CreateFileObject(const TSmartPath& pathFile) = 0; - virtual EPathsRelation GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) = 0; + virtual EPathsRelation GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) = 0; - virtual bool GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree) = 0; -}; + virtual bool GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree) = 0; + }; -typedef std::shared_ptr IFilesystemPtr; + typedef std::shared_ptr IFilesystemPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/IFilesystemFind.cpp =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IFilesystemFind.cpp (.../IFilesystemFind.cpp) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/IFilesystemFind.cpp (.../IFilesystemFind.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "IFilesystemFind.h" -BEGIN_CHCORE_NAMESPACE - -IFilesystemFind::~IFilesystemFind() +namespace chcore { + IFilesystemFind::~IFilesystemFind() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/IFilesystemFind.h =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IFilesystemFind.h (.../IFilesystemFind.h) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/IFilesystemFind.h (.../IFilesystemFind.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,19 +22,18 @@ #include "libchcore.h" #include "TFileInfoFwd.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API IFilesystemFind +namespace chcore { -public: - virtual ~IFilesystemFind(); + class LIBCHCORE_API IFilesystemFind + { + public: + virtual ~IFilesystemFind(); - virtual bool FindNext(TFileInfoPtr& rspFileInfo) = 0; - virtual void Close() = 0; -}; + virtual bool FindNext(TFileInfoPtr& rspFileInfo) = 0; + virtual void Close() = 0; + }; -typedef std::shared_ptr IFilesystemFindPtr; + typedef std::shared_ptr IFilesystemFindPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/IOverlappedDataBufferQueue.cpp =================================================================== diff -u -N -rea7d62521e78371cff90579749d136cb928c9e88 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IOverlappedDataBufferQueue.cpp (.../IOverlappedDataBufferQueue.cpp) (revision ea7d62521e78371cff90579749d136cb928c9e88) +++ src/libchcore/IOverlappedDataBufferQueue.cpp (.../IOverlappedDataBufferQueue.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "IOverlappedDataBufferQueue.h" -BEGIN_CHCORE_NAMESPACE - -IOverlappedDataBufferQueue::~IOverlappedDataBufferQueue() +namespace chcore { + IOverlappedDataBufferQueue::~IOverlappedDataBufferQueue() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/IOverlappedDataBufferQueue.h =================================================================== diff -u -N -r6103ac74583f2136b821dc67515ed8469abd8155 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IOverlappedDataBufferQueue.h (.../IOverlappedDataBufferQueue.h) (revision 6103ac74583f2136b821dc67515ed8469abd8155) +++ src/libchcore/IOverlappedDataBufferQueue.h (.../IOverlappedDataBufferQueue.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,26 +21,25 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class TOverlappedDataBuffer; - -class IOverlappedDataBufferQueue +namespace chcore { -public: - virtual ~IOverlappedDataBufferQueue(); + class TOverlappedDataBuffer; - // buffer management - virtual void AddEmptyBuffer(TOverlappedDataBuffer* pBuffer) = 0; - virtual TOverlappedDataBuffer* GetEmptyBuffer() = 0; + class IOverlappedDataBufferQueue + { + public: + virtual ~IOverlappedDataBufferQueue(); - virtual void AddFullBuffer(TOverlappedDataBuffer* pBuffer) = 0; - virtual TOverlappedDataBuffer* GetFullBuffer() = 0; + // buffer management + virtual void AddEmptyBuffer(TOverlappedDataBuffer* pBuffer) = 0; + virtual TOverlappedDataBuffer* GetEmptyBuffer() = 0; - virtual void AddFinishedBuffer(TOverlappedDataBuffer* pBuffer) = 0; - virtual TOverlappedDataBuffer* GetFinishedBuffer() = 0; -}; + virtual void AddFullBuffer(TOverlappedDataBuffer* pBuffer) = 0; + virtual TOverlappedDataBuffer* GetFullBuffer() = 0; -END_CHCORE_NAMESPACE + virtual void AddFinishedBuffer(TOverlappedDataBuffer* pBuffer) = 0; + virtual TOverlappedDataBuffer* GetFinishedBuffer() = 0; + }; +} #endif Index: src/libchcore/IRunningTimeControl.cpp =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IRunningTimeControl.cpp (.../IRunningTimeControl.cpp) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/IRunningTimeControl.cpp (.../IRunningTimeControl.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "IRunningTimeControl.h" -BEGIN_CHCORE_NAMESPACE - -IRunningTimeControl::~IRunningTimeControl() +namespace chcore { + IRunningTimeControl::~IRunningTimeControl() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/IRunningTimeControl.h =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/IRunningTimeControl.h (.../IRunningTimeControl.h) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/IRunningTimeControl.h (.../IRunningTimeControl.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,22 +21,21 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class IRunningTimeControl +namespace chcore { -public: - virtual ~IRunningTimeControl(); + class IRunningTimeControl + { + public: + virtual ~IRunningTimeControl(); - // time tracking - virtual void EnableTimeTracking() = 0; - virtual void DisableTimeTracking() = 0; + // time tracking + virtual void EnableTimeTracking() = 0; + virtual void DisableTimeTracking() = 0; - // running/not running state - virtual void MarkAsRunning() = 0; - virtual void MarkAsNotRunning() = 0; -}; + // running/not running state + virtual void MarkAsRunning() = 0; + virtual void MarkAsNotRunning() = 0; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ISQLiteSerializerSchema.cpp =================================================================== diff -u -N -r9479911a096555a7504c5c8a8eaee83ecb63440c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISQLiteSerializerSchema.cpp (.../ISQLiteSerializerSchema.cpp) (revision 9479911a096555a7504c5c8a8eaee83ecb63440c) +++ src/libchcore/ISQLiteSerializerSchema.cpp (.../ISQLiteSerializerSchema.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "ISQLiteSerializerSchema.h" -BEGIN_CHCORE_NAMESPACE - -ISQLiteSerializerSchema::~ISQLiteSerializerSchema() +namespace chcore { + ISQLiteSerializerSchema::~ISQLiteSerializerSchema() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/ISQLiteSerializerSchema.h =================================================================== diff -u -N -r9479911a096555a7504c5c8a8eaee83ecb63440c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISQLiteSerializerSchema.h (.../ISQLiteSerializerSchema.h) (revision 9479911a096555a7504c5c8a8eaee83ecb63440c) +++ src/libchcore/ISQLiteSerializerSchema.h (.../ISQLiteSerializerSchema.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,18 +22,17 @@ #include "libchcore.h" #include "TSQLiteDatabase.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API ISQLiteSerializerSchema +namespace chcore { -public: - virtual ~ISQLiteSerializerSchema(); + class LIBCHCORE_API ISQLiteSerializerSchema + { + public: + virtual ~ISQLiteSerializerSchema(); - virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) = 0; -}; + virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) = 0; + }; -typedef boost::shared_ptr ISerializerSchemaPtr; + typedef boost::shared_ptr ISerializerSchemaPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ISerializer.cpp =================================================================== diff -u -N -r9479911a096555a7504c5c8a8eaee83ecb63440c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializer.cpp (.../ISerializer.cpp) (revision 9479911a096555a7504c5c8a8eaee83ecb63440c) +++ src/libchcore/ISerializer.cpp (.../ISerializer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "ISerializer.h" -BEGIN_CHCORE_NAMESPACE - -ISerializer::~ISerializer() +namespace chcore { + ISerializer::~ISerializer() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/ISerializer.h =================================================================== diff -u -N -r9479911a096555a7504c5c8a8eaee83ecb63440c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializer.h (.../ISerializer.h) (revision 9479911a096555a7504c5c8a8eaee83ecb63440c) +++ src/libchcore/ISerializer.h (.../ISerializer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,21 +23,20 @@ #include "TPath.h" #include "ISerializerContainer.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API ISerializer +namespace chcore { -public: - virtual ~ISerializer(); + class LIBCHCORE_API ISerializer + { + public: + virtual ~ISerializer(); - virtual TSmartPath GetLocation() const = 0; - virtual ISerializerContainerPtr GetContainer(const TString& strContainerName) = 0; + virtual TSmartPath GetLocation() const = 0; + virtual ISerializerContainerPtr GetContainer(const TString& strContainerName) = 0; - virtual void Flush() = 0; -}; + virtual void Flush() = 0; + }; -typedef boost::shared_ptr ISerializerPtr; + typedef boost::shared_ptr ISerializerPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ISerializerContainer.cpp =================================================================== diff -u -N -r4a7f28238afbf60b9e3f3daeffe590ff1638ec74 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializerContainer.cpp (.../ISerializerContainer.cpp) (revision 4a7f28238afbf60b9e3f3daeffe590ff1638ec74) +++ src/libchcore/ISerializerContainer.cpp (.../ISerializerContainer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "ISerializerContainer.h" -BEGIN_CHCORE_NAMESPACE - -ISerializerContainer::~ISerializerContainer() +namespace chcore { + ISerializerContainer::~ISerializerContainer() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/ISerializerContainer.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializerContainer.h (.../ISerializerContainer.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/ISerializerContainer.h (.../ISerializerContainer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,30 +24,29 @@ #include "ISerializerRowReader.h" #include "SerializerDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -class ISerializerRowData; -class TRemovedObjects; - -class LIBCHCORE_API ISerializerContainer +namespace chcore { -public: - virtual ~ISerializerContainer(); + class ISerializerRowData; + class TRemovedObjects; - // columns - virtual IColumnsDefinition& GetColumnsDefinition() = 0; + class LIBCHCORE_API ISerializerContainer + { + public: + virtual ~ISerializerContainer(); - // prepare data to be stored - virtual ISerializerRowData& GetRow(object_id_t oidRowID, bool bMarkAsAdded) = 0; - virtual void DeleteRow(object_id_t oidRowID) = 0; - virtual void DeleteRows(const TRemovedObjects& setObjects) = 0; + // columns + virtual IColumnsDefinition& GetColumnsDefinition() = 0; - // getting data from the serialized archive - virtual ISerializerRowReaderPtr GetRowReader() = 0; -}; + // prepare data to be stored + virtual ISerializerRowData& GetRow(object_id_t oidRowID, bool bMarkAsAdded) = 0; + virtual void DeleteRow(object_id_t oidRowID) = 0; + virtual void DeleteRows(const TRemovedObjects& setObjects) = 0; -typedef boost::shared_ptr ISerializerContainerPtr; + // getting data from the serialized archive + virtual ISerializerRowReaderPtr GetRowReader() = 0; + }; -END_CHCORE_NAMESPACE + typedef boost::shared_ptr ISerializerContainerPtr; +} #endif Index: src/libchcore/ISerializerFactory.cpp =================================================================== diff -u -N -rd32a79f0e9220bad2c6eeb5e8a986228b6e832fb -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializerFactory.cpp (.../ISerializerFactory.cpp) (revision d32a79f0e9220bad2c6eeb5e8a986228b6e832fb) +++ src/libchcore/ISerializerFactory.cpp (.../ISerializerFactory.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "ISerializerFactory.h" -BEGIN_CHCORE_NAMESPACE - -ISerializerFactory::~ISerializerFactory() +namespace chcore { + ISerializerFactory::~ISerializerFactory() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/ISerializerFactory.h =================================================================== diff -u -N -rcdb4c898156398dd4f4bf8abd7c854eff42f6ae2 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializerFactory.h (.../ISerializerFactory.h) (revision cdb4c898156398dd4f4bf8abd7c854eff42f6ae2) +++ src/libchcore/ISerializerFactory.h (.../ISerializerFactory.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,19 +23,18 @@ #include "TString.h" #include "ISerializer.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API ISerializerFactory +namespace chcore { -public: - virtual ~ISerializerFactory(); + class LIBCHCORE_API ISerializerFactory + { + public: + virtual ~ISerializerFactory(); - virtual ISerializerPtr CreateTaskManagerSerializer(bool bForceRecreate = false) = 0; - virtual ISerializerPtr CreateTaskSerializer(const TString& strNameHint = _T(""), bool bForceRecreate = false) = 0; -}; + virtual ISerializerPtr CreateTaskManagerSerializer(bool bForceRecreate = false) = 0; + virtual ISerializerPtr CreateTaskSerializer(const TString& strNameHint = _T(""), bool bForceRecreate = false) = 0; + }; -typedef boost::shared_ptr ISerializerFactoryPtr; + typedef boost::shared_ptr ISerializerFactoryPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ISerializerRowData.cpp =================================================================== diff -u -N -r31c4b1fc46687ed2cf35dd9fa0acec2543ae1886 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializerRowData.cpp (.../ISerializerRowData.cpp) (revision 31c4b1fc46687ed2cf35dd9fa0acec2543ae1886) +++ src/libchcore/ISerializerRowData.cpp (.../ISerializerRowData.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "ISerializerRowData.h" -BEGIN_CHCORE_NAMESPACE - -ISerializerRowData::~ISerializerRowData() +namespace chcore { + ISerializerRowData::~ISerializerRowData() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/ISerializerRowData.h =================================================================== diff -u -N -r7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializerRowData.h (.../ISerializerRowData.h) (revision 7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66) +++ src/libchcore/ISerializerRowData.h (.../ISerializerRowData.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,43 +23,42 @@ #include "TString.h" #include "TPath.h" -BEGIN_CHCORE_NAMESPACE - -class ISerializerContainer; -typedef boost::shared_ptr ISerializerContainerPtr; - -class LIBCHCORE_API ISerializerRowData +namespace chcore { -public: - virtual ~ISerializerRowData(); + class ISerializerContainer; + typedef boost::shared_ptr ISerializerContainerPtr; - virtual ISerializerRowData& SetValue(size_t stColIndex, bool bValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, short iValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned short uiValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, int iValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned int uiValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, long lValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long ulValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, long long llValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long long llValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, double dValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, const TString& strValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, const TSmartPath& pathValue) = 0; + class LIBCHCORE_API ISerializerRowData + { + public: + virtual ~ISerializerRowData(); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, bool bValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, short iValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned short uiValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, int iValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned int uiValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long lValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long ulValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long long llValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long long llValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, double dValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TString& strValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue) = 0; -}; + virtual ISerializerRowData& SetValue(size_t stColIndex, bool bValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, short iValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned short uiValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, int iValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned int uiValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, long lValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long ulValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, long long llValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long long llValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, double dValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, const TString& strValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, const TSmartPath& pathValue) = 0; -END_CHCORE_NAMESPACE + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, bool bValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, short iValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned short uiValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, int iValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned int uiValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long lValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long ulValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long long llValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long long llValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, double dValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TString& strValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue) = 0; + }; +} #endif Index: src/libchcore/ISerializerRowReader.cpp =================================================================== diff -u -N -r9479911a096555a7504c5c8a8eaee83ecb63440c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializerRowReader.cpp (.../ISerializerRowReader.cpp) (revision 9479911a096555a7504c5c8a8eaee83ecb63440c) +++ src/libchcore/ISerializerRowReader.cpp (.../ISerializerRowReader.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #include "stdafx.h" #include "ISerializerRowReader.h" -BEGIN_CHCORE_NAMESPACE - -ISerializerRowReader::~ISerializerRowReader() +namespace chcore { + ISerializerRowReader::~ISerializerRowReader() + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/ISerializerRowReader.h =================================================================== diff -u -N -rfc67a825635691930b3ac00dc95b16e59f3d2fae -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ISerializerRowReader.h (.../ISerializerRowReader.h) (revision fc67a825635691930b3ac00dc95b16e59f3d2fae) +++ src/libchcore/ISerializerRowReader.h (.../ISerializerRowReader.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,31 +24,30 @@ #include "TPath.h" #include "IColumnsDefinition.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API ISerializerRowReader +namespace chcore { -public: - virtual ~ISerializerRowReader(); + class LIBCHCORE_API ISerializerRowReader + { + public: + virtual ~ISerializerRowReader(); - virtual bool Next() = 0; + virtual bool Next() = 0; - virtual void GetValue(const TString& strColName, bool& bValue) = 0; - virtual void GetValue(const TString& strColName, short& iValue) = 0; - virtual void GetValue(const TString& strColName, unsigned short& uiValue) = 0; - virtual void GetValue(const TString& strColName, int& iValue) = 0; - virtual void GetValue(const TString& strColName, unsigned int& uiValue) = 0; - virtual void GetValue(const TString& strColName, long& lValue) = 0; - virtual void GetValue(const TString& strColName, unsigned long& ulValue) = 0; - virtual void GetValue(const TString& strColName, long long& llValue) = 0; - virtual void GetValue(const TString& strColName, unsigned long long& llValue) = 0; - virtual void GetValue(const TString& strColName, double& dValue) = 0; - virtual void GetValue(const TString& strColName, TString& strValue) = 0; - virtual void GetValue(const TString& strColName, TSmartPath& pathValue) = 0; -}; + virtual void GetValue(const TString& strColName, bool& bValue) = 0; + virtual void GetValue(const TString& strColName, short& iValue) = 0; + virtual void GetValue(const TString& strColName, unsigned short& uiValue) = 0; + virtual void GetValue(const TString& strColName, int& iValue) = 0; + virtual void GetValue(const TString& strColName, unsigned int& uiValue) = 0; + virtual void GetValue(const TString& strColName, long& lValue) = 0; + virtual void GetValue(const TString& strColName, unsigned long& ulValue) = 0; + virtual void GetValue(const TString& strColName, long long& llValue) = 0; + virtual void GetValue(const TString& strColName, unsigned long long& llValue) = 0; + virtual void GetValue(const TString& strColName, double& dValue) = 0; + virtual void GetValue(const TString& strColName, TString& strValue) = 0; + virtual void GetValue(const TString& strColName, TSmartPath& pathValue) = 0; + }; -typedef boost::shared_ptr ISerializerRowReaderPtr; + typedef boost::shared_ptr ISerializerRowReaderPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/ITimestampProvider.h =================================================================== diff -u -N -rc8e73b75027d5e17fb8b1e1eb40e64f40fc62547 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/ITimestampProvider.h (.../ITimestampProvider.h) (revision c8e73b75027d5e17fb8b1e1eb40e64f40fc62547) +++ src/libchcore/ITimestampProvider.h (.../ITimestampProvider.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,17 +21,16 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API ITimestampProvider +namespace chcore { -public: - virtual ~ITimestampProvider() {} - virtual unsigned long long GetCurrentTimestamp() const = 0; -}; + class LIBCHCORE_API ITimestampProvider + { + public: + virtual ~ITimestampProvider() {} + virtual unsigned long long GetCurrentTimestamp() const = 0; + }; -typedef boost::shared_ptr ITimestampProviderPtr; + typedef boost::shared_ptr ITimestampProviderPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/MathFunctions.cpp =================================================================== diff -u -N -r9b8cccbee0fcfeca28a112cc0253a7641f73f74f -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/MathFunctions.cpp (.../MathFunctions.cpp) (revision 9b8cccbee0fcfeca28a112cc0253a7641f73f74f) +++ src/libchcore/MathFunctions.cpp (.../MathFunctions.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -2,24 +2,23 @@ #include "MathFunctions.h" #include -BEGIN_CHCORE_NAMESPACE - -namespace Math +namespace chcore { - double Div64(unsigned long long ullNumber, unsigned long long ullDenominator) + namespace Math { - if(ullDenominator == 0) - return 0.0; - - const unsigned long long ullMaxInt32 = (unsigned long long)std::numeric_limits::max(); - while(ullNumber > ullMaxInt32 || ullDenominator > ullMaxInt32) + double Div64(unsigned long long ullNumber, unsigned long long ullDenominator) { - ullNumber >>= 1; - ullDenominator >>= 1; - } + if (ullDenominator == 0) + return 0.0; - return boost::numeric_cast(ullNumber) / boost::numeric_cast(ullDenominator); + const unsigned long long ullMaxInt32 = (unsigned long long)std::numeric_limits::max(); + while (ullNumber > ullMaxInt32 || ullDenominator > ullMaxInt32) + { + ullNumber >>= 1; + ullDenominator >>= 1; + } + + return boost::numeric_cast(ullNumber) / boost::numeric_cast(ullDenominator); + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/MathFunctions.h =================================================================== diff -u -N -r9b8cccbee0fcfeca28a112cc0253a7641f73f74f -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/MathFunctions.h (.../MathFunctions.h) (revision 9b8cccbee0fcfeca28a112cc0253a7641f73f74f) +++ src/libchcore/MathFunctions.h (.../MathFunctions.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,13 +21,12 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -namespace Math +namespace chcore { - LIBCHCORE_API double Div64(unsigned long long ullNumber, unsigned long long ullDenominator); + namespace Math + { + LIBCHCORE_API double Div64(unsigned long long ullNumber, unsigned long long ullDenominator); + } } -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/RoundingFunctions.h =================================================================== diff -u -N -rcdc76e1a95383dff63a5254aeb8d37035028512c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/RoundingFunctions.h (.../RoundingFunctions.h) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/RoundingFunctions.h (.../RoundingFunctions.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,11 +21,10 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + template T RoundUp(T number, T roundValue) { return ((number + roundValue - 1) & ~(roundValue - 1)); } + template T RoundDown(T number, T roundValue) { return (number & ~(roundValue - 1)); } +} -template T RoundUp(T number, T roundValue) { return ((number + roundValue - 1) & ~(roundValue - 1)); } -template T RoundDown(T number, T roundValue) { return (number & ~(roundValue - 1)); } - -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/SerializerDataTypes.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/SerializerDataTypes.h (.../SerializerDataTypes.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/SerializerDataTypes.h (.../SerializerDataTypes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,10 +19,9 @@ #ifndef __SERIALIZERDATATYPES_H__ #define __SERIALIZERDATATYPES_H__ -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + typedef unsigned long object_id_t; +} -typedef unsigned long object_id_t; - -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TAutoHandles.h =================================================================== diff -u -N -rfb4c4006dee5aaf815d08bc3e89312445b994307 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TAutoHandles.h (.../TAutoHandles.h) (revision fb4c4006dee5aaf815d08bc3e89312445b994307) +++ src/libchcore/TAutoHandles.h (.../TAutoHandles.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,113 +25,112 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -/// class encapsulates windows HANDLE, allowing automatic closing it in destructor. -class TAutoFileHandle +namespace chcore { -public: - // ============================================================================ - /// TAutoFileHandle::TAutoFileHandle - /// @date 2010/08/26 - /// - /// @brief Constructs the TAutoFileHandle object. - // ============================================================================ - TAutoFileHandle() : - m_hHandle(INVALID_HANDLE_VALUE) + /// class encapsulates windows HANDLE, allowing automatic closing it in destructor. + class TAutoFileHandle { - } + public: + // ============================================================================ + /// TAutoFileHandle::TAutoFileHandle + /// @date 2010/08/26 + /// + /// @brief Constructs the TAutoFileHandle object. + // ============================================================================ + TAutoFileHandle() : + m_hHandle(INVALID_HANDLE_VALUE) + { + } - // ============================================================================ - /// TAutoFileHandle::TAutoFileHandle - /// @date 2010/08/26 - /// - /// @brief Constructs the TAutoFileHandle object with specified handle. - /// @param[in] hHandle - System handle to be managed by this class. - // ============================================================================ - TAutoFileHandle(HANDLE hHandle) : - m_hHandle(hHandle) - { - } + // ============================================================================ + /// TAutoFileHandle::TAutoFileHandle + /// @date 2010/08/26 + /// + /// @brief Constructs the TAutoFileHandle object with specified handle. + /// @param[in] hHandle - System handle to be managed by this class. + // ============================================================================ + TAutoFileHandle(HANDLE hHandle) : + m_hHandle(hHandle) + { + } - // ============================================================================ - /// TAutoFileHandle::~TAutoFileHandle - /// @date 2010/08/26 - /// - /// @brief Destructs the TAutoFileHandle object and closes handle if not closed already. - // ============================================================================ - ~TAutoFileHandle() - { - Close(); - } - - // ============================================================================ - /// TAutoFileHandle::operator= - /// @date 2010/08/26 - /// - /// @brief Assignment operator. - /// @param[in] hHandle - Handle to be assigned. - /// @return Reference to this object, - // ============================================================================ - TAutoFileHandle& operator=(HANDLE hHandle) - { - if(m_hHandle != hHandle) + // ============================================================================ + /// TAutoFileHandle::~TAutoFileHandle + /// @date 2010/08/26 + /// + /// @brief Destructs the TAutoFileHandle object and closes handle if not closed already. + // ============================================================================ + ~TAutoFileHandle() { Close(); - m_hHandle = hHandle; } - return *this; - } - // ============================================================================ - /// TAutoFileHandle::operator HANDLE - /// @date 2010/08/26 - /// - /// @brief Retrieves the system handle. - /// @return HANDLE value. - // ============================================================================ - operator HANDLE() - { - return m_hHandle; - } + // ============================================================================ + /// TAutoFileHandle::operator= + /// @date 2010/08/26 + /// + /// @brief Assignment operator. + /// @param[in] hHandle - Handle to be assigned. + /// @return Reference to this object, + // ============================================================================ + TAutoFileHandle& operator=(HANDLE hHandle) + { + if (m_hHandle != hHandle) + { + Close(); + m_hHandle = hHandle; + } + return *this; + } - // ============================================================================ - /// TAutoFileHandle::Close - /// @date 2010/08/26 - /// - /// @brief Closes the internal handle if needed. - /// @return Result of the CloseHandle() function. - // ============================================================================ - BOOL Close() - { - BOOL bResult = TRUE; - if(m_hHandle != INVALID_HANDLE_VALUE) + // ============================================================================ + /// TAutoFileHandle::operator HANDLE + /// @date 2010/08/26 + /// + /// @brief Retrieves the system handle. + /// @return HANDLE value. + // ============================================================================ + operator HANDLE() { - bResult = CloseHandle(m_hHandle); - m_hHandle = INVALID_HANDLE_VALUE; + return m_hHandle; } - return bResult; - } + // ============================================================================ + /// TAutoFileHandle::Close + /// @date 2010/08/26 + /// + /// @brief Closes the internal handle if needed. + /// @return Result of the CloseHandle() function. + // ============================================================================ + BOOL Close() + { + BOOL bResult = TRUE; + if (m_hHandle != INVALID_HANDLE_VALUE) + { + bResult = CloseHandle(m_hHandle); + m_hHandle = INVALID_HANDLE_VALUE; + } - // ============================================================================ - /// TAutoFileHandle::Detach - /// @date 2010/09/12 - /// - /// @brief Detaches the handle, so it won't be closed in destructor. - /// @return Returns current handle. - // ============================================================================ - HANDLE Detach() - { - HANDLE hHandle = m_hHandle; - m_hHandle = INVALID_HANDLE_VALUE; - return hHandle; - } + return bResult; + } -private: - HANDLE m_hHandle; ///< System handle -}; + // ============================================================================ + /// TAutoFileHandle::Detach + /// @date 2010/09/12 + /// + /// @brief Detaches the handle, so it won't be closed in destructor. + /// @return Returns current handle. + // ============================================================================ + HANDLE Detach() + { + HANDLE hHandle = m_hHandle; + m_hHandle = INVALID_HANDLE_VALUE; + return hHandle; + } -END_CHCORE_NAMESPACE + private: + HANDLE m_hHandle; ///< System handle + }; +} #endif Index: src/libchcore/TBaseException.cpp =================================================================== diff -u -N -r71943917b6b34fa6e4f9045558c374322bddfd46 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TBaseException.cpp (.../TBaseException.cpp) (revision 71943917b6b34fa6e4f9045558c374322bddfd46) +++ src/libchcore/TBaseException.cpp (.../TBaseException.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -1,57 +1,74 @@ +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ #include "stdafx.h" #include "TBaseException.h" #include -BEGIN_CHCORE_NAMESPACE - -TBaseException::TBaseException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - m_eErrorCode(eErrorCode), - m_pszMsg(pszMsg), - m_bDeleteMsg(false), - m_pszFile(pszFile), - m_stLineNumber(stLineNumber), - m_pszFunction(pszFunction) +namespace chcore { - ATLTRACE(_T("*** Base Exception is being thrown:\n\tMsg: %s\n\tError code: %ld\n\tFile: %s\n\tLine number: %ld\n\tFunction: %s\n"), pszMsg, eErrorCode, pszFile, stLineNumber, pszFunction); -} + TBaseException::TBaseException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + m_eErrorCode(eErrorCode), + m_pszMsg(pszMsg), + m_bDeleteMsg(false), + m_pszFile(pszFile), + m_stLineNumber(stLineNumber), + m_pszFunction(pszFunction) + { + ATLTRACE(_T("*** Base Exception is being thrown:\n\tMsg: %s\n\tError code: %ld\n\tFile: %s\n\tLine number: %ld\n\tFunction: %s\n"), pszMsg, eErrorCode, pszFile, stLineNumber, pszFunction); + } -TBaseException::TBaseException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - m_eErrorCode(eErrorCode), - m_pszMsg(NULL), - m_bDeleteMsg(false), - m_pszFile(pszFile), - m_stLineNumber(stLineNumber), - m_pszFunction(pszFunction) -{ - ATLTRACE(_T("*** Base Exception is being thrown:\n\tMsg: %S\n\tError code: %ld\n\tFile: %s\n\tLine number: %ld\n\tFunction: %s\n"), pszMsg, eErrorCode, pszFile, stLineNumber, pszFunction); - if(pszMsg) + TBaseException::TBaseException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + m_eErrorCode(eErrorCode), + m_pszMsg(NULL), + m_bDeleteMsg(false), + m_pszFile(pszFile), + m_stLineNumber(stLineNumber), + m_pszFunction(pszFunction) { - size_t stMsgLen = strlen(pszMsg); - m_pszMsg = new wchar_t[stMsgLen + 1]; - - size_t stResult = 0; - mbstowcs_s(&stResult, const_cast(m_pszMsg), stMsgLen + 1, pszMsg, _TRUNCATE); + ATLTRACE(_T("*** Base Exception is being thrown:\n\tMsg: %S\n\tError code: %ld\n\tFile: %s\n\tLine number: %ld\n\tFunction: %s\n"), pszMsg, eErrorCode, pszFile, stLineNumber, pszFunction); + if (pszMsg) + { + size_t stMsgLen = strlen(pszMsg); + m_pszMsg = new wchar_t[stMsgLen + 1]; + + size_t stResult = 0; + mbstowcs_s(&stResult, const_cast(m_pszMsg), stMsgLen + 1, pszMsg, _TRUNCATE); + } } -} -TBaseException::~TBaseException() -{ - if(m_bDeleteMsg) - delete [] m_pszMsg; -} + TBaseException::~TBaseException() + { + if (m_bDeleteMsg) + delete[] m_pszMsg; + } -void TBaseException::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const -{ - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s (error code: %ld)"), - m_pszMsg, m_eErrorCode); - pszBuffer[stMaxBuffer - 1] = _T('\0'); -} + void TBaseException::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s (error code: %ld)"), + m_pszMsg, m_eErrorCode); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } -void TBaseException::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const -{ - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s\r\nError code: %ld\r\nFile: %s\r\nFunction: %s\r\nLine no: %lu"), - m_pszMsg, m_eErrorCode, m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); - pszBuffer[stMaxBuffer - 1] = _T('\0'); + void TBaseException::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s\r\nError code: %ld\r\nFile: %s\r\nFunction: %s\r\nLine no: %lu"), + m_pszMsg, m_eErrorCode, m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TBaseException.h =================================================================== diff -u -N -r7972b0944e0a947144fbdb93262f7d73ac528dc7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TBaseException.h (.../TBaseException.h) (revision 7972b0944e0a947144fbdb93262f7d73ac528dc7) +++ src/libchcore/TBaseException.h (.../TBaseException.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,47 +22,46 @@ #include "libchcore.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - +namespace chcore +{ #pragma warning(push) #pragma warning(disable: 4275) -class LIBCHCORE_API TBaseException : public virtual std::exception -{ -public: - TBaseException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TBaseException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + class LIBCHCORE_API TBaseException : public virtual std::exception + { + public: + TBaseException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TBaseException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - virtual ~TBaseException(); + virtual ~TBaseException(); - // error information - EGeneralErrors GetErrorCode() const { return m_eErrorCode; } + // error information + EGeneralErrors GetErrorCode() const { return m_eErrorCode; } - virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; - virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; -private: - TBaseException(); + private: + TBaseException(); - // location info - const wchar_t* GetSourceFile() const { return m_pszFile; } - size_t GetSourceLineNumber() const { return m_stLineNumber; } - const wchar_t* GetFunctionName() const { return m_pszFunction; } + // location info + const wchar_t* GetSourceFile() const { return m_pszFile; } + size_t GetSourceLineNumber() const { return m_stLineNumber; } + const wchar_t* GetFunctionName() const { return m_pszFunction; } -protected: - // what happened? - EGeneralErrors m_eErrorCode; + protected: + // what happened? + EGeneralErrors m_eErrorCode; - // where it happened? - const wchar_t* m_pszMsg; - bool m_bDeleteMsg; + // where it happened? + const wchar_t* m_pszMsg; + bool m_bDeleteMsg; - const wchar_t* m_pszFile; - const wchar_t* m_pszFunction; - size_t m_stLineNumber; -}; + const wchar_t* m_pszFile; + const wchar_t* m_pszFunction; + size_t m_stLineNumber; + }; #pragma warning(pop) +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TBasePathData.cpp =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TBasePathData.cpp (.../TBasePathData.cpp) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/TBasePathData.cpp (.../TBasePathData.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -30,259 +30,258 @@ #include "TPathContainer.h" #include -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + ////////////////////////////////////////////////////////////////////////////// + // TBasePathData -////////////////////////////////////////////////////////////////////////////// -// TBasePathData + TBasePathData::TBasePathData() : + m_oidObjectID(0), + m_pathSrc(m_setModifications), + m_bSkipFurtherProcessing(m_setModifications, false), + m_pathDst(m_setModifications) + { + m_setModifications[eMod_Added] = true; + } -TBasePathData::TBasePathData() : - m_oidObjectID(0), - m_pathSrc(m_setModifications), - m_bSkipFurtherProcessing(m_setModifications, false), - m_pathDst(m_setModifications) -{ - m_setModifications[eMod_Added] = true; -} + TBasePathData::TBasePathData(const TBasePathData& rEntry) : + m_oidObjectID(rEntry.m_oidObjectID), + m_pathSrc(m_setModifications, rEntry.m_pathSrc), + m_pathDst(m_setModifications, rEntry.m_pathDst), + m_bSkipFurtherProcessing(m_setModifications, rEntry.m_bSkipFurtherProcessing) + { + m_setModifications = rEntry.m_setModifications; + } -TBasePathData::TBasePathData(const TBasePathData& rEntry) : - m_oidObjectID(rEntry.m_oidObjectID), - m_pathSrc(m_setModifications, rEntry.m_pathSrc), - m_pathDst(m_setModifications, rEntry.m_pathDst), - m_bSkipFurtherProcessing(m_setModifications, rEntry.m_bSkipFurtherProcessing) -{ - m_setModifications = rEntry.m_setModifications; -} + TBasePathData::TBasePathData(object_id_t oidObjectID, const TSmartPath& spSrcPath) : + m_oidObjectID(oidObjectID), + m_pathSrc(m_setModifications, spSrcPath), + m_bSkipFurtherProcessing(m_setModifications, false), + m_pathDst(m_setModifications) + { + m_setModifications[eMod_Added] = true; + } -TBasePathData::TBasePathData(object_id_t oidObjectID, const TSmartPath& spSrcPath) : - m_oidObjectID(oidObjectID), - m_pathSrc(m_setModifications, spSrcPath), - m_bSkipFurtherProcessing(m_setModifications, false), - m_pathDst(m_setModifications) -{ - m_setModifications[eMod_Added] = true; -} + void TBasePathData::SetDestinationPath(const TSmartPath& tPath) + { + m_pathDst = tPath; + } -void TBasePathData::SetDestinationPath(const TSmartPath& tPath) -{ - m_pathDst = tPath; -} + TSmartPath TBasePathData::GetDestinationPath() const + { + return m_pathDst; + } -TSmartPath TBasePathData::GetDestinationPath() const -{ - return m_pathDst; -} + bool TBasePathData::GetSkipFurtherProcessing() const + { + return m_bSkipFurtherProcessing; + } -bool TBasePathData::GetSkipFurtherProcessing() const -{ - return m_bSkipFurtherProcessing; -} + void TBasePathData::SetSkipFurtherProcessing(bool bSkipFurtherProcessing) + { + m_bSkipFurtherProcessing = bSkipFurtherProcessing; + } -void TBasePathData::SetSkipFurtherProcessing(bool bSkipFurtherProcessing) -{ - m_bSkipFurtherProcessing = bSkipFurtherProcessing; -} + bool TBasePathData::IsDestinationPathSet() const + { + return !m_pathDst.Get().IsEmpty(); + } -bool TBasePathData::IsDestinationPathSet() const -{ - return !m_pathDst.Get().IsEmpty(); -} + void TBasePathData::Store(const ISerializerContainerPtr& spContainer) const + { + if (!spContainer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); -void TBasePathData::Store(const ISerializerContainerPtr& spContainer) const -{ - if(!spContainer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + bool bAdded = m_setModifications[eMod_Added]; + if (m_setModifications.any()) + { + ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); + if (bAdded || m_setModifications[eMod_SrcPath]) + rRow.SetValue(_T("src_path"), m_pathSrc); + if (bAdded || m_setModifications[eMod_SkipProcessing]) + rRow.SetValue(_T("skip_processing"), m_bSkipFurtherProcessing); + if (bAdded || m_setModifications[eMod_DstPath]) + rRow.SetValue(_T("dst_path"), m_pathDst); - bool bAdded = m_setModifications[eMod_Added]; - if(m_setModifications.any()) + m_setModifications.reset(); + } + } + + void TBasePathData::InitColumns(IColumnsDefinition& rColumns) { - ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); - if(bAdded || m_setModifications[eMod_SrcPath]) - rRow.SetValue(_T("src_path"), m_pathSrc); - if(bAdded || m_setModifications[eMod_SkipProcessing]) - rRow.SetValue(_T("skip_processing"), m_bSkipFurtherProcessing); - if(bAdded || m_setModifications[eMod_DstPath]) - rRow.SetValue(_T("dst_path"), m_pathDst); + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("src_path"), IColumnsDefinition::eType_path); + rColumns.AddColumn(_T("skip_processing"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("dst_path"), IColumnsDefinition::eType_path); + } + void TBasePathData::Load(const ISerializerRowReaderPtr& spRowReader) + { + spRowReader->GetValue(_T("id"), m_oidObjectID); + spRowReader->GetValue(_T("src_path"), m_pathSrc.Modify()); + spRowReader->GetValue(_T("skip_processing"), m_bSkipFurtherProcessing.Modify()); + spRowReader->GetValue(_T("dst_path"), m_pathDst.Modify()); m_setModifications.reset(); } -} -void TBasePathData::InitColumns(IColumnsDefinition& rColumns) -{ - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("src_path"), IColumnsDefinition::eType_path); - rColumns.AddColumn(_T("skip_processing"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("dst_path"), IColumnsDefinition::eType_path); -} + TSmartPath TBasePathData::GetSrcPath() const + { + return m_pathSrc; + } -void TBasePathData::Load(const ISerializerRowReaderPtr& spRowReader) -{ - spRowReader->GetValue(_T("id"), m_oidObjectID); - spRowReader->GetValue(_T("src_path"), m_pathSrc.Modify()); - spRowReader->GetValue(_T("skip_processing"), m_bSkipFurtherProcessing.Modify()); - spRowReader->GetValue(_T("dst_path"), m_pathDst.Modify()); - m_setModifications.reset(); -} + void TBasePathData::SetSrcPath(const TSmartPath& pathSrc) + { + m_pathSrc = pathSrc; + } -TSmartPath TBasePathData::GetSrcPath() const -{ - return m_pathSrc; -} + object_id_t TBasePathData::GetObjectID() const + { + return m_oidObjectID; + } -void TBasePathData::SetSrcPath(const TSmartPath& pathSrc) -{ - m_pathSrc = pathSrc; -} + void TBasePathData::SetObjectID(object_id_t oidObjectID) + { + m_oidObjectID = oidObjectID; + } -object_id_t TBasePathData::GetObjectID() const -{ - return m_oidObjectID; -} + ////////////////////////////////////////////////////////////////////////////// + // TBasePathDataContainer -void TBasePathData::SetObjectID(object_id_t oidObjectID) -{ - m_oidObjectID = oidObjectID; -} + TBasePathDataContainer::TBasePathDataContainer() : + m_oidLastObjectID(0) + { + } -////////////////////////////////////////////////////////////////////////////// -// TBasePathDataContainer + TBasePathDataContainer::~TBasePathDataContainer() + { + // clear works with critical section to avoid destruction while item in use + Clear(); + } -TBasePathDataContainer::TBasePathDataContainer() : - m_oidLastObjectID(0) -{ -} + void TBasePathDataContainer::Store(const ISerializerContainerPtr& spContainer) const + { + if (!spContainer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); -TBasePathDataContainer::~TBasePathDataContainer() -{ - // clear works with critical section to avoid destruction while item in use - Clear(); -} + boost::shared_lock lock(m_lock); -void TBasePathDataContainer::Store(const ISerializerContainerPtr& spContainer) const -{ - if(!spContainer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + InitColumns(spContainer); - boost::shared_lock lock(m_lock); + spContainer->DeleteRows(m_setRemovedObjects); + m_setRemovedObjects.Clear(); - InitColumns(spContainer); + BOOST_FOREACH(const TBasePathDataPtr& spEntry, m_vEntries) + { + spEntry->Store(spContainer); + } + } - spContainer->DeleteRows(m_setRemovedObjects); - m_setRemovedObjects.Clear(); - - BOOST_FOREACH(const TBasePathDataPtr& spEntry, m_vEntries) + void TBasePathDataContainer::Load(const ISerializerContainerPtr& spContainer) { - spEntry->Store(spContainer); - } -} + if (!spContainer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); -void TBasePathDataContainer::Load(const ISerializerContainerPtr& spContainer) -{ - if(!spContainer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + boost::unique_lock lock(m_lock); + m_setRemovedObjects.Clear(); + m_vEntries.clear(); - boost::unique_lock lock(m_lock); - m_setRemovedObjects.Clear(); - m_vEntries.clear(); + InitColumns(spContainer); - InitColumns(spContainer); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + while (spRowReader->Next()) + { + TBasePathDataPtr spPathData(new TBasePathData); - while(spRowReader->Next()) - { - TBasePathDataPtr spPathData(new TBasePathData); + spPathData->Load(spRowReader); - spPathData->Load(spRowReader); + m_vEntries.push_back(spPathData); + } + } - m_vEntries.push_back(spPathData); + void TBasePathDataContainer::Add(const TBasePathDataPtr& spEntry) + { + boost::unique_lock lock(m_lock); + spEntry->SetObjectID(++m_oidLastObjectID); + m_vEntries.push_back(spEntry); } -} -void TBasePathDataContainer::Add(const TBasePathDataPtr& spEntry) -{ - boost::unique_lock lock(m_lock); - spEntry->SetObjectID(++m_oidLastObjectID); - m_vEntries.push_back(spEntry); -} + void TBasePathDataContainer::RemoveAt(file_count_t fcIndex) + { + boost::unique_lock lock(m_lock); + if (fcIndex >= m_vEntries.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -void TBasePathDataContainer::RemoveAt(file_count_t fcIndex) -{ - boost::unique_lock lock(m_lock); - if(fcIndex >= m_vEntries.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + m_setRemovedObjects.Add(m_vEntries[boost::numeric_cast(fcIndex)]->GetObjectID()); + m_vEntries.erase(m_vEntries.begin() + boost::numeric_cast(fcIndex)); + } - m_setRemovedObjects.Add(m_vEntries[boost::numeric_cast(fcIndex)]->GetObjectID()); - m_vEntries.erase(m_vEntries.begin() + boost::numeric_cast(fcIndex)); -} + TBasePathDataPtr TBasePathDataContainer::GetAt(file_count_t fcIndex) const + { + boost::shared_lock lock(m_lock); + return m_vEntries.at(boost::numeric_cast(fcIndex)); + } -TBasePathDataPtr TBasePathDataContainer::GetAt(file_count_t fcIndex) const -{ - boost::shared_lock lock(m_lock); - return m_vEntries.at(boost::numeric_cast(fcIndex)); -} - -TBasePathDataPtr TBasePathDataContainer::FindByID(size_t stObjectID) const -{ - boost::shared_lock lock(m_lock); - BOOST_FOREACH(const TBasePathDataPtr& spItem, m_vEntries) + TBasePathDataPtr TBasePathDataContainer::FindByID(size_t stObjectID) const { - if(spItem->GetObjectID() == stObjectID) - return spItem; + boost::shared_lock lock(m_lock); + BOOST_FOREACH(const TBasePathDataPtr& spItem, m_vEntries) + { + if (spItem->GetObjectID() == stObjectID) + return spItem; + } + + THROW_CORE_EXCEPTION(eErr_InvalidArgument); } - THROW_CORE_EXCEPTION(eErr_InvalidArgument); -} + void TBasePathDataContainer::ClearNL() + { + BOOST_FOREACH(const TBasePathDataPtr& spItem, m_vEntries) + { + m_setRemovedObjects.Add(spItem->GetObjectID()); + } -void TBasePathDataContainer::ClearNL() -{ - BOOST_FOREACH(const TBasePathDataPtr& spItem, m_vEntries) + m_vEntries.clear(); + } + + void TBasePathDataContainer::Clear() { - m_setRemovedObjects.Add(spItem->GetObjectID()); + boost::unique_lock lock(m_lock); + ClearNL(); } - m_vEntries.clear(); -} + bool TBasePathDataContainer::IsEmpty() const + { + boost::shared_lock lock(m_lock); -void TBasePathDataContainer::Clear() -{ - boost::unique_lock lock(m_lock); - ClearNL(); -} + return m_vEntries.empty(); + } -bool TBasePathDataContainer::IsEmpty() const -{ - boost::shared_lock lock(m_lock); + file_count_t TBasePathDataContainer::GetCount() const + { + boost::shared_lock lock(m_lock); + return boost::numeric_cast(m_vEntries.size()); + } - return m_vEntries.empty(); -} + TBasePathDataContainer& TBasePathDataContainer::operator=(const TPathContainer& tPaths) + { + boost::unique_lock lock(m_lock); + ClearNL(); -file_count_t TBasePathDataContainer::GetCount() const -{ - boost::shared_lock lock(m_lock); - return boost::numeric_cast(m_vEntries.size()); -} + for (size_t stIndex = 0; stIndex < tPaths.GetCount(); ++stIndex) + { + TBasePathDataPtr spPathData = boost::make_shared(++m_oidLastObjectID, tPaths.GetAt(stIndex)); + m_vEntries.push_back(spPathData); + } -TBasePathDataContainer& TBasePathDataContainer::operator=(const TPathContainer& tPaths) -{ - boost::unique_lock lock(m_lock); - ClearNL(); + return *this; + } - for(size_t stIndex = 0; stIndex < tPaths.GetCount(); ++stIndex) + void TBasePathDataContainer::InitColumns(const ISerializerContainerPtr& spContainer) const { - TBasePathDataPtr spPathData = boost::make_shared(++m_oidLastObjectID, tPaths.GetAt(stIndex)); - m_vEntries.push_back(spPathData); + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TBasePathData::InitColumns(rColumns); } - - return *this; } - -void TBasePathDataContainer::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) - TBasePathData::InitColumns(rColumns); -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TBasePathData.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TBasePathData.h (.../TBasePathData.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TBasePathData.h (.../TBasePathData.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -33,112 +33,111 @@ #include "ISerializerRowReader.h" #include "CommonDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -class TPathContainer; - -///////////////////////////////////////////////////////////////////////////// -// TBasePathData -class LIBCHCORE_API TBasePathData +namespace chcore { -private: - enum EModifications + class TPathContainer; + + ///////////////////////////////////////////////////////////////////////////// + // TBasePathData + class LIBCHCORE_API TBasePathData { - eMod_Added, - eMod_SrcPath, - eMod_SkipProcessing, - eMod_DstPath, + private: + enum EModifications + { + eMod_Added, + eMod_SrcPath, + eMod_SkipProcessing, + eMod_DstPath, - eMod_Last - }; + eMod_Last + }; -public: - TBasePathData(); - TBasePathData(object_id_t oidObjectID, const TSmartPath& spSrcPath); - TBasePathData(const TBasePathData& rEntry); + public: + TBasePathData(); + TBasePathData(object_id_t oidObjectID, const TSmartPath& spSrcPath); + TBasePathData(const TBasePathData& rEntry); - object_id_t GetObjectID() const; - void SetObjectID(object_id_t oidObjectID); + object_id_t GetObjectID() const; + void SetObjectID(object_id_t oidObjectID); - TSmartPath GetSrcPath() const; - void SetSrcPath(const TSmartPath& pathSrc); + TSmartPath GetSrcPath() const; + void SetSrcPath(const TSmartPath& pathSrc); - bool GetSkipFurtherProcessing() const; - void SetSkipFurtherProcessing(bool bSkipFurtherProcessing); + bool GetSkipFurtherProcessing() const; + void SetSkipFurtherProcessing(bool bSkipFurtherProcessing); - void SetDestinationPath(const TSmartPath& strPath); - TSmartPath GetDestinationPath() const; - bool IsDestinationPathSet() const; + void SetDestinationPath(const TSmartPath& strPath); + TSmartPath GetDestinationPath() const; + bool IsDestinationPathSet() const; - void Store(const ISerializerContainerPtr& spContainer) const; - static void InitColumns(IColumnsDefinition& rColumnDefs); - void Load(const ISerializerRowReaderPtr& spRowReader); + void Store(const ISerializerContainerPtr& spContainer) const; + static void InitColumns(IColumnsDefinition& rColumnDefs); + void Load(const ISerializerRowReaderPtr& spRowReader); -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - // modification management - typedef std::bitset BitSet; - mutable BitSet m_setModifications; + // modification management + typedef std::bitset BitSet; + mutable BitSet m_setModifications; - // attributes - object_id_t m_oidObjectID; - TSharedModificationTracker m_pathSrc; - TSharedModificationTracker m_bSkipFurtherProcessing; // specifies if the path should be (or not) processed further - TSharedModificationTracker m_pathDst; + // attributes + object_id_t m_oidObjectID; + TSharedModificationTracker m_pathSrc; + TSharedModificationTracker m_bSkipFurtherProcessing; // specifies if the path should be (or not) processed further + TSharedModificationTracker m_pathDst; #pragma warning(pop) -}; + }; -typedef boost::shared_ptr TBasePathDataPtr; + typedef boost::shared_ptr TBasePathDataPtr; -////////////////////////////////////////////////////////////////////////// -// TBasePathDataContainer + ////////////////////////////////////////////////////////////////////////// + // TBasePathDataContainer -class LIBCHCORE_API TBasePathDataContainer -{ -public: - // constructors/destructor - TBasePathDataContainer(); - ~TBasePathDataContainer(); + class LIBCHCORE_API TBasePathDataContainer + { + public: + // constructors/destructor + TBasePathDataContainer(); + ~TBasePathDataContainer(); - TBasePathDataContainer& operator=(const TPathContainer& tPaths); + TBasePathDataContainer& operator=(const TPathContainer& tPaths); - // standard access to data - void Add(const TBasePathDataPtr& spEntry); - void RemoveAt(file_count_t fcIndex); - TBasePathDataPtr GetAt(file_count_t fcIndex) const; - TBasePathDataPtr FindByID(size_t fcObjectID) const; + // standard access to data + void Add(const TBasePathDataPtr& spEntry); + void RemoveAt(file_count_t fcIndex); + TBasePathDataPtr GetAt(file_count_t fcIndex) const; + TBasePathDataPtr FindByID(size_t fcObjectID) const; - void Clear(); + void Clear(); - bool IsEmpty() const; - file_count_t GetCount() const; + bool IsEmpty() const; + file_count_t GetCount() const; - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); - void InitColumns(const ISerializerContainerPtr& spContainer) const; + void InitColumns(const ISerializerContainerPtr& spContainer) const; -private: - TBasePathDataContainer(const TBasePathDataContainer& rSrc); - TBasePathDataContainer& operator=(const TBasePathDataContainer& rSrc); + private: + TBasePathDataContainer(const TBasePathDataContainer& rSrc); + TBasePathDataContainer& operator=(const TBasePathDataContainer& rSrc); - void ClearNL(); + void ClearNL(); -protected: + protected: #pragma warning(push) #pragma warning(disable: 4251) - typedef std::vector VecEntries; - VecEntries m_vEntries; - mutable TRemovedObjects m_setRemovedObjects; + typedef std::vector VecEntries; + VecEntries m_vEntries; + mutable TRemovedObjects m_setRemovedObjects; - mutable boost::shared_mutex m_lock; + mutable boost::shared_mutex m_lock; #pragma warning(pop) - object_id_t m_oidLastObjectID; -}; + object_id_t m_oidLastObjectID; + }; -typedef boost::shared_ptr TBasePathDataContainerPtr; + typedef boost::shared_ptr TBasePathDataContainerPtr; +} -END_CHCORE_NAMESPACE - #endif // __TBASEPATHDATA_H__ Index: src/libchcore/TBasePathDataFwd.h =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TBasePathDataFwd.h (.../TBasePathDataFwd.h) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TBasePathDataFwd.h (.../TBasePathDataFwd.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,11 +21,10 @@ #include -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + class TBasePathData; + typedef boost::shared_ptr TBasePathDataPtr; +} -class TBasePathData; -typedef boost::shared_ptr TBasePathDataPtr; - -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TBufferSizes.cpp =================================================================== diff -u -N -rcdc76e1a95383dff63a5254aeb8d37035028512c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TBufferSizes.cpp (.../TBufferSizes.cpp) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/TBufferSizes.cpp (.../TBufferSizes.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,120 +22,119 @@ #include "ErrorCodes.h" #include "RoundingFunctions.h" -BEGIN_CHCORE_NAMESPACE - -TBufferSizes::TBufferSizes() : - m_uiDefaultSize(BufferGranularity), - m_uiOneDiskSize(BufferGranularity), - m_uiTwoDisksSize(BufferGranularity), - m_uiCDSize(BufferGranularity), - m_uiLANSize(BufferGranularity), - m_bOnlyDefault(false), - m_uiBufferCount(MinBufferCount) +namespace chcore { -} + TBufferSizes::TBufferSizes() : + m_uiDefaultSize(BufferGranularity), + m_uiOneDiskSize(BufferGranularity), + m_uiTwoDisksSize(BufferGranularity), + m_uiCDSize(BufferGranularity), + m_uiLANSize(BufferGranularity), + m_bOnlyDefault(false), + m_uiBufferCount(MinBufferCount) + { + } -TBufferSizes::TBufferSizes(bool bOnlyDefault, UINT uiBufferCount, UINT uiDefaultSize, UINT uiOneDiskSize, UINT uiTwoDisksSize, UINT uiCDSize, UINT uiLANSize) : - m_uiDefaultSize(std::max(BufferGranularity, RoundUp(uiDefaultSize, BufferGranularity))), - m_uiOneDiskSize(std::max(BufferGranularity, RoundUp(uiOneDiskSize, BufferGranularity))), - m_uiTwoDisksSize(std::max(BufferGranularity, RoundUp(uiTwoDisksSize, BufferGranularity))), - m_uiCDSize(std::max(BufferGranularity, RoundUp(uiCDSize, BufferGranularity))), - m_uiLANSize(std::max(BufferGranularity, RoundUp(uiLANSize, BufferGranularity))), - m_bOnlyDefault(bOnlyDefault), - m_uiBufferCount(std::max(uiBufferCount, MinBufferCount)) -{ -} + TBufferSizes::TBufferSizes(bool bOnlyDefault, UINT uiBufferCount, UINT uiDefaultSize, UINT uiOneDiskSize, UINT uiTwoDisksSize, UINT uiCDSize, UINT uiLANSize) : + m_uiDefaultSize(std::max(BufferGranularity, RoundUp(uiDefaultSize, BufferGranularity))), + m_uiOneDiskSize(std::max(BufferGranularity, RoundUp(uiOneDiskSize, BufferGranularity))), + m_uiTwoDisksSize(std::max(BufferGranularity, RoundUp(uiTwoDisksSize, BufferGranularity))), + m_uiCDSize(std::max(BufferGranularity, RoundUp(uiCDSize, BufferGranularity))), + m_uiLANSize(std::max(BufferGranularity, RoundUp(uiLANSize, BufferGranularity))), + m_bOnlyDefault(bOnlyDefault), + m_uiBufferCount(std::max(uiBufferCount, MinBufferCount)) + { + } -void TBufferSizes::Clear() -{ - m_uiDefaultSize = BufferGranularity; - m_uiOneDiskSize = BufferGranularity; - m_uiTwoDisksSize = BufferGranularity; - m_uiCDSize = BufferGranularity; - m_uiLANSize = BufferGranularity; - m_bOnlyDefault = false; - m_uiBufferCount = MinBufferCount; -} + void TBufferSizes::Clear() + { + m_uiDefaultSize = BufferGranularity; + m_uiOneDiskSize = BufferGranularity; + m_uiTwoDisksSize = BufferGranularity; + m_uiCDSize = BufferGranularity; + m_uiLANSize = BufferGranularity; + m_bOnlyDefault = false; + m_uiBufferCount = MinBufferCount; + } -UINT TBufferSizes::GetSizeByType(EBufferType eType) const -{ - switch(eType) + UINT TBufferSizes::GetSizeByType(EBufferType eType) const { - case eBuffer_Default: - return m_uiDefaultSize; - case eBuffer_OneDisk: - return m_uiOneDiskSize; - case eBuffer_TwoDisks: - return m_uiTwoDisksSize; - case eBuffer_CD: - return m_uiCDSize; - case eBuffer_LAN: - return m_uiLANSize; - default: - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + switch (eType) + { + case eBuffer_Default: + return m_uiDefaultSize; + case eBuffer_OneDisk: + return m_uiOneDiskSize; + case eBuffer_TwoDisks: + return m_uiTwoDisksSize; + case eBuffer_CD: + return m_uiCDSize; + case eBuffer_LAN: + return m_uiLANSize; + default: + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + } } -} -void TBufferSizes::SetSizeByType(EBufferType eType, UINT uiSize) -{ - switch(eType) + void TBufferSizes::SetSizeByType(EBufferType eType, UINT uiSize) { - case eBuffer_Default: + switch (eType) + { + case eBuffer_Default: + m_uiDefaultSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); + break; + case eBuffer_OneDisk: + m_uiOneDiskSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); + break; + case eBuffer_TwoDisks: + m_uiTwoDisksSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); + break; + case eBuffer_CD: + m_uiCDSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); + break; + case eBuffer_LAN: + m_uiLANSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); + break; + default: + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + } + } + + void chcore::TBufferSizes::SetDefaultSize(UINT uiSize) + { m_uiDefaultSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); - break; - case eBuffer_OneDisk: + } + + void chcore::TBufferSizes::SetOneDiskSize(UINT uiSize) + { m_uiOneDiskSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); - break; - case eBuffer_TwoDisks: + } + + void chcore::TBufferSizes::SetTwoDisksSize(UINT uiSize) + { m_uiTwoDisksSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); - break; - case eBuffer_CD: + } + + void chcore::TBufferSizes::SetCDSize(UINT uiSize) + { m_uiCDSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); - break; - case eBuffer_LAN: + } + + void chcore::TBufferSizes::SetLANSize(UINT uiSize) + { m_uiLANSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); - break; - default: - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); } -} -void chcore::TBufferSizes::SetDefaultSize(UINT uiSize) -{ - m_uiDefaultSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); -} + void chcore::TBufferSizes::SetBufferCount(UINT uiBufferCount) + { + m_uiBufferCount = std::max(uiBufferCount, MinBufferCount); + } -void chcore::TBufferSizes::SetOneDiskSize(UINT uiSize) -{ - m_uiOneDiskSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); -} + UINT TBufferSizes::GetMaxSize() const + { + if (m_bOnlyDefault) + return m_uiDefaultSize; -void chcore::TBufferSizes::SetTwoDisksSize(UINT uiSize) -{ - m_uiTwoDisksSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); + return std::max({ m_uiDefaultSize, m_uiOneDiskSize, m_uiTwoDisksSize, m_uiCDSize, m_uiLANSize }); + } } - -void chcore::TBufferSizes::SetCDSize(UINT uiSize) -{ - m_uiCDSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); -} - -void chcore::TBufferSizes::SetLANSize(UINT uiSize) -{ - m_uiLANSize = std::max(BufferGranularity, RoundUp(uiSize, BufferGranularity)); -} - -void chcore::TBufferSizes::SetBufferCount(UINT uiBufferCount) -{ - m_uiBufferCount = std::max(uiBufferCount, MinBufferCount); -} - -UINT TBufferSizes::GetMaxSize() const -{ - if(m_bOnlyDefault) - return m_uiDefaultSize; - - return std::max({ m_uiDefaultSize, m_uiOneDiskSize, m_uiTwoDisksSize, m_uiCDSize, m_uiLANSize }); -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TBufferSizes.h =================================================================== diff -u -N -rcdc76e1a95383dff63a5254aeb8d37035028512c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TBufferSizes.h (.../TBufferSizes.h) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/TBufferSizes.h (.../TBufferSizes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,66 +21,65 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TBufferSizes +namespace chcore { -public: - enum EBufferType + class LIBCHCORE_API TBufferSizes { - eBuffer_Default = 0, - eBuffer_OneDisk = 1, - eBuffer_TwoDisks = 2, - eBuffer_CD = 3, - eBuffer_LAN = 4, + public: + enum EBufferType + { + eBuffer_Default = 0, + eBuffer_OneDisk = 1, + eBuffer_TwoDisks = 2, + eBuffer_CD = 3, + eBuffer_LAN = 4, - // do not remove this marker - eBuffer_Last - }; + // do not remove this marker + eBuffer_Last + }; - static const unsigned int BufferGranularity = 4096; - static const unsigned int MinBufferCount = 1; + static const unsigned int BufferGranularity = 4096; + static const unsigned int MinBufferCount = 1; -public: - TBufferSizes(); - TBufferSizes(bool bOnlyDefault, UINT uiBufferCount, UINT uiDefaultSize, - UINT uiOneDiskSize, UINT uiTwoDisksSize, UINT uiCDSize, UINT uiLANSize); + public: + TBufferSizes(); + TBufferSizes(bool bOnlyDefault, UINT uiBufferCount, UINT uiDefaultSize, + UINT uiOneDiskSize, UINT uiTwoDisksSize, UINT uiCDSize, UINT uiLANSize); - void Clear(); + void Clear(); - bool IsOnlyDefault() const { return m_bOnlyDefault; } - UINT GetDefaultSize() const { return m_uiDefaultSize; } - UINT GetOneDiskSize() const { return m_uiOneDiskSize; } - UINT GetTwoDisksSize() const { return m_uiTwoDisksSize; } - UINT GetCDSize() const { return m_uiCDSize; } - UINT GetLANSize() const { return m_uiLANSize; } + bool IsOnlyDefault() const { return m_bOnlyDefault; } + UINT GetDefaultSize() const { return m_uiDefaultSize; } + UINT GetOneDiskSize() const { return m_uiOneDiskSize; } + UINT GetTwoDisksSize() const { return m_uiTwoDisksSize; } + UINT GetCDSize() const { return m_uiCDSize; } + UINT GetLANSize() const { return m_uiLANSize; } - void SetOnlyDefault(bool bOnlyDefault) { m_bOnlyDefault = bOnlyDefault; } - void SetDefaultSize(UINT uiSize); - void SetOneDiskSize(UINT uiSize); - void SetTwoDisksSize(UINT uiSize); - void SetCDSize(UINT uiSize); - void SetLANSize(UINT uiSize); + void SetOnlyDefault(bool bOnlyDefault) { m_bOnlyDefault = bOnlyDefault; } + void SetDefaultSize(UINT uiSize); + void SetOneDiskSize(UINT uiSize); + void SetTwoDisksSize(UINT uiSize); + void SetCDSize(UINT uiSize); + void SetLANSize(UINT uiSize); - UINT GetBufferCount() const { return m_uiBufferCount; } - void SetBufferCount(UINT uiBufferCount); + UINT GetBufferCount() const { return m_uiBufferCount; } + void SetBufferCount(UINT uiBufferCount); - UINT GetSizeByType(EBufferType eType) const; - void SetSizeByType(EBufferType eType, UINT uiSize); + UINT GetSizeByType(EBufferType eType) const; + void SetSizeByType(EBufferType eType, UINT uiSize); - UINT GetMaxSize() const; + UINT GetMaxSize() const; -private: - UINT m_uiDefaultSize; - UINT m_uiOneDiskSize; - UINT m_uiTwoDisksSize; - UINT m_uiCDSize; - UINT m_uiLANSize; + private: + UINT m_uiDefaultSize; + UINT m_uiOneDiskSize; + UINT m_uiTwoDisksSize; + UINT m_uiCDSize; + UINT m_uiLANSize; - bool m_bOnlyDefault; - UINT m_uiBufferCount; -}; + bool m_bOnlyDefault; + UINT m_uiBufferCount; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TConfig.cpp =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TConfig.cpp (.../TConfig.cpp) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/TConfig.cpp (.../TConfig.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -41,490 +41,489 @@ #include "TCoreException.h" #include "ISerializerRowData.h" -BEGIN_CHCORE_NAMESPACE - -///////////////////////////////////////////////////////////////////////////////////////////// -// class TConfig - -using namespace details; - -TConfig::TConfig() : - m_pImpl(new details::ConfigNodeContainer) +namespace chcore { -} + ///////////////////////////////////////////////////////////////////////////////////////////// + // class TConfig -TConfig::TConfig(const TConfig& rSrc) : - m_pImpl(new details::ConfigNodeContainer(*rSrc.m_pImpl)) -{ -} + using namespace details; -TConfig& TConfig::operator=(const TConfig& rSrc) -{ - if(this != &rSrc) - *m_pImpl = *rSrc.m_pImpl; + TConfig::TConfig() : + m_pImpl(new details::ConfigNodeContainer) + { + } - return *this; -} + TConfig::TConfig(const TConfig& rSrc) : + m_pImpl(new details::ConfigNodeContainer(*rSrc.m_pImpl)) + { + } -TConfig::~TConfig() -{ - delete m_pImpl; -} + TConfig& TConfig::operator=(const TConfig& rSrc) + { + if (this != &rSrc) + *m_pImpl = *rSrc.m_pImpl; -// read/write -void TConfig::Read(PCTSTR pszFile) -{ - if(!pszFile) - THROW(_T("Invalid argument"), 0, 0, 0); + return *this; + } + TConfig::~TConfig() { - boost::unique_lock lock(GetImpl()->m_lock); - // Note: we need to store filename for later use BEFORE trying to open a file - // since it might be nonexistent, but we still would like to store config to this file later - ClearNL(); - GetImpl()->m_strFilePath = pszFile; + delete m_pImpl; } - // convert our underlying data to a property tree (currently probably the easiest way to convert data to xml - boost::property_tree::wiptree tPropertyTree; + // read/write + void TConfig::Read(PCTSTR pszFile) + { + if (!pszFile) + THROW(_T("Invalid argument"), 0, 0, 0); - std::wifstream ifs(pszFile, std::ios_base::in); - boost::property_tree::xml_parser::read_xml(ifs, tPropertyTree); + { + boost::unique_lock lock(GetImpl()->m_lock); + // Note: we need to store filename for later use BEFORE trying to open a file + // since it might be nonexistent, but we still would like to store config to this file later + ClearNL(); + GetImpl()->m_strFilePath = pszFile; + } - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->ImportFromPropertyTree(tPropertyTree, lock); -} + // convert our underlying data to a property tree (currently probably the easiest way to convert data to xml + boost::property_tree::wiptree tPropertyTree; -void TConfig::Write() -{ - // NOTE: locking is done inside ExportToPropertyTree() - boost::property_tree::wiptree tPropertyTree; - GetImpl()->ExportToPropertyTree(tPropertyTree); + std::wifstream ifs(pszFile, std::ios_base::in); + boost::property_tree::xml_parser::read_xml(ifs, tPropertyTree); - std::wofstream ofs(GetImpl()->m_strFilePath.c_str(), std::ios_base::out); - boost::property_tree::xml_parser::write_xml(ofs, tPropertyTree); -} + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->ImportFromPropertyTree(tPropertyTree, lock); + } -void TConfig::ReadFromString(const TString& strInput) -{ - if(strInput.IsEmpty()) - THROW(_T("Invalid argument"), 0, 0, 0); + void TConfig::Write() + { + // NOTE: locking is done inside ExportToPropertyTree() + boost::property_tree::wiptree tPropertyTree; + GetImpl()->ExportToPropertyTree(tPropertyTree); - boost::property_tree::wiptree tPropertyTree; + std::wofstream ofs(GetImpl()->m_strFilePath.c_str(), std::ios_base::out); + boost::property_tree::xml_parser::write_xml(ofs, tPropertyTree); + } - std::wistringstream ifs(strInput.c_str(), std::ios_base::in); - boost::property_tree::xml_parser::read_xml(ifs, tPropertyTree); + void TConfig::ReadFromString(const TString& strInput) + { + if (strInput.IsEmpty()) + THROW(_T("Invalid argument"), 0, 0, 0); - boost::unique_lock lock(GetImpl()->m_lock); + boost::property_tree::wiptree tPropertyTree; - ClearNL(); + std::wistringstream ifs(strInput.c_str(), std::ios_base::in); + boost::property_tree::xml_parser::read_xml(ifs, tPropertyTree); - GetImpl()->ImportFromPropertyTree(tPropertyTree, lock); -} + boost::unique_lock lock(GetImpl()->m_lock); -void TConfig::WriteToString(TString& strOutput) -{ - // NOTE: locking is done inside ExportToPropertyTree() + ClearNL(); - boost::property_tree::wiptree tPropertyTree; - GetImpl()->ExportToPropertyTree(tPropertyTree); + GetImpl()->ImportFromPropertyTree(tPropertyTree, lock); + } - std::wostringstream ofs(std::ios_base::out); - boost::property_tree::xml_parser::write_xml(ofs, tPropertyTree); + void TConfig::WriteToString(TString& strOutput) + { + // NOTE: locking is done inside ExportToPropertyTree() - strOutput = ofs.str().c_str(); -} + boost::property_tree::wiptree tPropertyTree; + GetImpl()->ExportToPropertyTree(tPropertyTree); + std::wostringstream ofs(std::ios_base::out); + boost::property_tree::xml_parser::write_xml(ofs, tPropertyTree); -void TConfig::Store(const ISerializerContainerPtr& spContainer) const -{ - if(!spContainer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + strOutput = ofs.str().c_str(); + } - boost::shared_lock lock(GetImpl()->m_lock); - InitColumns(spContainer); + void TConfig::Store(const ISerializerContainerPtr& spContainer) const + { + if (!spContainer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spContainer->DeleteRows(m_pImpl->m_setRemovedObjects); - m_pImpl->m_setRemovedObjects.Clear(); + boost::shared_lock lock(GetImpl()->m_lock); - BOOST_FOREACH(const ConfigNode& rNode, m_pImpl->m_mic) - { - bool bAdded = rNode.m_setModifications[ConfigNode::eMod_Added]; - if(rNode.m_setModifications.any()) + InitColumns(spContainer); + + spContainer->DeleteRows(m_pImpl->m_setRemovedObjects); + m_pImpl->m_setRemovedObjects.Clear(); + + BOOST_FOREACH(const ConfigNode& rNode, m_pImpl->m_mic) { - ISerializerRowData& rRow = spContainer->GetRow(rNode.m_oidObjectID, bAdded); - if(bAdded || rNode.m_setModifications[ConfigNode::eMod_NodeName]) - rRow.SetValue(_T("name"), rNode.GetNodeName()); - if(bAdded || rNode.m_setModifications[ConfigNode::eMod_Order]) - rRow.SetValue(_T("node_order"), rNode.GetOrder()); - if(bAdded || rNode.m_setModifications[ConfigNode::eMod_Value]) - rRow.SetValue(_T("value"), rNode.m_strValue.Get()); + bool bAdded = rNode.m_setModifications[ConfigNode::eMod_Added]; + if (rNode.m_setModifications.any()) + { + ISerializerRowData& rRow = spContainer->GetRow(rNode.m_oidObjectID, bAdded); + if (bAdded || rNode.m_setModifications[ConfigNode::eMod_NodeName]) + rRow.SetValue(_T("name"), rNode.GetNodeName()); + if (bAdded || rNode.m_setModifications[ConfigNode::eMod_Order]) + rRow.SetValue(_T("node_order"), rNode.GetOrder()); + if (bAdded || rNode.m_setModifications[ConfigNode::eMod_Value]) + rRow.SetValue(_T("value"), rNode.m_strValue.Get()); - rNode.m_setModifications.reset(); + rNode.m_setModifications.reset(); + } } } -} -void TConfig::Load(const ISerializerContainerPtr& spContainer) const -{ - if(!spContainer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + void TConfig::Load(const ISerializerContainerPtr& spContainer) const + { + if (!spContainer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); - boost::unique_lock lock(GetImpl()->m_lock); - m_pImpl->m_setRemovedObjects.Clear(); - m_pImpl->m_mic.clear(); + boost::unique_lock lock(GetImpl()->m_lock); + m_pImpl->m_setRemovedObjects.Clear(); + m_pImpl->m_mic.clear(); - InitColumns(spContainer); + InitColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - while(spRowReader->Next()) - { - TString strName; - int iOrder = 0; - TString strValue; + while (spRowReader->Next()) + { + TString strName; + int iOrder = 0; + TString strValue; - spRowReader->GetValue(_T("name"), strName); - spRowReader->GetValue(_T("node_order"), iOrder); - spRowReader->GetValue(_T("value"), strValue); + spRowReader->GetValue(_T("name"), strName); + spRowReader->GetValue(_T("node_order"), iOrder); + spRowReader->GetValue(_T("value"), strValue); - m_pImpl->AddEntry(strName.c_str(), iOrder, strValue); // also resets modification state inside + m_pImpl->AddEntry(strName.c_str(), iOrder, strValue); // also resets modification state inside + } } -} -void TConfig::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) + void TConfig::InitColumns(const ISerializerContainerPtr& spContainer) const { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("name"), IColumnsDefinition::eType_string); - rColumns.AddColumn(_T("node_order"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("value"), IColumnsDefinition::eType_string); + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("name"), IColumnsDefinition::eType_string); + rColumns.AddColumn(_T("node_order"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("value"), IColumnsDefinition::eType_string); + } } -} -void TConfig::SetFilePath(PCTSTR pszPath) -{ - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->m_strFilePath = pszPath; -} + void TConfig::SetFilePath(PCTSTR pszPath) + { + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->m_strFilePath = pszPath; + } -void TConfig::Clear() -{ - boost::unique_lock lock(GetImpl()->m_lock); + void TConfig::Clear() + { + boost::unique_lock lock(GetImpl()->m_lock); - ClearNL(); -} + ClearNL(); + } -void TConfig::ClearNL() -{ - GetImpl()->m_mic.clear(); - GetImpl()->m_setDelayedNotifications.Clear(); - GetImpl()->m_bDelayedEnabled = false; - GetImpl()->m_strFilePath.Clear(); -} + void TConfig::ClearNL() + { + GetImpl()->m_mic.clear(); + GetImpl()->m_setDelayedNotifications.Clear(); + GetImpl()->m_bDelayedEnabled = false; + GetImpl()->m_strFilePath.Clear(); + } -// value setting/retrieval -bool TConfig::GetBool(PCTSTR pszPropName, bool bDefault) const -{ - return GetImpl()->GetValue(pszPropName, bDefault); -} + // value setting/retrieval + bool TConfig::GetBool(PCTSTR pszPropName, bool bDefault) const + { + return GetImpl()->GetValue(pszPropName, bDefault); + } -bool TConfig::GetValue(PCTSTR pszPropName, bool& bValue) const -{ - return GetImpl()->GetValueNoDefault(pszPropName, bValue); -} + bool TConfig::GetValue(PCTSTR pszPropName, bool& bValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, bValue); + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, bool bValue) -{ - if(GetImpl()->SetValue(pszPropName, bValue)) - SendNotification(pszPropName); + TConfig& TConfig::SetValue(PCTSTR pszPropName, bool bValue) + { + if (GetImpl()->SetValue(pszPropName, bValue)) + SendNotification(pszPropName); - return *this; -} + return *this; + } -int TConfig::GetInt(PCTSTR pszPropName, int iDefault) const -{ - return GetImpl()->GetValue(pszPropName, iDefault); -} + int TConfig::GetInt(PCTSTR pszPropName, int iDefault) const + { + return GetImpl()->GetValue(pszPropName, iDefault); + } -bool TConfig::GetValue(PCTSTR pszPropName, int& iValue) const -{ - return GetImpl()->GetValueNoDefault(pszPropName, iValue); -} + bool TConfig::GetValue(PCTSTR pszPropName, int& iValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, iValue); + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, int iValue) -{ - if(GetImpl()->SetValue(pszPropName, iValue)) - SendNotification(pszPropName); + TConfig& TConfig::SetValue(PCTSTR pszPropName, int iValue) + { + if (GetImpl()->SetValue(pszPropName, iValue)) + SendNotification(pszPropName); - return *this; -} + return *this; + } -unsigned int TConfig::GetUInt(PCTSTR pszPropName, unsigned int uiDefault) const -{ - return GetImpl()->GetValue(pszPropName, uiDefault); -} + unsigned int TConfig::GetUInt(PCTSTR pszPropName, unsigned int uiDefault) const + { + return GetImpl()->GetValue(pszPropName, uiDefault); + } -bool TConfig::GetValue(PCTSTR pszPropName, unsigned int& uiValue) const -{ - return GetImpl()->GetValueNoDefault(pszPropName, uiValue); -} + bool TConfig::GetValue(PCTSTR pszPropName, unsigned int& uiValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, uiValue); + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, unsigned int uiValue) -{ - if(GetImpl()->SetValue(pszPropName, uiValue)) - SendNotification(pszPropName); + TConfig& TConfig::SetValue(PCTSTR pszPropName, unsigned int uiValue) + { + if (GetImpl()->SetValue(pszPropName, uiValue)) + SendNotification(pszPropName); - return *this; -} + return *this; + } -long long TConfig::GetLongLong(PCTSTR pszPropName, long long llDefault) const -{ - return GetImpl()->GetValue(pszPropName, llDefault); -} + long long TConfig::GetLongLong(PCTSTR pszPropName, long long llDefault) const + { + return GetImpl()->GetValue(pszPropName, llDefault); + } -bool TConfig::GetValue(PCTSTR pszPropName, long long& llValue) const -{ - return GetImpl()->GetValueNoDefault(pszPropName, llValue); -} + bool TConfig::GetValue(PCTSTR pszPropName, long long& llValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, llValue); + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, long long llValue) -{ - if(GetImpl()->SetValue(pszPropName, llValue)) - SendNotification(pszPropName); + TConfig& TConfig::SetValue(PCTSTR pszPropName, long long llValue) + { + if (GetImpl()->SetValue(pszPropName, llValue)) + SendNotification(pszPropName); - return *this; -} + return *this; + } -unsigned long long TConfig::GetULongLong(PCTSTR pszPropName, unsigned long long ullDefault) const -{ - return GetImpl()->GetValue(pszPropName, ullDefault); -} + unsigned long long TConfig::GetULongLong(PCTSTR pszPropName, unsigned long long ullDefault) const + { + return GetImpl()->GetValue(pszPropName, ullDefault); + } -bool TConfig::GetValue(PCTSTR pszPropName, unsigned long long& ullValue) const -{ - return GetImpl()->GetValueNoDefault(pszPropName, ullValue); -} + bool TConfig::GetValue(PCTSTR pszPropName, unsigned long long& ullValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, ullValue); + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, unsigned long long ullValue) -{ - if(GetImpl()->SetValue(pszPropName, ullValue)) - SendNotification(pszPropName); + TConfig& TConfig::SetValue(PCTSTR pszPropName, unsigned long long ullValue) + { + if (GetImpl()->SetValue(pszPropName, ullValue)) + SendNotification(pszPropName); - return *this; -} + return *this; + } -double TConfig::GetDouble(PCTSTR pszPropName, double dDefault) const -{ - return GetImpl()->GetValue(pszPropName, dDefault); -} + double TConfig::GetDouble(PCTSTR pszPropName, double dDefault) const + { + return GetImpl()->GetValue(pszPropName, dDefault); + } -bool TConfig::GetValue(PCTSTR pszPropName, double& dValue) const -{ - return GetImpl()->GetValueNoDefault(pszPropName, dValue); -} + bool TConfig::GetValue(PCTSTR pszPropName, double& dValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, dValue); + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, double dValue) -{ - if(GetImpl()->SetValue(pszPropName, dValue)) - SendNotification(pszPropName); + TConfig& TConfig::SetValue(PCTSTR pszPropName, double dValue) + { + if (GetImpl()->SetValue(pszPropName, dValue)) + SendNotification(pszPropName); - return *this; -} + return *this; + } -TString TConfig::GetString(PCTSTR pszPropName, const TString& strDefault) const -{ - return GetImpl()->GetValue(pszPropName, strDefault); -} + TString TConfig::GetString(PCTSTR pszPropName, const TString& strDefault) const + { + return GetImpl()->GetValue(pszPropName, strDefault); + } -bool TConfig::GetValue(PCTSTR pszPropName, TString& rstrValue) const -{ - return GetImpl()->GetValueNoDefault(pszPropName, rstrValue); -} + bool TConfig::GetValue(PCTSTR pszPropName, TString& rstrValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, rstrValue); + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, const TString& strValue) -{ - if(GetImpl()->SetValue(pszPropName, strValue)) - SendNotification(pszPropName); + TConfig& TConfig::SetValue(PCTSTR pszPropName, const TString& strValue) + { + if (GetImpl()->SetValue(pszPropName, strValue)) + SendNotification(pszPropName); - return *this; -} + return *this; + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, PCTSTR pszValue) -{ - return SetValue(pszPropName, TString(pszValue)); -} + TConfig& TConfig::SetValue(PCTSTR pszPropName, PCTSTR pszValue) + { + return SetValue(pszPropName, TString(pszValue)); + } -bool TConfig::GetValue(PCTSTR pszPropName, TStringArray& rvValues) const -{ - return GetImpl()->GetArrayValueNoDefault(pszPropName, rvValues); -} + bool TConfig::GetValue(PCTSTR pszPropName, TStringArray& rvValues) const + { + return GetImpl()->GetArrayValueNoDefault(pszPropName, rvValues); + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, const TStringArray& rvValues) -{ - if(GetImpl()->SetArrayValue(pszPropName, rvValues)) - SendNotification(pszPropName); + TConfig& TConfig::SetValue(PCTSTR pszPropName, const TStringArray& rvValues) + { + if (GetImpl()->SetArrayValue(pszPropName, rvValues)) + SendNotification(pszPropName); - return *this; -} + return *this; + } -void TConfig::DeleteNode(PCTSTR pszNodeName) -{ - GetImpl()->DeleteNode(pszNodeName); -} + void TConfig::DeleteNode(PCTSTR pszNodeName) + { + GetImpl()->DeleteNode(pszNodeName); + } -// extraction of subtrees -bool TConfig::ExtractSubConfig(PCTSTR pszSubTreeName, TConfig& rSubConfig) const -{ - return GetImpl()->ExtractNodes(pszSubTreeName, *rSubConfig.m_pImpl); -} + // extraction of subtrees + bool TConfig::ExtractSubConfig(PCTSTR pszSubTreeName, TConfig& rSubConfig) const + { + return GetImpl()->ExtractNodes(pszSubTreeName, *rSubConfig.m_pImpl); + } -bool TConfig::ExtractMultiSubConfigs(PCTSTR pszSubTreeName, TConfigArray& rSubConfigs) const -{ - rSubConfigs.Clear(); - - std::vector vNodeContainers; - if(!GetImpl()->ExtractMultipleNodes(pszSubTreeName, vNodeContainers)) - return false; - - BOOST_FOREACH(const ConfigNodeContainer& rNode, vNodeContainers) + bool TConfig::ExtractMultiSubConfigs(PCTSTR pszSubTreeName, TConfigArray& rSubConfigs) const { - TConfig cfg; - *cfg.m_pImpl = rNode; + rSubConfigs.Clear(); - rSubConfigs.Add(cfg); - } + std::vector vNodeContainers; + if (!GetImpl()->ExtractMultipleNodes(pszSubTreeName, vNodeContainers)) + return false; - return true; -} + BOOST_FOREACH(const ConfigNodeContainer& rNode, vNodeContainers) + { + TConfig cfg; + *cfg.m_pImpl = rNode; -void TConfig::PutSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig) -{ - GetImpl()->ImportNodes(pszSubTreeName, *rSubConfig.m_pImpl); -} + rSubConfigs.Add(cfg); + } -void TConfig::AddSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig) -{ - GetImpl()->AddNodes(pszSubTreeName, *rSubConfig.m_pImpl); -} + return true; + } -void TConfig::ConnectToNotifier(void (*pfnCallback)(const TStringSet&, void*), void* pParam) -{ - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->m_notifier.connect(TConfigNotifier(pfnCallback, pParam)); -} + void TConfig::PutSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig) + { + GetImpl()->ImportNodes(pszSubTreeName, *rSubConfig.m_pImpl); + } -void TConfig::DisconnectFromNotifier(void (*pfnCallback)(const TStringSet&, void*)) -{ - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->m_notifier.disconnect(TConfigNotifier(pfnCallback, NULL)); -} + void TConfig::AddSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig) + { + GetImpl()->AddNodes(pszSubTreeName, *rSubConfig.m_pImpl); + } -void TConfig::DelayNotifications() -{ - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->m_bDelayedEnabled = true; -} + void TConfig::ConnectToNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam) + { + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->m_notifier.connect(TConfigNotifier(pfnCallback, pParam)); + } -void TConfig::ResumeNotifications() -{ - TStringSet setNotifications; + void TConfig::DisconnectFromNotifier(void(*pfnCallback)(const TStringSet&, void*)) + { + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->m_notifier.disconnect(TConfigNotifier(pfnCallback, NULL)); + } - // separate scope for shared mutex (to avoid calling notifier inside critical section) + void TConfig::DelayNotifications() { - boost::upgrade_lock lock(GetImpl()->m_lock); - if(GetImpl()->m_bDelayedEnabled) + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->m_bDelayedEnabled = true; + } + + void TConfig::ResumeNotifications() + { + TStringSet setNotifications; + + // separate scope for shared mutex (to avoid calling notifier inside critical section) { - GetImpl()->m_bDelayedEnabled = false; - if(!GetImpl()->m_setDelayedNotifications.IsEmpty()) + boost::upgrade_lock lock(GetImpl()->m_lock); + if (GetImpl()->m_bDelayedEnabled) { - setNotifications = GetImpl()->m_setDelayedNotifications; + GetImpl()->m_bDelayedEnabled = false; + if (!GetImpl()->m_setDelayedNotifications.IsEmpty()) + { + setNotifications = GetImpl()->m_setDelayedNotifications; - boost::upgrade_to_unique_lock upgraded_lock(lock); - GetImpl()->m_setDelayedNotifications.Clear(); + boost::upgrade_to_unique_lock upgraded_lock(lock); + GetImpl()->m_setDelayedNotifications.Clear(); + } } } + + // NOTE: no locking here! + if (!setNotifications.IsEmpty()) + SendNotification(setNotifications); } - // NOTE: no locking here! - if(!setNotifications.IsEmpty()) - SendNotification(setNotifications); -} - -void TConfig::SendNotification(const TStringSet& rsetInfo) -{ - // separate scope for shared mutex (to avoid calling notifier inside critical section) + void TConfig::SendNotification(const TStringSet& rsetInfo) { - boost::upgrade_lock lock(GetImpl()->m_lock); - if(GetImpl()->m_bDelayedEnabled) + // separate scope for shared mutex (to avoid calling notifier inside critical section) { - boost::upgrade_to_unique_lock upgraded_lock(lock); + boost::upgrade_lock lock(GetImpl()->m_lock); + if (GetImpl()->m_bDelayedEnabled) + { + boost::upgrade_to_unique_lock upgraded_lock(lock); - GetImpl()->m_setDelayedNotifications.Insert(rsetInfo); - return; + GetImpl()->m_setDelayedNotifications.Insert(rsetInfo); + return; + } } + + // NOTE: we don't lock here + GetImpl()->m_notifier(rsetInfo); } - // NOTE: we don't lock here - GetImpl()->m_notifier(rsetInfo); -} - -void TConfig::SendNotification(PCTSTR pszInfo) -{ - // separate scope for shared mutex (to avoid calling notifier inside critical section) + void TConfig::SendNotification(PCTSTR pszInfo) { - boost::upgrade_lock lock(GetImpl()->m_lock); - if(GetImpl()->m_bDelayedEnabled) + // separate scope for shared mutex (to avoid calling notifier inside critical section) { - boost::upgrade_to_unique_lock upgraded_lock(lock); + boost::upgrade_lock lock(GetImpl()->m_lock); + if (GetImpl()->m_bDelayedEnabled) + { + boost::upgrade_to_unique_lock upgraded_lock(lock); - GetImpl()->m_setDelayedNotifications.Insert(pszInfo); - return; + GetImpl()->m_setDelayedNotifications.Insert(pszInfo); + return; + } } + + // NOTE: we don't lock here + TStringSet setData; + setData.Insert(pszInfo); + GetImpl()->m_notifier(setData); } - // NOTE: we don't lock here - TStringSet setData; - setData.Insert(pszInfo); - GetImpl()->m_notifier(setData); -} + details::ConfigNodeContainer* TConfig::GetImpl() + { + return m_pImpl; + } -details::ConfigNodeContainer* TConfig::GetImpl() -{ - return m_pImpl; -} + const details::ConfigNodeContainer* TConfig::GetImpl() const + { + return m_pImpl; + } -const details::ConfigNodeContainer* TConfig::GetImpl() const -{ - return m_pImpl; -} + TSmartPath TConfig::GetPath(PCTSTR pszPropName, const TSmartPath& pathDefault) const + { + return PathFromWString(GetString(pszPropName, pathDefault.ToWString())); + } -TSmartPath TConfig::GetPath(PCTSTR pszPropName, const TSmartPath& pathDefault) const -{ - return PathFromWString(GetString(pszPropName, pathDefault.ToWString())); -} + bool TConfig::GetValue(PCTSTR pszPropName, TSmartPath& rpathValue) const + { + TString strPath; + bool bResult = GetValue(pszPropName, strPath); + rpathValue = PathFromWString(strPath); + return bResult; + } -bool TConfig::GetValue(PCTSTR pszPropName, TSmartPath& rpathValue) const -{ - TString strPath; - bool bResult = GetValue(pszPropName, strPath); - rpathValue = PathFromWString(strPath); - return bResult; -} + TConfig& TConfig::SetValue(PCTSTR pszPropName, const TSmartPath& pathValue) + { + return SetValue(pszPropName, pathValue.ToWString()); + } -TConfig& TConfig::SetValue(PCTSTR pszPropName, const TSmartPath& pathValue) -{ - return SetValue(pszPropName, pathValue.ToWString()); -} - #ifdef _DEBUG -void TConfig::Dump() -{ - GetImpl()->Dump(); -} + void TConfig::Dump() + { + GetImpl()->Dump(); + } #endif - -END_CHCORE_NAMESPACE +} Index: src/libchcore/TConfig.h =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TConfig.h (.../TConfig.h) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/TConfig.h (.../TConfig.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,133 +26,133 @@ #include "libchcore.h" #include "ISerializerContainer.h" -BEGIN_CHCORE_NAMESPACE - -class TConfigArray; -class TStringSet; - -namespace details +namespace chcore { - struct ConfigNodeContainer; -} + class TConfigArray; + class TStringSet; -// class for handling configuration settings -class LIBCHCORE_API TConfig -{ -public: - TConfig(); - TConfig(const TConfig& rSrc); - ~TConfig(); + namespace details + { + struct ConfigNodeContainer; + } - TConfig& operator=(const TConfig& rSrc); + // class for handling configuration settings + class LIBCHCORE_API TConfig + { + public: + TConfig(); + TConfig(const TConfig& rSrc); + ~TConfig(); - void Clear(); + TConfig& operator=(const TConfig& rSrc); - // read/write - void Read(PCTSTR pszFile); - void Write(); - void SetFilePath(PCTSTR pszPath); + void Clear(); - void ReadFromString(const TString& strInput); - void WriteToString(TString& strOutput); + // read/write + void Read(PCTSTR pszFile); + void Write(); + void SetFilePath(PCTSTR pszPath); - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer) const; - void InitColumns(const ISerializerContainerPtr& spContainer) const; + void ReadFromString(const TString& strInput); + void WriteToString(TString& strOutput); - // value setting/retrieval - bool GetBool(PCTSTR pszPropName, bool bDefault = false) const; - bool GetValue(PCTSTR pszPropName, bool& bValue) const; - TConfig& SetValue(PCTSTR pszPropName, bool bValue); + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer) const; + void InitColumns(const ISerializerContainerPtr& spContainer) const; - int GetInt(PCTSTR pszPropName, int iDefault = 0) const; - bool GetValue(PCTSTR pszPropName, int& iValue) const; - TConfig& SetValue(PCTSTR pszPropName, int iValue); + // value setting/retrieval + bool GetBool(PCTSTR pszPropName, bool bDefault = false) const; + bool GetValue(PCTSTR pszPropName, bool& bValue) const; + TConfig& SetValue(PCTSTR pszPropName, bool bValue); - unsigned int GetUInt(PCTSTR pszPropName, unsigned int uiDefault = 0) const; - bool GetValue(PCTSTR pszPropName, unsigned int& uiValue) const; - TConfig& SetValue(PCTSTR pszPropName, unsigned int uiValue); + int GetInt(PCTSTR pszPropName, int iDefault = 0) const; + bool GetValue(PCTSTR pszPropName, int& iValue) const; + TConfig& SetValue(PCTSTR pszPropName, int iValue); - long long GetLongLong(PCTSTR pszPropName, long long llDefault = 0) const; - bool GetValue(PCTSTR pszPropName, long long& llValue) const; - TConfig& SetValue(PCTSTR pszPropName, long long llValue); + unsigned int GetUInt(PCTSTR pszPropName, unsigned int uiDefault = 0) const; + bool GetValue(PCTSTR pszPropName, unsigned int& uiValue) const; + TConfig& SetValue(PCTSTR pszPropName, unsigned int uiValue); - unsigned long long GetULongLong(PCTSTR pszPropName, unsigned long long ullDefault = 0) const; - bool GetValue(PCTSTR pszPropName, unsigned long long& ullValue) const; - TConfig& SetValue(PCTSTR pszPropName, unsigned long long ullValue); + long long GetLongLong(PCTSTR pszPropName, long long llDefault = 0) const; + bool GetValue(PCTSTR pszPropName, long long& llValue) const; + TConfig& SetValue(PCTSTR pszPropName, long long llValue); - double GetDouble(PCTSTR pszPropName, double dDefault = 0.0) const; - bool GetValue(PCTSTR pszPropName, double& dValue) const; - TConfig& SetValue(PCTSTR pszPropName, double dValue); + unsigned long long GetULongLong(PCTSTR pszPropName, unsigned long long ullDefault = 0) const; + bool GetValue(PCTSTR pszPropName, unsigned long long& ullValue) const; + TConfig& SetValue(PCTSTR pszPropName, unsigned long long ullValue); - TString GetString(PCTSTR pszPropName, const TString& strDefault = TString()) const; - bool GetValue(PCTSTR pszPropName, TString& rstrValue) const; - TConfig& SetValue(PCTSTR pszPropName, const TString& strValue); - TConfig& SetValue(PCTSTR pszPropName, PCTSTR pszValue); + double GetDouble(PCTSTR pszPropName, double dDefault = 0.0) const; + bool GetValue(PCTSTR pszPropName, double& dValue) const; + TConfig& SetValue(PCTSTR pszPropName, double dValue); - TSmartPath GetPath(PCTSTR pszPropName, const TSmartPath& pathDefault = TSmartPath()) const; - bool GetValue(PCTSTR pszPropName, TSmartPath& rpathValue) const; - TConfig& SetValue(PCTSTR pszPropName, const TSmartPath& pathValue); + TString GetString(PCTSTR pszPropName, const TString& strDefault = TString()) const; + bool GetValue(PCTSTR pszPropName, TString& rstrValue) const; + TConfig& SetValue(PCTSTR pszPropName, const TString& strValue); + TConfig& SetValue(PCTSTR pszPropName, PCTSTR pszValue); - bool GetValue(PCTSTR pszPropName, TStringArray& rvValues) const; - TConfig& SetValue(PCTSTR pszPropName, const TStringArray& rvValues); + TSmartPath GetPath(PCTSTR pszPropName, const TSmartPath& pathDefault = TSmartPath()) const; + bool GetValue(PCTSTR pszPropName, TSmartPath& rpathValue) const; + TConfig& SetValue(PCTSTR pszPropName, const TSmartPath& pathValue); - void DeleteNode(PCTSTR pszNodeName); + bool GetValue(PCTSTR pszPropName, TStringArray& rvValues) const; + TConfig& SetValue(PCTSTR pszPropName, const TStringArray& rvValues); - // extraction of subtrees - bool ExtractSubConfig(PCTSTR pszSubTreeName, TConfig& rSubConfig) const; - bool ExtractMultiSubConfigs(PCTSTR pszSubTreeName, TConfigArray& rSubConfigs) const; - void PutSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig); - void AddSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig); + void DeleteNode(PCTSTR pszNodeName); - // property change notification - void ConnectToNotifier(void (*pfnCallback)(const TStringSet&, void*), void* pParam); - void DisconnectFromNotifier(void (*pfnCallback)(const TStringSet&, void*)); + // extraction of subtrees + bool ExtractSubConfig(PCTSTR pszSubTreeName, TConfig& rSubConfig) const; + bool ExtractMultiSubConfigs(PCTSTR pszSubTreeName, TConfigArray& rSubConfigs) const; + void PutSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig); + void AddSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig); - void DelayNotifications(); - void ResumeNotifications(); + // property change notification + void ConnectToNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam); + void DisconnectFromNotifier(void(*pfnCallback)(const TStringSet&, void*)); + void DelayNotifications(); + void ResumeNotifications(); + #ifdef _DEBUG - void Dump(); + void Dump(); #endif -protected: - void SendNotification(const TStringSet& rsetInfo); - void SendNotification(PCTSTR pszInfo); + protected: + void SendNotification(const TStringSet& rsetInfo); + void SendNotification(PCTSTR pszInfo); - void ClearNL(); + void ClearNL(); -private: - details::ConfigNodeContainer* GetImpl(); - const details::ConfigNodeContainer* GetImpl() const; + private: + details::ConfigNodeContainer* GetImpl(); + const details::ConfigNodeContainer* GetImpl() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - details::ConfigNodeContainer* m_pImpl; + details::ConfigNodeContainer* m_pImpl; #pragma warning(pop) -}; + }; -template -inline void SetConfigValue(TConfig& rConfig, PCTSTR pszPropName, const Type& rValue) -{ - rConfig.SetValue(pszPropName, rValue); -} + template + inline void SetConfigValue(TConfig& rConfig, PCTSTR pszPropName, const Type& rValue) + { + rConfig.SetValue(pszPropName, rValue); + } -template -inline Type GetConfigValueDef(const TConfig& rConfig, PCTSTR pszPropName, const Type& rDefault) -{ - Type tValue; - if(!rConfig.GetValue(pszPropName, tValue)) - tValue = rDefault; - return tValue; -} + template + inline Type GetConfigValueDef(const TConfig& rConfig, PCTSTR pszPropName, const Type& rDefault) + { + Type tValue; + if (!rConfig.GetValue(pszPropName, tValue)) + tValue = rDefault; + return tValue; + } -template -inline bool GetConfigValue(const TConfig& rConfig, PCTSTR pszPropName, Type& rValue) -{ - return rConfig.GetValue(pszPropName, rValue); -} + template + inline bool GetConfigValue(const TConfig& rConfig, PCTSTR pszPropName, Type& rValue) + { + return rConfig.GetValue(pszPropName, rValue); + } #define CONFIG_MEMBER_SERIALIZATION(cls)\ namespace chcore {\ @@ -201,7 +201,6 @@ return ReadFromConfig(rValue, rConfig, pszPropName);\ }\ } +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TConfigArray.cpp =================================================================== diff -u -N -r960167a493c3ae7ecbdc7e8c2b91619106d7a685 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TConfigArray.cpp (.../TConfigArray.cpp) (revision 960167a493c3ae7ecbdc7e8c2b91619106d7a685) +++ src/libchcore/TConfigArray.cpp (.../TConfigArray.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,68 +19,66 @@ #include "stdafx.h" #include "TConfigArray.h" -BEGIN_CHCORE_NAMESPACE - - -///////////////////////////////////////////////////////////////////////////////////////////// -// class TConfigArray - -TConfigArray::TConfigArray() +namespace chcore { -} + ///////////////////////////////////////////////////////////////////////////////////////////// + // class TConfigArray -TConfigArray::TConfigArray(const TConfigArray& rSrc) : -m_vConfigs(rSrc.m_vConfigs) -{ -} + TConfigArray::TConfigArray() + { + } -TConfigArray::~TConfigArray() -{ -} + TConfigArray::TConfigArray(const TConfigArray& rSrc) : + m_vConfigs(rSrc.m_vConfigs) + { + } -TConfigArray& TConfigArray::operator=(const TConfigArray& rSrc) -{ - if(this != &rSrc) + TConfigArray::~TConfigArray() { - m_vConfigs = rSrc.m_vConfigs; } - return *this; -} + TConfigArray& TConfigArray::operator=(const TConfigArray& rSrc) + { + if (this != &rSrc) + { + m_vConfigs = rSrc.m_vConfigs; + } -size_t TConfigArray::GetCount() const -{ - return m_vConfigs.size(); -} + return *this; + } -bool TConfigArray::IsEmpty() const -{ - return m_vConfigs.empty(); -} + size_t TConfigArray::GetCount() const + { + return m_vConfigs.size(); + } -const TConfig& TConfigArray::GetAt(size_t stIndex) const -{ - return m_vConfigs[stIndex]; -} + bool TConfigArray::IsEmpty() const + { + return m_vConfigs.empty(); + } -TConfig& TConfigArray::GetAt(size_t stIndex) -{ - return m_vConfigs[stIndex]; -} + const TConfig& TConfigArray::GetAt(size_t stIndex) const + { + return m_vConfigs[stIndex]; + } -void TConfigArray::Add(const TConfig& rSrc) -{ - m_vConfigs.push_back(rSrc); -} + TConfig& TConfigArray::GetAt(size_t stIndex) + { + return m_vConfigs[stIndex]; + } -void TConfigArray::RemoveAt(size_t stIndex) -{ - m_vConfigs.erase(m_vConfigs.begin() + stIndex); -} + void TConfigArray::Add(const TConfig& rSrc) + { + m_vConfigs.push_back(rSrc); + } -void TConfigArray::Clear() -{ - m_vConfigs.clear(); -} + void TConfigArray::RemoveAt(size_t stIndex) + { + m_vConfigs.erase(m_vConfigs.begin() + stIndex); + } -END_CHCORE_NAMESPACE + void TConfigArray::Clear() + { + m_vConfigs.clear(); + } +} Index: src/libchcore/TConfigArray.h =================================================================== diff -u -N -r960167a493c3ae7ecbdc7e8c2b91619106d7a685 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TConfigArray.h (.../TConfigArray.h) (revision 960167a493c3ae7ecbdc7e8c2b91619106d7a685) +++ src/libchcore/TConfigArray.h (.../TConfigArray.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,35 +22,34 @@ #include "libchcore.h" #include "TConfig.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TConfigArray +namespace chcore { -public: - TConfigArray(); - TConfigArray(const TConfigArray& rSrc); - ~TConfigArray(); + class LIBCHCORE_API TConfigArray + { + public: + TConfigArray(); + TConfigArray(const TConfigArray& rSrc); + ~TConfigArray(); - TConfigArray& operator=(const TConfigArray& rSrc); + TConfigArray& operator=(const TConfigArray& rSrc); - size_t GetCount() const; - bool IsEmpty() const; + size_t GetCount() const; + bool IsEmpty() const; - const TConfig& GetAt(size_t stIndex) const; - TConfig& GetAt(size_t stIndex); + const TConfig& GetAt(size_t stIndex) const; + TConfig& GetAt(size_t stIndex); - void Add(const TConfig& rSrc); + void Add(const TConfig& rSrc); - void RemoveAt(size_t stIndex); - void Clear(); + void RemoveAt(size_t stIndex); + void Clear(); -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::vector m_vConfigs; + std::vector m_vConfigs; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TConfigNotifier.cpp =================================================================== diff -u -N -r960167a493c3ae7ecbdc7e8c2b91619106d7a685 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TConfigNotifier.cpp (.../TConfigNotifier.cpp) (revision 960167a493c3ae7ecbdc7e8c2b91619106d7a685) +++ src/libchcore/TConfigNotifier.cpp (.../TConfigNotifier.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,42 +21,41 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////////////////////////// + // class TConfigNotifier -/////////////////////////////////////////////////////////////////////////////////////////////// -// class TConfigNotifier + TConfigNotifier::TConfigNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam) : + m_pfnCallback(pfnCallback), + m_pParam(pParam) + { + } -TConfigNotifier::TConfigNotifier(void (*pfnCallback)(const TStringSet&, void*), void* pParam) : - m_pfnCallback(pfnCallback), - m_pParam(pParam) -{ -} + TConfigNotifier::~TConfigNotifier() + { + } -TConfigNotifier::~TConfigNotifier() -{ -} + void TConfigNotifier::operator()(const TStringSet& rsetPropNames) + { + if (!m_pfnCallback) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); -void TConfigNotifier::operator()(const TStringSet& rsetPropNames) -{ - if(!m_pfnCallback) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + (*m_pfnCallback)(rsetPropNames, m_pParam); + } - (*m_pfnCallback)(rsetPropNames, m_pParam); -} + TConfigNotifier& TConfigNotifier::operator=(const TConfigNotifier& rNotifier) + { + if (this != &rNotifier) + { + m_pfnCallback = rNotifier.m_pfnCallback; + m_pParam = rNotifier.m_pParam; + } + return *this; + } -TConfigNotifier& TConfigNotifier::operator=(const TConfigNotifier& rNotifier) -{ - if(this != &rNotifier) + bool TConfigNotifier::operator==(const TConfigNotifier& rNotifier) const { - m_pfnCallback = rNotifier.m_pfnCallback; - m_pParam = rNotifier.m_pParam; + return m_pfnCallback == rNotifier.m_pfnCallback/* && m_pParam == rNotifier.m_pParam*/; } - return *this; } - -bool TConfigNotifier::operator==(const TConfigNotifier& rNotifier) const -{ - return m_pfnCallback == rNotifier.m_pfnCallback/* && m_pParam == rNotifier.m_pParam*/; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TConfigNotifier.h =================================================================== diff -u -N -r960167a493c3ae7ecbdc7e8c2b91619106d7a685 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TConfigNotifier.h (.../TConfigNotifier.h) (revision 960167a493c3ae7ecbdc7e8c2b91619106d7a685) +++ src/libchcore/TConfigNotifier.h (.../TConfigNotifier.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,26 +22,25 @@ #include "libchcore.h" #include "TStringSet.h" -BEGIN_CHCORE_NAMESPACE - -// class defines configuration change notification record; not to be used outside -class TConfigNotifier +namespace chcore { -public: - TConfigNotifier(void (*pfnCallback)(const TStringSet&, void*), void* pParam); - ~TConfigNotifier(); + // class defines configuration change notification record; not to be used outside + class TConfigNotifier + { + public: + TConfigNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam); + ~TConfigNotifier(); - void operator()(const TStringSet& rsetPropNames); + void operator()(const TStringSet& rsetPropNames); - TConfigNotifier& operator=(const TConfigNotifier& rNotifier); + TConfigNotifier& operator=(const TConfigNotifier& rNotifier); - bool operator==(const TConfigNotifier& rNotifier) const; + bool operator==(const TConfigNotifier& rNotifier) const; -private: - void (*m_pfnCallback)(const TStringSet&, void*); - void* m_pParam; -}; + private: + void(*m_pfnCallback)(const TStringSet&, void*); + void* m_pParam; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TConfigSerializers.h =================================================================== diff -u -N -r2fe97a93f21771d75901d4b6559057d1ea055104 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TConfigSerializers.h (.../TConfigSerializers.h) (revision 2fe97a93f21771d75901d4b6559057d1ea055104) +++ src/libchcore/TConfigSerializers.h (.../TConfigSerializers.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,64 +26,61 @@ #include "TConfig.h" #include "TStringArray.h" -BEGIN_CHCORE_NAMESPACE - +namespace chcore +{ #ifdef _MFC_VER -// CString config serializer + // CString config serializer + static void StoreInConfig(const CString& strValue, TConfig& rConfig, PCTSTR pszPropName) + { + rConfig.SetValue(pszPropName, TString((PCTSTR)strValue)); + } -static void StoreInConfig(const CString& strValue, TConfig& rConfig, PCTSTR pszPropName) -{ - rConfig.SetValue(pszPropName, TString((PCTSTR)strValue)); -} - -static bool ReadFromConfig(CString& strValue, const TConfig& rConfig, PCTSTR pszPropName) -{ - TString wstrData; - bool bRes = rConfig.GetValue(pszPropName, wstrData); - if(bRes) - strValue = wstrData.c_str(); - else - strValue.Empty(); - return bRes; -} - -// vector config serializer - -static void StoreInConfig(const std::vector& vValues, TConfig& rConfig, PCTSTR pszPropName) -{ - // convert to vector of wstrings (ineffective; there should be a better way to do this) - TStringArray vToStore; - BOOST_FOREACH(const CString& strVal, vValues) + static bool ReadFromConfig(CString& strValue, const TConfig& rConfig, PCTSTR pszPropName) { - vToStore.Add((PCTSTR)strVal); + TString wstrData; + bool bRes = rConfig.GetValue(pszPropName, wstrData); + if (bRes) + strValue = wstrData.c_str(); + else + strValue.Empty(); + return bRes; } - - rConfig.SetValue(pszPropName, vToStore); -} -static bool ReadFromConfig(std::vector& vValues, const TConfig& rConfig, PCTSTR pszPropName) -{ - vValues.clear(); + // vector config serializer + static void StoreInConfig(const std::vector& vValues, TConfig& rConfig, PCTSTR pszPropName) + { + // convert to vector of wstrings (ineffective; there should be a better way to do this) + TStringArray vToStore; + BOOST_FOREACH(const CString& strVal, vValues) + { + vToStore.Add((PCTSTR)strVal); + } - TStringArray vToConvert; + rConfig.SetValue(pszPropName, vToStore); + } - bool bRes = rConfig.GetValue(pszPropName, vToConvert); - if(bRes) + static bool ReadFromConfig(std::vector& vValues, const TConfig& rConfig, PCTSTR pszPropName) { - for(size_t stIndex = 0; stIndex < vToConvert.GetCount(); ++stIndex) + vValues.clear(); + + TStringArray vToConvert; + + bool bRes = rConfig.GetValue(pszPropName, vToConvert); + if (bRes) { - vValues.push_back(vToConvert.GetAt(stIndex).c_str()); + for (size_t stIndex = 0; stIndex < vToConvert.GetCount(); ++stIndex) + { + vValues.push_back(vToConvert.GetAt(stIndex).c_str()); + } } + + return bRes; } - return bRes; +#endif } -#endif - -END_CHCORE_NAMESPACE - CONFIG_STANDALONE_SERIALIZATION(CString) CONFIG_STANDALONE_SERIALIZATION(std::vector) Index: src/libchcore/TCoreException.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TCoreException.cpp (.../TCoreException.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TCoreException.cpp (.../TCoreException.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -20,74 +20,73 @@ #include "TCoreException.h" #include -BEGIN_CHCORE_NAMESPACE - -// ============================================================================ -/// TCoreException::TCoreException -/// @date 2009/11/30 -/// -/// @brief Constructs core exception object with additional data. -/// @param[in] eErrorCode - error code -/// @param[in] pszFile - source file name -/// @param[in] stLineNumber - source line number -/// @param[in] pszFunction - function name in which the problem occured. -// ============================================================================ -TCoreException::TCoreException(EGeneralErrors eErrorCode, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction) : - TBaseException(eErrorCode, _T(""), pszFile, stLineNumber, pszFunction) +namespace chcore { -} + // ============================================================================ + /// TCoreException::TCoreException + /// @date 2009/11/30 + /// + /// @brief Constructs core exception object with additional data. + /// @param[in] eErrorCode - error code + /// @param[in] pszFile - source file name + /// @param[in] stLineNumber - source line number + /// @param[in] pszFunction - function name in which the problem occured. + // ============================================================================ + TCoreException::TCoreException(EGeneralErrors eErrorCode, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction) : + TBaseException(eErrorCode, _T(""), pszFile, stLineNumber, pszFunction) + { + } -// ============================================================================ -/// TCoreException::TCoreException -/// @date 2009/11/30 -/// -/// @brief Constructs core exception object with additional data. -/// @param[in] eErrorCode - error code -/// @param[in] stdException - standard exception info -/// @param[in] pszFile - source file name -/// @param[in] stLineNumber - source line number -/// @param[in] pszFunction - function name in which the problem occured. -// ============================================================================ -TCoreException::TCoreException(EGeneralErrors eErrorCode, std::exception& stdException, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction) : - TBaseException(eErrorCode, stdException.what(), pszFile, stLineNumber, pszFunction) -{ -} + // ============================================================================ + /// TCoreException::TCoreException + /// @date 2009/11/30 + /// + /// @brief Constructs core exception object with additional data. + /// @param[in] eErrorCode - error code + /// @param[in] stdException - standard exception info + /// @param[in] pszFile - source file name + /// @param[in] stLineNumber - source line number + /// @param[in] pszFunction - function name in which the problem occured. + // ============================================================================ + TCoreException::TCoreException(EGeneralErrors eErrorCode, std::exception& stdException, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction) : + TBaseException(eErrorCode, stdException.what(), pszFile, stLineNumber, pszFunction) + { + } -// ============================================================================ -/// TCoreWin32Exception::TCoreWin32Exception -/// @date 2011/07/18 -/// -/// @brief Constructs core win32 exception. -/// @param[in] eErrorCode - core error code -/// @param[in] dwWin32Exception - win32 error code -/// @param[in] pszFile -source file where the exception was thrown -/// @param[in] stLineNumber - source code line number where the exception was thrown -/// @param[in] pszFunction - function throwing the exception -// ============================================================================ -TCoreWin32Exception::TCoreWin32Exception(EGeneralErrors eErrorCode, DWORD dwWin32Exception, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction) : - TBaseException(eErrorCode, _T(""), pszFile, stLineNumber, pszFunction), - m_dwWin32ErrorCode(dwWin32Exception) -{ -} + // ============================================================================ + /// TCoreWin32Exception::TCoreWin32Exception + /// @date 2011/07/18 + /// + /// @brief Constructs core win32 exception. + /// @param[in] eErrorCode - core error code + /// @param[in] dwWin32Exception - win32 error code + /// @param[in] pszFile -source file where the exception was thrown + /// @param[in] stLineNumber - source code line number where the exception was thrown + /// @param[in] pszFunction - function throwing the exception + // ============================================================================ + TCoreWin32Exception::TCoreWin32Exception(EGeneralErrors eErrorCode, DWORD dwWin32Exception, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction) : + TBaseException(eErrorCode, _T(""), pszFile, stLineNumber, pszFunction), + m_dwWin32ErrorCode(dwWin32Exception) + { + } -// ============================================================================ -/// TCoreWin32Exception::GetErrorInfo -/// @date 2011/07/18 -/// -/// @brief Retrieves formatted exception information. -/// @param[in] pszBuffer - buffer for formatted string -/// @param[in] stMaxBuffer - max size of buffer -// ============================================================================ -void TCoreWin32Exception::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const -{ - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("Error code: %ld (win32 error code: %lu)"), m_eErrorCode, m_dwWin32ErrorCode); - pszBuffer[stMaxBuffer - 1] = _T('\0'); -} + // ============================================================================ + /// TCoreWin32Exception::GetErrorInfo + /// @date 2011/07/18 + /// + /// @brief Retrieves formatted exception information. + /// @param[in] pszBuffer - buffer for formatted string + /// @param[in] stMaxBuffer - max size of buffer + // ============================================================================ + void TCoreWin32Exception::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("Error code: %ld (win32 error code: %lu)"), m_eErrorCode, m_dwWin32ErrorCode); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } -void TCoreWin32Exception::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const -{ - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("Error code: %ld\r\nWin32 error code: %lu\r\nFile: %s\r\nFunction: %s\r\nLine no: %lu"), m_eErrorCode, m_dwWin32ErrorCode, m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); - pszBuffer[stMaxBuffer - 1] = _T('\0'); + void TCoreWin32Exception::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("Error code: %ld\r\nWin32 error code: %lu\r\nFile: %s\r\nFunction: %s\r\nLine no: %lu"), m_eErrorCode, m_dwWin32ErrorCode, m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TCoreException.h =================================================================== diff -u -N -r548382442cbf7bed7f744b279ce3f66b54992724 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TCoreException.h (.../TCoreException.h) (revision 548382442cbf7bed7f744b279ce3f66b54992724) +++ src/libchcore/TCoreException.h (.../TCoreException.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,9 +23,9 @@ #include "ErrorCodes.h" #include "TBaseException.h" -BEGIN_CHCORE_NAMESPACE - -// throws core exception object +namespace chcore +{ + // throws core exception object #define THROW_CORE_EXCEPTION(error_code)\ throw TCoreException(error_code, __FILEW__, __LINE__, __FUNCTIONW__) @@ -35,34 +35,33 @@ #define THROW_CORE_EXCEPTION_WIN32(error_code, win32_error_code)\ throw TCoreWin32Exception(error_code, win32_error_code, __FILEW__, __LINE__, __FUNCTIONW__) -class LIBCHCORE_API TCoreException : public TBaseException -{ -public: - TCoreException(EGeneralErrors eErrorCode, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction); - TCoreException(EGeneralErrors eErrorCode, std::exception& stdException, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction); + class LIBCHCORE_API TCoreException : public TBaseException + { + public: + TCoreException(EGeneralErrors eErrorCode, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction); + TCoreException(EGeneralErrors eErrorCode, std::exception& stdException, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction); -private: - TCoreException(); -}; + private: + TCoreException(); + }; -class LIBCHCORE_API TCoreWin32Exception : public TBaseException -{ -public: - TCoreWin32Exception(EGeneralErrors eErrorCode, DWORD dwWin32Exception, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction); + class LIBCHCORE_API TCoreWin32Exception : public TBaseException + { + public: + TCoreWin32Exception(EGeneralErrors eErrorCode, DWORD dwWin32Exception, const tchar_t* pszFile, size_t stLineNumber, const tchar_t* pszFunction); - DWORD GetWin32ErrorCode() const { return m_dwWin32ErrorCode; } + DWORD GetWin32ErrorCode() const { return m_dwWin32ErrorCode; } - virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; - virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; -private: - TCoreWin32Exception(); + private: + TCoreWin32Exception(); -protected: - // what happened? - DWORD m_dwWin32ErrorCode; -}; + protected: + // what happened? + DWORD m_dwWin32ErrorCode; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TDateTime.cpp =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TDateTime.cpp (.../TDateTime.cpp) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TDateTime.cpp (.../TDateTime.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,208 +25,207 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -TDateTime::TDateTime() : - m_tTime(0) +namespace chcore { -} + TDateTime::TDateTime() : + m_tTime(0) + { + } -TDateTime::TDateTime(int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond) -{ - if(iYear < 1900) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + TDateTime::TDateTime(int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond) + { + if (iYear < 1900) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - tm tTime; + tm tTime; - tTime.tm_sec = iSecond; - tTime.tm_min = iMinute; - tTime.tm_hour = iHour; - tTime.tm_mday = iDay; - tTime.tm_mon = iMonth - 1; - tTime.tm_year = iYear - 1900; - tTime.tm_isdst = -1; + tTime.tm_sec = iSecond; + tTime.tm_min = iMinute; + tTime.tm_hour = iHour; + tTime.tm_mday = iDay; + tTime.tm_mon = iMonth - 1; + tTime.tm_year = iYear - 1900; + tTime.tm_isdst = -1; - m_tTime = _mktime64(&tTime); - if(m_tTime == -1) - THROW_CORE_EXCEPTION_WIN32(eErr_InvalidArgument, GetLastError()); -} + m_tTime = _mktime64(&tTime); + if (m_tTime == -1) + THROW_CORE_EXCEPTION_WIN32(eErr_InvalidArgument, GetLastError()); + } -TDateTime::TDateTime(FILETIME ftDateTime) -{ - operator=(ftDateTime); -} + TDateTime::TDateTime(FILETIME ftDateTime) + { + operator=(ftDateTime); + } -TDateTime::TDateTime(SYSTEMTIME sysDateTime) -{ - operator=(sysDateTime); -} + TDateTime::TDateTime(SYSTEMTIME sysDateTime) + { + operator=(sysDateTime); + } -TDateTime::TDateTime(time_t tDateTime) : - m_tTime(tDateTime) -{ -} + TDateTime::TDateTime(time_t tDateTime) : + m_tTime(tDateTime) + { + } -TDateTime& TDateTime::operator=(FILETIME ftDateTime) -{ - // convert and process as system time - FILETIME tLocalFileTime; - if(!FileTimeToLocalFileTime(&ftDateTime, &tLocalFileTime)) - THROW_CORE_EXCEPTION_WIN32(eErr_InvalidArgument, GetLastError()); + TDateTime& TDateTime::operator=(FILETIME ftDateTime) + { + // convert and process as system time + FILETIME tLocalFileTime; + if (!FileTimeToLocalFileTime(&ftDateTime, &tLocalFileTime)) + THROW_CORE_EXCEPTION_WIN32(eErr_InvalidArgument, GetLastError()); - SYSTEMTIME sysTime; - if(!FileTimeToSystemTime(&tLocalFileTime, &sysTime)) - THROW_CORE_EXCEPTION_WIN32(eErr_InvalidArgument, GetLastError()); + SYSTEMTIME sysTime; + if (!FileTimeToSystemTime(&tLocalFileTime, &sysTime)) + THROW_CORE_EXCEPTION_WIN32(eErr_InvalidArgument, GetLastError()); - return operator=(sysTime); -} + return operator=(sysTime); + } -TDateTime& TDateTime::operator=(SYSTEMTIME sysDateTime) -{ - if(sysDateTime.wYear < 1900) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + TDateTime& TDateTime::operator=(SYSTEMTIME sysDateTime) + { + if (sysDateTime.wYear < 1900) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - tm tTime; + tm tTime; - tTime.tm_sec = sysDateTime.wSecond; - tTime.tm_min = sysDateTime.wMinute; - tTime.tm_hour = sysDateTime.wHour; - tTime.tm_mday = sysDateTime.wDay; - tTime.tm_mon = sysDateTime.wMonth - 1; - tTime.tm_year = sysDateTime.wYear - 1900; - tTime.tm_isdst = -1; + tTime.tm_sec = sysDateTime.wSecond; + tTime.tm_min = sysDateTime.wMinute; + tTime.tm_hour = sysDateTime.wHour; + tTime.tm_mday = sysDateTime.wDay; + tTime.tm_mon = sysDateTime.wMonth - 1; + tTime.tm_year = sysDateTime.wYear - 1900; + tTime.tm_isdst = -1; - m_tTime = _mktime64(&tTime); - if(m_tTime == -1) - THROW_CORE_EXCEPTION_WIN32(eErr_InvalidArgument, GetLastError()); + m_tTime = _mktime64(&tTime); + if (m_tTime == -1) + THROW_CORE_EXCEPTION_WIN32(eErr_InvalidArgument, GetLastError()); - return *this; -} + return *this; + } -TDateTime& TDateTime::operator=(time_t tDateTime) -{ - m_tTime = tDateTime; - return *this; -} + TDateTime& TDateTime::operator=(time_t tDateTime) + { + m_tTime = tDateTime; + return *this; + } -void TDateTime::Clear() -{ - m_tTime = 0; -} + void TDateTime::Clear() + { + m_tTime = 0; + } -void TDateTime::SetCurrentDateTime() -{ - m_tTime = _time64(NULL); -} + void TDateTime::SetCurrentDateTime() + { + m_tTime = _time64(NULL); + } -void TDateTime::GetAsSystemTime(SYSTEMTIME& tSystemTime) const -{ - tm tThisTimeInfo; - errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); - if(err != 0) - THROW_CORE_EXCEPTION(eErr_InvalidData); + void TDateTime::GetAsSystemTime(SYSTEMTIME& tSystemTime) const + { + tm tThisTimeInfo; + errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); + if (err != 0) + THROW_CORE_EXCEPTION(eErr_InvalidData); - tSystemTime.wYear = (WORD)(tThisTimeInfo.tm_year + 1900); - tSystemTime.wMonth = (WORD)(tThisTimeInfo.tm_mon + 1); - tSystemTime.wDayOfWeek = (WORD)tThisTimeInfo.tm_wday; - tSystemTime.wDay = (WORD)tThisTimeInfo.tm_mday; - tSystemTime.wHour = (WORD)tThisTimeInfo.tm_hour; - tSystemTime.wMinute = (WORD)tThisTimeInfo.tm_min; - tSystemTime.wSecond = (WORD)tThisTimeInfo.tm_sec; - tSystemTime.wMilliseconds = 0; -} + tSystemTime.wYear = (WORD)(tThisTimeInfo.tm_year + 1900); + tSystemTime.wMonth = (WORD)(tThisTimeInfo.tm_mon + 1); + tSystemTime.wDayOfWeek = (WORD)tThisTimeInfo.tm_wday; + tSystemTime.wDay = (WORD)tThisTimeInfo.tm_mday; + tSystemTime.wHour = (WORD)tThisTimeInfo.tm_hour; + tSystemTime.wMinute = (WORD)tThisTimeInfo.tm_min; + tSystemTime.wSecond = (WORD)tThisTimeInfo.tm_sec; + tSystemTime.wMilliseconds = 0; + } -TString TDateTime::Format(bool bUseDate, bool bUseTime) const -{ - if(!bUseDate && !bUseTime) - return TString(); + TString TDateTime::Format(bool bUseDate, bool bUseTime) const + { + if (!bUseDate && !bUseTime) + return TString(); - TString strTmp; - const size_t stMaxBufSize = 1024; - wchar_t* pszBuffer = strTmp.GetBuffer(stMaxBufSize); + TString strTmp; + const size_t stMaxBufSize = 1024; + wchar_t* pszBuffer = strTmp.GetBuffer(stMaxBufSize); - PCTSTR pszFmt = NULL; - if(bUseDate && bUseTime) - pszFmt = _T("%x %X"); - else if(bUseDate) - pszFmt = _T("%x"); - else if(bUseTime) - pszFmt = _T("%X"); + PCTSTR pszFmt = NULL; + if (bUseDate && bUseTime) + pszFmt = _T("%x %X"); + else if (bUseDate) + pszFmt = _T("%x"); + else if (bUseTime) + pszFmt = _T("%X"); - tm tThisTimeInfo; - errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); - if(err != 0) - THROW_CORE_EXCEPTION(eErr_InvalidData); + tm tThisTimeInfo; + errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); + if (err != 0) + THROW_CORE_EXCEPTION(eErr_InvalidData); - if(!_tcsftime(pszBuffer, stMaxBufSize, pszFmt, &tThisTimeInfo)) - THROW_CORE_EXCEPTION(eErr_InvalidData); + if (!_tcsftime(pszBuffer, stMaxBufSize, pszFmt, &tThisTimeInfo)) + THROW_CORE_EXCEPTION(eErr_InvalidData); - strTmp.ReleaseBuffer(); - return strTmp; -} + strTmp.ReleaseBuffer(); + return strTmp; + } -time_t TDateTime::Compare(const TDateTime& rOtherDateTime, bool bCompareDate, bool bCompareTime) const -{ - if(!bCompareDate && !bCompareTime) - return 0; + time_t TDateTime::Compare(const TDateTime& rOtherDateTime, bool bCompareDate, bool bCompareTime) const + { + if (!bCompareDate && !bCompareTime) + return 0; - tm tThisTimeInfo; - tm tOtherTimeInfo; - errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); - if(err != 0) - THROW_CORE_EXCEPTION(eErr_InvalidData); - err = _localtime64_s(&tOtherTimeInfo, &rOtherDateTime.m_tTime); - if(err != 0) - THROW_CORE_EXCEPTION(eErr_InvalidData); + tm tThisTimeInfo; + tm tOtherTimeInfo; + errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); + if (err != 0) + THROW_CORE_EXCEPTION(eErr_InvalidData); + err = _localtime64_s(&tOtherTimeInfo, &rOtherDateTime.m_tTime); + if (err != 0) + THROW_CORE_EXCEPTION(eErr_InvalidData); - time_t tDiffDateTime = 0; - if(bCompareDate) - { - time_t tThisCompoundDate = (tThisTimeInfo.tm_year - 1900) * 32140800 + tThisTimeInfo.tm_mon * 2678400 + tThisTimeInfo.tm_mday * 86400; - time_t tOtherCompoundDate = (tOtherTimeInfo.tm_year - 1900) * 32140800 + tOtherTimeInfo.tm_mon * 2678400 + tOtherTimeInfo.tm_mday * 86400; + time_t tDiffDateTime = 0; + if (bCompareDate) + { + time_t tThisCompoundDate = (tThisTimeInfo.tm_year - 1900) * 32140800 + tThisTimeInfo.tm_mon * 2678400 + tThisTimeInfo.tm_mday * 86400; + time_t tOtherCompoundDate = (tOtherTimeInfo.tm_year - 1900) * 32140800 + tOtherTimeInfo.tm_mon * 2678400 + tOtherTimeInfo.tm_mday * 86400; - // <0 means that this date is less than other date, 0 means they are equal, >0 means that other date is less than this date - tDiffDateTime = tOtherCompoundDate - tThisCompoundDate; + // <0 means that this date is less than other date, 0 means they are equal, >0 means that other date is less than this date + tDiffDateTime = tOtherCompoundDate - tThisCompoundDate; - // at this point we can return only if this date differs from other date; if they are equal, process time comparison if needed - if(tDiffDateTime != 0) - return tDiffDateTime; + // at this point we can return only if this date differs from other date; if they are equal, process time comparison if needed + if (tDiffDateTime != 0) + return tDiffDateTime; + } + + if (bCompareTime) + { + time_t tThisCompoundTime = tThisTimeInfo.tm_hour * 3600 + tThisTimeInfo.tm_min * 60 + tThisTimeInfo.tm_sec; + time_t tOtherCompoundTime = tOtherTimeInfo.tm_hour * 3600 + tOtherTimeInfo.tm_min * 60 + tOtherTimeInfo.tm_sec; + + tDiffDateTime = tOtherCompoundTime - tThisCompoundTime; + } + + return tDiffDateTime; } - if(bCompareTime) + void TDateTime::StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const { - time_t tThisCompoundTime = tThisTimeInfo.tm_hour * 3600 + tThisTimeInfo.tm_min * 60 + tThisTimeInfo.tm_sec; - time_t tOtherCompoundTime = tOtherTimeInfo.tm_hour * 3600 + tOtherTimeInfo.tm_min * 60 + tOtherTimeInfo.tm_sec; + rConfig.SetValue(pszNodeName, m_tTime); + } - tDiffDateTime = tOtherCompoundTime - tThisCompoundTime; + bool TDateTime::ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName) + { + return rConfig.GetValue(pszNodeName, m_tTime); } - return tDiffDateTime; -} + time_t TDateTime::GetAsTimeT() const + { + return m_tTime; + } -void TDateTime::StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const -{ - rConfig.SetValue(pszNodeName, m_tTime); -} + bool TDateTime::operator==(const TDateTime& rSrc) const + { + return m_tTime == rSrc.m_tTime; + } -bool TDateTime::ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName) -{ - return rConfig.GetValue(pszNodeName, m_tTime); + bool TDateTime::operator!=(const TDateTime& rSrc) const + { + return m_tTime != rSrc.m_tTime; + } } - -time_t TDateTime::GetAsTimeT() const -{ - return m_tTime; -} - -bool TDateTime::operator==(const TDateTime& rSrc) const -{ - return m_tTime == rSrc.m_tTime; -} - -bool TDateTime::operator!=(const TDateTime& rSrc) const -{ - return m_tTime != rSrc.m_tTime; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TDateTime.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TDateTime.h (.../TDateTime.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TDateTime.h (.../TDateTime.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,47 +26,46 @@ #include "libchcore.h" #include "TConfig.h" -BEGIN_CHCORE_NAMESPACE - -class TConfig; - -class LIBCHCORE_API TDateTime +namespace chcore { -public: - TDateTime(); - TDateTime(int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond); - TDateTime(FILETIME ftDateTime); - TDateTime(SYSTEMTIME sysDateTime); - TDateTime(time_t tDateTime); + class TConfig; - TDateTime& operator=(FILETIME ftDateTime); - TDateTime& operator=(SYSTEMTIME sysDateTime); - TDateTime& operator=(time_t tDateTime); + class LIBCHCORE_API TDateTime + { + public: + TDateTime(); + TDateTime(int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond); + TDateTime(FILETIME ftDateTime); + TDateTime(SYSTEMTIME sysDateTime); + TDateTime(time_t tDateTime); - bool operator==(const TDateTime& rSrc) const; - bool operator!=(const TDateTime& rSrc) const; + TDateTime& operator=(FILETIME ftDateTime); + TDateTime& operator=(SYSTEMTIME sysDateTime); + TDateTime& operator=(time_t tDateTime); - // content modification - void Clear(); - void SetCurrentDateTime(); + bool operator==(const TDateTime& rSrc) const; + bool operator!=(const TDateTime& rSrc) const; - // content extraction - void GetAsSystemTime(SYSTEMTIME& tSystemTime) const; - time_t GetAsTimeT() const; - TString Format(bool bUseDate, bool bUseTime) const; + // content modification + void Clear(); + void SetCurrentDateTime(); - // comparison - time_t Compare(const TDateTime& rOtherDateTime, bool bCompareDate, bool bCompareTime) const; + // content extraction + void GetAsSystemTime(SYSTEMTIME& tSystemTime) const; + time_t GetAsTimeT() const; + TString Format(bool bUseDate, bool bUseTime) const; - // serialization - void StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const; - bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName); + // comparison + time_t Compare(const TDateTime& rOtherDateTime, bool bCompareDate, bool bCompareTime) const; -private: - time_t m_tTime; -}; + // serialization + void StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const; + bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName); -END_CHCORE_NAMESPACE + private: + time_t m_tTime; + }; +} CONFIG_MEMBER_SERIALIZATION(TDateTime) Index: src/libchcore/TEvent.cpp =================================================================== diff -u -N -r6103ac74583f2136b821dc67515ed8469abd8155 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TEvent.cpp (.../TEvent.cpp) (revision 6103ac74583f2136b821dc67515ed8469abd8155) +++ src/libchcore/TEvent.cpp (.../TEvent.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,18 +21,17 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -TEvent::TEvent(bool bManualReset, bool bInitialState) +namespace chcore { - m_hEvent = CreateEvent(NULL, bManualReset, bInitialState, NULL); - if (m_hEvent == NULL) - THROW_CORE_EXCEPTION(eErr_CannotCreateEvent); -} + TEvent::TEvent(bool bManualReset, bool bInitialState) + { + m_hEvent = CreateEvent(NULL, bManualReset, bInitialState, NULL); + if (m_hEvent == NULL) + THROW_CORE_EXCEPTION(eErr_CannotCreateEvent); + } -TEvent::~TEvent() -{ - CloseHandle(m_hEvent); + TEvent::~TEvent() + { + CloseHandle(m_hEvent); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TEvent.h =================================================================== diff -u -N -r6103ac74583f2136b821dc67515ed8469abd8155 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TEvent.h (.../TEvent.h) (revision 6103ac74583f2136b821dc67515ed8469abd8155) +++ src/libchcore/TEvent.h (.../TEvent.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,24 +21,23 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TEvent +namespace chcore { -public: - TEvent(bool bManualReset, bool bInitialState); - virtual ~TEvent(); + class LIBCHCORE_API TEvent + { + public: + TEvent(bool bManualReset, bool bInitialState); + virtual ~TEvent(); - HANDLE Get() const { return m_hEvent; } - void SetEvent() { ::SetEvent(m_hEvent); } - void ResetEvent() { ::ResetEvent(m_hEvent); } + HANDLE Get() const { return m_hEvent; } + void SetEvent() { ::SetEvent(m_hEvent); } + void ResetEvent() { ::ResetEvent(m_hEvent); } - HANDLE Handle() const { return m_hEvent; } + HANDLE Handle() const { return m_hEvent; } -private: - HANDLE m_hEvent; -}; + private: + HANDLE m_hEvent; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TFakeFileSerializer.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFakeFileSerializer.cpp (.../TFakeFileSerializer.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TFakeFileSerializer.cpp (.../TFakeFileSerializer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,30 +21,29 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -TFakeFileSerializer::TFakeFileSerializer(const TSmartPath& rPath) : - m_pathFileSerializer(rPath) +namespace chcore { -} + TFakeFileSerializer::TFakeFileSerializer(const TSmartPath& rPath) : + m_pathFileSerializer(rPath) + { + } -TFakeFileSerializer::~TFakeFileSerializer() -{ -} + TFakeFileSerializer::~TFakeFileSerializer() + { + } -TSmartPath TFakeFileSerializer::GetLocation() const -{ - return m_pathFileSerializer; -} + TSmartPath TFakeFileSerializer::GetLocation() const + { + return m_pathFileSerializer; + } -ISerializerContainerPtr TFakeFileSerializer::GetContainer(const TString& /*strContainerName*/) -{ - throw TCoreException(eErr_InvalidSerializer, m_pathFileSerializer.ToString(), __LINE__, __FUNCTIONW__); -} + ISerializerContainerPtr TFakeFileSerializer::GetContainer(const TString& /*strContainerName*/) + { + throw TCoreException(eErr_InvalidSerializer, m_pathFileSerializer.ToString(), __LINE__, __FUNCTIONW__); + } -void TFakeFileSerializer::Flush() -{ - throw TCoreException(eErr_InvalidSerializer, m_pathFileSerializer.ToString(), __LINE__, __FUNCTIONW__); + void TFakeFileSerializer::Flush() + { + throw TCoreException(eErr_InvalidSerializer, m_pathFileSerializer.ToString(), __LINE__, __FUNCTIONW__); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TFakeFileSerializer.h =================================================================== diff -u -N -rcdb4c898156398dd4f4bf8abd7c854eff42f6ae2 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFakeFileSerializer.h (.../TFakeFileSerializer.h) (revision cdb4c898156398dd4f4bf8abd7c854eff42f6ae2) +++ src/libchcore/TFakeFileSerializer.h (.../TFakeFileSerializer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,27 +22,26 @@ #include "libchcore.h" #include "ISerializer.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TFakeFileSerializer : public ISerializer +namespace chcore { -public: - TFakeFileSerializer(const TSmartPath& rPath); - virtual ~TFakeFileSerializer(); + class LIBCHCORE_API TFakeFileSerializer : public ISerializer + { + public: + TFakeFileSerializer(const TSmartPath& rPath); + virtual ~TFakeFileSerializer(); - TFakeFileSerializer(const TFakeFileSerializer& rSrc) = delete; - TFakeFileSerializer& operator=(const TFakeFileSerializer& rSrc) = delete; + TFakeFileSerializer(const TFakeFileSerializer& rSrc) = delete; + TFakeFileSerializer& operator=(const TFakeFileSerializer& rSrc) = delete; - virtual TSmartPath GetLocation() const override; - virtual ISerializerContainerPtr GetContainer(const TString& strContainerName) override; - virtual void Flush() override; + virtual TSmartPath GetLocation() const override; + virtual ISerializerContainerPtr GetContainer(const TString& strContainerName) override; + virtual void Flush() override; -private: - TSmartPath m_pathFileSerializer; -}; + private: + TSmartPath m_pathFileSerializer; + }; -typedef boost::shared_ptr TFakeFileSerializerPtr; + typedef boost::shared_ptr TFakeFileSerializerPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TFakeVolumeInfo.cpp =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFakeVolumeInfo.cpp (.../TFakeVolumeInfo.cpp) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/TFakeVolumeInfo.cpp (.../TFakeVolumeInfo.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,47 +19,46 @@ #include "stdafx.h" #include "TFakeVolumeInfo.h" -BEGIN_CHCORE_NAMESPACE - -TFakeVolumeInfo::TFakeVolumeInfo(file_size_t fsTotalSize, UINT uiDriveType, DWORD dwPhysicalDriveNumber) : - m_fsTotalSize(fsTotalSize), - m_uiDriveType(uiDriveType), - m_dwPhysicalDriveNumber(dwPhysicalDriveNumber) +namespace chcore { -} + TFakeVolumeInfo::TFakeVolumeInfo(file_size_t fsTotalSize, UINT uiDriveType, DWORD dwPhysicalDriveNumber) : + m_fsTotalSize(fsTotalSize), + m_uiDriveType(uiDriveType), + m_dwPhysicalDriveNumber(dwPhysicalDriveNumber) + { + } -TFakeVolumeInfo::~TFakeVolumeInfo() -{ -} + TFakeVolumeInfo::~TFakeVolumeInfo() + { + } -void TFakeVolumeInfo::SetTotalSize(file_size_t fsTotalSize) -{ - m_fsTotalSize = fsTotalSize; -} + void TFakeVolumeInfo::SetTotalSize(file_size_t fsTotalSize) + { + m_fsTotalSize = fsTotalSize; + } -file_size_t TFakeVolumeInfo::GetTotalSize() const -{ - return m_fsTotalSize; -} + file_size_t TFakeVolumeInfo::GetTotalSize() const + { + return m_fsTotalSize; + } -void TFakeVolumeInfo::SetDriveType(UINT uiDriveType) -{ - m_uiDriveType = uiDriveType; -} + void TFakeVolumeInfo::SetDriveType(UINT uiDriveType) + { + m_uiDriveType = uiDriveType; + } -UINT TFakeVolumeInfo::GetDriveType() const -{ - return m_uiDriveType; -} + UINT TFakeVolumeInfo::GetDriveType() const + { + return m_uiDriveType; + } -void TFakeVolumeInfo::SetPhysicalDriveNumber(DWORD dwDriveNumber) -{ - m_dwPhysicalDriveNumber = dwDriveNumber; -} + void TFakeVolumeInfo::SetPhysicalDriveNumber(DWORD dwDriveNumber) + { + m_dwPhysicalDriveNumber = dwDriveNumber; + } -DWORD TFakeVolumeInfo::GetPhysicalDriveNumber() const -{ - return m_dwPhysicalDriveNumber; + DWORD TFakeVolumeInfo::GetPhysicalDriveNumber() const + { + return m_dwPhysicalDriveNumber; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TFakeVolumeInfo.h =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFakeVolumeInfo.h (.../TFakeVolumeInfo.h) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/TFakeVolumeInfo.h (.../TFakeVolumeInfo.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,29 +22,28 @@ #include "libchcore.h" #include "CommonDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TFakeVolumeInfo +namespace chcore { -public: - TFakeVolumeInfo(file_size_t fsTotalSize, UINT uiDriveType, DWORD dwPhysicalDriveNumber); - ~TFakeVolumeInfo(); + class LIBCHCORE_API TFakeVolumeInfo + { + public: + TFakeVolumeInfo(file_size_t fsTotalSize, UINT uiDriveType, DWORD dwPhysicalDriveNumber); + ~TFakeVolumeInfo(); - void SetTotalSize(file_size_t fsTotalSize); - file_size_t GetTotalSize() const; + void SetTotalSize(file_size_t fsTotalSize); + file_size_t GetTotalSize() const; - void SetDriveType(UINT uiDriveType); - UINT GetDriveType() const; + void SetDriveType(UINT uiDriveType); + UINT GetDriveType() const; - void SetPhysicalDriveNumber(DWORD dwDriveNumber); - DWORD GetPhysicalDriveNumber() const; + void SetPhysicalDriveNumber(DWORD dwDriveNumber); + DWORD GetPhysicalDriveNumber() const; -private: - file_size_t m_fsTotalSize; - UINT m_uiDriveType; - DWORD m_dwPhysicalDriveNumber; -}; + private: + file_size_t m_fsTotalSize; + UINT m_uiDriveType; + DWORD m_dwPhysicalDriveNumber; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TFeedbackHandlerBase.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFeedbackHandlerBase.cpp (.../TFeedbackHandlerBase.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TFeedbackHandlerBase.cpp (.../TFeedbackHandlerBase.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,124 +21,123 @@ #include "SerializerDataTypes.h" #include "ISerializerContainer.h" -BEGIN_CHCORE_NAMESPACE - -TFeedbackHandlerBase::TFeedbackHandlerBase() : - m_eFileError(m_setModifications, EFeedbackResult::eResult_Unknown), - m_eFileAlreadyExists(m_setModifications, EFeedbackResult::eResult_Unknown), - m_eNotEnoughSpace(m_setModifications, EFeedbackResult::eResult_Unknown), - m_eOperationFinished(m_setModifications, EFeedbackResult::eResult_Unknown), - m_eOperationError(m_setModifications, EFeedbackResult::eResult_Unknown) +namespace chcore { - m_setModifications[eMod_Added] = true; -} + TFeedbackHandlerBase::TFeedbackHandlerBase() : + m_eFileError(m_setModifications, EFeedbackResult::eResult_Unknown), + m_eFileAlreadyExists(m_setModifications, EFeedbackResult::eResult_Unknown), + m_eNotEnoughSpace(m_setModifications, EFeedbackResult::eResult_Unknown), + m_eOperationFinished(m_setModifications, EFeedbackResult::eResult_Unknown), + m_eOperationError(m_setModifications, EFeedbackResult::eResult_Unknown) + { + m_setModifications[eMod_Added] = true; + } -TFeedbackHandlerBase::~TFeedbackHandlerBase() -{ -} + TFeedbackHandlerBase::~TFeedbackHandlerBase() + { + } -void TFeedbackHandlerBase::Store(const ISerializerContainerPtr& spContainer) const -{ - boost::shared_lock lock(m_lock); - - if (m_setModifications.any()) + void TFeedbackHandlerBase::Store(const ISerializerContainerPtr& spContainer) const { - InitColumns(spContainer); + boost::shared_lock lock(m_lock); - bool bAdded = m_setModifications[eMod_Added]; - ISerializerRowData& rRowData = spContainer->GetRow(0, bAdded); + if (m_setModifications.any()) + { + InitColumns(spContainer); - if (bAdded || m_eFileError.IsModified()) - rRowData.SetValue(_T("file_error"), m_eFileError); + bool bAdded = m_setModifications[eMod_Added]; + ISerializerRowData& rRowData = spContainer->GetRow(0, bAdded); - if (bAdded || m_eFileAlreadyExists.IsModified()) - rRowData.SetValue(_T("file_already_exists"), m_eFileAlreadyExists); + if (bAdded || m_eFileError.IsModified()) + rRowData.SetValue(_T("file_error"), m_eFileError); - if (bAdded || m_eNotEnoughSpace.IsModified()) - rRowData.SetValue(_T("not_enough_space"), m_eNotEnoughSpace); + if (bAdded || m_eFileAlreadyExists.IsModified()) + rRowData.SetValue(_T("file_already_exists"), m_eFileAlreadyExists); - if (bAdded || m_eOperationFinished.IsModified()) - rRowData.SetValue(_T("operation_finished"), m_eOperationFinished); + if (bAdded || m_eNotEnoughSpace.IsModified()) + rRowData.SetValue(_T("not_enough_space"), m_eNotEnoughSpace); - if (bAdded || m_eOperationError.IsModified()) - rRowData.SetValue(_T("operation_error"), m_eOperationError); + if (bAdded || m_eOperationFinished.IsModified()) + rRowData.SetValue(_T("operation_finished"), m_eOperationFinished); - m_setModifications.reset(); + if (bAdded || m_eOperationError.IsModified()) + rRowData.SetValue(_T("operation_error"), m_eOperationError); + + m_setModifications.reset(); + } } -} -void TFeedbackHandlerBase::InitColumns(const ISerializerContainerPtr& spContainer) -{ - IColumnsDefinition& rColumnDefs = spContainer->GetColumnsDefinition(); - if (rColumnDefs.IsEmpty()) + void TFeedbackHandlerBase::InitColumns(const ISerializerContainerPtr& spContainer) { - rColumnDefs.AddColumn(_T("id"), ColumnType::value); - rColumnDefs.AddColumn(_T("file_error"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("file_already_exists"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("not_enough_space"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("operation_finished"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("operation_error"), IColumnsDefinition::eType_int); + IColumnsDefinition& rColumnDefs = spContainer->GetColumnsDefinition(); + if (rColumnDefs.IsEmpty()) + { + rColumnDefs.AddColumn(_T("id"), ColumnType::value); + rColumnDefs.AddColumn(_T("file_error"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("file_already_exists"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("not_enough_space"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("operation_finished"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("operation_error"), IColumnsDefinition::eType_int); + } } -} -void TFeedbackHandlerBase::Load(const ISerializerContainerPtr& spContainer) -{ - boost::unique_lock lock(m_lock); - - InitColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if (spRowReader->Next()) + void TFeedbackHandlerBase::Load(const ISerializerContainerPtr& spContainer) { - int iFeedbackResult = eResult_Unknown; + boost::unique_lock lock(m_lock); - spRowReader->GetValue(_T("file_error"), iFeedbackResult); - m_eFileError = (EFeedbackResult) iFeedbackResult; + InitColumns(spContainer); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + { + int iFeedbackResult = eResult_Unknown; - spRowReader->GetValue(_T("file_already_exists"), iFeedbackResult); - m_eFileAlreadyExists = (EFeedbackResult) iFeedbackResult; - spRowReader->GetValue(_T("not_enough_space"), iFeedbackResult); - m_eNotEnoughSpace = (EFeedbackResult) iFeedbackResult; - spRowReader->GetValue(_T("operation_finished"), iFeedbackResult); - m_eOperationFinished = (EFeedbackResult) iFeedbackResult; - spRowReader->GetValue(_T("operation_error"), iFeedbackResult); - m_eOperationError = (EFeedbackResult) iFeedbackResult; + spRowReader->GetValue(_T("file_error"), iFeedbackResult); + m_eFileError = (EFeedbackResult)iFeedbackResult; - m_setModifications.reset(); + spRowReader->GetValue(_T("file_already_exists"), iFeedbackResult); + m_eFileAlreadyExists = (EFeedbackResult)iFeedbackResult; + spRowReader->GetValue(_T("not_enough_space"), iFeedbackResult); + m_eNotEnoughSpace = (EFeedbackResult)iFeedbackResult; + spRowReader->GetValue(_T("operation_finished"), iFeedbackResult); + m_eOperationFinished = (EFeedbackResult)iFeedbackResult; + spRowReader->GetValue(_T("operation_error"), iFeedbackResult); + m_eOperationError = (EFeedbackResult)iFeedbackResult; + + m_setModifications.reset(); + } } -} -void TFeedbackHandlerBase::RestoreDefaults() -{ - m_eFileError = EFeedbackResult::eResult_Unknown; - m_eFileAlreadyExists = EFeedbackResult::eResult_Unknown; - m_eNotEnoughSpace = EFeedbackResult::eResult_Unknown; - m_eOperationFinished = EFeedbackResult::eResult_Unknown; - m_eOperationError = EFeedbackResult::eResult_Unknown; -} + void TFeedbackHandlerBase::RestoreDefaults() + { + m_eFileError = EFeedbackResult::eResult_Unknown; + m_eFileAlreadyExists = EFeedbackResult::eResult_Unknown; + m_eNotEnoughSpace = EFeedbackResult::eResult_Unknown; + m_eOperationFinished = EFeedbackResult::eResult_Unknown; + m_eOperationError = EFeedbackResult::eResult_Unknown; + } -EFeedbackResult TFeedbackHandlerBase::FileError(const TString& /*strSrcPath*/, const TString& /*strDstPath*/, EFileError /*eFileError*/, unsigned long /*ulError*/) -{ - return m_eFileError; -} + EFeedbackResult TFeedbackHandlerBase::FileError(const TString& /*strSrcPath*/, const TString& /*strDstPath*/, EFileError /*eFileError*/, unsigned long /*ulError*/) + { + return m_eFileError; + } -EFeedbackResult TFeedbackHandlerBase::FileAlreadyExists(const TFileInfoPtr& /*spSrcFileInfo*/, const TFileInfoPtr& /*spDstFileInfo*/) -{ - return m_eFileAlreadyExists; -} + EFeedbackResult TFeedbackHandlerBase::FileAlreadyExists(const TFileInfoPtr& /*spSrcFileInfo*/, const TFileInfoPtr& /*spDstFileInfo*/) + { + return m_eFileAlreadyExists; + } -EFeedbackResult TFeedbackHandlerBase::NotEnoughSpace(const TString& /*strSrcPath*/, const TString& /*strDstPath*/, unsigned long long /*ullRequiredSize*/) -{ - return m_eNotEnoughSpace; -} + EFeedbackResult TFeedbackHandlerBase::NotEnoughSpace(const TString& /*strSrcPath*/, const TString& /*strDstPath*/, unsigned long long /*ullRequiredSize*/) + { + return m_eNotEnoughSpace; + } -EFeedbackResult TFeedbackHandlerBase::OperationFinished() -{ - return m_eOperationFinished; -} + EFeedbackResult TFeedbackHandlerBase::OperationFinished() + { + return m_eOperationFinished; + } -EFeedbackResult TFeedbackHandlerBase::OperationError() -{ - return m_eOperationError; + EFeedbackResult TFeedbackHandlerBase::OperationError() + { + return m_eOperationError; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TFeedbackHandlerBase.h =================================================================== diff -u -N -r2755e12daeccb1935f569e7235e685e566b0b098 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFeedbackHandlerBase.h (.../TFeedbackHandlerBase.h) (revision 2755e12daeccb1935f569e7235e685e566b0b098) +++ src/libchcore/TFeedbackHandlerBase.h (.../TFeedbackHandlerBase.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -27,70 +27,69 @@ #include #include "TSharedModificationTracker.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TFeedbackHandlerBase : public IFeedbackHandler +namespace chcore { -public: - TFeedbackHandlerBase(); - virtual ~TFeedbackHandlerBase(); + class LIBCHCORE_API TFeedbackHandlerBase : public IFeedbackHandler + { + public: + TFeedbackHandlerBase(); + virtual ~TFeedbackHandlerBase(); - virtual EFeedbackResult FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) override; - virtual EFeedbackResult FileAlreadyExists(const TFileInfoPtr& spSrcFileInfo, const TFileInfoPtr& spDstFileInfo) override; - virtual EFeedbackResult NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) override; + virtual EFeedbackResult FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) override; + virtual EFeedbackResult FileAlreadyExists(const TFileInfoPtr& spSrcFileInfo, const TFileInfoPtr& spDstFileInfo) override; + virtual EFeedbackResult NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) override; - virtual EFeedbackResult OperationFinished() override; - virtual EFeedbackResult OperationError() override; + virtual EFeedbackResult OperationFinished() override; + virtual EFeedbackResult OperationError() override; - // marking responses as permanent - void SetFileErrorPermanentResponse(EFeedbackResult ePermanentResult) { m_eFileError = ePermanentResult; } - EFeedbackResult GetFileErrorPermanentResponse() const { return m_eFileError; } + // marking responses as permanent + void SetFileErrorPermanentResponse(EFeedbackResult ePermanentResult) { m_eFileError = ePermanentResult; } + EFeedbackResult GetFileErrorPermanentResponse() const { return m_eFileError; } - void SetFileAlreadyExistsPermanentResponse(EFeedbackResult ePermanentResult) { m_eFileAlreadyExists = ePermanentResult; } - EFeedbackResult GetFileAlreadyExistsPermanentResponse() const { return m_eFileAlreadyExists; } + void SetFileAlreadyExistsPermanentResponse(EFeedbackResult ePermanentResult) { m_eFileAlreadyExists = ePermanentResult; } + EFeedbackResult GetFileAlreadyExistsPermanentResponse() const { return m_eFileAlreadyExists; } - void SetNotEnoughSpacePermanentResponse(EFeedbackResult ePermanentResult) { m_eNotEnoughSpace = ePermanentResult; } - EFeedbackResult GetNotEnoughSpacePermanentResponse() const { return m_eNotEnoughSpace; } + void SetNotEnoughSpacePermanentResponse(EFeedbackResult ePermanentResult) { m_eNotEnoughSpace = ePermanentResult; } + EFeedbackResult GetNotEnoughSpacePermanentResponse() const { return m_eNotEnoughSpace; } - // resets the permanent status from all responses - virtual void RestoreDefaults() override; + // resets the permanent status from all responses + virtual void RestoreDefaults() override; - // serialization - void Store(const ISerializerContainerPtr& spContainer) const; - static void InitColumns(const ISerializerContainerPtr& spContainer); - void Load(const ISerializerContainerPtr& spContainer); + // serialization + void Store(const ISerializerContainerPtr& spContainer) const; + static void InitColumns(const ISerializerContainerPtr& spContainer); + void Load(const ISerializerContainerPtr& spContainer); -private: - enum EModifications - { - eMod_Added = 0, - eMod_FileError, - eMod_FileAlreadyExists, - eMod_NotEnoughSpace, - eMod_OperationFinished, - eMod_OperationError, + private: + enum EModifications + { + eMod_Added = 0, + eMod_FileError, + eMod_FileAlreadyExists, + eMod_NotEnoughSpace, + eMod_OperationFinished, + eMod_OperationError, - // last item - eMod_Last - }; + // last item + eMod_Last + }; #pragma warning(push) #pragma warning(disable: 4251) - mutable boost::shared_mutex m_lock; + mutable boost::shared_mutex m_lock; - using Bitset = std::bitset; - mutable Bitset m_setModifications; + using Bitset = std::bitset; + mutable Bitset m_setModifications; - TSharedModificationTracker m_eFileError; - TSharedModificationTracker m_eFileAlreadyExists; - TSharedModificationTracker m_eNotEnoughSpace; - TSharedModificationTracker m_eOperationFinished; - TSharedModificationTracker m_eOperationError; + TSharedModificationTracker m_eFileError; + TSharedModificationTracker m_eFileAlreadyExists; + TSharedModificationTracker m_eNotEnoughSpace; + TSharedModificationTracker m_eOperationFinished; + TSharedModificationTracker m_eOperationError; #pragma warning(pop) -}; + }; -typedef boost::shared_ptr TFeedbackHandlerBasePtr; + typedef boost::shared_ptr TFeedbackHandlerBasePtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TFeedbackHandlerWrapper.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFeedbackHandlerWrapper.cpp (.../TFeedbackHandlerWrapper.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TFeedbackHandlerWrapper.cpp (.../TFeedbackHandlerWrapper.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -20,66 +20,65 @@ #include "TFeedbackHandlerWrapper.h" #include "TScopedRunningTimeTrackerPause.h" -BEGIN_CHCORE_NAMESPACE - -TFeedbackHandlerWrapper::TFeedbackHandlerWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, TScopedRunningTimeTracker& rTimeGuard) : - m_spFeedbackHandler(spFeedbackHandler), - m_rTimeGuard(rTimeGuard) +namespace chcore { -} + TFeedbackHandlerWrapper::TFeedbackHandlerWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, TScopedRunningTimeTracker& rTimeGuard) : + m_spFeedbackHandler(spFeedbackHandler), + m_rTimeGuard(rTimeGuard) + { + } -TFeedbackHandlerWrapper::~TFeedbackHandlerWrapper() -{ -} + TFeedbackHandlerWrapper::~TFeedbackHandlerWrapper() + { + } -EFeedbackResult TFeedbackHandlerWrapper::FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) -{ - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + EFeedbackResult TFeedbackHandlerWrapper::FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - return m_spFeedbackHandler->FileError(strSrcPath, strDstPath, eFileError, ulError); -} + return m_spFeedbackHandler->FileError(strSrcPath, strDstPath, eFileError, ulError); + } -EFeedbackResult TFeedbackHandlerWrapper::FileAlreadyExists(const TFileInfoPtr& spSrcFileInfo, const TFileInfoPtr& spDstFileInfo) -{ - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + EFeedbackResult TFeedbackHandlerWrapper::FileAlreadyExists(const TFileInfoPtr& spSrcFileInfo, const TFileInfoPtr& spDstFileInfo) + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - return m_spFeedbackHandler->FileAlreadyExists(spSrcFileInfo, spDstFileInfo); -} + return m_spFeedbackHandler->FileAlreadyExists(spSrcFileInfo, spDstFileInfo); + } -EFeedbackResult TFeedbackHandlerWrapper::NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) -{ - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + EFeedbackResult TFeedbackHandlerWrapper::NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - return m_spFeedbackHandler->NotEnoughSpace(strSrcPath, strDstPath, ullRequiredSize); -} + return m_spFeedbackHandler->NotEnoughSpace(strSrcPath, strDstPath, ullRequiredSize); + } -EFeedbackResult TFeedbackHandlerWrapper::OperationFinished() -{ - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + EFeedbackResult TFeedbackHandlerWrapper::OperationFinished() + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - return m_spFeedbackHandler->OperationFinished(); -} + return m_spFeedbackHandler->OperationFinished(); + } -EFeedbackResult TFeedbackHandlerWrapper::OperationError() -{ - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + EFeedbackResult TFeedbackHandlerWrapper::OperationError() + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - return m_spFeedbackHandler->OperationError(); -} + return m_spFeedbackHandler->OperationError(); + } -void TFeedbackHandlerWrapper::RestoreDefaults() -{ - return m_spFeedbackHandler->RestoreDefaults(); -} + void TFeedbackHandlerWrapper::RestoreDefaults() + { + return m_spFeedbackHandler->RestoreDefaults(); + } -void TFeedbackHandlerWrapper::Store(const ISerializerContainerPtr& spContainer) const -{ - return m_spFeedbackHandler->Store(spContainer); -} + void TFeedbackHandlerWrapper::Store(const ISerializerContainerPtr& spContainer) const + { + return m_spFeedbackHandler->Store(spContainer); + } -void TFeedbackHandlerWrapper::Load(const ISerializerContainerPtr& spContainer) -{ - return m_spFeedbackHandler->Load(spContainer); + void TFeedbackHandlerWrapper::Load(const ISerializerContainerPtr& spContainer) + { + return m_spFeedbackHandler->Load(spContainer); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TFeedbackHandlerWrapper.h =================================================================== diff -u -N -r671f4b1792a20d98b186f4e0a9cc6a620dede019 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFeedbackHandlerWrapper.h (.../TFeedbackHandlerWrapper.h) (revision 671f4b1792a20d98b186f4e0a9cc6a620dede019) +++ src/libchcore/TFeedbackHandlerWrapper.h (.../TFeedbackHandlerWrapper.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,37 +23,36 @@ #include "IFeedbackHandler.h" #include -BEGIN_CHCORE_NAMESPACE - -class TScopedRunningTimeTracker; - -class TFeedbackHandlerWrapper : public IFeedbackHandler +namespace chcore { -public: - TFeedbackHandlerWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, TScopedRunningTimeTracker& rTimeGuard); - virtual ~TFeedbackHandlerWrapper(); + class TScopedRunningTimeTracker; - TFeedbackHandlerWrapper(const TFeedbackHandlerWrapper&) = delete; - TFeedbackHandlerWrapper& operator=(const TFeedbackHandlerWrapper&) = delete; + class TFeedbackHandlerWrapper : public IFeedbackHandler + { + public: + TFeedbackHandlerWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, TScopedRunningTimeTracker& rTimeGuard); + virtual ~TFeedbackHandlerWrapper(); - virtual EFeedbackResult FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) override; - virtual EFeedbackResult FileAlreadyExists(const TFileInfoPtr& spSrcFileInfo, const TFileInfoPtr& spDstFileInfo) override; - virtual EFeedbackResult NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) override; - virtual EFeedbackResult OperationFinished() override; - virtual EFeedbackResult OperationError() override; + TFeedbackHandlerWrapper(const TFeedbackHandlerWrapper&) = delete; + TFeedbackHandlerWrapper& operator=(const TFeedbackHandlerWrapper&) = delete; - virtual void RestoreDefaults() override; + virtual EFeedbackResult FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) override; + virtual EFeedbackResult FileAlreadyExists(const TFileInfoPtr& spSrcFileInfo, const TFileInfoPtr& spDstFileInfo) override; + virtual EFeedbackResult NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) override; + virtual EFeedbackResult OperationFinished() override; + virtual EFeedbackResult OperationError() override; - virtual void Store(const ISerializerContainerPtr& spContainer) const override; - virtual void Load(const ISerializerContainerPtr& spContainer) override; + virtual void RestoreDefaults() override; -private: - IFeedbackHandlerPtr m_spFeedbackHandler; - TScopedRunningTimeTracker& m_rTimeGuard; -}; + virtual void Store(const ISerializerContainerPtr& spContainer) const override; + virtual void Load(const ISerializerContainerPtr& spContainer) override; -typedef boost::shared_ptr TFeedbackHandlerWrapperPtr; + private: + IFeedbackHandlerPtr m_spFeedbackHandler; + TScopedRunningTimeTracker& m_rTimeGuard; + }; -END_CHCORE_NAMESPACE + typedef boost::shared_ptr TFeedbackHandlerWrapperPtr; +} #endif Index: src/libchcore/TFileErrorFilter.h =================================================================== diff -u -N -rf7314a3065ebf529a998aa0f98072049d06d192f -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileErrorFilter.h (.../TFileErrorFilter.h) (revision f7314a3065ebf529a998aa0f98072049d06d192f) +++ src/libchcore/TFileErrorFilter.h (.../TFileErrorFilter.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,19 +24,18 @@ #include "TString.h" #include "EFileError.h" -BEGIN_CHCORE_NAMESPACE - -class TFileErrorFilter +namespace chcore { -public: - TFileErrorFilter(); + class TFileErrorFilter + { + public: + TFileErrorFilter(); - EFeedbackResult Match(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError); + EFeedbackResult Match(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError); -private: - TString m_strSrcPathMask; -}; + private: + TString m_strSrcPathMask; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TFileFilter.cpp =================================================================== diff -u -N -r2755e12daeccb1935f569e7235e685e566b0b098 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileFilter.cpp (.../TFileFilter.cpp) (revision 2755e12daeccb1935f569e7235e685e566b0b098) +++ src/libchcore/TFileFilter.cpp (.../TFileFilter.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,884 +21,881 @@ #include "TFileInfo.h" #include "TConfig.h" -BEGIN_CHCORE_NAMESPACE - -//////////////////////////////////////////////////////////////////////////// - -TFileFilter::TFileFilter() : - m_oidObjectID(0), - m_setModifications(), - m_bUseMask(m_setModifications, false), - m_astrMask(m_setModifications), - m_bUseExcludeMask(m_setModifications, false), - m_astrExcludeMask(m_setModifications), - m_bUseSize1(m_setModifications, false), - m_eSizeCmpType1(m_setModifications, eSizeCmp_Greater), - m_ullSize1(m_setModifications, 0), - m_bUseSize2(m_setModifications, false), - m_eSizeCmpType2(m_setModifications, eSizeCmp_Less), - m_ullSize2(m_setModifications, 0), - m_bUseDateTime1(m_setModifications, false), - m_eDateType(m_setModifications, eDateType_Created), - m_eDateCmpType1(m_setModifications, eDateCmp_Greater), - m_bUseDate1(m_setModifications, false), - m_bUseTime1(m_setModifications, false), - m_tDateTime1(m_setModifications), - m_bUseDateTime2(m_setModifications, false), - m_eDateCmpType2(m_setModifications, eDateCmp_Less), - m_bUseDate2(m_setModifications, false), - m_bUseTime2(m_setModifications, false), - m_tDateTime2(m_setModifications), - m_bUseAttributes(m_setModifications, false), - m_iArchive(m_setModifications, 2), - m_iReadOnly(m_setModifications, 2), - m_iHidden(m_setModifications, 2), - m_iSystem(m_setModifications, 2), - m_iDirectory(m_setModifications, 2) +namespace chcore { - m_setModifications[eMod_Added] = true; + TFileFilter::TFileFilter() : + m_oidObjectID(0), + m_setModifications(), + m_bUseMask(m_setModifications, false), + m_astrMask(m_setModifications), + m_bUseExcludeMask(m_setModifications, false), + m_astrExcludeMask(m_setModifications), + m_bUseSize1(m_setModifications, false), + m_eSizeCmpType1(m_setModifications, eSizeCmp_Greater), + m_ullSize1(m_setModifications, 0), + m_bUseSize2(m_setModifications, false), + m_eSizeCmpType2(m_setModifications, eSizeCmp_Less), + m_ullSize2(m_setModifications, 0), + m_bUseDateTime1(m_setModifications, false), + m_eDateType(m_setModifications, eDateType_Created), + m_eDateCmpType1(m_setModifications, eDateCmp_Greater), + m_bUseDate1(m_setModifications, false), + m_bUseTime1(m_setModifications, false), + m_tDateTime1(m_setModifications), + m_bUseDateTime2(m_setModifications, false), + m_eDateCmpType2(m_setModifications, eDateCmp_Less), + m_bUseDate2(m_setModifications, false), + m_bUseTime2(m_setModifications, false), + m_tDateTime2(m_setModifications), + m_bUseAttributes(m_setModifications, false), + m_iArchive(m_setModifications, 2), + m_iReadOnly(m_setModifications, 2), + m_iHidden(m_setModifications, 2), + m_iSystem(m_setModifications, 2), + m_iDirectory(m_setModifications, 2) + { + m_setModifications[eMod_Added] = true; - m_tDateTime1.Modify().SetCurrentDateTime(); - m_tDateTime2.Modify().SetCurrentDateTime(); -} + m_tDateTime1.Modify().SetCurrentDateTime(); + m_tDateTime2.Modify().SetCurrentDateTime(); + } -TFileFilter::TFileFilter(const TFileFilter& rFilter) : - m_oidObjectID(rFilter.m_oidObjectID), - m_setModifications(rFilter.m_setModifications), - m_bUseMask(rFilter.m_bUseMask, m_setModifications), - m_astrMask(rFilter.m_astrMask, m_setModifications), - m_bUseExcludeMask(rFilter.m_bUseExcludeMask, m_setModifications), - m_astrExcludeMask(rFilter.m_astrExcludeMask, m_setModifications), - m_bUseSize1(rFilter.m_bUseSize1, m_setModifications), - m_eSizeCmpType1(rFilter.m_eSizeCmpType1, m_setModifications), - m_ullSize1(rFilter.m_ullSize1, m_setModifications), - m_bUseSize2(rFilter.m_bUseSize2, m_setModifications), - m_eSizeCmpType2(rFilter.m_eSizeCmpType2, m_setModifications), - m_ullSize2(rFilter.m_ullSize2, m_setModifications), - m_bUseDateTime1(rFilter.m_bUseDateTime1, m_setModifications), - m_eDateType(rFilter.m_eDateType, m_setModifications), - m_eDateCmpType1(rFilter.m_eDateCmpType1, m_setModifications), - m_bUseDate1(rFilter.m_bUseDate1, m_setModifications), - m_bUseTime1(rFilter.m_bUseTime1, m_setModifications), - m_tDateTime1(rFilter.m_tDateTime1, m_setModifications), - m_bUseDateTime2(rFilter.m_bUseDateTime2, m_setModifications), - m_eDateCmpType2(rFilter.m_eDateCmpType2, m_setModifications), - m_bUseDate2(rFilter.m_bUseDate2, m_setModifications), - m_bUseTime2(rFilter.m_bUseTime2, m_setModifications), - m_tDateTime2(rFilter.m_tDateTime2, m_setModifications), - m_bUseAttributes(rFilter.m_bUseAttributes, m_setModifications), - m_iArchive(rFilter.m_iArchive, m_setModifications), - m_iReadOnly(rFilter.m_iReadOnly, m_setModifications), - m_iHidden(rFilter.m_iHidden, m_setModifications), - m_iSystem(rFilter.m_iSystem, m_setModifications), - m_iDirectory(rFilter.m_iDirectory, m_setModifications) -{ -} + TFileFilter::TFileFilter(const TFileFilter& rFilter) : + m_oidObjectID(rFilter.m_oidObjectID), + m_setModifications(rFilter.m_setModifications), + m_bUseMask(rFilter.m_bUseMask, m_setModifications), + m_astrMask(rFilter.m_astrMask, m_setModifications), + m_bUseExcludeMask(rFilter.m_bUseExcludeMask, m_setModifications), + m_astrExcludeMask(rFilter.m_astrExcludeMask, m_setModifications), + m_bUseSize1(rFilter.m_bUseSize1, m_setModifications), + m_eSizeCmpType1(rFilter.m_eSizeCmpType1, m_setModifications), + m_ullSize1(rFilter.m_ullSize1, m_setModifications), + m_bUseSize2(rFilter.m_bUseSize2, m_setModifications), + m_eSizeCmpType2(rFilter.m_eSizeCmpType2, m_setModifications), + m_ullSize2(rFilter.m_ullSize2, m_setModifications), + m_bUseDateTime1(rFilter.m_bUseDateTime1, m_setModifications), + m_eDateType(rFilter.m_eDateType, m_setModifications), + m_eDateCmpType1(rFilter.m_eDateCmpType1, m_setModifications), + m_bUseDate1(rFilter.m_bUseDate1, m_setModifications), + m_bUseTime1(rFilter.m_bUseTime1, m_setModifications), + m_tDateTime1(rFilter.m_tDateTime1, m_setModifications), + m_bUseDateTime2(rFilter.m_bUseDateTime2, m_setModifications), + m_eDateCmpType2(rFilter.m_eDateCmpType2, m_setModifications), + m_bUseDate2(rFilter.m_bUseDate2, m_setModifications), + m_bUseTime2(rFilter.m_bUseTime2, m_setModifications), + m_tDateTime2(rFilter.m_tDateTime2, m_setModifications), + m_bUseAttributes(rFilter.m_bUseAttributes, m_setModifications), + m_iArchive(rFilter.m_iArchive, m_setModifications), + m_iReadOnly(rFilter.m_iReadOnly, m_setModifications), + m_iHidden(rFilter.m_iHidden, m_setModifications), + m_iSystem(rFilter.m_iSystem, m_setModifications), + m_iDirectory(rFilter.m_iDirectory, m_setModifications) + { + } -TFileFilter& TFileFilter::operator=(const TFileFilter& rFilter) -{ - if(this == &rFilter) - return *this; + TFileFilter& TFileFilter::operator=(const TFileFilter& rFilter) + { + if (this == &rFilter) + return *this; - m_oidObjectID = rFilter.m_oidObjectID; - m_setModifications = rFilter.m_setModifications; + m_oidObjectID = rFilter.m_oidObjectID; + m_setModifications = rFilter.m_setModifications; - // files mask - m_bUseMask = rFilter.m_bUseMask; - m_astrMask = rFilter.m_astrMask; + // files mask + m_bUseMask = rFilter.m_bUseMask; + m_astrMask = rFilter.m_astrMask; - m_bUseExcludeMask=rFilter.m_bUseExcludeMask; - m_astrExcludeMask = rFilter.m_astrExcludeMask; + m_bUseExcludeMask = rFilter.m_bUseExcludeMask; + m_astrExcludeMask = rFilter.m_astrExcludeMask; - // size filtering - m_bUseSize1=rFilter.m_bUseSize1; - m_eSizeCmpType1=rFilter.m_eSizeCmpType1; - m_ullSize1=rFilter.m_ullSize1; - m_bUseSize2=rFilter.m_bUseSize2; - m_eSizeCmpType2=rFilter.m_eSizeCmpType2; - m_ullSize2=rFilter.m_ullSize2; + // size filtering + m_bUseSize1 = rFilter.m_bUseSize1; + m_eSizeCmpType1 = rFilter.m_eSizeCmpType1; + m_ullSize1 = rFilter.m_ullSize1; + m_bUseSize2 = rFilter.m_bUseSize2; + m_eSizeCmpType2 = rFilter.m_eSizeCmpType2; + m_ullSize2 = rFilter.m_ullSize2; - // date filtering - m_bUseDateTime1=rFilter.m_bUseDateTime1; - m_eDateType=rFilter.m_eDateType; - m_eDateCmpType1=rFilter.m_eDateCmpType1; - m_bUseDate1=rFilter.m_bUseDate1; - m_bUseTime1=rFilter.m_bUseTime1; - m_tDateTime1 = rFilter.m_tDateTime1; + // date filtering + m_bUseDateTime1 = rFilter.m_bUseDateTime1; + m_eDateType = rFilter.m_eDateType; + m_eDateCmpType1 = rFilter.m_eDateCmpType1; + m_bUseDate1 = rFilter.m_bUseDate1; + m_bUseTime1 = rFilter.m_bUseTime1; + m_tDateTime1 = rFilter.m_tDateTime1; - m_bUseDateTime2=rFilter.m_bUseDateTime2; - m_eDateCmpType2=rFilter.m_eDateCmpType2; - m_bUseDate2=rFilter.m_bUseDate2; - m_bUseTime2=rFilter.m_bUseTime2; - m_tDateTime2 = rFilter.m_tDateTime2; + m_bUseDateTime2 = rFilter.m_bUseDateTime2; + m_eDateCmpType2 = rFilter.m_eDateCmpType2; + m_bUseDate2 = rFilter.m_bUseDate2; + m_bUseTime2 = rFilter.m_bUseTime2; + m_tDateTime2 = rFilter.m_tDateTime2; - // attribute filtering - m_bUseAttributes=rFilter.m_bUseAttributes; - m_iArchive=rFilter.m_iArchive; - m_iReadOnly=rFilter.m_iReadOnly; - m_iHidden=rFilter.m_iHidden; - m_iSystem=rFilter.m_iSystem; - m_iDirectory=rFilter.m_iDirectory; + // attribute filtering + m_bUseAttributes = rFilter.m_bUseAttributes; + m_iArchive = rFilter.m_iArchive; + m_iReadOnly = rFilter.m_iReadOnly; + m_iHidden = rFilter.m_iHidden; + m_iSystem = rFilter.m_iSystem; + m_iDirectory = rFilter.m_iDirectory; - return *this; -} + return *this; + } -TString TFileFilter::GetCombinedMask() const -{ - TString strMask; - size_t stCount = m_astrMask.Get().GetCount(); - if(stCount > 0) + TString TFileFilter::GetCombinedMask() const { - strMask = m_astrMask.Get().GetAt(0).ToSerializedString(); - for(size_t stIndex = 1; stIndex < stCount; stIndex++) + TString strMask; + size_t stCount = m_astrMask.Get().GetCount(); + if (stCount > 0) { - strMask += _T("|") + m_astrMask.Get().GetAt(stIndex).ToSerializedString(); + strMask = m_astrMask.Get().GetAt(0).ToSerializedString(); + for (size_t stIndex = 1; stIndex < stCount; stIndex++) + { + strMask += _T("|") + m_astrMask.Get().GetAt(stIndex).ToSerializedString(); + } } + + return strMask; } - return strMask; -} + void TFileFilter::SetCombinedMask(const TString& strMask) + { + TStringArray arrMasks; + strMask.Split(_T("|"), arrMasks); -void TFileFilter::SetCombinedMask(const TString& strMask) -{ - TStringArray arrMasks; - strMask.Split(_T("|"), arrMasks); + TStringPatternArray& rPatterns = m_astrMask.Modify(); + rPatterns.Clear(); + for (size_t stIndex = 0; stIndex < arrMasks.GetCount(); ++stIndex) + { + rPatterns.Add(TStringPattern::CreateFromSerializedString(arrMasks.GetAt(stIndex))); + } + } - TStringPatternArray& rPatterns = m_astrMask.Modify(); - rPatterns.Clear(); - for (size_t stIndex = 0; stIndex < arrMasks.GetCount(); ++stIndex) + TString TFileFilter::GetCombinedExcludeMask() const { - rPatterns.Add(TStringPattern::CreateFromSerializedString(arrMasks.GetAt(stIndex))); + TString strMask; + size_t stCount = m_astrExcludeMask.Get().GetCount(); + if (stCount > 0) + { + strMask = m_astrExcludeMask.Get().GetAt(0).ToSerializedString(); + for (size_t stIndex = 1; stIndex < stCount; stIndex++) + { + strMask += _T("|") + m_astrExcludeMask.Get().GetAt(stIndex).ToSerializedString(); + } + } + + return strMask; } -} -TString TFileFilter::GetCombinedExcludeMask() const -{ - TString strMask; - size_t stCount = m_astrExcludeMask.Get().GetCount(); - if(stCount > 0) + void TFileFilter::SetCombinedExcludeMask(const TString& strMask) { - strMask = m_astrExcludeMask.Get().GetAt(0).ToSerializedString(); - for(size_t stIndex = 1; stIndex < stCount; stIndex++) + TStringArray arrMasks; + strMask.Split(_T("|"), arrMasks); + + TStringPatternArray& rPatterns = m_astrExcludeMask.Modify(); + rPatterns.Clear(); + for (size_t stIndex = 0; stIndex < arrMasks.GetCount(); ++stIndex) { - strMask += _T("|") + m_astrExcludeMask.Get().GetAt(stIndex).ToSerializedString(); + rPatterns.Add(TStringPattern::CreateFromSerializedString(arrMasks.GetAt(stIndex))); } } - return strMask; -} - -void TFileFilter::SetCombinedExcludeMask(const TString& strMask) -{ - TStringArray arrMasks; - strMask.Split(_T("|"), arrMasks); - - TStringPatternArray& rPatterns = m_astrExcludeMask.Modify(); - rPatterns.Clear(); - for (size_t stIndex = 0; stIndex < arrMasks.GetCount(); ++stIndex) + void TFileFilter::StoreInConfig(TConfig& rConfig) const { - rPatterns.Add(TStringPattern::CreateFromSerializedString(arrMasks.GetAt(stIndex))); - } -} + SetConfigValue(rConfig, _T("IncludeMask.Use"), m_bUseMask.Get()); + SetConfigValue(rConfig, _T("IncludeMask.MaskList.Mask"), m_astrMask.Get().ToStringArray()); -void TFileFilter::StoreInConfig(TConfig& rConfig) const -{ - SetConfigValue(rConfig, _T("IncludeMask.Use"), m_bUseMask.Get()); - SetConfigValue(rConfig, _T("IncludeMask.MaskList.Mask"), m_astrMask.Get().ToStringArray()); + SetConfigValue(rConfig, _T("ExcludeMask.Use"), m_bUseExcludeMask.Get()); + SetConfigValue(rConfig, _T("ExcludeMask.MaskList.Mask"), m_astrExcludeMask.Get().ToStringArray()); - SetConfigValue(rConfig, _T("ExcludeMask.Use"), m_bUseExcludeMask.Get()); - SetConfigValue(rConfig, _T("ExcludeMask.MaskList.Mask"), m_astrExcludeMask.Get().ToStringArray()); + SetConfigValue(rConfig, _T("SizeA.Use"), m_bUseSize1.Get()); + SetConfigValue(rConfig, _T("SizeA.FilteringType"), m_eSizeCmpType1.Get()); + SetConfigValue(rConfig, _T("SizeA.Value"), m_ullSize1.Get()); + SetConfigValue(rConfig, _T("SizeB.Use"), m_bUseSize2.Get()); + SetConfigValue(rConfig, _T("SizeB.FilteringType"), m_eSizeCmpType2.Get()); + SetConfigValue(rConfig, _T("SizeB.Value"), m_ullSize2.Get()); - SetConfigValue(rConfig, _T("SizeA.Use"), m_bUseSize1.Get()); - SetConfigValue(rConfig, _T("SizeA.FilteringType"), m_eSizeCmpType1.Get()); - SetConfigValue(rConfig, _T("SizeA.Value"), m_ullSize1.Get()); - SetConfigValue(rConfig, _T("SizeB.Use"), m_bUseSize2.Get()); - SetConfigValue(rConfig, _T("SizeB.FilteringType"), m_eSizeCmpType2.Get()); - SetConfigValue(rConfig, _T("SizeB.Value"), m_ullSize2.Get()); + SetConfigValue(rConfig, _T("DateA.Use"), m_bUseDateTime1.Get()); + SetConfigValue(rConfig, _T("DateA.Type"), m_eDateType.Get()); // created/last modified/last accessed + SetConfigValue(rConfig, _T("DateA.FilteringType"), m_eDateCmpType1.Get()); // before/after + SetConfigValue(rConfig, _T("DateA.EnableDatePart"), m_bUseDate1.Get()); + SetConfigValue(rConfig, _T("DateA.EnableTimePart"), m_bUseTime1.Get()); + SetConfigValue(rConfig, _T("DateA.DateTimeValue"), m_tDateTime1.Get()); - SetConfigValue(rConfig, _T("DateA.Use"), m_bUseDateTime1.Get()); - SetConfigValue(rConfig, _T("DateA.Type"), m_eDateType.Get()); // created/last modified/last accessed - SetConfigValue(rConfig, _T("DateA.FilteringType"), m_eDateCmpType1.Get()); // before/after - SetConfigValue(rConfig, _T("DateA.EnableDatePart"), m_bUseDate1.Get()); - SetConfigValue(rConfig, _T("DateA.EnableTimePart"), m_bUseTime1.Get()); - SetConfigValue(rConfig, _T("DateA.DateTimeValue"), m_tDateTime1.Get()); + SetConfigValue(rConfig, _T("DateB.Type"), m_bUseDateTime2.Get()); + SetConfigValue(rConfig, _T("DateB.FilteringType"), m_eDateCmpType2.Get()); + SetConfigValue(rConfig, _T("DateB.EnableDatePart"), m_bUseDate2.Get()); + SetConfigValue(rConfig, _T("DateB.EnableTimePart"), m_bUseTime2.Get()); + SetConfigValue(rConfig, _T("DateB.DateTimeValue"), m_tDateTime2.Get()); - SetConfigValue(rConfig, _T("DateB.Type"), m_bUseDateTime2.Get()); - SetConfigValue(rConfig, _T("DateB.FilteringType"), m_eDateCmpType2.Get()); - SetConfigValue(rConfig, _T("DateB.EnableDatePart"), m_bUseDate2.Get()); - SetConfigValue(rConfig, _T("DateB.EnableTimePart"), m_bUseTime2.Get()); - SetConfigValue(rConfig, _T("DateB.DateTimeValue"), m_tDateTime2.Get()); + SetConfigValue(rConfig, _T("Attributes.Use"), m_bUseAttributes.Get()); + SetConfigValue(rConfig, _T("Attributes.Archive"), m_iArchive.Get()); + SetConfigValue(rConfig, _T("Attributes.ReadOnly"), m_iReadOnly.Get()); + SetConfigValue(rConfig, _T("Attributes.Hidden"), m_iHidden.Get()); + SetConfigValue(rConfig, _T("Attributes.System"), m_iSystem.Get()); + SetConfigValue(rConfig, _T("Attributes.Directory"), m_iDirectory.Get()); + } - SetConfigValue(rConfig, _T("Attributes.Use"), m_bUseAttributes.Get()); - SetConfigValue(rConfig, _T("Attributes.Archive"), m_iArchive.Get()); - SetConfigValue(rConfig, _T("Attributes.ReadOnly"), m_iReadOnly.Get()); - SetConfigValue(rConfig, _T("Attributes.Hidden"), m_iHidden.Get()); - SetConfigValue(rConfig, _T("Attributes.System"), m_iSystem.Get()); - SetConfigValue(rConfig, _T("Attributes.Directory"), m_iDirectory.Get()); -} + void TFileFilter::ReadFromConfig(const TConfig& rConfig) + { + if (!GetConfigValue(rConfig, _T("IncludeMask.Use"), m_bUseMask.Modify())) + m_bUseMask = false; -void TFileFilter::ReadFromConfig(const TConfig& rConfig) -{ - if(!GetConfigValue(rConfig, _T("IncludeMask.Use"), m_bUseMask.Modify())) - m_bUseMask = false; + TStringArray arrMask; + m_astrMask.Modify().Clear(); + GetConfigValue(rConfig, _T("IncludeMask.MaskList.Mask"), arrMask); + m_astrMask.Modify().FromStringArray(arrMask); - TStringArray arrMask; - m_astrMask.Modify().Clear(); - GetConfigValue(rConfig, _T("IncludeMask.MaskList.Mask"), arrMask); - m_astrMask.Modify().FromStringArray(arrMask); + if (!GetConfigValue(rConfig, _T("ExcludeMask.Use"), m_bUseExcludeMask.Modify())) + m_bUseExcludeMask = false; - if(!GetConfigValue(rConfig, _T("ExcludeMask.Use"), m_bUseExcludeMask.Modify())) - m_bUseExcludeMask = false; + m_astrExcludeMask.Modify().Clear(); + GetConfigValue(rConfig, _T("ExcludeMask.MaskList.Mask"), arrMask); + m_astrExcludeMask.Modify().FromStringArray(arrMask); - m_astrExcludeMask.Modify().Clear(); - GetConfigValue(rConfig, _T("ExcludeMask.MaskList.Mask"), arrMask); - m_astrExcludeMask.Modify().FromStringArray(arrMask); + if (!GetConfigValue(rConfig, _T("SizeA.Use"), m_bUseSize1.Modify())) + m_bUseSize1 = false; + if (!GetConfigValue(rConfig, _T("SizeA.FilteringType"), *(int*)m_eSizeCmpType1.Modify())) + m_eSizeCmpType1 = eSizeCmp_Equal; + if (!GetConfigValue(rConfig, _T("SizeA.Value"), m_ullSize1.Modify())) + m_ullSize1 = 0; + if (!GetConfigValue(rConfig, _T("SizeB.Use"), m_bUseSize2.Modify())) + m_bUseSize2 = false; + if (!GetConfigValue(rConfig, _T("SizeB.FilteringType"), *(int*)m_eSizeCmpType2.Modify())) + m_eSizeCmpType2 = eSizeCmp_Equal; + if (!GetConfigValue(rConfig, _T("SizeB.Value"), m_ullSize2.Modify())) + m_ullSize2 = 0; - if(!GetConfigValue(rConfig, _T("SizeA.Use"), m_bUseSize1.Modify())) - m_bUseSize1 = false; - if(!GetConfigValue(rConfig, _T("SizeA.FilteringType"), *(int*)m_eSizeCmpType1.Modify())) - m_eSizeCmpType1 = eSizeCmp_Equal; - if(!GetConfigValue(rConfig, _T("SizeA.Value"), m_ullSize1.Modify())) - m_ullSize1 = 0; - if(!GetConfigValue(rConfig, _T("SizeB.Use"), m_bUseSize2.Modify())) - m_bUseSize2 = false; - if(!GetConfigValue(rConfig, _T("SizeB.FilteringType"), *(int*)m_eSizeCmpType2.Modify())) - m_eSizeCmpType2 = eSizeCmp_Equal; - if(!GetConfigValue(rConfig, _T("SizeB.Value"), m_ullSize2.Modify())) - m_ullSize2 = 0; + if (!GetConfigValue(rConfig, _T("DateA.Use"), m_bUseDateTime1.Modify())) + m_bUseDateTime1 = false; - if(!GetConfigValue(rConfig, _T("DateA.Use"), m_bUseDateTime1.Modify())) - m_bUseDateTime1 = false; + if (!GetConfigValue(rConfig, _T("DateA.Type"), *(int*)m_eDateType.Modify())) // created/last modified/last accessed + m_eDateType = eDateType_Created; + if (!GetConfigValue(rConfig, _T("DateA.FilteringType"), *(int*)m_eDateCmpType1.Modify())) // before/after + m_eDateCmpType1 = eDateCmp_Equal; + if (!GetConfigValue(rConfig, _T("DateA.EnableDatePart"), m_bUseDate1.Modify())) + m_bUseDate1 = false; + if (!GetConfigValue(rConfig, _T("DateA.EnableTimePart"), m_bUseTime1.Modify())) + m_bUseTime1 = false; - if(!GetConfigValue(rConfig, _T("DateA.Type"), *(int*)m_eDateType.Modify())) // created/last modified/last accessed - m_eDateType = eDateType_Created; - if(!GetConfigValue(rConfig, _T("DateA.FilteringType"), *(int*)m_eDateCmpType1.Modify())) // before/after - m_eDateCmpType1 = eDateCmp_Equal; - if(!GetConfigValue(rConfig, _T("DateA.EnableDatePart"), m_bUseDate1.Modify())) - m_bUseDate1 = false; - if(!GetConfigValue(rConfig, _T("DateA.EnableTimePart"), m_bUseTime1.Modify())) - m_bUseTime1 = false; + if (!GetConfigValue(rConfig, _T("DateA.DateTimeValue"), m_tDateTime1.Modify())) + m_tDateTime1.Modify().Clear(); - if(!GetConfigValue(rConfig, _T("DateA.DateTimeValue"), m_tDateTime1.Modify())) - m_tDateTime1.Modify().Clear(); + if (!GetConfigValue(rConfig, _T("DateB.Type"), m_bUseDateTime2.Modify())) + m_bUseDateTime2 = false; + if (!GetConfigValue(rConfig, _T("DateB.FilteringType"), *(int*)m_eDateCmpType2.Modify())) + m_eDateCmpType2 = eDateCmp_Equal; + if (!GetConfigValue(rConfig, _T("DateB.EnableDatePart"), m_bUseDate2.Modify())) + m_bUseDate2 = false; - if(!GetConfigValue(rConfig, _T("DateB.Type"), m_bUseDateTime2.Modify())) - m_bUseDateTime2 = false; - if(!GetConfigValue(rConfig, _T("DateB.FilteringType"), *(int*)m_eDateCmpType2.Modify())) - m_eDateCmpType2 = eDateCmp_Equal; - if(!GetConfigValue(rConfig, _T("DateB.EnableDatePart"), m_bUseDate2.Modify())) - m_bUseDate2 = false; + if (!GetConfigValue(rConfig, _T("DateB.DateTimeValue"), m_tDateTime2.Modify())) + m_tDateTime2.Modify().Clear(); + if (!GetConfigValue(rConfig, _T("DateB.EnableTimePart"), m_bUseTime2.Modify())) + m_bUseTime2 = false; - if(!GetConfigValue(rConfig, _T("DateB.DateTimeValue"), m_tDateTime2.Modify())) - m_tDateTime2.Modify().Clear(); - if(!GetConfigValue(rConfig, _T("DateB.EnableTimePart"), m_bUseTime2.Modify())) - m_bUseTime2 = false; - - if(!GetConfigValue(rConfig, _T("Attributes.Use"), m_bUseAttributes.Modify())) - m_bUseAttributes = false; - if(!GetConfigValue(rConfig, _T("Attributes.Archive"), m_iArchive.Modify())) - m_iArchive = 0; - if(!GetConfigValue(rConfig, _T("Attributes.ReadOnly"), m_iReadOnly.Modify())) - m_iReadOnly = 0; - if(!GetConfigValue(rConfig, _T("Attributes.Hidden"), m_iHidden.Modify())) - m_iHidden = 0; - if(!GetConfigValue(rConfig, _T("Attributes.System"), m_iSystem.Modify())) - m_iSystem = 0; - if(!GetConfigValue(rConfig, _T("Attributes.Directory"), m_iDirectory.Modify())) - m_iDirectory = 0; -} - -bool TFileFilter::Match(const TFileInfoPtr& spInfo) const -{ - // check by mask - if(m_bUseMask) - { - if (!m_astrMask.Get().MatchesAny(spInfo->GetFullFilePath().GetFileName().ToString())) - return false; + if (!GetConfigValue(rConfig, _T("Attributes.Use"), m_bUseAttributes.Modify())) + m_bUseAttributes = false; + if (!GetConfigValue(rConfig, _T("Attributes.Archive"), m_iArchive.Modify())) + m_iArchive = 0; + if (!GetConfigValue(rConfig, _T("Attributes.ReadOnly"), m_iReadOnly.Modify())) + m_iReadOnly = 0; + if (!GetConfigValue(rConfig, _T("Attributes.Hidden"), m_iHidden.Modify())) + m_iHidden = 0; + if (!GetConfigValue(rConfig, _T("Attributes.System"), m_iSystem.Modify())) + m_iSystem = 0; + if (!GetConfigValue(rConfig, _T("Attributes.Directory"), m_iDirectory.Modify())) + m_iDirectory = 0; } - // excluding mask - if(m_bUseExcludeMask) + bool TFileFilter::Match(const TFileInfoPtr& spInfo) const { - if (m_astrExcludeMask.Get().MatchesAny(spInfo->GetFullFilePath().GetFileName().ToString())) - return false; - } + // check by mask + if (m_bUseMask) + { + if (!m_astrMask.Get().MatchesAny(spInfo->GetFullFilePath().GetFileName().ToString())) + return false; + } - // by size - if (m_bUseSize1) - { - switch (m_eSizeCmpType1) + // excluding mask + if (m_bUseExcludeMask) { - case eSizeCmp_Less: - if (m_ullSize1 <= spInfo->GetLength64()) + if (m_astrExcludeMask.Get().MatchesAny(spInfo->GetFullFilePath().GetFileName().ToString())) return false; - break; - case eSizeCmp_LessOrEqual: - if (m_ullSize1 < spInfo->GetLength64()) - return false; - break; - case eSizeCmp_Equal: - if (m_ullSize1 != spInfo->GetLength64()) - return false; - break; - case eSizeCmp_GreaterOrEqual: - if (m_ullSize1 > spInfo->GetLength64()) - return false; - break; - case eSizeCmp_Greater: - if (m_ullSize1 >= spInfo->GetLength64()) - return false; - break; } - // second part - if (m_bUseSize2) + // by size + if (m_bUseSize1) { - switch (m_eSizeCmpType2) + switch (m_eSizeCmpType1) { case eSizeCmp_Less: - if (m_ullSize2 <= spInfo->GetLength64()) + if (m_ullSize1 <= spInfo->GetLength64()) return false; break; case eSizeCmp_LessOrEqual: - if (m_ullSize2 < spInfo->GetLength64()) + if (m_ullSize1 < spInfo->GetLength64()) return false; break; case eSizeCmp_Equal: - if (m_ullSize2 != spInfo->GetLength64()) + if (m_ullSize1 != spInfo->GetLength64()) return false; break; case eSizeCmp_GreaterOrEqual: - if (m_ullSize2 > spInfo->GetLength64()) + if (m_ullSize1 > spInfo->GetLength64()) return false; break; case eSizeCmp_Greater: - if (m_ullSize2 >= spInfo->GetLength64()) + if (m_ullSize1 >= spInfo->GetLength64()) return false; break; } - } - } - // date - get the time from rInfo - if (m_bUseDateTime1) - { - TDateTime tDateTime; - switch(m_eDateType) - { - case eDateType_Created: - tDateTime = spInfo->GetCreationTime().GetAsFiletime(); - break; - case eDateType_Modified: - tDateTime = spInfo->GetLastWriteTime().GetAsFiletime(); - break; - case eDateType_LastAccessed: - tDateTime = spInfo->GetLastAccessTime().GetAsFiletime(); - break; + // second part + if (m_bUseSize2) + { + switch (m_eSizeCmpType2) + { + case eSizeCmp_Less: + if (m_ullSize2 <= spInfo->GetLength64()) + return false; + break; + case eSizeCmp_LessOrEqual: + if (m_ullSize2 < spInfo->GetLength64()) + return false; + break; + case eSizeCmp_Equal: + if (m_ullSize2 != spInfo->GetLength64()) + return false; + break; + case eSizeCmp_GreaterOrEqual: + if (m_ullSize2 > spInfo->GetLength64()) + return false; + break; + case eSizeCmp_Greater: + if (m_ullSize2 >= spInfo->GetLength64()) + return false; + break; + } + } } - // counting... - time_t tDiff = m_tDateTime1.Get().Compare(tDateTime, m_bUseDate1, m_bUseTime1); - - // ... and comparing - switch(m_eDateCmpType1) + // date - get the time from rInfo + if (m_bUseDateTime1) { - case eDateCmp_Less: - if(tDiff >= 0) - return false; - break; - case eDateCmp_LessOrEqual: - if(tDiff > 0) - return false; - break; - case eDateCmp_Equal: - if(tDiff != 0) - return false; - break; - case eDateCmp_GreaterOrEqual: - if(tDiff < 0) - return false; - break; - case eDateCmp_Greater: - if(tDiff <= 0) - return false; - break; - } + TDateTime tDateTime; + switch (m_eDateType) + { + case eDateType_Created: + tDateTime = spInfo->GetCreationTime().GetAsFiletime(); + break; + case eDateType_Modified: + tDateTime = spInfo->GetLastWriteTime().GetAsFiletime(); + break; + case eDateType_LastAccessed: + tDateTime = spInfo->GetLastAccessTime().GetAsFiletime(); + break; + } - if (m_bUseDateTime2) - { // counting... - tDiff = m_tDateTime2.Get().Compare(tDateTime, m_bUseDate2, m_bUseTime2); + time_t tDiff = m_tDateTime1.Get().Compare(tDateTime, m_bUseDate1, m_bUseTime1); - // ... comparing - switch (m_eDateCmpType2) + // ... and comparing + switch (m_eDateCmpType1) { case eDateCmp_Less: - if(tDiff >= 0) + if (tDiff >= 0) return false; break; case eDateCmp_LessOrEqual: - if(tDiff > 0) + if (tDiff > 0) return false; break; case eDateCmp_Equal: - if(tDiff != 0) + if (tDiff != 0) return false; break; case eDateCmp_GreaterOrEqual: - if(tDiff < 0) + if (tDiff < 0) return false; break; case eDateCmp_Greater: - if(tDiff <= 0) + if (tDiff <= 0) return false; break; } + + if (m_bUseDateTime2) + { + // counting... + tDiff = m_tDateTime2.Get().Compare(tDateTime, m_bUseDate2, m_bUseTime2); + + // ... comparing + switch (m_eDateCmpType2) + { + case eDateCmp_Less: + if (tDiff >= 0) + return false; + break; + case eDateCmp_LessOrEqual: + if (tDiff > 0) + return false; + break; + case eDateCmp_Equal: + if (tDiff != 0) + return false; + break; + case eDateCmp_GreaterOrEqual: + if (tDiff < 0) + return false; + break; + case eDateCmp_Greater: + if (tDiff <= 0) + return false; + break; + } + } + } // of m_bUseDate + + // attributes + if (m_bUseAttributes) + { + if ((m_iArchive == 1 && !spInfo->IsArchived()) || (m_iArchive == 0 && spInfo->IsArchived())) + return false; + if ((m_iReadOnly == 1 && !spInfo->IsReadOnly()) || (m_iReadOnly == 0 && spInfo->IsReadOnly())) + return false; + if ((m_iHidden == 1 && !spInfo->IsHidden()) || (m_iHidden == 0 && spInfo->IsHidden())) + return false; + if ((m_iSystem == 1 && !spInfo->IsSystem()) || (m_iSystem == 0 && spInfo->IsSystem())) + return false; + if ((m_iDirectory == 1 && !spInfo->IsDirectory()) || (m_iDirectory == 0 && spInfo->IsDirectory())) + return false; } - } // of m_bUseDate - // attributes - if (m_bUseAttributes) + return true; + } + + void TFileFilter::InitColumns(IColumnsDefinition& rColumns) { - if ( (m_iArchive == 1 && !spInfo->IsArchived()) || (m_iArchive == 0 && spInfo->IsArchived())) - return false; - if ( (m_iReadOnly == 1 && !spInfo->IsReadOnly()) || (m_iReadOnly == 0 && spInfo->IsReadOnly())) - return false; - if ( (m_iHidden == 1 && !spInfo->IsHidden()) || (m_iHidden == 0 && spInfo->IsHidden())) - return false; - if ( (m_iSystem == 1 && !spInfo->IsSystem()) || (m_iSystem == 0 && spInfo->IsSystem())) - return false; - if ( (m_iDirectory == 1 && !spInfo->IsDirectory()) || (m_iDirectory == 0 && spInfo->IsDirectory())) - return false; + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("use_mask"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("mask"), IColumnsDefinition::eType_string); + rColumns.AddColumn(_T("use_exclude_mask"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("exclude_mask"), IColumnsDefinition::eType_string); + rColumns.AddColumn(_T("use_size_1"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("compare_type_1"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("size_1"), IColumnsDefinition::eType_ulonglong); + rColumns.AddColumn(_T("use_size_2"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("compare_type_2"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("size_2"), IColumnsDefinition::eType_ulonglong); + rColumns.AddColumn(_T("date_type"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("use_date_time_1"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("date_compare_type_1"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("use_date_1"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("use_time_1"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("datetime_1"), IColumnsDefinition::eType_ulonglong); + rColumns.AddColumn(_T("use_date_time_2"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("date_compare_type_2"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("use_date_2"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("use_time_2"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("datetime_2"), IColumnsDefinition::eType_ulonglong); + rColumns.AddColumn(_T("use_attributes"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("attr_archive"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("attr_ro"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("attr_hidden"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("attr_system"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("attr_directory"), IColumnsDefinition::eType_int); } - return true; -} + void TFileFilter::Store(const ISerializerContainerPtr& spContainer) const + { + bool bAdded = m_setModifications[eMod_Added]; + if (m_setModifications.any()) + { + ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); -void TFileFilter::InitColumns(IColumnsDefinition& rColumns) -{ - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("use_mask"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("mask"), IColumnsDefinition::eType_string); - rColumns.AddColumn(_T("use_exclude_mask"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("exclude_mask"), IColumnsDefinition::eType_string); - rColumns.AddColumn(_T("use_size_1"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("compare_type_1"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("size_1"), IColumnsDefinition::eType_ulonglong); - rColumns.AddColumn(_T("use_size_2"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("compare_type_2"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("size_2"), IColumnsDefinition::eType_ulonglong); - rColumns.AddColumn(_T("date_type"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("use_date_time_1"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("date_compare_type_1"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("use_date_1"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("use_time_1"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("datetime_1"), IColumnsDefinition::eType_ulonglong); - rColumns.AddColumn(_T("use_date_time_2"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("date_compare_type_2"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("use_date_2"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("use_time_2"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("datetime_2"), IColumnsDefinition::eType_ulonglong); - rColumns.AddColumn(_T("use_attributes"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("attr_archive"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("attr_ro"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("attr_hidden"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("attr_system"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("attr_directory"), IColumnsDefinition::eType_int); -} + if (bAdded || m_setModifications[eMod_UseMask]) + rRow.SetValue(_T("use_mask"), m_bUseMask); + if (bAdded || m_setModifications[eMod_Mask]) + rRow.SetValue(_T("mask"), GetCombinedMask()); + if (bAdded || m_setModifications[eMod_UseExcludeMask]) + rRow.SetValue(_T("use_exclude_mask"), m_bUseExcludeMask); + if (bAdded || m_setModifications[eMod_ExcludeMask]) + rRow.SetValue(_T("exclude_mask"), GetCombinedExcludeMask()); + if (bAdded || m_setModifications[eMod_UseSize1]) + rRow.SetValue(_T("use_size_1"), m_bUseSize1); + if (bAdded || m_setModifications[eMod_SizeCmpType1]) + rRow.SetValue(_T("compare_type_1"), m_eSizeCmpType1); + if (bAdded || m_setModifications[eMod_Size1]) + rRow.SetValue(_T("size_1"), m_ullSize1); + if (bAdded || m_setModifications[eMod_UseSize2]) + rRow.SetValue(_T("use_size_2"), m_bUseSize2); + if (bAdded || m_setModifications[eMod_SizeCmpType2]) + rRow.SetValue(_T("compare_type_2"), m_eSizeCmpType2); + if (bAdded || m_setModifications[eMod_Size2]) + rRow.SetValue(_T("size_2"), m_ullSize2); + if (bAdded || m_setModifications[eMod_DateType]) + rRow.SetValue(_T("date_type"), m_eDateType); + if (bAdded || m_setModifications[eMod_UseDateTime1]) + rRow.SetValue(_T("use_date_time_1"), m_bUseDateTime1); + if (bAdded || m_setModifications[eMod_DateCmpType1]) + rRow.SetValue(_T("date_compare_type_1"), m_eDateCmpType1); + if (bAdded || m_setModifications[eMod_UseDate1]) + rRow.SetValue(_T("use_date_1"), m_bUseDate1); + if (bAdded || m_setModifications[eMod_UseTime1]) + rRow.SetValue(_T("use_time_1"), m_bUseTime1); + if (bAdded || m_setModifications[eMod_DateTime1]) + rRow.SetValue(_T("datetime_1"), m_tDateTime1.Get().GetAsTimeT()); + if (bAdded || m_setModifications[eMod_UseDateTime2]) + rRow.SetValue(_T("use_date_time_2"), m_bUseDateTime2); + if (bAdded || m_setModifications[eMod_DateCmpType2]) + rRow.SetValue(_T("date_compare_type_2"), m_eDateCmpType2); + if (bAdded || m_setModifications[eMod_UseDate2]) + rRow.SetValue(_T("use_date_2"), m_bUseDate2); + if (bAdded || m_setModifications[eMod_UseTime2]) + rRow.SetValue(_T("use_time_2"), m_bUseTime2); + if (bAdded || m_setModifications[eMod_DateTime2]) + rRow.SetValue(_T("datetime_2"), m_tDateTime2.Get().GetAsTimeT()); + if (bAdded || m_setModifications[eMod_UseAttributes]) + rRow.SetValue(_T("use_attributes"), m_bUseAttributes); + if (bAdded || m_setModifications[eMod_AttrArchive]) + rRow.SetValue(_T("attr_archive"), m_iArchive); + if (bAdded || m_setModifications[eMod_AttrReadOnly]) + rRow.SetValue(_T("attr_ro"), m_iReadOnly); + if (bAdded || m_setModifications[eMod_AttrHidden]) + rRow.SetValue(_T("attr_hidden"), m_iHidden); + if (bAdded || m_setModifications[eMod_AttrSystem]) + rRow.SetValue(_T("attr_system"), m_iSystem); + if (bAdded || m_setModifications[eMod_AttrDirectory]) + rRow.SetValue(_T("attr_directory"), m_iDirectory); -void TFileFilter::Store(const ISerializerContainerPtr& spContainer) const -{ - bool bAdded = m_setModifications[eMod_Added]; - if(m_setModifications.any()) + m_setModifications.reset(); + } + } + + void TFileFilter::Load(const ISerializerRowReaderPtr& spRowReader) { - ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); + time_t tValue = 0; + TString strMask; - if(bAdded || m_setModifications[eMod_UseMask]) - rRow.SetValue(_T("use_mask"), m_bUseMask); - if(bAdded || m_setModifications[eMod_Mask]) - rRow.SetValue(_T("mask"), GetCombinedMask()); - if(bAdded || m_setModifications[eMod_UseExcludeMask]) - rRow.SetValue(_T("use_exclude_mask"), m_bUseExcludeMask); - if(bAdded || m_setModifications[eMod_ExcludeMask]) - rRow.SetValue(_T("exclude_mask"), GetCombinedExcludeMask()); - if(bAdded || m_setModifications[eMod_UseSize1]) - rRow.SetValue(_T("use_size_1"), m_bUseSize1); - if(bAdded || m_setModifications[eMod_SizeCmpType1]) - rRow.SetValue(_T("compare_type_1"), m_eSizeCmpType1); - if(bAdded || m_setModifications[eMod_Size1]) - rRow.SetValue(_T("size_1"), m_ullSize1); - if(bAdded || m_setModifications[eMod_UseSize2]) - rRow.SetValue(_T("use_size_2"), m_bUseSize2); - if(bAdded || m_setModifications[eMod_SizeCmpType2]) - rRow.SetValue(_T("compare_type_2"), m_eSizeCmpType2); - if(bAdded || m_setModifications[eMod_Size2]) - rRow.SetValue(_T("size_2"), m_ullSize2); - if(bAdded || m_setModifications[eMod_DateType]) - rRow.SetValue(_T("date_type"), m_eDateType); - if(bAdded || m_setModifications[eMod_UseDateTime1]) - rRow.SetValue(_T("use_date_time_1"), m_bUseDateTime1); - if(bAdded || m_setModifications[eMod_DateCmpType1]) - rRow.SetValue(_T("date_compare_type_1"), m_eDateCmpType1); - if(bAdded || m_setModifications[eMod_UseDate1]) - rRow.SetValue(_T("use_date_1"), m_bUseDate1); - if(bAdded || m_setModifications[eMod_UseTime1]) - rRow.SetValue(_T("use_time_1"), m_bUseTime1); - if(bAdded || m_setModifications[eMod_DateTime1]) - rRow.SetValue(_T("datetime_1"), m_tDateTime1.Get().GetAsTimeT()); - if(bAdded || m_setModifications[eMod_UseDateTime2]) - rRow.SetValue(_T("use_date_time_2"), m_bUseDateTime2); - if(bAdded || m_setModifications[eMod_DateCmpType2]) - rRow.SetValue(_T("date_compare_type_2"), m_eDateCmpType2); - if(bAdded || m_setModifications[eMod_UseDate2]) - rRow.SetValue(_T("use_date_2"), m_bUseDate2); - if(bAdded || m_setModifications[eMod_UseTime2]) - rRow.SetValue(_T("use_time_2"), m_bUseTime2); - if(bAdded || m_setModifications[eMod_DateTime2]) - rRow.SetValue(_T("datetime_2"), m_tDateTime2.Get().GetAsTimeT()); - if(bAdded || m_setModifications[eMod_UseAttributes]) - rRow.SetValue(_T("use_attributes"), m_bUseAttributes); - if(bAdded || m_setModifications[eMod_AttrArchive]) - rRow.SetValue(_T("attr_archive"), m_iArchive); - if(bAdded || m_setModifications[eMod_AttrReadOnly]) - rRow.SetValue(_T("attr_ro"), m_iReadOnly); - if(bAdded || m_setModifications[eMod_AttrHidden]) - rRow.SetValue(_T("attr_hidden"), m_iHidden); - if(bAdded || m_setModifications[eMod_AttrSystem]) - rRow.SetValue(_T("attr_system"), m_iSystem); - if(bAdded || m_setModifications[eMod_AttrDirectory]) - rRow.SetValue(_T("attr_directory"), m_iDirectory); + spRowReader->GetValue(_T("use_mask"), m_bUseMask.Modify()); + spRowReader->GetValue(_T("mask"), strMask); + SetCombinedMask(strMask); + spRowReader->GetValue(_T("use_exclude_mask"), m_bUseExcludeMask.Modify()); + spRowReader->GetValue(_T("exclude_mask"), strMask); + SetCombinedExcludeMask(strMask); + spRowReader->GetValue(_T("use_size_1"), m_bUseSize1.Modify()); + spRowReader->GetValue(_T("compare_type_1"), *(int*)&m_eSizeCmpType1.Modify()); + spRowReader->GetValue(_T("size_1"), m_ullSize1.Modify()); + spRowReader->GetValue(_T("use_size_2"), m_bUseSize2.Modify()); + spRowReader->GetValue(_T("compare_type_2"), *(int*)&m_eSizeCmpType2.Modify()); + spRowReader->GetValue(_T("size_2"), m_ullSize2.Modify()); + spRowReader->GetValue(_T("date_type"), *(int*)&m_eDateType.Modify()); + spRowReader->GetValue(_T("use_date_time_1"), m_bUseDateTime1.Modify()); + spRowReader->GetValue(_T("date_compare_type_1"), *(int*)&m_eDateCmpType1.Modify()); + spRowReader->GetValue(_T("use_date_1"), m_bUseDate1.Modify()); + spRowReader->GetValue(_T("use_time_1"), m_bUseTime1.Modify()); + spRowReader->GetValue(_T("datetime_1"), tValue); + m_tDateTime1 = tValue; + spRowReader->GetValue(_T("use_date_time_2"), m_bUseDateTime2.Modify()); + spRowReader->GetValue(_T("date_compare_type_2"), *(int*)&m_eDateCmpType2.Modify()); + spRowReader->GetValue(_T("use_date_2"), m_bUseDate2.Modify()); + spRowReader->GetValue(_T("use_time_2"), m_bUseTime2.Modify()); + spRowReader->GetValue(_T("datetime_2"), tValue); + m_tDateTime2 = tValue; + spRowReader->GetValue(_T("use_attributes"), m_bUseAttributes.Modify()); + spRowReader->GetValue(_T("attr_archive"), m_iArchive.Modify()); + spRowReader->GetValue(_T("attr_ro"), m_iReadOnly.Modify()); + spRowReader->GetValue(_T("attr_hidden"), m_iHidden.Modify()); + spRowReader->GetValue(_T("attr_system"), m_iSystem.Modify()); + spRowReader->GetValue(_T("attr_directory"), m_iDirectory.Modify()); m_setModifications.reset(); } -} -void TFileFilter::Load(const ISerializerRowReaderPtr& spRowReader) -{ - time_t tValue = 0; - TString strMask; + object_id_t TFileFilter::GetObjectID() const + { + return m_oidObjectID; + } - spRowReader->GetValue(_T("use_mask"), m_bUseMask.Modify()); - spRowReader->GetValue(_T("mask"), strMask); - SetCombinedMask(strMask); - spRowReader->GetValue(_T("use_exclude_mask"), m_bUseExcludeMask.Modify()); - spRowReader->GetValue(_T("exclude_mask"), strMask); - SetCombinedExcludeMask(strMask); - spRowReader->GetValue(_T("use_size_1"), m_bUseSize1.Modify()); - spRowReader->GetValue(_T("compare_type_1"), *(int*)&m_eSizeCmpType1.Modify()); - spRowReader->GetValue(_T("size_1"), m_ullSize1.Modify()); - spRowReader->GetValue(_T("use_size_2"), m_bUseSize2.Modify()); - spRowReader->GetValue(_T("compare_type_2"), *(int*)&m_eSizeCmpType2.Modify()); - spRowReader->GetValue(_T("size_2"), m_ullSize2.Modify()); - spRowReader->GetValue(_T("date_type"), *(int*)&m_eDateType.Modify()); - spRowReader->GetValue(_T("use_date_time_1"), m_bUseDateTime1.Modify()); - spRowReader->GetValue(_T("date_compare_type_1"), *(int*)&m_eDateCmpType1.Modify()); - spRowReader->GetValue(_T("use_date_1"), m_bUseDate1.Modify()); - spRowReader->GetValue(_T("use_time_1"), m_bUseTime1.Modify()); - spRowReader->GetValue(_T("datetime_1"), tValue); - m_tDateTime1 = tValue; - spRowReader->GetValue(_T("use_date_time_2"), m_bUseDateTime2.Modify()); - spRowReader->GetValue(_T("date_compare_type_2"), *(int*)&m_eDateCmpType2.Modify()); - spRowReader->GetValue(_T("use_date_2"), m_bUseDate2.Modify()); - spRowReader->GetValue(_T("use_time_2"), m_bUseTime2.Modify()); - spRowReader->GetValue(_T("datetime_2"), tValue); - m_tDateTime2 = tValue; - spRowReader->GetValue(_T("use_attributes"), m_bUseAttributes.Modify()); - spRowReader->GetValue(_T("attr_archive"), m_iArchive.Modify()); - spRowReader->GetValue(_T("attr_ro"), m_iReadOnly.Modify()); - spRowReader->GetValue(_T("attr_hidden"), m_iHidden.Modify()); - spRowReader->GetValue(_T("attr_system"), m_iSystem.Modify()); - spRowReader->GetValue(_T("attr_directory"), m_iDirectory.Modify()); + void TFileFilter::SetObjectID(object_id_t oidObjectID) + { + m_oidObjectID = oidObjectID; + } - m_setModifications.reset(); -} + void TFileFilter::ResetModifications() + { + m_setModifications.reset(); + } -object_id_t TFileFilter::GetObjectID() const -{ - return m_oidObjectID; -} + void TFileFilter::SetData(const TFileFilter& rFilter) + { + if (this == &rFilter) + return; -void TFileFilter::SetObjectID(object_id_t oidObjectID) -{ - m_oidObjectID = oidObjectID; -} + // files mask + m_bUseMask = rFilter.m_bUseMask; + m_astrMask = rFilter.m_astrMask; -void TFileFilter::ResetModifications() -{ - m_setModifications.reset(); -} + m_bUseExcludeMask = rFilter.m_bUseExcludeMask; + m_astrExcludeMask = rFilter.m_astrExcludeMask; -void TFileFilter::SetData(const TFileFilter& rFilter) -{ - if(this == &rFilter) - return; + // size filtering + m_bUseSize1 = rFilter.m_bUseSize1; + m_eSizeCmpType1 = rFilter.m_eSizeCmpType1; + m_ullSize1 = rFilter.m_ullSize1; + m_bUseSize2 = rFilter.m_bUseSize2; + m_eSizeCmpType2 = rFilter.m_eSizeCmpType2; + m_ullSize2 = rFilter.m_ullSize2; - // files mask - m_bUseMask = rFilter.m_bUseMask; - m_astrMask = rFilter.m_astrMask; + // date filtering + m_bUseDateTime1 = rFilter.m_bUseDateTime1; + m_eDateType = rFilter.m_eDateType; + m_eDateCmpType1 = rFilter.m_eDateCmpType1; + m_bUseDate1 = rFilter.m_bUseDate1; + m_bUseTime1 = rFilter.m_bUseTime1; + m_tDateTime1 = rFilter.m_tDateTime1; - m_bUseExcludeMask = rFilter.m_bUseExcludeMask; - m_astrExcludeMask = rFilter.m_astrExcludeMask; + m_bUseDateTime2 = rFilter.m_bUseDateTime2; + m_eDateCmpType2 = rFilter.m_eDateCmpType2; + m_bUseDate2 = rFilter.m_bUseDate2; + m_bUseTime2 = rFilter.m_bUseTime2; + m_tDateTime2 = rFilter.m_tDateTime2; - // size filtering - m_bUseSize1 = rFilter.m_bUseSize1; - m_eSizeCmpType1 = rFilter.m_eSizeCmpType1; - m_ullSize1 = rFilter.m_ullSize1; - m_bUseSize2 = rFilter.m_bUseSize2; - m_eSizeCmpType2 = rFilter.m_eSizeCmpType2; - m_ullSize2 = rFilter.m_ullSize2; + // attribute filtering + m_bUseAttributes = rFilter.m_bUseAttributes; + m_iArchive = rFilter.m_iArchive; + m_iReadOnly = rFilter.m_iReadOnly; + m_iHidden = rFilter.m_iHidden; + m_iSystem = rFilter.m_iSystem; + m_iDirectory = rFilter.m_iDirectory; + } - // date filtering - m_bUseDateTime1 = rFilter.m_bUseDateTime1; - m_eDateType = rFilter.m_eDateType; - m_eDateCmpType1 = rFilter.m_eDateCmpType1; - m_bUseDate1 = rFilter.m_bUseDate1; - m_bUseTime1 = rFilter.m_bUseTime1; - m_tDateTime1 = rFilter.m_tDateTime1; + void TFileFilter::SetUseMask(bool bUseMask) + { + m_bUseMask = bUseMask; + } - m_bUseDateTime2 = rFilter.m_bUseDateTime2; - m_eDateCmpType2 = rFilter.m_eDateCmpType2; - m_bUseDate2 = rFilter.m_bUseDate2; - m_bUseTime2 = rFilter.m_bUseTime2; - m_tDateTime2 = rFilter.m_tDateTime2; + bool TFileFilter::GetUseMask() const + { + return m_bUseMask; + } - // attribute filtering - m_bUseAttributes = rFilter.m_bUseAttributes; - m_iArchive = rFilter.m_iArchive; - m_iReadOnly = rFilter.m_iReadOnly; - m_iHidden = rFilter.m_iHidden; - m_iSystem = rFilter.m_iSystem; - m_iDirectory = rFilter.m_iDirectory; -} + bool TFileFilter::GetUseExcludeMask() const + { + return m_bUseExcludeMask; + } -void TFileFilter::SetUseMask(bool bUseMask) -{ - m_bUseMask = bUseMask; -} + void TFileFilter::SetUseExcludeMask(bool bUseExcludeMask) + { + m_bUseExcludeMask = bUseExcludeMask; + } -bool TFileFilter::GetUseMask() const -{ - return m_bUseMask; -} + bool TFileFilter::GetUseSize1() const + { + return m_bUseSize1; + } -bool TFileFilter::GetUseExcludeMask() const -{ - return m_bUseExcludeMask; -} + void TFileFilter::SetUseSize1(bool bUseSize1) + { + m_bUseSize1 = bUseSize1; + } -void TFileFilter::SetUseExcludeMask(bool bUseExcludeMask) -{ - m_bUseExcludeMask = bUseExcludeMask; -} + TFileFilter::ESizeCompareType TFileFilter::GetSizeType1() const + { + return m_eSizeCmpType1; + } -bool TFileFilter::GetUseSize1() const -{ - return m_bUseSize1; -} + void TFileFilter::SetSizeType1(ESizeCompareType eSizeType1) + { + m_eSizeCmpType1 = eSizeType1; + } -void TFileFilter::SetUseSize1(bool bUseSize1) -{ - m_bUseSize1 = bUseSize1; -} + unsigned long long TFileFilter::GetSize1() const + { + return m_ullSize1; + } -TFileFilter::ESizeCompareType TFileFilter::GetSizeType1() const -{ - return m_eSizeCmpType1; -} + void TFileFilter::SetSize1(unsigned long long ullSize1) + { + m_ullSize1 = ullSize1; + } -void TFileFilter::SetSizeType1(ESizeCompareType eSizeType1) -{ - m_eSizeCmpType1 = eSizeType1; -} + bool TFileFilter::GetUseSize2() const + { + return m_bUseSize2; + } -unsigned long long TFileFilter::GetSize1() const -{ - return m_ullSize1; -} + void TFileFilter::SetUseSize2(bool bUseSize2) + { + m_bUseSize2 = bUseSize2; + } -void TFileFilter::SetSize1(unsigned long long ullSize1) -{ - m_ullSize1 = ullSize1; -} + TFileFilter::ESizeCompareType TFileFilter::GetSizeType2() const + { + return m_eSizeCmpType2; + } -bool TFileFilter::GetUseSize2() const -{ - return m_bUseSize2; -} + void TFileFilter::SetSizeType2(ESizeCompareType eSizeType2) + { + m_eSizeCmpType2 = eSizeType2; + } -void TFileFilter::SetUseSize2(bool bUseSize2) -{ - m_bUseSize2 = bUseSize2; -} + unsigned long long TFileFilter::GetSize2() const + { + return m_ullSize2; + } -TFileFilter::ESizeCompareType TFileFilter::GetSizeType2() const -{ - return m_eSizeCmpType2; -} + void TFileFilter::SetSize2(unsigned long long ullSize2) + { + m_ullSize2 = ullSize2; + } -void TFileFilter::SetSizeType2(ESizeCompareType eSizeType2) -{ - m_eSizeCmpType2 = eSizeType2; -} + TFileFilter::EDateType TFileFilter::GetDateType() const + { + return m_eDateType; + } -unsigned long long TFileFilter::GetSize2() const -{ - return m_ullSize2; -} + void TFileFilter::SetDateType(TFileFilter::EDateType eDateType) + { + m_eDateType = eDateType; + } -void TFileFilter::SetSize2(unsigned long long ullSize2) -{ - m_ullSize2 = ullSize2; -} + bool TFileFilter::GetUseDateTime1() const + { + return m_bUseDateTime1; + } -TFileFilter::EDateType TFileFilter::GetDateType() const -{ - return m_eDateType; -} + void TFileFilter::SetUseDateTime1(bool bUseDateTime1) + { + m_bUseDateTime1 = bUseDateTime1; + } -void TFileFilter::SetDateType(TFileFilter::EDateType eDateType) -{ - m_eDateType = eDateType; -} + TFileFilter::EDateCompareType TFileFilter::GetDateCmpType1() const + { + return m_eDateCmpType1; + } -bool TFileFilter::GetUseDateTime1() const -{ - return m_bUseDateTime1; -} + void TFileFilter::SetDateCmpType1(TFileFilter::EDateCompareType eCmpType1) + { + m_eDateCmpType1 = eCmpType1; + } -void TFileFilter::SetUseDateTime1(bool bUseDateTime1) -{ - m_bUseDateTime1 = bUseDateTime1; -} + bool TFileFilter::GetUseDate1() const + { + return m_bUseDate1; + } -TFileFilter::EDateCompareType TFileFilter::GetDateCmpType1() const -{ - return m_eDateCmpType1; -} + void TFileFilter::SetUseDate1(bool tDate1) + { + m_bUseDate1 = tDate1; + } -void TFileFilter::SetDateCmpType1(TFileFilter::EDateCompareType eCmpType1) -{ - m_eDateCmpType1 = eCmpType1; -} + bool TFileFilter::GetUseTime1() const + { + return m_bUseTime1; + } -bool TFileFilter::GetUseDate1() const -{ - return m_bUseDate1; -} + void TFileFilter::SetUseTime1(bool tTime1) + { + m_bUseTime1 = tTime1; + } -void TFileFilter::SetUseDate1(bool tDate1) -{ - m_bUseDate1 = tDate1; -} + const TDateTime& TFileFilter::GetDateTime1() const + { + return m_tDateTime1; + } -bool TFileFilter::GetUseTime1() const -{ - return m_bUseTime1; -} + void TFileFilter::SetDateTime1(const TDateTime& tDateTime1) + { + m_tDateTime1 = tDateTime1; + } -void TFileFilter::SetUseTime1(bool tTime1) -{ - m_bUseTime1 = tTime1; -} + bool TFileFilter::GetUseDateTime2() const + { + return m_bUseDateTime2; + } -const TDateTime& TFileFilter::GetDateTime1() const -{ - return m_tDateTime1; -} + void TFileFilter::SetUseDateTime2(bool bUseDateTime2) + { + m_bUseDateTime2 = bUseDateTime2; + } -void TFileFilter::SetDateTime1(const TDateTime& tDateTime1) -{ - m_tDateTime1 = tDateTime1; -} + TFileFilter::EDateCompareType TFileFilter::GetDateCmpType2() const + { + return m_eDateCmpType2; + } -bool TFileFilter::GetUseDateTime2() const -{ - return m_bUseDateTime2; -} + void TFileFilter::SetDateCmpType2(TFileFilter::EDateCompareType eCmpType2) + { + m_eDateCmpType2 = eCmpType2; + } -void TFileFilter::SetUseDateTime2(bool bUseDateTime2) -{ - m_bUseDateTime2 = bUseDateTime2; -} + bool TFileFilter::GetUseDate2() const + { + return m_bUseDate2; + } -TFileFilter::EDateCompareType TFileFilter::GetDateCmpType2() const -{ - return m_eDateCmpType2; -} + void TFileFilter::SetUseDate2(bool tDate2) + { + m_bUseDate2 = tDate2; + } -void TFileFilter::SetDateCmpType2(TFileFilter::EDateCompareType eCmpType2) -{ - m_eDateCmpType2 = eCmpType2; -} + bool TFileFilter::GetUseTime2() const + { + return m_bUseTime2; + } -bool TFileFilter::GetUseDate2() const -{ - return m_bUseDate2; -} + void TFileFilter::SetUseTime2(bool tTime2) + { + m_bUseTime2 = tTime2; + } -void TFileFilter::SetUseDate2(bool tDate2) -{ - m_bUseDate2 = tDate2; -} + const TDateTime& TFileFilter::GetDateTime2() const + { + return m_tDateTime2; + } -bool TFileFilter::GetUseTime2() const -{ - return m_bUseTime2; -} + void TFileFilter::SetDateTime2(const TDateTime& tDateTime2) + { + m_tDateTime2 = tDateTime2; + } -void TFileFilter::SetUseTime2(bool tTime2) -{ - m_bUseTime2 = tTime2; -} + bool TFileFilter::GetUseAttributes() const + { + return m_bUseAttributes; + } -const TDateTime& TFileFilter::GetDateTime2() const -{ - return m_tDateTime2; -} + void TFileFilter::SetUseAttributes(bool bUseAttributes) + { + m_bUseAttributes = bUseAttributes; + } -void TFileFilter::SetDateTime2(const TDateTime& tDateTime2) -{ - m_tDateTime2 = tDateTime2; -} + int TFileFilter::GetArchive() const + { + return m_iArchive; + } -bool TFileFilter::GetUseAttributes() const -{ - return m_bUseAttributes; -} + void TFileFilter::SetArchive(int iArchive) + { + m_iArchive = iArchive; + } -void TFileFilter::SetUseAttributes(bool bUseAttributes) -{ - m_bUseAttributes = bUseAttributes; -} + int TFileFilter::GetReadOnly() const + { + return m_iReadOnly; + } -int TFileFilter::GetArchive() const -{ - return m_iArchive; -} + void TFileFilter::SetReadOnly(int iReadOnly) + { + m_iReadOnly = iReadOnly; + } -void TFileFilter::SetArchive(int iArchive) -{ - m_iArchive = iArchive; -} + int TFileFilter::GetHidden() const + { + return m_iHidden; + } -int TFileFilter::GetReadOnly() const -{ - return m_iReadOnly; + void TFileFilter::SetHidden(int iHidden) + { + m_iHidden = iHidden; + } } - -void TFileFilter::SetReadOnly(int iReadOnly) -{ - m_iReadOnly = iReadOnly; -} - -int TFileFilter::GetHidden() const -{ - return m_iHidden; -} - -void TFileFilter::SetHidden(int iHidden) -{ - m_iHidden = iHidden; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TFileFilter.h =================================================================== diff -u -N -r2755e12daeccb1935f569e7235e685e566b0b098 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileFilter.h (.../TFileFilter.h) (revision 2755e12daeccb1935f569e7235e685e566b0b098) +++ src/libchcore/TFileFilter.h (.../TFileFilter.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -27,237 +27,236 @@ #include #include "TSharedModificationTracker.h" -BEGIN_CHCORE_NAMESPACE - -class TConfig; -class TFileInfo; -typedef boost::shared_ptr TFileInfoPtr; - -class LIBCHCORE_API TFileFilter +namespace chcore { -public: - enum ESizeCompareType - { - eSizeCmp_Less = 0, - eSizeCmp_LessOrEqual = 1, - eSizeCmp_Equal = 2, - eSizeCmp_GreaterOrEqual = 3, - eSizeCmp_Greater = 4 - }; + class TConfig; + class TFileInfo; + typedef boost::shared_ptr TFileInfoPtr; - enum EDateCompareType + class LIBCHCORE_API TFileFilter { - eDateCmp_Less = 0, - eDateCmp_LessOrEqual = 1, - eDateCmp_Equal = 2, - eDateCmp_GreaterOrEqual = 3, - eDateCmp_Greater = 4 - }; + public: + enum ESizeCompareType + { + eSizeCmp_Less = 0, + eSizeCmp_LessOrEqual = 1, + eSizeCmp_Equal = 2, + eSizeCmp_GreaterOrEqual = 3, + eSizeCmp_Greater = 4 + }; - enum EDateType - { - eDateType_Created = 0, - eDateType_Modified = 1, - eDateType_LastAccessed = 2 - }; + enum EDateCompareType + { + eDateCmp_Less = 0, + eDateCmp_LessOrEqual = 1, + eDateCmp_Equal = 2, + eDateCmp_GreaterOrEqual = 3, + eDateCmp_Greater = 4 + }; -public: - TFileFilter(); - TFileFilter(const TFileFilter& rFilter); - TFileFilter& operator=(const TFileFilter& rFilter); + enum EDateType + { + eDateType_Created = 0, + eDateType_Modified = 1, + eDateType_LastAccessed = 2 + }; - void SetData(const TFileFilter& rSrc); + public: + TFileFilter(); + TFileFilter(const TFileFilter& rFilter); + TFileFilter& operator=(const TFileFilter& rFilter); - // matching - bool Match(const TFileInfoPtr& spInfo) const; + void SetData(const TFileFilter& rSrc); - // serialization - void StoreInConfig(TConfig& rConfig) const; - void ReadFromConfig(const TConfig& rConfig); + // matching + bool Match(const TFileInfoPtr& spInfo) const; - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerRowReaderPtr& spRowReader); - static void InitColumns(IColumnsDefinition& rColumns); + // serialization + void StoreInConfig(TConfig& rConfig) const; + void ReadFromConfig(const TConfig& rConfig); - // other - object_id_t GetObjectID() const; - void SetObjectID(object_id_t oidObjectID); - void ResetModifications(); + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerRowReaderPtr& spRowReader); + static void InitColumns(IColumnsDefinition& rColumns); - // atrributes access - bool GetUseMask() const; - void SetUseMask(bool bUseMask); + // other + object_id_t GetObjectID() const; + void SetObjectID(object_id_t oidObjectID); + void ResetModifications(); - TString GetCombinedMask() const; - void SetCombinedMask(const TString& pMask); + // atrributes access + bool GetUseMask() const; + void SetUseMask(bool bUseMask); - bool GetUseExcludeMask() const; - void SetUseExcludeMask(bool bUseExcludeMask); + TString GetCombinedMask() const; + void SetCombinedMask(const TString& pMask); - TString GetCombinedExcludeMask() const; - void SetCombinedExcludeMask(const TString& pMask); + bool GetUseExcludeMask() const; + void SetUseExcludeMask(bool bUseExcludeMask); - bool GetUseSize1() const; - void SetUseSize1(bool bUseSize1); + TString GetCombinedExcludeMask() const; + void SetCombinedExcludeMask(const TString& pMask); - ESizeCompareType GetSizeType1() const; - void SetSizeType1(ESizeCompareType eSizeType1); + bool GetUseSize1() const; + void SetUseSize1(bool bUseSize1); - unsigned long long GetSize1() const; - void SetSize1(unsigned long long ullSize1); + ESizeCompareType GetSizeType1() const; + void SetSizeType1(ESizeCompareType eSizeType1); - bool GetUseSize2() const; - void SetUseSize2(bool bUseSize2); + unsigned long long GetSize1() const; + void SetSize1(unsigned long long ullSize1); - ESizeCompareType GetSizeType2() const; - void SetSizeType2(ESizeCompareType eSizeType2); + bool GetUseSize2() const; + void SetUseSize2(bool bUseSize2); - unsigned long long GetSize2() const; - void SetSize2(unsigned long long ullSize2); + ESizeCompareType GetSizeType2() const; + void SetSizeType2(ESizeCompareType eSizeType2); - // dates - TFileFilter::EDateType GetDateType() const; - void SetDateType(TFileFilter::EDateType eDateType); + unsigned long long GetSize2() const; + void SetSize2(unsigned long long ullSize2); - // date 1 - bool GetUseDateTime1() const; - void SetUseDateTime1(bool bUseDateTime1); + // dates + TFileFilter::EDateType GetDateType() const; + void SetDateType(TFileFilter::EDateType eDateType); - TFileFilter::EDateCompareType GetDateCmpType1() const; - void SetDateCmpType1(TFileFilter::EDateCompareType eCmpType1); + // date 1 + bool GetUseDateTime1() const; + void SetUseDateTime1(bool bUseDateTime1); - bool GetUseDate1() const; - void SetUseDate1(bool tDate1); + TFileFilter::EDateCompareType GetDateCmpType1() const; + void SetDateCmpType1(TFileFilter::EDateCompareType eCmpType1); - bool GetUseTime1() const; - void SetUseTime1(bool tTime1); + bool GetUseDate1() const; + void SetUseDate1(bool tDate1); - const TDateTime& GetDateTime1() const; - void SetDateTime1(const TDateTime& tDateTime1); + bool GetUseTime1() const; + void SetUseTime1(bool tTime1); - // date 2 - bool GetUseDateTime2() const; - void SetUseDateTime2(bool bUseDateTime2); + const TDateTime& GetDateTime1() const; + void SetDateTime1(const TDateTime& tDateTime1); - TFileFilter::EDateCompareType GetDateCmpType2() const; - void SetDateCmpType2(TFileFilter::EDateCompareType eCmpType2); + // date 2 + bool GetUseDateTime2() const; + void SetUseDateTime2(bool bUseDateTime2); - bool GetUseDate2() const; - void SetUseDate2(bool tDate2); + TFileFilter::EDateCompareType GetDateCmpType2() const; + void SetDateCmpType2(TFileFilter::EDateCompareType eCmpType2); - bool GetUseTime2() const; - void SetUseTime2(bool tTime2); + bool GetUseDate2() const; + void SetUseDate2(bool tDate2); - const TDateTime& GetDateTime2() const; - void SetDateTime2(const TDateTime& tDateTime2); + bool GetUseTime2() const; + void SetUseTime2(bool tTime2); - // attributes - bool GetUseAttributes() const; - void SetUseAttributes(bool bUseAttributes); + const TDateTime& GetDateTime2() const; + void SetDateTime2(const TDateTime& tDateTime2); - int GetArchive() const; - void SetArchive(int iArchive); + // attributes + bool GetUseAttributes() const; + void SetUseAttributes(bool bUseAttributes); - int GetReadOnly() const; - void SetReadOnly(int iReadOnly); + int GetArchive() const; + void SetArchive(int iArchive); - int GetHidden() const; - void SetHidden(int iHidden); + int GetReadOnly() const; + void SetReadOnly(int iReadOnly); - int GetSystem() const { return m_iSystem; } - void SetSystem(int iSystem) { m_iSystem = iSystem; } + int GetHidden() const; + void SetHidden(int iHidden); - int GetDirectory() const { return m_iDirectory; } - void SetDirectory(int iDirectory) { m_iDirectory = iDirectory; } + int GetSystem() const { return m_iSystem; } + void SetSystem(int iSystem) { m_iSystem = iSystem; } -private: - enum EModifications - { - eMod_Added, - eMod_UseMask, - eMod_Mask, - eMod_UseExcludeMask, - eMod_ExcludeMask, - eMod_UseSize1, - eMod_SizeCmpType1, - eMod_Size1, - eMod_UseSize2, - eMod_SizeCmpType2, - eMod_Size2, - eMod_DateType, - eMod_UseDateTime1, - eMod_DateCmpType1, - eMod_UseDate1, - eMod_UseTime1, - eMod_DateTime1, - eMod_UseDateTime2, - eMod_DateCmpType2, - eMod_UseDate2, - eMod_UseTime2, - eMod_DateTime2, - eMod_UseAttributes, - eMod_AttrArchive, - eMod_AttrReadOnly, - eMod_AttrHidden, - eMod_AttrSystem, - eMod_AttrDirectory, + int GetDirectory() const { return m_iDirectory; } + void SetDirectory(int iDirectory) { m_iDirectory = iDirectory; } - eMod_Last - }; + private: + enum EModifications + { + eMod_Added, + eMod_UseMask, + eMod_Mask, + eMod_UseExcludeMask, + eMod_ExcludeMask, + eMod_UseSize1, + eMod_SizeCmpType1, + eMod_Size1, + eMod_UseSize2, + eMod_SizeCmpType2, + eMod_Size2, + eMod_DateType, + eMod_UseDateTime1, + eMod_DateCmpType1, + eMod_UseDate1, + eMod_UseTime1, + eMod_DateTime1, + eMod_UseDateTime2, + eMod_DateCmpType2, + eMod_UseDate2, + eMod_UseTime2, + eMod_DateTime2, + eMod_UseAttributes, + eMod_AttrArchive, + eMod_AttrReadOnly, + eMod_AttrHidden, + eMod_AttrSystem, + eMod_AttrDirectory, - // object identification - object_id_t m_oidObjectID; + eMod_Last + }; - // modification management + // object identification + object_id_t m_oidObjectID; + + // modification management #pragma warning(push) #pragma warning(disable: 4251) - typedef std::bitset Bitset; - mutable Bitset m_setModifications; + typedef std::bitset Bitset; + mutable Bitset m_setModifications; - // files mask - TSharedModificationTracker m_bUseMask; - TSharedModificationTracker m_astrMask; + // files mask + TSharedModificationTracker m_bUseMask; + TSharedModificationTracker m_astrMask; - // files mask- - TSharedModificationTracker m_bUseExcludeMask; - TSharedModificationTracker m_astrExcludeMask; + // files mask- + TSharedModificationTracker m_bUseExcludeMask; + TSharedModificationTracker m_astrExcludeMask; - // size filtering - TSharedModificationTracker m_bUseSize1; - TSharedModificationTracker m_eSizeCmpType1; - TSharedModificationTracker m_ullSize1; + // size filtering + TSharedModificationTracker m_bUseSize1; + TSharedModificationTracker m_eSizeCmpType1; + TSharedModificationTracker m_ullSize1; - TSharedModificationTracker m_bUseSize2; - TSharedModificationTracker m_eSizeCmpType2; - TSharedModificationTracker m_ullSize2; + TSharedModificationTracker m_bUseSize2; + TSharedModificationTracker m_eSizeCmpType2; + TSharedModificationTracker m_ullSize2; - // date filtering - TSharedModificationTracker m_eDateType; // created/last modified/last accessed + // date filtering + TSharedModificationTracker m_eDateType; // created/last modified/last accessed - TSharedModificationTracker m_bUseDateTime1; + TSharedModificationTracker m_bUseDateTime1; - TSharedModificationTracker m_eDateCmpType1; // before/after - TSharedModificationTracker m_bUseDate1; - TSharedModificationTracker m_bUseTime1; - TSharedModificationTracker m_tDateTime1; + TSharedModificationTracker m_eDateCmpType1; // before/after + TSharedModificationTracker m_bUseDate1; + TSharedModificationTracker m_bUseTime1; + TSharedModificationTracker m_tDateTime1; - TSharedModificationTracker m_bUseDateTime2; + TSharedModificationTracker m_bUseDateTime2; - TSharedModificationTracker m_eDateCmpType2; - TSharedModificationTracker m_bUseDate2; - TSharedModificationTracker m_bUseTime2; - TSharedModificationTracker m_tDateTime2; + TSharedModificationTracker m_eDateCmpType2; + TSharedModificationTracker m_bUseDate2; + TSharedModificationTracker m_bUseTime2; + TSharedModificationTracker m_tDateTime2; - // attribute filtering - TSharedModificationTracker m_bUseAttributes; - TSharedModificationTracker m_iArchive; - TSharedModificationTracker m_iReadOnly; - TSharedModificationTracker m_iHidden; - TSharedModificationTracker m_iSystem; - TSharedModificationTracker m_iDirectory; + // attribute filtering + TSharedModificationTracker m_bUseAttributes; + TSharedModificationTracker m_iArchive; + TSharedModificationTracker m_iReadOnly; + TSharedModificationTracker m_iHidden; + TSharedModificationTracker m_iSystem; + TSharedModificationTracker m_iDirectory; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TFileFiltersArray.cpp =================================================================== diff -u -N -re92d7e2b63df1305b23aa04132c45ad8747dc22c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileFiltersArray.cpp (.../TFileFiltersArray.cpp) (revision e92d7e2b63df1305b23aa04132c45ad8747dc22c) +++ src/libchcore/TFileFiltersArray.cpp (.../TFileFiltersArray.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,168 +22,167 @@ #include "TConfig.h" #include "TConfigArray.h" -BEGIN_CHCORE_NAMESPACE - -TFileFiltersArray::TFileFiltersArray() +namespace chcore { -} + TFileFiltersArray::TFileFiltersArray() + { + } -TFileFiltersArray::~TFileFiltersArray() -{ -} - -TFileFiltersArray& TFileFiltersArray::operator=(const TFileFiltersArray& rSrc) -{ - if(this != &rSrc) + TFileFiltersArray::~TFileFiltersArray() { - m_vFilters = rSrc.m_vFilters; } - return *this; -} + TFileFiltersArray& TFileFiltersArray::operator=(const TFileFiltersArray& rSrc) + { + if (this != &rSrc) + { + m_vFilters = rSrc.m_vFilters; + } -bool TFileFiltersArray::Match(const TFileInfoPtr& spInfo) const -{ - if(m_vFilters.empty()) - return true; + return *this; + } - // if only one of the filters matches - return true - for(std::vector::const_iterator iterFilter = m_vFilters.begin(); iterFilter != m_vFilters.end(); iterFilter++) + bool TFileFiltersArray::Match(const TFileInfoPtr& spInfo) const { - if((*iterFilter).Match(spInfo)) + if (m_vFilters.empty()) return true; - } - return false; -} + // if only one of the filters matches - return true + for (std::vector::const_iterator iterFilter = m_vFilters.begin(); iterFilter != m_vFilters.end(); iterFilter++) + { + if ((*iterFilter).Match(spInfo)) + return true; + } -void TFileFiltersArray::StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const -{ - rConfig.DeleteNode(pszNodeName); - BOOST_FOREACH(const TFileFilter& rFilter, m_vFilters) + return false; + } + + void TFileFiltersArray::StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const { - TConfig cfgNode; - rFilter.StoreInConfig(cfgNode); + rConfig.DeleteNode(pszNodeName); + BOOST_FOREACH(const TFileFilter& rFilter, m_vFilters) + { + TConfig cfgNode; + rFilter.StoreInConfig(cfgNode); - TString strNode = TString(pszNodeName) + _T(".FilterDefinition"); - rConfig.AddSubConfig(strNode.c_str(), cfgNode); + TString strNode = TString(pszNodeName) + _T(".FilterDefinition"); + rConfig.AddSubConfig(strNode.c_str(), cfgNode); + } } -} -bool TFileFiltersArray::ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName) -{ - m_vFilters.clear(); + bool TFileFiltersArray::ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName) + { + m_vFilters.clear(); - TConfigArray vConfigs; - if(!rConfig.ExtractMultiSubConfigs(pszNodeName, vConfigs)) - return false; + TConfigArray vConfigs; + if (!rConfig.ExtractMultiSubConfigs(pszNodeName, vConfigs)) + return false; - for(size_t stIndex = 0; stIndex < vConfigs.GetCount(); ++stIndex) - { - const TConfig& rCfg = vConfigs.GetAt(stIndex); - TFileFilter tFilter; - tFilter.ReadFromConfig(rCfg); + for (size_t stIndex = 0; stIndex < vConfigs.GetCount(); ++stIndex) + { + const TConfig& rCfg = vConfigs.GetAt(stIndex); + TFileFilter tFilter; + tFilter.ReadFromConfig(rCfg); - m_vFilters.push_back(tFilter); + m_vFilters.push_back(tFilter); + } + return true; } - return true; -} -bool TFileFiltersArray::IsEmpty() const -{ - return m_vFilters.empty(); -} + bool TFileFiltersArray::IsEmpty() const + { + return m_vFilters.empty(); + } -void TFileFiltersArray::Add(const TFileFilter& rFilter) -{ - m_vFilters.push_back(rFilter); -} + void TFileFiltersArray::Add(const TFileFilter& rFilter) + { + m_vFilters.push_back(rFilter); + } -bool TFileFiltersArray::SetAt(size_t stIndex, const TFileFilter& rNewFilter) -{ - BOOST_ASSERT(stIndex < m_vFilters.size()); - if(stIndex < m_vFilters.size()) + bool TFileFiltersArray::SetAt(size_t stIndex, const TFileFilter& rNewFilter) { - TFileFilter& rFilter = m_vFilters.at(stIndex); + BOOST_ASSERT(stIndex < m_vFilters.size()); + if (stIndex < m_vFilters.size()) + { + TFileFilter& rFilter = m_vFilters.at(stIndex); - rFilter.SetData(rNewFilter); - return true; + rFilter.SetData(rNewFilter); + return true; + } + else + return false; } - else - return false; -} -const TFileFilter* TFileFiltersArray::GetAt(size_t stIndex) const -{ - BOOST_ASSERT(stIndex < m_vFilters.size()); - if(stIndex < m_vFilters.size()) - return &m_vFilters.at(stIndex); - else - return NULL; -} + const TFileFilter* TFileFiltersArray::GetAt(size_t stIndex) const + { + BOOST_ASSERT(stIndex < m_vFilters.size()); + if (stIndex < m_vFilters.size()) + return &m_vFilters.at(stIndex); + else + return NULL; + } -bool TFileFiltersArray::RemoveAt(size_t stIndex) -{ - BOOST_ASSERT(stIndex < m_vFilters.size()); - if(stIndex < m_vFilters.size()) + bool TFileFiltersArray::RemoveAt(size_t stIndex) { - m_setRemovedObjects.Add(m_vFilters[stIndex].GetObjectID()); + BOOST_ASSERT(stIndex < m_vFilters.size()); + if (stIndex < m_vFilters.size()) + { + m_setRemovedObjects.Add(m_vFilters[stIndex].GetObjectID()); - m_vFilters.erase(m_vFilters.begin() + stIndex); - return true; + m_vFilters.erase(m_vFilters.begin() + stIndex); + return true; + } + else + return false; } - else - return false; -} -size_t TFileFiltersArray::GetSize() const -{ - return m_vFilters.size(); -} + size_t TFileFiltersArray::GetSize() const + { + return m_vFilters.size(); + } -void TFileFiltersArray::Clear() -{ - BOOST_FOREACH(const TFileFilter& rFilter, m_vFilters) + void TFileFiltersArray::Clear() { - m_setRemovedObjects.Add(rFilter.GetObjectID()); + BOOST_FOREACH(const TFileFilter& rFilter, m_vFilters) + { + m_setRemovedObjects.Add(rFilter.GetObjectID()); + } + m_vFilters.clear(); } - m_vFilters.clear(); -} -void TFileFiltersArray::Store(const ISerializerContainerPtr& spContainer) const -{ - InitColumns(spContainer); + void TFileFiltersArray::Store(const ISerializerContainerPtr& spContainer) const + { + InitColumns(spContainer); - spContainer->DeleteRows(m_setRemovedObjects); - m_setRemovedObjects.Clear(); + spContainer->DeleteRows(m_setRemovedObjects); + m_setRemovedObjects.Clear(); - BOOST_FOREACH(const TFileFilter& rFilter, m_vFilters) - { - rFilter.Store(spContainer); + BOOST_FOREACH(const TFileFilter& rFilter, m_vFilters) + { + rFilter.Store(spContainer); + } } -} -void TFileFiltersArray::Load(const ISerializerContainerPtr& spContainer) -{ - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - while(spRowReader->Next()) + void TFileFiltersArray::Load(const ISerializerContainerPtr& spContainer) { - TFileFilter tFileFilter; - tFileFilter.Load(spRowReader); + InitColumns(spContainer); - tFileFilter.ResetModifications(); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + while (spRowReader->Next()) + { + TFileFilter tFileFilter; + tFileFilter.Load(spRowReader); - m_vFilters.push_back(tFileFilter); + tFileFilter.ResetModifications(); + + m_vFilters.push_back(tFileFilter); + } } -} -void TFileFiltersArray::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) - TFileFilter::InitColumns(rColumns); + void TFileFiltersArray::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TFileFilter::InitColumns(rColumns); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TFileFiltersArray.h =================================================================== diff -u -N -re92d7e2b63df1305b23aa04132c45ad8747dc22c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileFiltersArray.h (.../TFileFiltersArray.h) (revision e92d7e2b63df1305b23aa04132c45ad8747dc22c) +++ src/libchcore/TFileFiltersArray.h (.../TFileFiltersArray.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,49 +24,48 @@ #include "ISerializerContainer.h" #include "TRemovedObjects.h" -BEGIN_CHCORE_NAMESPACE - -class TConfig; -class TFileInfo; -typedef boost::shared_ptr TFileInfoPtr; - -class LIBCHCORE_API TFileFiltersArray +namespace chcore { -public: - TFileFiltersArray(); - ~TFileFiltersArray(); + class TConfig; + class TFileInfo; + typedef boost::shared_ptr TFileInfoPtr; - TFileFiltersArray& operator=(const TFileFiltersArray& rSrc); - bool Match(const TFileInfoPtr& spInfo) const; + class LIBCHCORE_API TFileFiltersArray + { + public: + TFileFiltersArray(); + ~TFileFiltersArray(); - void StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const; - bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName); + TFileFiltersArray& operator=(const TFileFiltersArray& rSrc); + bool Match(const TFileInfoPtr& spInfo) const; - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); + void StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const; + bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName); - void InitColumns(const ISerializerContainerPtr& spContainer) const; + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); - bool IsEmpty() const; + void InitColumns(const ISerializerContainerPtr& spContainer) const; - void Add(const TFileFilter& rFilter); - bool SetAt(size_t stIndex, const TFileFilter& rNewFilter); - const TFileFilter* GetAt(size_t stIndex) const; - bool RemoveAt(size_t stIndex); - size_t GetSize() const; + bool IsEmpty() const; - void Clear(); + void Add(const TFileFilter& rFilter); + bool SetAt(size_t stIndex, const TFileFilter& rNewFilter); + const TFileFilter* GetAt(size_t stIndex) const; + bool RemoveAt(size_t stIndex); + size_t GetSize() const; -private: + void Clear(); + + private: #pragma warning(push) #pragma warning(disable: 4251) - std::vector m_vFilters; + std::vector m_vFilters; #pragma warning(pop) - mutable TRemovedObjects m_setRemovedObjects; -}; + mutable TRemovedObjects m_setRemovedObjects; + }; +} -END_CHCORE_NAMESPACE - CONFIG_MEMBER_SERIALIZATION(TFileFiltersArray) #endif Index: src/libchcore/TFileInfoArray.cpp =================================================================== diff -u -N -re92d7e2b63df1305b23aa04132c45ad8747dc22c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileInfoArray.cpp (.../TFileInfoArray.cpp) (revision e92d7e2b63df1305b23aa04132c45ad8747dc22c) +++ src/libchcore/TFileInfoArray.cpp (.../TFileInfoArray.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,158 +26,157 @@ #include "ISerializerContainer.h" #include -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////// -// Array -TFileInfoArray::TFileInfoArray() : - m_bComplete(false), - m_oidLastObjectID(0) +namespace chcore { -} + /////////////////////////////////////////////////////////////////////// + // Array + TFileInfoArray::TFileInfoArray() : + m_bComplete(false), + m_oidLastObjectID(0) + { + } -TFileInfoArray::~TFileInfoArray() -{ -} + TFileInfoArray::~TFileInfoArray() + { + } -void TFileInfoArray::AddFileInfo(const TFileInfoPtr& spFileInfo) -{ - boost::unique_lock lock(m_lock); - spFileInfo->SetObjectID(++m_oidLastObjectID); - m_vFiles.push_back(spFileInfo); -} + void TFileInfoArray::AddFileInfo(const TFileInfoPtr& spFileInfo) + { + boost::unique_lock lock(m_lock); + spFileInfo->SetObjectID(++m_oidLastObjectID); + m_vFiles.push_back(spFileInfo); + } -file_count_t TFileInfoArray::GetSize() const -{ - boost::shared_lock lock(m_lock); - return boost::numeric_cast(m_vFiles.size()); -} + file_count_t TFileInfoArray::GetSize() const + { + boost::shared_lock lock(m_lock); + return boost::numeric_cast(m_vFiles.size()); + } -TFileInfoPtr TFileInfoArray::GetAt(file_count_t fcIndex) const -{ - boost::shared_lock lock(m_lock); - - if(fcIndex >= m_vFiles.size()) - THROW(_T("Out of bounds"), 0, 0, 0); - - return m_vFiles.at(boost::numeric_cast(fcIndex)); -} + TFileInfoPtr TFileInfoArray::GetAt(file_count_t fcIndex) const + { + boost::shared_lock lock(m_lock); -TFileInfo TFileInfoArray::GetCopyAt(file_count_t fcIndex) const -{ - boost::shared_lock lock(m_lock); - - if(fcIndex >= m_vFiles.size()) - THROW(_T("Out of bounds"), 0, 0, 0); - const TFileInfoPtr& spInfo = m_vFiles.at(boost::numeric_cast(fcIndex)); - if(!spInfo) - THROW(_T("Invalid pointer"), 0, 0, 0); + if (fcIndex >= m_vFiles.size()) + THROW(_T("Out of bounds"), 0, 0, 0); - return *spInfo; -} + return m_vFiles.at(boost::numeric_cast(fcIndex)); + } -void TFileInfoArray::Clear() -{ - boost::unique_lock lock(m_lock); - m_bComplete = false; - BOOST_FOREACH(const TFileInfoPtr& spFileInfo, m_vFiles) + TFileInfo TFileInfoArray::GetCopyAt(file_count_t fcIndex) const { - m_setRemovedObjects.Add(spFileInfo->GetObjectID()); - } - m_vFiles.clear(); -} + boost::shared_lock lock(m_lock); -unsigned long long TFileInfoArray::CalculateTotalSize() const -{ - unsigned long long ullSize = 0; + if (fcIndex >= m_vFiles.size()) + THROW(_T("Out of bounds"), 0, 0, 0); + const TFileInfoPtr& spInfo = m_vFiles.at(boost::numeric_cast(fcIndex)); + if (!spInfo) + THROW(_T("Invalid pointer"), 0, 0, 0); - boost::shared_lock lock(m_lock); - BOOST_FOREACH(const TFileInfoPtr& spFileInfo, m_vFiles) + return *spInfo; + } + + void TFileInfoArray::Clear() { - ullSize += spFileInfo->GetLength64(); + boost::unique_lock lock(m_lock); + m_bComplete = false; + BOOST_FOREACH(const TFileInfoPtr& spFileInfo, m_vFiles) + { + m_setRemovedObjects.Add(spFileInfo->GetObjectID()); + } + m_vFiles.clear(); } - return ullSize; -} + unsigned long long TFileInfoArray::CalculateTotalSize() const + { + unsigned long long ullSize = 0; -void TFileInfoArray::SetComplete(bool bComplete) -{ - boost::unique_lock lock(m_lock); - m_bComplete = bComplete; -} + boost::shared_lock lock(m_lock); + BOOST_FOREACH(const TFileInfoPtr& spFileInfo, m_vFiles) + { + ullSize += spFileInfo->GetLength64(); + } -bool TFileInfoArray::IsComplete() const -{ - boost::shared_lock lock(m_lock); - return m_bComplete; -} + return ullSize; + } -unsigned long long TFileInfoArray::CalculatePartialSize(file_count_t fcCount) -{ - unsigned long long ullSize = 0; + void TFileInfoArray::SetComplete(bool bComplete) + { + boost::unique_lock lock(m_lock); + m_bComplete = bComplete; + } - boost::shared_lock lock(m_lock); - if(fcCount > m_vFiles.size()) - THROW(_T("Invalid argument"), 0, 0, 0); - - for(std::vector::iterator iter = m_vFiles.begin(); iter != m_vFiles.begin() + boost::numeric_cast(fcCount); ++iter) + bool TFileInfoArray::IsComplete() const { - ullSize += (*iter)->GetLength64(); + boost::shared_lock lock(m_lock); + return m_bComplete; } - return ullSize; -} + unsigned long long TFileInfoArray::CalculatePartialSize(file_count_t fcCount) + { + unsigned long long ullSize = 0; -void TFileInfoArray::Store(const ISerializerContainerPtr& spContainer) const -{ - boost::shared_lock lock(m_lock); + boost::shared_lock lock(m_lock); + if (fcCount > m_vFiles.size()) + THROW(_T("Invalid argument"), 0, 0, 0); - InitColumns(spContainer); + for (std::vector::iterator iter = m_vFiles.begin(); iter != m_vFiles.begin() + boost::numeric_cast(fcCount); ++iter) + { + ullSize += (*iter)->GetLength64(); + } - // store only if there is a complete collection of items inside - // (this container is used in the directory scanning process. There is no - // point storing only partially scanned data in the serializer as we - // can't use this data after loading serialized data (dir scan will have - // to scan again)). - if(m_bComplete) + return ullSize; + } + + void TFileInfoArray::Store(const ISerializerContainerPtr& spContainer) const { - spContainer->DeleteRows(m_setRemovedObjects); - m_setRemovedObjects.Clear(); + boost::shared_lock lock(m_lock); - BOOST_FOREACH(const TFileInfoPtr& spFileInfo, m_vFiles) + InitColumns(spContainer); + + // store only if there is a complete collection of items inside + // (this container is used in the directory scanning process. There is no + // point storing only partially scanned data in the serializer as we + // can't use this data after loading serialized data (dir scan will have + // to scan again)). + if (m_bComplete) { - spFileInfo->Store(spContainer); + spContainer->DeleteRows(m_setRemovedObjects); + m_setRemovedObjects.Clear(); + + BOOST_FOREACH(const TFileInfoPtr& spFileInfo, m_vFiles) + { + spFileInfo->Store(spContainer); + } } } -} -void TFileInfoArray::Load(const ISerializerContainerPtr& spContainer, const TBasePathDataContainerPtr& spBasePaths) -{ - InitColumns(spContainer); - - std::vector vEntries; - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - while(spRowReader->Next()) + void TFileInfoArray::Load(const ISerializerContainerPtr& spContainer, const TBasePathDataContainerPtr& spBasePaths) { - TFileInfoPtr spFileInfo(new TFileInfo); - spFileInfo->Load(spRowReader, spBasePaths); + InitColumns(spContainer); - vEntries.push_back(spFileInfo); + std::vector vEntries; + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + while (spRowReader->Next()) + { + TFileInfoPtr spFileInfo(new TFileInfo); + spFileInfo->Load(spRowReader, spBasePaths); - m_oidLastObjectID = std::max(m_oidLastObjectID, spFileInfo->GetObjectID()); - } + vEntries.push_back(spFileInfo); - boost::unique_lock lock(m_lock); - m_vFiles = std::move(vEntries); - m_bComplete = !m_vFiles.empty(); // we're marking empty/non-empty based on scanned file count; this is due to the - // fact, that no scanned files are stored in DB unless scanning is complete; -} + m_oidLastObjectID = std::max(m_oidLastObjectID, spFileInfo->GetObjectID()); + } -void TFileInfoArray::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) - TFileInfo::InitColumns(rColumns); -} + boost::unique_lock lock(m_lock); + m_vFiles = std::move(vEntries); + m_bComplete = !m_vFiles.empty(); // we're marking empty/non-empty based on scanned file count; this is due to the + // fact, that no scanned files are stored in DB unless scanning is complete; + } -END_CHCORE_NAMESPACE + void TFileInfoArray::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TFileInfo::InitColumns(rColumns); + } +} Index: src/libchcore/TFileInfoArray.h =================================================================== diff -u -N -re92d7e2b63df1305b23aa04132c45ad8747dc22c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileInfoArray.h (.../TFileInfoArray.h) (revision e92d7e2b63df1305b23aa04132c45ad8747dc22c) +++ src/libchcore/TFileInfoArray.h (.../TFileInfoArray.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -27,59 +27,58 @@ #include "TBasePathData.h" #include "CommonDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -class TFileInfo; -typedef boost::shared_ptr TFileInfoPtr; - -class LIBCHCORE_API TFileInfoArray +namespace chcore { -public: - TFileInfoArray(); - ~TFileInfoArray(); + class TFileInfo; + typedef boost::shared_ptr TFileInfoPtr; - // Adds a new object info to this container - void AddFileInfo(const TFileInfoPtr& spFileInfo); + class LIBCHCORE_API TFileInfoArray + { + public: + TFileInfoArray(); + ~TFileInfoArray(); - /// Retrieves count of elements in this object - file_count_t GetSize() const; + // Adds a new object info to this container + void AddFileInfo(const TFileInfoPtr& spFileInfo); - /// Retrieves an element at the specified index - TFileInfoPtr GetAt(file_count_t stIndex) const; + /// Retrieves count of elements in this object + file_count_t GetSize() const; - /// Retrieves a copy of the element at a specified index - TFileInfo GetCopyAt(file_count_t stIndex) const; + /// Retrieves an element at the specified index + TFileInfoPtr GetAt(file_count_t stIndex) const; - /// Removes all elements from this object - void Clear(); + /// Retrieves a copy of the element at a specified index + TFileInfo GetCopyAt(file_count_t stIndex) const; - // specialized operations on contents of m_vFiles - /// Calculates the size of the first fcCount file info objects - unsigned long long CalculatePartialSize(file_count_t fcCount); + /// Removes all elements from this object + void Clear(); - /// Calculates the size of all file info objects inside this object - unsigned long long CalculateTotalSize() const; + // specialized operations on contents of m_vFiles + /// Calculates the size of the first fcCount file info objects + unsigned long long CalculatePartialSize(file_count_t fcCount); - void SetComplete(bool bComplete); - bool IsComplete() const; + /// Calculates the size of all file info objects inside this object + unsigned long long CalculateTotalSize() const; - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer, const TBasePathDataContainerPtr& spBasePaths); + void SetComplete(bool bComplete); + bool IsComplete() const; - void InitColumns(const ISerializerContainerPtr& spContainer) const; + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer, const TBasePathDataContainerPtr& spBasePaths); -protected: - bool m_bComplete; + void InitColumns(const ISerializerContainerPtr& spContainer) const; + protected: + bool m_bComplete; + #pragma warning(push) #pragma warning(disable: 4251) - mutable TRemovedObjects m_setRemovedObjects; - std::vector m_vFiles; - mutable boost::shared_mutex m_lock; + mutable TRemovedObjects m_setRemovedObjects; + std::vector m_vFiles; + mutable boost::shared_mutex m_lock; #pragma warning(pop) - object_id_t m_oidLastObjectID; -}; + object_id_t m_oidLastObjectID; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TFileInfoFwd.h =================================================================== diff -u -N -re8c6030871e49b16323212d81f827e1e130c8d48 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileInfoFwd.h (.../TFileInfoFwd.h) (revision e8c6030871e49b16323212d81f827e1e130c8d48) +++ src/libchcore/TFileInfoFwd.h (.../TFileInfoFwd.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,11 +21,10 @@ #include -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + class TFileInfo; + typedef boost::shared_ptr TFileInfoPtr; +} -class TFileInfo; -typedef boost::shared_ptr TFileInfoPtr; - -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TFileTime.cpp =================================================================== diff -u -N -ra5aa3c3cb78f3767641de2627d1a49a1dc35b429 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileTime.cpp (.../TFileTime.cpp) (revision a5aa3c3cb78f3767641de2627d1a49a1dc35b429) +++ src/libchcore/TFileTime.cpp (.../TFileTime.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,76 +19,75 @@ #include "stdafx.h" #include "TFileTime.h" -BEGIN_CHCORE_NAMESPACE - -TFileTime::TFileTime() +namespace chcore { - m_ftTime.dwHighDateTime = 0; - m_ftTime.dwLowDateTime = 0; -} + TFileTime::TFileTime() + { + m_ftTime.dwHighDateTime = 0; + m_ftTime.dwLowDateTime = 0; + } -TFileTime::TFileTime(const TFileTime& rSrc) : - m_ftTime(rSrc.m_ftTime) -{ -} + TFileTime::TFileTime(const TFileTime& rSrc) : + m_ftTime(rSrc.m_ftTime) + { + } -TFileTime::TFileTime(const FILETIME& rftTime) : - m_ftTime(rftTime) -{ -} + TFileTime::TFileTime(const FILETIME& rftTime) : + m_ftTime(rftTime) + { + } -TFileTime::~TFileTime() -{ -} - -TFileTime& TFileTime::operator=(const TFileTime& rSrc) -{ - if(this != &rSrc) + TFileTime::~TFileTime() { - m_ftTime = rSrc.m_ftTime; } - return *this; -} + TFileTime& TFileTime::operator=(const TFileTime& rSrc) + { + if (this != &rSrc) + { + m_ftTime = rSrc.m_ftTime; + } -TFileTime& TFileTime::operator=(const FILETIME& rSrc) -{ - m_ftTime = rSrc; + return *this; + } - return *this; -} + TFileTime& TFileTime::operator=(const FILETIME& rSrc) + { + m_ftTime = rSrc; + return *this; + } -bool TFileTime::operator==(const TFileTime& rSrc) const -{ - return m_ftTime.dwHighDateTime == rSrc.m_ftTime.dwHighDateTime && m_ftTime.dwLowDateTime == rSrc.m_ftTime.dwLowDateTime; -} -bool TFileTime::operator!=(const TFileTime& rSrc) const -{ - return m_ftTime.dwHighDateTime != rSrc.m_ftTime.dwHighDateTime || m_ftTime.dwLowDateTime != rSrc.m_ftTime.dwLowDateTime; -} + bool TFileTime::operator==(const TFileTime& rSrc) const + { + return m_ftTime.dwHighDateTime == rSrc.m_ftTime.dwHighDateTime && m_ftTime.dwLowDateTime == rSrc.m_ftTime.dwLowDateTime; + } -void TFileTime::FromUInt64(unsigned long long ullTime) -{ - ULARGE_INTEGER uli; - uli.QuadPart = ullTime; - m_ftTime.dwLowDateTime = uli.LowPart; - m_ftTime.dwHighDateTime = uli.HighPart; -} + bool TFileTime::operator!=(const TFileTime& rSrc) const + { + return m_ftTime.dwHighDateTime != rSrc.m_ftTime.dwHighDateTime || m_ftTime.dwLowDateTime != rSrc.m_ftTime.dwLowDateTime; + } -unsigned long long TFileTime::ToUInt64() const -{ - ULARGE_INTEGER uli; - uli.HighPart = m_ftTime.dwHighDateTime; - uli.LowPart = m_ftTime.dwLowDateTime; + void TFileTime::FromUInt64(unsigned long long ullTime) + { + ULARGE_INTEGER uli; + uli.QuadPart = ullTime; + m_ftTime.dwLowDateTime = uli.LowPart; + m_ftTime.dwHighDateTime = uli.HighPart; + } - return uli.QuadPart; -} + unsigned long long TFileTime::ToUInt64() const + { + ULARGE_INTEGER uli; + uli.HighPart = m_ftTime.dwHighDateTime; + uli.LowPart = m_ftTime.dwLowDateTime; -const FILETIME& TFileTime::GetAsFiletime() const -{ - return m_ftTime; -} + return uli.QuadPart; + } -END_CHCORE_NAMESPACE + const FILETIME& TFileTime::GetAsFiletime() const + { + return m_ftTime; + } +} Index: src/libchcore/TFileTime.h =================================================================== diff -u -N -ra5aa3c3cb78f3767641de2627d1a49a1dc35b429 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TFileTime.h (.../TFileTime.h) (revision a5aa3c3cb78f3767641de2627d1a49a1dc35b429) +++ src/libchcore/TFileTime.h (.../TFileTime.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,33 +21,32 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TFileTime +namespace chcore { -public: - TFileTime(); - TFileTime(const FILETIME& rftTime); - TFileTime(const TFileTime& rSrc); - ~TFileTime(); + class LIBCHCORE_API TFileTime + { + public: + TFileTime(); + TFileTime(const FILETIME& rftTime); + TFileTime(const TFileTime& rSrc); + ~TFileTime(); - TFileTime& operator=(const TFileTime& rSrc); - TFileTime& operator=(const FILETIME& rSrc); + TFileTime& operator=(const TFileTime& rSrc); + TFileTime& operator=(const FILETIME& rSrc); - bool operator==(const TFileTime& rSrc) const; - bool operator!=(const TFileTime& rSrc) const; + bool operator==(const TFileTime& rSrc) const; + bool operator!=(const TFileTime& rSrc) const; - const FILETIME& GetAsFiletime() const; - - void FromUInt64(unsigned long long ullTime); - unsigned long long ToUInt64() const; + const FILETIME& GetAsFiletime() const; -private: - FILETIME m_ftTime; -}; + void FromUInt64(unsigned long long ullTime); + unsigned long long ToUInt64() const; -typedef boost::shared_ptr TFileTimePtr; + private: + FILETIME m_ftTime; + }; -END_CHCORE_NAMESPACE + typedef boost::shared_ptr TFileTimePtr; +} #endif Index: src/libchcore/TLocalFilesystem.cpp =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TLocalFilesystem.cpp (.../TLocalFilesystem.cpp) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/TLocalFilesystem.cpp (.../TLocalFilesystem.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -45,288 +45,284 @@ #include #include "TLocalFilesystemFind.h" -BEGIN_CHCORE_NAMESPACE - -TLocalFilesystem::TLocalFilesystem() +namespace chcore { -} + TLocalFilesystem::TLocalFilesystem() + { + } -TLocalFilesystem::~TLocalFilesystem() -{ -} + TLocalFilesystem::~TLocalFilesystem() + { + } -UINT TLocalFilesystem::GetDriveData(const TSmartPath& spPath) -{ - UINT uiDrvType = DRIVE_UNKNOWN; - if(!spPath.IsNetworkPath()) + UINT TLocalFilesystem::GetDriveData(const TSmartPath& spPath) { - if(!spPath.IsEmpty()) + UINT uiDrvType = DRIVE_UNKNOWN; + if (!spPath.IsNetworkPath()) { - TSmartPath pathDrive = spPath.GetDrive(); - pathDrive.AppendSeparatorIfDoesNotExist(); + if (!spPath.IsEmpty()) + { + TSmartPath pathDrive = spPath.GetDrive(); + pathDrive.AppendSeparatorIfDoesNotExist(); - uiDrvType = GetDriveType(pathDrive.ToString()); - if(uiDrvType == DRIVE_NO_ROOT_DIR) - uiDrvType = DRIVE_UNKNOWN; + uiDrvType = GetDriveType(pathDrive.ToString()); + if (uiDrvType == DRIVE_NO_ROOT_DIR) + uiDrvType = DRIVE_UNKNOWN; + } } + else + uiDrvType = DRIVE_REMOTE; + + return uiDrvType; } - else - uiDrvType = DRIVE_REMOTE; - return uiDrvType; -} + bool TLocalFilesystem::PathExist(const TSmartPath& pathToCheck) + { + WIN32_FIND_DATA fd; -bool TLocalFilesystem::PathExist(const TSmartPath& pathToCheck) -{ - WIN32_FIND_DATA fd; + // search by exact name + HANDLE hFind = FindFirstFile(PrependPathExtensionIfNeeded(pathToCheck).ToString(), &fd); + if (hFind != INVALID_HANDLE_VALUE) + { + FindClose(hFind); + return true; + } - // search by exact name - HANDLE hFind = FindFirstFile(PrependPathExtensionIfNeeded(pathToCheck).ToString(), &fd); - if(hFind != INVALID_HANDLE_VALUE) - { - FindClose(hFind); - return true; + // another try (add '\\' if needed and '*' for marking that we look for ie. c:\* + // instead of c:\, which would never be found prev. way) + TSmartPath findPath = pathToCheck; + findPath.AppendIfNotExists(_T("*"), false); + + hFind = FindFirstFile(PrependPathExtensionIfNeeded(findPath).ToString(), &fd); + if (hFind != INVALID_HANDLE_VALUE) + { + ::FindClose(hFind); + return true; + } + else + return false; } - // another try (add '\\' if needed and '*' for marking that we look for ie. c:\* - // instead of c:\, which would never be found prev. way) - TSmartPath findPath = pathToCheck; - findPath.AppendIfNotExists(_T("*"), false); - - hFind = FindFirstFile(PrependPathExtensionIfNeeded(findPath).ToString(), &fd); - if(hFind != INVALID_HANDLE_VALUE) + bool TLocalFilesystem::SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) { - ::FindClose(hFind); - return true; - } - else - return false; -} + TAutoFileHandle hFile = CreateFile(PrependPathExtensionIfNeeded(pathFileDir).ToString(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (hFile == INVALID_HANDLE_VALUE) + return false; -bool TLocalFilesystem::SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) -{ - TAutoFileHandle hFile = CreateFile(PrependPathExtensionIfNeeded(pathFileDir).ToString(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL); - if(hFile == INVALID_HANDLE_VALUE) - return false; + BOOL bResult = SetFileTime(hFile, &ftCreationTime.GetAsFiletime(), &ftLastAccessTime.GetAsFiletime(), &ftLastWriteTime.GetAsFiletime()); - BOOL bResult = SetFileTime(hFile, &ftCreationTime.GetAsFiletime(), &ftLastAccessTime.GetAsFiletime(), &ftLastWriteTime.GetAsFiletime()); + if (!hFile.Close()) + return false; - if(!hFile.Close()) - return false; + return bResult != FALSE; + } - return bResult != FALSE; -} - -bool TLocalFilesystem::SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) -{ - return ::SetFileAttributes(PrependPathExtensionIfNeeded(pathFileDir).ToString(), dwAttributes) != FALSE; -} - -bool TLocalFilesystem::CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) -{ - if(!bCreateFullPath) - return ::CreateDirectory(PrependPathExtensionIfNeeded(pathDirectory).ToString(), NULL) != FALSE; - else + bool TLocalFilesystem::SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) { - TPathContainer vComponents; - pathDirectory.SplitPath(vComponents); + return ::SetFileAttributes(PrependPathExtensionIfNeeded(pathFileDir).ToString(), dwAttributes) != FALSE; + } - TSmartPath pathToTest; - for(size_t stIndex = 0; stIndex < vComponents.GetCount(); ++stIndex) + bool TLocalFilesystem::CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) + { + if (!bCreateFullPath) + return ::CreateDirectory(PrependPathExtensionIfNeeded(pathDirectory).ToString(), NULL) != FALSE; + else { - const TSmartPath& pathComponent = vComponents.GetAt(stIndex); + TPathContainer vComponents; + pathDirectory.SplitPath(vComponents); - pathToTest += pathComponent; - // try to create subsequent paths - if(!pathToTest.IsDrive() && !pathToTest.IsServerName()) + TSmartPath pathToTest; + for (size_t stIndex = 0; stIndex < vComponents.GetCount(); ++stIndex) { - // try to create the specified path - BOOL bRes = ::CreateDirectory(PrependPathExtensionIfNeeded(pathToTest).ToString(), NULL); - if(!bRes && GetLastError() != ERROR_ALREADY_EXISTS) - return false; + const TSmartPath& pathComponent = vComponents.GetAt(stIndex); + + pathToTest += pathComponent; + // try to create subsequent paths + if (!pathToTest.IsDrive() && !pathToTest.IsServerName()) + { + // try to create the specified path + BOOL bRes = ::CreateDirectory(PrependPathExtensionIfNeeded(pathToTest).ToString(), NULL); + if (!bRes && GetLastError() != ERROR_ALREADY_EXISTS) + return false; + } } } + + return true; } - return true; -} + bool TLocalFilesystem::RemoveDirectory(const TSmartPath& pathFile) + { + return ::RemoveDirectory(PrependPathExtensionIfNeeded(pathFile).ToString()) != FALSE; + } -bool TLocalFilesystem::RemoveDirectory(const TSmartPath& pathFile) -{ - return ::RemoveDirectory(PrependPathExtensionIfNeeded(pathFile).ToString()) != FALSE; -} + bool TLocalFilesystem::DeleteFile(const TSmartPath& pathFile) + { + return ::DeleteFile(PrependPathExtensionIfNeeded(pathFile).ToString()) != FALSE; + } -bool TLocalFilesystem::DeleteFile(const TSmartPath& pathFile) -{ - return ::DeleteFile(PrependPathExtensionIfNeeded(pathFile).ToString()) != FALSE; -} + bool TLocalFilesystem::GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData) + { + if (!rFileInfo) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); -bool TLocalFilesystem::GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData) -{ - if(!rFileInfo) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + WIN32_FIND_DATA wfd; + HANDLE hFind = FindFirstFile(PrependPathExtensionIfNeeded(pathFile).ToString(), &wfd); - WIN32_FIND_DATA wfd; - HANDLE hFind = FindFirstFile(PrependPathExtensionIfNeeded(pathFile).ToString(), &wfd); + if (hFind != INVALID_HANDLE_VALUE) + { + FindClose(hFind); - if(hFind != INVALID_HANDLE_VALUE) - { - FindClose(hFind); + // new instance of path to accomodate the corrected path (i.e. input path might have lower case names, but we'd like to + // preserve the original case contained in the filesystem) + TSmartPath pathNew(pathFile); + pathNew.DeleteFileName(); - // new instance of path to accomodate the corrected path (i.e. input path might have lower case names, but we'd like to - // preserve the original case contained in the filesystem) - TSmartPath pathNew(pathFile); - pathNew.DeleteFileName(); + // copy data from W32_F_D + rFileInfo->Init(spBasePathData, pathNew + PathFromString(wfd.cFileName), + wfd.dwFileAttributes, (((ULONGLONG)wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow, wfd.ftCreationTime, + wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); - // copy data from W32_F_D - rFileInfo->Init(spBasePathData, pathNew + PathFromString(wfd.cFileName), - wfd.dwFileAttributes, (((ULONGLONG) wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow, wfd.ftCreationTime, - wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); + return true; + } + else + { + FILETIME fi = { 0, 0 }; + rFileInfo->Init(TSmartPath(), (DWORD)-1, 0, fi, fi, fi, 0); + return false; + } + } - return true; + bool TLocalFilesystem::FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) + { + return ::MoveFile(PrependPathExtensionIfNeeded(pathSource).ToString(), PrependPathExtensionIfNeeded(pathDestination).ToString()) != FALSE; } - else + + IFilesystemFindPtr TLocalFilesystem::CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) { - FILETIME fi = { 0, 0 }; - rFileInfo->Init(TSmartPath(), (DWORD)-1, 0, fi, fi, fi, 0); - return false; + return std::shared_ptr(new TLocalFilesystemFind(pathDir, pathMask)); } -} -bool TLocalFilesystem::FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) -{ - return ::MoveFile(PrependPathExtensionIfNeeded(pathSource).ToString(), PrependPathExtensionIfNeeded(pathDestination).ToString()) != FALSE; -} + IFilesystemFilePtr TLocalFilesystem::CreateFileObject(const TSmartPath& pathFile) + { + return std::shared_ptr(new TLocalFilesystemFile(pathFile)); + } -IFilesystemFindPtr TLocalFilesystem::CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) -{ - return std::shared_ptr(new TLocalFilesystemFind(pathDir, pathMask)); -} + TSmartPath TLocalFilesystem::PrependPathExtensionIfNeeded(const TSmartPath& pathInput) + { + if (pathInput.GetLength() >= 248) + return PathFromString(_T("\\\\?\\")) + pathInput; + else + return pathInput; + } -IFilesystemFilePtr TLocalFilesystem::CreateFileObject(const TSmartPath& pathFile) -{ - return std::shared_ptr(new TLocalFilesystemFile(pathFile)); -} - -TSmartPath TLocalFilesystem::PrependPathExtensionIfNeeded(const TSmartPath& pathInput) -{ - if(pathInput.GetLength() >= 248) - return PathFromString(_T("\\\\?\\")) + pathInput; - else - return pathInput; -} - -TLocalFilesystem::EPathsRelation TLocalFilesystem::GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) -{ - if(pathFirst.IsEmpty() || pathSecond.IsEmpty()) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); - - // get information about both paths - UINT uiFirstDriveType = 0; - uiFirstDriveType = GetDriveData(pathFirst); - - UINT uiSecondDriveType = 0; - uiSecondDriveType = GetDriveData(pathSecond); - - // what kind of relation... - EPathsRelation eRelation = eRelation_Other; - if(uiFirstDriveType == DRIVE_REMOTE || uiSecondDriveType == DRIVE_REMOTE) - eRelation = eRelation_Network; - else if(uiFirstDriveType == DRIVE_CDROM || uiSecondDriveType == DRIVE_CDROM) - eRelation = eRelation_CDRom; - else if(uiFirstDriveType == DRIVE_FIXED && uiSecondDriveType == DRIVE_FIXED) + TLocalFilesystem::EPathsRelation TLocalFilesystem::GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) { - // two hdd's - is this the same physical disk ? - wchar_t wchFirstDrive = pathFirst.GetDriveLetter(); - wchar_t wchSecondDrive = pathSecond.GetDriveLetter(); + if (pathFirst.IsEmpty() || pathSecond.IsEmpty()) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - if(wchFirstDrive == L'\0' || wchSecondDrive == L'\0') - THROW_CORE_EXCEPTION(eErr_FixedDriveWithoutDriveLetter); + // get information about both paths + UINT uiFirstDriveType = 0; + uiFirstDriveType = GetDriveData(pathFirst); - if(wchFirstDrive == wchSecondDrive) - eRelation = eRelation_SinglePhysicalDisk; - else + UINT uiSecondDriveType = 0; + uiSecondDriveType = GetDriveData(pathSecond); + + // what kind of relation... + EPathsRelation eRelation = eRelation_Other; + if (uiFirstDriveType == DRIVE_REMOTE || uiSecondDriveType == DRIVE_REMOTE) + eRelation = eRelation_Network; + else if (uiFirstDriveType == DRIVE_CDROM || uiSecondDriveType == DRIVE_CDROM) + eRelation = eRelation_CDRom; + else if (uiFirstDriveType == DRIVE_FIXED && uiSecondDriveType == DRIVE_FIXED) { - DWORD dwFirstPhysicalDisk = GetPhysicalDiskNumber(wchFirstDrive); - DWORD dwSecondPhysicalDisk = GetPhysicalDiskNumber(wchSecondDrive); - if(dwFirstPhysicalDisk == std::numeric_limits::max() || dwSecondPhysicalDisk == std::numeric_limits::max()) - { - // NOTE: disabled throwing an exception here - when testing, it came out that some DRIVE_FIXED - // volumes might have problems handling this detection (TrueCrypt volumes for example). - // So for now we report it as two different physical disks. - //THROW(_T("Problem with physical disk detection"), 0, 0, 0); - eRelation = eRelation_TwoPhysicalDisks; - } + // two hdd's - is this the same physical disk ? + wchar_t wchFirstDrive = pathFirst.GetDriveLetter(); + wchar_t wchSecondDrive = pathSecond.GetDriveLetter(); - if(dwFirstPhysicalDisk == dwSecondPhysicalDisk) + if (wchFirstDrive == L'\0' || wchSecondDrive == L'\0') + THROW_CORE_EXCEPTION(eErr_FixedDriveWithoutDriveLetter); + + if (wchFirstDrive == wchSecondDrive) eRelation = eRelation_SinglePhysicalDisk; else - eRelation = eRelation_TwoPhysicalDisks; + { + DWORD dwFirstPhysicalDisk = GetPhysicalDiskNumber(wchFirstDrive); + DWORD dwSecondPhysicalDisk = GetPhysicalDiskNumber(wchSecondDrive); + if (dwFirstPhysicalDisk == std::numeric_limits::max() || dwSecondPhysicalDisk == std::numeric_limits::max()) + { + // NOTE: disabled throwing an exception here - when testing, it came out that some DRIVE_FIXED + // volumes might have problems handling this detection (TrueCrypt volumes for example). + // So for now we report it as two different physical disks. + //THROW(_T("Problem with physical disk detection"), 0, 0, 0); + eRelation = eRelation_TwoPhysicalDisks; + } + + if (dwFirstPhysicalDisk == dwSecondPhysicalDisk) + eRelation = eRelation_SinglePhysicalDisk; + else + eRelation = eRelation_TwoPhysicalDisks; + } } + + return eRelation; } - return eRelation; -} - -DWORD TLocalFilesystem::GetPhysicalDiskNumber(wchar_t wchDrive) -{ + DWORD TLocalFilesystem::GetPhysicalDiskNumber(wchar_t wchDrive) { - boost::shared_lock lock(m_lockDriveLetterToPhysicalDisk); + { + boost::shared_lock lock(m_lockDriveLetterToPhysicalDisk); - std::map::iterator iterMap = m_mapDriveLetterToPhysicalDisk.find(wchDrive); - if(iterMap != m_mapDriveLetterToPhysicalDisk.end()) - return (*iterMap).second; - } + std::map::iterator iterMap = m_mapDriveLetterToPhysicalDisk.find(wchDrive); + if (iterMap != m_mapDriveLetterToPhysicalDisk.end()) + return (*iterMap).second; + } - wchar_t szDrive[] = { L'\\', L'\\', L'.', L'\\', wchDrive, L':', L'\0' }; + wchar_t szDrive[] = { L'\\', L'\\', L'.', L'\\', wchDrive, L':', L'\0' }; - HANDLE hDevice = CreateFile(szDrive, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - if(hDevice == INVALID_HANDLE_VALUE) - return std::numeric_limits::max(); + HANDLE hDevice = CreateFile(szDrive, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + if (hDevice == INVALID_HANDLE_VALUE) + return std::numeric_limits::max(); - // buffer for data (cannot make member nor static because this function might be called by many threads at once) - // buffer is larger than one extent to allow getting information in multi-extent volumes (raid?) - const int stSize = sizeof(VOLUME_DISK_EXTENTS) + 20 * sizeof(DISK_EXTENT); - boost::shared_array spData(new BYTE[stSize]); + // buffer for data (cannot make member nor static because this function might be called by many threads at once) + // buffer is larger than one extent to allow getting information in multi-extent volumes (raid?) + const int stSize = sizeof(VOLUME_DISK_EXTENTS) + 20 * sizeof(DISK_EXTENT); + boost::shared_array spData(new BYTE[stSize]); - VOLUME_DISK_EXTENTS* pVolumeDiskExtents = (VOLUME_DISK_EXTENTS*)spData.get(); - DWORD dwBytesReturned = 0; - BOOL bResult = DeviceIoControl(hDevice, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, pVolumeDiskExtents, stSize, &dwBytesReturned, NULL); - if(!bResult) - { - // NOTE: when ERROR_INVALID_FUNCTION is reported here, it probably means that underlying volume - // cannot support IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS properly (such case includes TrueCrypt volumes) - return std::numeric_limits::max(); - } + VOLUME_DISK_EXTENTS* pVolumeDiskExtents = (VOLUME_DISK_EXTENTS*)spData.get(); + DWORD dwBytesReturned = 0; + BOOL bResult = DeviceIoControl(hDevice, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, pVolumeDiskExtents, stSize, &dwBytesReturned, NULL); + if (!bResult) + { + // NOTE: when ERROR_INVALID_FUNCTION is reported here, it probably means that underlying volume + // cannot support IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS properly (such case includes TrueCrypt volumes) + return std::numeric_limits::max(); + } - CloseHandle(hDevice); + CloseHandle(hDevice); - if(pVolumeDiskExtents->NumberOfDiskExtents == 0) - return std::numeric_limits::max(); + if (pVolumeDiskExtents->NumberOfDiskExtents == 0) + return std::numeric_limits::max(); - DISK_EXTENT* pDiskExtent = &pVolumeDiskExtents->Extents[0]; + DISK_EXTENT* pDiskExtent = &pVolumeDiskExtents->Extents[0]; - boost::unique_lock lock(m_lockDriveLetterToPhysicalDisk); - m_mapDriveLetterToPhysicalDisk.insert(std::make_pair(wchDrive, pDiskExtent->DiskNumber)); + boost::unique_lock lock(m_lockDriveLetterToPhysicalDisk); + m_mapDriveLetterToPhysicalDisk.insert(std::make_pair(wchDrive, pDiskExtent->DiskNumber)); - return pDiskExtent->DiskNumber; -} + return pDiskExtent->DiskNumber; + } -bool TLocalFilesystem::GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree) -{ - rullFree = 0; - - ULARGE_INTEGER ui64Available, ui64Total; - if(GetDiskFreeSpaceEx(path.ToString(), &ui64Available, &ui64Total, NULL)) + bool TLocalFilesystem::GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree) { - rullFree = ui64Available.QuadPart; - return true; + rullFree = 0; + + ULARGE_INTEGER ui64Available, ui64Total; + if (GetDiskFreeSpaceEx(path.ToString(), &ui64Available, &ui64Total, NULL)) + { + rullFree = ui64Available.QuadPart; + return true; + } + else + return false; } - else - return false; } - -///////////////////////////////////////////////////////////////////////////////////// -// class TLocalFilesystemFind - -END_CHCORE_NAMESPACE Index: src/libchcore/TLocalFilesystem.h =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TLocalFilesystem.h (.../TLocalFilesystem.h) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/TLocalFilesystem.h (.../TLocalFilesystem.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -29,56 +29,55 @@ #include "TFileInfoFwd.h" #include "IFilesystem.h" -BEGIN_CHCORE_NAMESPACE - -class TAutoFileHandle; -class TLocalFilesystemFind; -class TLocalFilesystemFile; -class TSimpleDataBuffer; -class TFileTime; -class TOverlappedDataBuffer; - -class LIBCHCORE_API TLocalFilesystem : public IFilesystem +namespace chcore { -public: - TLocalFilesystem(); - virtual ~TLocalFilesystem(); + class TAutoFileHandle; + class TLocalFilesystemFind; + class TLocalFilesystemFile; + class TSimpleDataBuffer; + class TFileTime; + class TOverlappedDataBuffer; - virtual bool PathExist(const TSmartPath& strPath) override; // check for file or folder existence + class LIBCHCORE_API TLocalFilesystem : public IFilesystem + { + public: + TLocalFilesystem(); + virtual ~TLocalFilesystem(); - virtual bool SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) override; - virtual bool SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) override; + virtual bool PathExist(const TSmartPath& strPath) override; // check for file or folder existence - virtual bool CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) override; - virtual bool RemoveDirectory(const TSmartPath& pathFile) override; - virtual bool DeleteFile(const TSmartPath& pathFile) override; + virtual bool SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) override; + virtual bool SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) override; - virtual bool GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData = TBasePathDataPtr()) override; - virtual bool FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) override; + virtual bool CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) override; + virtual bool RemoveDirectory(const TSmartPath& pathFile) override; + virtual bool DeleteFile(const TSmartPath& pathFile) override; - virtual IFilesystemFindPtr CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) override; - virtual IFilesystemFilePtr CreateFileObject(const TSmartPath& pathFile) override; + virtual bool GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData = TBasePathDataPtr()) override; + virtual bool FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) override; - virtual EPathsRelation GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) override; + virtual IFilesystemFindPtr CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) override; + virtual IFilesystemFilePtr CreateFileObject(const TSmartPath& pathFile) override; - virtual bool GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree) override; + virtual EPathsRelation GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) override; -private: - static TSmartPath PrependPathExtensionIfNeeded(const TSmartPath& pathInput); - static UINT GetDriveData(const TSmartPath& spPath); - DWORD GetPhysicalDiskNumber(wchar_t wchDrive); + virtual bool GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree) override; -private: + private: + static TSmartPath PrependPathExtensionIfNeeded(const TSmartPath& pathInput); + static UINT GetDriveData(const TSmartPath& spPath); + DWORD GetPhysicalDiskNumber(wchar_t wchDrive); + + private: #pragma warning(push) #pragma warning(disable: 4251) - std::map m_mapDriveLetterToPhysicalDisk; // caches drive letter -> physical disk number - boost::shared_mutex m_lockDriveLetterToPhysicalDisk; + std::map m_mapDriveLetterToPhysicalDisk; // caches drive letter -> physical disk number + boost::shared_mutex m_lockDriveLetterToPhysicalDisk; #pragma warning(pop) - friend class TLocalFilesystemFind; - friend class TLocalFilesystemFile; -}; + friend class TLocalFilesystemFind; + friend class TLocalFilesystemFile; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TLocalFilesystemFind.cpp =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TLocalFilesystemFind.cpp (.../TLocalFilesystemFind.cpp) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TLocalFilesystemFind.cpp (.../TLocalFilesystemFind.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,65 +21,64 @@ #include "TLocalFilesystem.h" #include "TFileInfo.h" -BEGIN_CHCORE_NAMESPACE - -TLocalFilesystemFind::TLocalFilesystemFind(const TSmartPath& pathDir, const TSmartPath& pathMask) : - m_pathDir(pathDir), - m_pathMask(pathMask), - m_hFind(INVALID_HANDLE_VALUE) +namespace chcore { -} + TLocalFilesystemFind::TLocalFilesystemFind(const TSmartPath& pathDir, const TSmartPath& pathMask) : + m_pathDir(pathDir), + m_pathMask(pathMask), + m_hFind(INVALID_HANDLE_VALUE) + { + } -TLocalFilesystemFind::~TLocalFilesystemFind() -{ - Close(); -} - -bool TLocalFilesystemFind::FindNext(TFileInfoPtr& rspFileInfo) -{ - WIN32_FIND_DATA wfd; - TSmartPath pathCurrent = m_pathDir + m_pathMask; - - // Iterate through dirs & files - bool bContinue = true; - if (m_hFind != INVALID_HANDLE_VALUE) - bContinue = (FindNextFile(m_hFind, &wfd) != FALSE); - else + TLocalFilesystemFind::~TLocalFilesystemFind() { - m_hFind = FindFirstFile(TLocalFilesystem::PrependPathExtensionIfNeeded(pathCurrent).ToString(), &wfd); // in this case we always continue - bContinue = (m_hFind != INVALID_HANDLE_VALUE); + Close(); } - if (bContinue) + + bool TLocalFilesystemFind::FindNext(TFileInfoPtr& rspFileInfo) { - do + WIN32_FIND_DATA wfd; + TSmartPath pathCurrent = m_pathDir + m_pathMask; + + // Iterate through dirs & files + bool bContinue = true; + if (m_hFind != INVALID_HANDLE_VALUE) + bContinue = (FindNextFile(m_hFind, &wfd) != FALSE); + else { - if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + m_hFind = FindFirstFile(TLocalFilesystem::PrependPathExtensionIfNeeded(pathCurrent).ToString(), &wfd); // in this case we always continue + bContinue = (m_hFind != INVALID_HANDLE_VALUE); + } + if (bContinue) + { + do { - rspFileInfo->Init(m_pathDir + PathFromString(wfd.cFileName), wfd.dwFileAttributes, (((ULONGLONG)wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow, wfd.ftCreationTime, - wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); - return true; - } - else if (wfd.cFileName[0] != _T('.') || (wfd.cFileName[1] != _T('\0') && (wfd.cFileName[1] != _T('.') || wfd.cFileName[2] != _T('\0')))) - { - // Add directory itself - rspFileInfo->Init(m_pathDir + PathFromString(wfd.cFileName), - wfd.dwFileAttributes, (((ULONGLONG)wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow, wfd.ftCreationTime, - wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); - return true; - } - } while (m_hFind != INVALID_HANDLE_VALUE && ::FindNextFile(m_hFind, &wfd)); // checking m_hFind in case other thread changed it (it shouldn't happen though) + if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + { + rspFileInfo->Init(m_pathDir + PathFromString(wfd.cFileName), wfd.dwFileAttributes, (((ULONGLONG)wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow, wfd.ftCreationTime, + wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); + return true; + } + else if (wfd.cFileName[0] != _T('.') || (wfd.cFileName[1] != _T('\0') && (wfd.cFileName[1] != _T('.') || wfd.cFileName[2] != _T('\0')))) + { + // Add directory itself + rspFileInfo->Init(m_pathDir + PathFromString(wfd.cFileName), + wfd.dwFileAttributes, (((ULONGLONG)wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow, wfd.ftCreationTime, + wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); + return true; + } + } while (m_hFind != INVALID_HANDLE_VALUE && ::FindNextFile(m_hFind, &wfd)); // checking m_hFind in case other thread changed it (it shouldn't happen though) - Close(); + Close(); + } + + return false; } - return false; + void TLocalFilesystemFind::Close() + { + if (m_hFind != INVALID_HANDLE_VALUE) + FindClose(m_hFind); + m_hFind = INVALID_HANDLE_VALUE; + } } - -void TLocalFilesystemFind::Close() -{ - if (m_hFind != INVALID_HANDLE_VALUE) - FindClose(m_hFind); - m_hFind = INVALID_HANDLE_VALUE; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TLocalFilesystemFind.h =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TLocalFilesystemFind.h (.../TLocalFilesystemFind.h) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TLocalFilesystemFind.h (.../TLocalFilesystemFind.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,27 +24,26 @@ #include "TPath.h" #include "IFilesystemFind.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TLocalFilesystemFind : public IFilesystemFind +namespace chcore { -public: - virtual ~TLocalFilesystemFind(); + class LIBCHCORE_API TLocalFilesystemFind : public IFilesystemFind + { + public: + virtual ~TLocalFilesystemFind(); - virtual bool FindNext(TFileInfoPtr& rspFileInfo) override; - virtual void Close() override; + virtual bool FindNext(TFileInfoPtr& rspFileInfo) override; + virtual void Close() override; -private: - TLocalFilesystemFind(const TSmartPath& pathDir, const TSmartPath& pathMask); + private: + TLocalFilesystemFind(const TSmartPath& pathDir, const TSmartPath& pathMask); -private: - TSmartPath m_pathDir; - TSmartPath m_pathMask; - HANDLE m_hFind; + private: + TSmartPath m_pathDir; + TSmartPath m_pathMask; + HANDLE m_hFind; - friend class TLocalFilesystem; -}; + friend class TLocalFilesystem; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TLogger.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TLogger.cpp (.../TLogger.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TLogger.cpp (.../TLogger.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,103 +24,102 @@ #include "libchcore.h" #include "TLogger.h" -BEGIN_CHCORE_NAMESPACE - -TLogger TLogger::S_Logger; - -// ============================================================================ -/// TLogger::TLogger -/// @date 2009/05/23 -/// -/// @brief Constructs the TLogger object. -// ============================================================================ -TLogger::TLogger() : - m_bEnabled(false) +namespace chcore { -} + TLogger TLogger::S_Logger; -// ============================================================================ -/// TLogger::Acquire -/// @date 2009/05/20 -/// -/// @brief Acquires logger object. -/// @return Reference to the logger object. -// ============================================================================ -TLogger& TLogger::Acquire() -{ - return S_Logger; -} + // ============================================================================ + /// TLogger::TLogger + /// @date 2009/05/23 + /// + /// @brief Constructs the TLogger object. + // ============================================================================ + TLogger::TLogger() : + m_bEnabled(false) + { + } -// ============================================================================ -/// TLogger::LogDebug -/// @date 2009/05/20 -/// -/// @brief Logs an information to file (debug level). -/// @param[in] pszText Text to be logged. -// ============================================================================ -void TLogger::LogDebug(const tchar_t* pszText) -{ - BOOST_ASSERT(pszText); - if(!pszText) - return; + // ============================================================================ + /// TLogger::Acquire + /// @date 2009/05/20 + /// + /// @brief Acquires logger object. + /// @return Reference to the logger object. + // ============================================================================ + TLogger& TLogger::Acquire() + { + return S_Logger; + } - TLogger& rLogger = Acquire(); - if(rLogger.m_bEnabled && rLogger.is_initialized()) - rLogger.logd(pszText); -} + // ============================================================================ + /// TLogger::LogDebug + /// @date 2009/05/20 + /// + /// @brief Logs an information to file (debug level). + /// @param[in] pszText Text to be logged. + // ============================================================================ + void TLogger::LogDebug(const tchar_t* pszText) + { + BOOST_ASSERT(pszText); + if (!pszText) + return; -// ============================================================================ -/// TLogger::LogInfo -/// @date 2009/05/20 -/// -/// @brief Logs an information to the file (info level). -/// @param[in] pszText Text to be logged. -// ============================================================================ -void TLogger::LogInfo(const tchar_t* pszText) -{ - BOOST_ASSERT(pszText); - if(!pszText) - return; + TLogger& rLogger = Acquire(); + if (rLogger.m_bEnabled && rLogger.is_initialized()) + rLogger.logd(pszText); + } - TLogger& rLogger = Acquire(); - if(rLogger.m_bEnabled && rLogger.is_initialized()) - rLogger.logi(pszText); -} + // ============================================================================ + /// TLogger::LogInfo + /// @date 2009/05/20 + /// + /// @brief Logs an information to the file (info level). + /// @param[in] pszText Text to be logged. + // ============================================================================ + void TLogger::LogInfo(const tchar_t* pszText) + { + BOOST_ASSERT(pszText); + if (!pszText) + return; -// ============================================================================ -/// TLogger::LogWarning -/// @date 2009/05/20 -/// -/// @brief Logs an information to the file (info level). -/// @param[in] pszText Text to be logged. -// ============================================================================ -void TLogger::LogWarning(const tchar_t* pszText) -{ - BOOST_ASSERT(pszText); - if(!pszText) - return; + TLogger& rLogger = Acquire(); + if (rLogger.m_bEnabled && rLogger.is_initialized()) + rLogger.logi(pszText); + } - TLogger& rLogger = Acquire(); - if(rLogger.m_bEnabled && rLogger.is_initialized()) - rLogger.logw(pszText); -} + // ============================================================================ + /// TLogger::LogWarning + /// @date 2009/05/20 + /// + /// @brief Logs an information to the file (info level). + /// @param[in] pszText Text to be logged. + // ============================================================================ + void TLogger::LogWarning(const tchar_t* pszText) + { + BOOST_ASSERT(pszText); + if (!pszText) + return; -// ============================================================================ -/// TLogger::LogError -/// @date 2009/05/20 -/// -/// @brief Logs an information to the file (info level). -/// @param[in] pszText Text to be logged. -// ============================================================================ -void TLogger::LogError(const tchar_t* pszText) -{ - BOOST_ASSERT(pszText); - if(!pszText) - return; + TLogger& rLogger = Acquire(); + if (rLogger.m_bEnabled && rLogger.is_initialized()) + rLogger.logw(pszText); + } - TLogger& rLogger = Acquire(); - if(rLogger.m_bEnabled && rLogger.is_initialized()) - rLogger.loge(pszText); -} + // ============================================================================ + /// TLogger::LogError + /// @date 2009/05/20 + /// + /// @brief Logs an information to the file (info level). + /// @param[in] pszText Text to be logged. + // ============================================================================ + void TLogger::LogError(const tchar_t* pszText) + { + BOOST_ASSERT(pszText); + if (!pszText) + return; -END_CHCORE_NAMESPACE + TLogger& rLogger = Acquire(); + if (rLogger.m_bEnabled && rLogger.is_initialized()) + rLogger.loge(pszText); + } +} Index: src/libchcore/TLogger.h =================================================================== diff -u -N -r95e140c080a7424faba1bc9f35098e3cfd56d4e9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TLogger.h (.../TLogger.h) (revision 95e140c080a7424faba1bc9f35098e3cfd56d4e9) +++ src/libchcore/TLogger.h (.../TLogger.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -38,31 +38,30 @@ #define LOG_ERROR(text)\ chcore::TLogger::LogError(text) -BEGIN_CHCORE_NAMESPACE - -// Class manages logging of informations to a file. -class LIBCHCORE_API TLogger : public icpf::log_file +namespace chcore { -public: - TLogger(); + // Class manages logging of informations to a file. + class LIBCHCORE_API TLogger : public icpf::log_file + { + public: + TLogger(); - // Retrieving global object instance - static TLogger& Acquire(); ///< Acquires the Logger object + // Retrieving global object instance + static TLogger& Acquire(); ///< Acquires the Logger object - // Logging - static void LogDebug(const tchar_t* pszText); - static void LogInfo(const tchar_t* pszText); - static void LogWarning(const tchar_t* pszText); - static void LogError(const tchar_t* pszText); + // Logging + static void LogDebug(const tchar_t* pszText); + static void LogInfo(const tchar_t* pszText); + static void LogWarning(const tchar_t* pszText); + static void LogError(const tchar_t* pszText); - // Initialization/settings - void Enable(bool bEnable) throw() { m_bEnabled = bEnable; } + // Initialization/settings + void Enable(bool bEnable) throw() { m_bEnabled = bEnable; } -protected: - static TLogger S_Logger; - bool m_bEnabled; // logging enabled? -}; + protected: + static TLogger S_Logger; + bool m_bEnabled; // logging enabled? + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TModPathContainer.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TModPathContainer.cpp (.../TModPathContainer.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TModPathContainer.cpp (.../TModPathContainer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,316 +23,315 @@ #include "TPathContainer.h" #include "ISerializerRowData.h" -BEGIN_CHCORE_NAMESPACE - -// ============================================================================ -/// TModPathContainer::TModPathContainer -/// @date 2009/11/30 -/// -/// @brief Constructs an empty path container object. -// ============================================================================ -TModPathContainer::TModPathContainer() : - m_vPaths(), - m_oidNextObjectID(1) +namespace chcore { -} + // ============================================================================ + /// TModPathContainer::TModPathContainer + /// @date 2009/11/30 + /// + /// @brief Constructs an empty path container object. + // ============================================================================ + TModPathContainer::TModPathContainer() : + m_vPaths(), + m_oidNextObjectID(1) + { + } -// ============================================================================ -/// TModPathContainer::TModPathContainer -/// @date 2009/11/30 -/// -/// @brief Constructs the path container object from another path container. -/// @param[in] rSrcContainer - path container to copy paths from. -// ============================================================================ -TModPathContainer::TModPathContainer(const TModPathContainer& rSrcContainer) : - m_vPaths(rSrcContainer.m_vPaths), - m_oidNextObjectID(rSrcContainer.m_oidNextObjectID) -{ -} + // ============================================================================ + /// TModPathContainer::TModPathContainer + /// @date 2009/11/30 + /// + /// @brief Constructs the path container object from another path container. + /// @param[in] rSrcContainer - path container to copy paths from. + // ============================================================================ + TModPathContainer::TModPathContainer(const TModPathContainer& rSrcContainer) : + m_vPaths(rSrcContainer.m_vPaths), + m_oidNextObjectID(rSrcContainer.m_oidNextObjectID) + { + } -// ============================================================================ -/// TModPathContainer::~TModPathContainer -/// @date 2009/11/30 -/// -/// @brief Destructs this path container object. -// ============================================================================ -TModPathContainer::~TModPathContainer() -{ -} - -// ============================================================================ -/// TModPathContainer::operator= -/// @date 2009/11/30 -/// -/// @brief Assigns another path container object to this one. -/// @param[in] rSrcContainer - container with paths to copy from. -/// @return Reference to this object. -// ============================================================================ -TModPathContainer& TModPathContainer::operator=(const TModPathContainer& rSrcContainer) -{ - if(this != &rSrcContainer) + // ============================================================================ + /// TModPathContainer::~TModPathContainer + /// @date 2009/11/30 + /// + /// @brief Destructs this path container object. + // ============================================================================ + TModPathContainer::~TModPathContainer() { - m_vPaths = rSrcContainer.m_vPaths; - m_oidNextObjectID = rSrcContainer.m_oidNextObjectID; } - return *this; -} + // ============================================================================ + /// TModPathContainer::operator= + /// @date 2009/11/30 + /// + /// @brief Assigns another path container object to this one. + /// @param[in] rSrcContainer - container with paths to copy from. + /// @return Reference to this object. + // ============================================================================ + TModPathContainer& TModPathContainer::operator=(const TModPathContainer& rSrcContainer) + { + if (this != &rSrcContainer) + { + m_vPaths = rSrcContainer.m_vPaths; + m_oidNextObjectID = rSrcContainer.m_oidNextObjectID; + } -TModPathContainer& TModPathContainer::operator=(const TPathContainer& rSrcContainer) -{ - Clear(true); + return *this; + } - for(size_t stIndex = 0; stIndex < rSrcContainer.GetCount(); ++stIndex) + TModPathContainer& TModPathContainer::operator=(const TPathContainer& rSrcContainer) { - m_vPaths.insert(std::make_pair(m_oidNextObjectID++, TModificationTracker(rSrcContainer.GetAt(stIndex), true))); - } + Clear(true); - return *this; -} + for (size_t stIndex = 0; stIndex < rSrcContainer.GetCount(); ++stIndex) + { + m_vPaths.insert(std::make_pair(m_oidNextObjectID++, TModificationTracker(rSrcContainer.GetAt(stIndex), true))); + } -// ============================================================================ -/// TModPathContainer::Add -/// @date 2009/11/30 -/// -/// @brief Adds a path to the end of list. -/// @param[in] spPath - path to be added. -// ============================================================================ -void TModPathContainer::Add(const TSmartPath& spPath) -{ - m_vPaths.insert(std::make_pair(m_oidNextObjectID++, TModificationTracker(spPath, true))); -} + return *this; + } -// ============================================================================ -/// TModPathContainer::GetAt -/// @date 2009/11/30 -/// -/// @brief Retrieves path at specified index. -/// @param[in] stIndex - index at which to retrieve item. -/// @return Reference to the path object. -// ============================================================================ -const TSmartPath& TModPathContainer::GetAt(size_t stIndex) const -{ - if(stIndex > m_vPaths.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + // ============================================================================ + /// TModPathContainer::Add + /// @date 2009/11/30 + /// + /// @brief Adds a path to the end of list. + /// @param[in] spPath - path to be added. + // ============================================================================ + void TModPathContainer::Add(const TSmartPath& spPath) + { + m_vPaths.insert(std::make_pair(m_oidNextObjectID++, TModificationTracker(spPath, true))); + } - DataMap::const_iterator iter = m_vPaths.cbegin() + stIndex; - return iter->second; -} + // ============================================================================ + /// TModPathContainer::GetAt + /// @date 2009/11/30 + /// + /// @brief Retrieves path at specified index. + /// @param[in] stIndex - index at which to retrieve item. + /// @return Reference to the path object. + // ============================================================================ + const TSmartPath& TModPathContainer::GetAt(size_t stIndex) const + { + if (stIndex > m_vPaths.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -// ============================================================================ -/// TModPathContainer::GetAt -/// @date 2009/11/30 -/// -/// @brief Retrieves path at specified index. -/// @param[in] stIndex - index at which to retrieve item. -/// @return Reference to the path object. -// ============================================================================ -TSmartPath& TModPathContainer::GetAt(size_t stIndex) -{ - if(stIndex > m_vPaths.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + DataMap::const_iterator iter = m_vPaths.cbegin() + stIndex; + return iter->second; + } - DataMap::iterator iter = m_vPaths.begin() + stIndex; - return iter->second.Modify(); -} + // ============================================================================ + /// TModPathContainer::GetAt + /// @date 2009/11/30 + /// + /// @brief Retrieves path at specified index. + /// @param[in] stIndex - index at which to retrieve item. + /// @return Reference to the path object. + // ============================================================================ + TSmartPath& TModPathContainer::GetAt(size_t stIndex) + { + if (stIndex > m_vPaths.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -object_id_t TModPathContainer::GetOidAt(size_t stIndex) const -{ - if(stIndex > m_vPaths.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + DataMap::iterator iter = m_vPaths.begin() + stIndex; + return iter->second.Modify(); + } - DataMap::const_iterator iter = m_vPaths.begin() + stIndex; - return iter->first; -} + object_id_t TModPathContainer::GetOidAt(size_t stIndex) const + { + if (stIndex > m_vPaths.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -// ============================================================================ -/// TModPathContainer::SetAt -/// @date 2009/11/30 -/// -/// @brief Sets a path at a specified index. -/// @param[in] stIndex - index at which to set the path. -/// @param[in] spPath - path to be set. -// ============================================================================ -void TModPathContainer::SetAt(size_t stIndex, const TSmartPath& spPath) -{ - if(stIndex > m_vPaths.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + DataMap::const_iterator iter = m_vPaths.begin() + stIndex; + return iter->first; + } - DataMap::iterator iter = m_vPaths.begin() + stIndex; - iter->second = spPath; -} + // ============================================================================ + /// TModPathContainer::SetAt + /// @date 2009/11/30 + /// + /// @brief Sets a path at a specified index. + /// @param[in] stIndex - index at which to set the path. + /// @param[in] spPath - path to be set. + // ============================================================================ + void TModPathContainer::SetAt(size_t stIndex, const TSmartPath& spPath) + { + if (stIndex > m_vPaths.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -// ============================================================================ -/// TModPathContainer::DeleteAt -/// @date 2009/11/30 -/// -/// @brief Removes a path from container at specified index. -/// @param[in] stIndex - index at which to delete. -// ============================================================================ -void TModPathContainer::DeleteAt(size_t stIndex) -{ - if(stIndex > m_vPaths.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + DataMap::iterator iter = m_vPaths.begin() + stIndex; + iter->second = spPath; + } - DataMap::iterator iterDel = m_vPaths.begin() + stIndex; - m_setRemovedItems.Add(iterDel->first); - m_vPaths.erase(iterDel); -} + // ============================================================================ + /// TModPathContainer::DeleteAt + /// @date 2009/11/30 + /// + /// @brief Removes a path from container at specified index. + /// @param[in] stIndex - index at which to delete. + // ============================================================================ + void TModPathContainer::DeleteAt(size_t stIndex) + { + if (stIndex > m_vPaths.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -// ============================================================================ -/// TModPathContainer::Clear -/// @date 2009/11/30 -/// -/// @brief Removes all paths from this container. -// ============================================================================ -void TModPathContainer::Clear(bool bClearModificationsData) -{ - if(!bClearModificationsData) + DataMap::iterator iterDel = m_vPaths.begin() + stIndex; + m_setRemovedItems.Add(iterDel->first); + m_vPaths.erase(iterDel); + } + + // ============================================================================ + /// TModPathContainer::Clear + /// @date 2009/11/30 + /// + /// @brief Removes all paths from this container. + // ============================================================================ + void TModPathContainer::Clear(bool bClearModificationsData) { - for(DataMap::iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) + if (!bClearModificationsData) { - m_setRemovedItems.Add(iterDel->first); + for (DataMap::iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) + { + m_setRemovedItems.Add(iterDel->first); + } } + else + { + m_setRemovedItems.Clear(); + m_oidNextObjectID = 1; + } + + m_vPaths.clear(); } - else + + // ============================================================================ + /// TModPathContainer::GetCount + /// @date 2009/11/30 + /// + /// @brief Retrieves count of elements in the container. + /// @return Count of elements. + // ============================================================================ + size_t TModPathContainer::GetCount() const { - m_setRemovedItems.Clear(); - m_oidNextObjectID = 1; + return m_vPaths.size(); } - m_vPaths.clear(); -} + // ============================================================================ + /// TModPathContainer::GetCount + /// @date 2010/10/12 + /// + /// @brief Retrieves info if this container is empty. + /// @return True if empty, false otherwise. + // ============================================================================ + bool TModPathContainer::IsEmpty() const + { + return m_vPaths.empty(); + } -// ============================================================================ -/// TModPathContainer::GetCount -/// @date 2009/11/30 -/// -/// @brief Retrieves count of elements in the container. -/// @return Count of elements. -// ============================================================================ -size_t TModPathContainer::GetCount() const -{ - return m_vPaths.size(); -} + const TSmartPath& TModPathContainer::GetAtOid(object_id_t oidObjectID) const + { + return m_vPaths.at(oidObjectID); + } -// ============================================================================ -/// TModPathContainer::GetCount -/// @date 2010/10/12 -/// -/// @brief Retrieves info if this container is empty. -/// @return True if empty, false otherwise. -// ============================================================================ -bool TModPathContainer::IsEmpty() const -{ - return m_vPaths.empty(); -} + TSmartPath& TModPathContainer::GetAtOid(object_id_t oidObjectID) + { + return m_vPaths.at(oidObjectID).Modify(); + } -const TSmartPath& TModPathContainer::GetAtOid(object_id_t oidObjectID) const -{ - return m_vPaths.at(oidObjectID); -} + void TModPathContainer::SetByOid(object_id_t oidObjectID, const TSmartPath& spPath) + { + DataMap::iterator iterFnd = m_vPaths.find(oidObjectID); + if (iterFnd != m_vPaths.end()) + iterFnd->second = spPath; + else + m_vPaths.insert(std::make_pair(oidObjectID, TModificationTracker(spPath, true))); + } -TSmartPath& TModPathContainer::GetAtOid(object_id_t oidObjectID) -{ - return m_vPaths.at(oidObjectID).Modify(); -} + void TModPathContainer::DeleteOid(object_id_t oidObjectID) + { + m_vPaths.erase(oidObjectID); + m_setRemovedItems.Add(oidObjectID); + } -void TModPathContainer::SetByOid(object_id_t oidObjectID, const TSmartPath& spPath) -{ - DataMap::iterator iterFnd = m_vPaths.find(oidObjectID); - if(iterFnd != m_vPaths.end()) - iterFnd->second = spPath; - else - m_vPaths.insert(std::make_pair(oidObjectID, TModificationTracker(spPath, true))); -} - -void TModPathContainer::DeleteOid(object_id_t oidObjectID) -{ - m_vPaths.erase(oidObjectID); - m_setRemovedItems.Add(oidObjectID); -} - -bool TModPathContainer::HasModifications() const -{ - if(!m_setRemovedItems.IsEmpty()) - return true; - - for(DataMap::const_iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) + bool TModPathContainer::HasModifications() const { - if(iterDel->second.IsModified() || iterDel->second.IsAdded()) + if (!m_setRemovedItems.IsEmpty()) return true; - } - return false; -} + for (DataMap::const_iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) + { + if (iterDel->second.IsModified() || iterDel->second.IsAdded()) + return true; + } -void TModPathContainer::ClearModifications() -{ - m_setRemovedItems.Clear(); + return false; + } - for(DataMap::iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) + void TModPathContainer::ClearModifications() { - iterDel->second.ClearModifications(); + m_setRemovedItems.Clear(); + + for (DataMap::iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) + { + iterDel->second.ClearModifications(); + } } -} -void TModPathContainer::Store(const ISerializerContainerPtr& spContainer) const -{ - InitColumns(spContainer); - - // delete items first - spContainer->DeleteRows(m_setRemovedItems); - m_setRemovedItems.Clear(); - - // add/modify - for(DataMap::const_iterator iterPath = m_vPaths.begin(); iterPath != m_vPaths.end(); ++iterPath) + void TModPathContainer::Store(const ISerializerContainerPtr& spContainer) const { - const TModificationTracker& rItem = iterPath->second; + InitColumns(spContainer); - if(rItem.IsModified()) + // delete items first + spContainer->DeleteRows(m_setRemovedItems); + m_setRemovedItems.Clear(); + + // add/modify + for (DataMap::const_iterator iterPath = m_vPaths.begin(); iterPath != m_vPaths.end(); ++iterPath) { - ISerializerRowData& rRow = spContainer->GetRow(iterPath->first, rItem.IsAdded()); - rRow.SetValue(_T("path"), rItem); + const TModificationTracker& rItem = iterPath->second; - rItem.ClearModifications(); + if (rItem.IsModified()) + { + ISerializerRowData& rRow = spContainer->GetRow(iterPath->first, rItem.IsAdded()); + rRow.SetValue(_T("path"), rItem); + + rItem.ClearModifications(); + } + else + continue; } - else - continue; } -} -void TModPathContainer::Load(const ISerializerContainerPtr& spContainer) -{ - m_setRemovedItems.Clear(); - m_vPaths.clear(); - m_oidNextObjectID = 1; + void TModPathContainer::Load(const ISerializerContainerPtr& spContainer) + { + m_setRemovedItems.Clear(); + m_vPaths.clear(); + m_oidNextObjectID = 1; - InitColumns(spContainer); + InitColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - while(spRowReader->Next()) - { - object_id_t oidObjectID = 0; - TSmartPath path; + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + while (spRowReader->Next()) + { + object_id_t oidObjectID = 0; + TSmartPath path; - spRowReader->GetValue(_T("id"), oidObjectID); - spRowReader->GetValue(_T("path"), path); + spRowReader->GetValue(_T("id"), oidObjectID); + spRowReader->GetValue(_T("path"), path); - m_vPaths.insert(std::make_pair(oidObjectID, TModificationTracker(path, false))); + m_vPaths.insert(std::make_pair(oidObjectID, TModificationTracker(path, false))); + } + + ClearModifications(); } - ClearModifications(); -} - -void TModPathContainer::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) + void TModPathContainer::InitColumns(const ISerializerContainerPtr& spContainer) const { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("path"), IColumnsDefinition::eType_path); + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("path"), IColumnsDefinition::eType_path); + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TModPathContainer.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TModPathContainer.h (.../TModPathContainer.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TModPathContainer.h (.../TModPathContainer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,68 +26,67 @@ #include "ISerializerContainer.h" #include "TRemovedObjects.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TModPathContainer +namespace chcore { -public: - TModPathContainer(); - TModPathContainer(const TModPathContainer& rSrcContainer); - ~TModPathContainer(); + class LIBCHCORE_API TModPathContainer + { + public: + TModPathContainer(); + TModPathContainer(const TModPathContainer& rSrcContainer); + ~TModPathContainer(); - TModPathContainer& operator=(const TModPathContainer& rSrcContainer); - TModPathContainer& operator=(const TPathContainer& rSrcContainer); + TModPathContainer& operator=(const TModPathContainer& rSrcContainer); + TModPathContainer& operator=(const TPathContainer& rSrcContainer); #pragma region Index-based interface - void Add(const TSmartPath& spPath); + void Add(const TSmartPath& spPath); - const TSmartPath& GetAt(size_t stIndex) const; - TSmartPath& GetAt(size_t stIndex); - object_id_t GetOidAt(size_t stIndex) const; + const TSmartPath& GetAt(size_t stIndex) const; + TSmartPath& GetAt(size_t stIndex); + object_id_t GetOidAt(size_t stIndex) const; - void SetAt(size_t stIndex, const TSmartPath& spPath); + void SetAt(size_t stIndex, const TSmartPath& spPath); - void DeleteAt(size_t stIndex); + void DeleteAt(size_t stIndex); #pragma endregion #pragma region Object id-based interface - const TSmartPath& GetAtOid(object_id_t oidObjectID) const; - TSmartPath& GetAtOid(object_id_t oidObjectID); + const TSmartPath& GetAtOid(object_id_t oidObjectID) const; + TSmartPath& GetAtOid(object_id_t oidObjectID); - void SetByOid(object_id_t oidObjectID, const TSmartPath& spPath); - void DeleteOid(object_id_t oidObjectID); + void SetByOid(object_id_t oidObjectID, const TSmartPath& spPath); + void DeleteOid(object_id_t oidObjectID); #pragma endregion #pragma region Generic interface - void Clear(bool bClearModificationsData); + void Clear(bool bClearModificationsData); - size_t GetCount() const; - bool IsEmpty() const; + size_t GetCount() const; + bool IsEmpty() const; #pragma endregion #pragma region Modifications management - bool HasModifications() const; - void ClearModifications(); + bool HasModifications() const; + void ClearModifications(); #pragma endregion #pragma region Serialization - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); - void InitColumns(const ISerializerContainerPtr& spContainer) const; + void InitColumns(const ISerializerContainerPtr& spContainer) const; #pragma endregion -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - mutable TRemovedObjects m_setRemovedItems; - typedef boost::container::flat_map > DataMap; - DataMap m_vPaths; + mutable TRemovedObjects m_setRemovedItems; + typedef boost::container::flat_map > DataMap; + DataMap m_vPaths; #pragma warning(pop) - object_id_t m_oidNextObjectID; -}; + object_id_t m_oidNextObjectID; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TModificationTracker.h =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TModificationTracker.h (.../TModificationTracker.h) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/TModificationTracker.h (.../TModificationTracker.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,94 +21,93 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -template -class TModificationTracker +namespace chcore { -public: - TModificationTracker() : - m_tValue(), - m_chModified(eMod_Modified) + template + class TModificationTracker { - } + public: + TModificationTracker() : + m_tValue(), + m_chModified(eMod_Modified) + { + } - template - TModificationTracker(const V& rValue, bool bAdded) : - m_tValue(rValue), - m_chModified((char)eMod_Modified | (bAdded ? (char)eMod_Added : (char)eMod_None)) - { - } + template + TModificationTracker(const V& rValue, bool bAdded) : + m_tValue(rValue), + m_chModified((char)eMod_Modified | (bAdded ? (char)eMod_Added : (char)eMod_None)) + { + } - TModificationTracker(const TModificationTracker& rSrc) : - m_chModified(rSrc.m_chModified), - m_tValue(rSrc.m_tValue) - { - } + TModificationTracker(const TModificationTracker& rSrc) : + m_chModified(rSrc.m_chModified), + m_tValue(rSrc.m_tValue) + { + } - TModificationTracker& operator=(const TModificationTracker& rSrc) - { - m_chModified = rSrc.m_chModified; - m_tValue = rSrc.m_tValue; + TModificationTracker& operator=(const TModificationTracker& rSrc) + { + m_chModified = rSrc.m_chModified; + m_tValue = rSrc.m_tValue; - return *this; - } + return *this; + } - template - TModificationTracker& operator=(const V& rValue) - { - if(m_tValue != rValue) + template + TModificationTracker& operator=(const V& rValue) { - m_tValue = rValue; - m_chModified |= eMod_Modified; + if (m_tValue != rValue) + { + m_tValue = rValue; + m_chModified |= eMod_Modified; + } + + return *this; } - return *this; - } + operator const T&() const + { + return m_tValue; + } - operator const T&() const - { - return m_tValue; - } + const T& Get() const + { + return m_tValue; + } - const T& Get() const - { - return m_tValue; - } + T& Modify() + { + m_chModified |= eMod_Modified; + return m_tValue; + } - T& Modify() - { - m_chModified |= eMod_Modified; - return m_tValue; - } + void ClearModifications() const + { + m_chModified = eMod_None; + } - void ClearModifications() const - { - m_chModified = eMod_None; - } + bool IsModified() const + { + return m_chModified != 0; // must also include 'Added' status! + } - bool IsModified() const - { - return m_chModified != 0; // must also include 'Added' status! - } + bool IsAdded() const + { + return (m_chModified & eMod_Added) != 0; + } - bool IsAdded() const - { - return (m_chModified & eMod_Added) != 0; - } + private: + enum EModifiedFlags + { + eMod_None = 0, + eMod_Added = 1, + eMod_Modified = 2 + }; -private: - enum EModifiedFlags - { - eMod_None = 0, - eMod_Added = 1, - eMod_Modified = 2 + T m_tValue; + mutable char m_chModified; }; +} - T m_tValue; - mutable char m_chModified; -}; - -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TObsoleteFiles.cpp =================================================================== diff -u -N -ra99c8baeb8f6c237603df46c0f5c4cf943152c09 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TObsoleteFiles.cpp (.../TObsoleteFiles.cpp) (revision a99c8baeb8f6c237603df46c0f5c4cf943152c09) +++ src/libchcore/TObsoleteFiles.cpp (.../TObsoleteFiles.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -20,96 +20,95 @@ #include "TObsoleteFiles.h" #include "ISerializerContainer.h" -BEGIN_CHCORE_NAMESPACE - -ObsoleteFileInfo::ObsoleteFileInfo(TSmartPath path, bool bAdded) : - m_path(path), - m_bAdded(bAdded) +namespace chcore { -} + ObsoleteFileInfo::ObsoleteFileInfo(TSmartPath path, bool bAdded) : + m_path(path), + m_bAdded(bAdded) + { + } -ObsoleteFileInfo::ObsoleteFileInfo() : - m_bAdded(false) -{ -} + ObsoleteFileInfo::ObsoleteFileInfo() : + m_bAdded(false) + { + } -TObsoleteFiles::TObsoleteFiles() : - m_oidLast(0) -{ -} + TObsoleteFiles::TObsoleteFiles() : + m_oidLast(0) + { + } -TObsoleteFiles::~TObsoleteFiles() -{ -} + TObsoleteFiles::~TObsoleteFiles() + { + } -void TObsoleteFiles::DeleteObsoleteFile(const TSmartPath& pathToDelete) -{ - if(!DeleteFile(pathToDelete.ToString()) && GetLastError() != ERROR_FILE_NOT_FOUND) - m_mapPaths.insert(std::make_pair(++m_oidLast, ObsoleteFileInfo(pathToDelete, true))); -} + void TObsoleteFiles::DeleteObsoleteFile(const TSmartPath& pathToDelete) + { + if (!DeleteFile(pathToDelete.ToString()) && GetLastError() != ERROR_FILE_NOT_FOUND) + m_mapPaths.insert(std::make_pair(++m_oidLast, ObsoleteFileInfo(pathToDelete, true))); + } -void TObsoleteFiles::Store(const ISerializerContainerPtr& spContainer) const -{ - InitColumns(spContainer); + void TObsoleteFiles::Store(const ISerializerContainerPtr& spContainer) const + { + InitColumns(spContainer); - spContainer->DeleteRows(m_setRemovedObjects); - m_setRemovedObjects.Clear(); + spContainer->DeleteRows(m_setRemovedObjects); + m_setRemovedObjects.Clear(); - for(MapPaths::const_iterator iter = m_mapPaths.begin(); iter != m_mapPaths.end(); ++iter) - { - if(iter->second.m_bAdded) + for (MapPaths::const_iterator iter = m_mapPaths.begin(); iter != m_mapPaths.end(); ++iter) { - ISerializerRowData& rRow = spContainer->GetRow(iter->first, true); - rRow.SetValue(_T("path"), iter->second.m_path); - } + if (iter->second.m_bAdded) + { + ISerializerRowData& rRow = spContainer->GetRow(iter->first, true); + rRow.SetValue(_T("path"), iter->second.m_path); + } - iter->second.m_bAdded = false; + iter->second.m_bAdded = false; + } } -} -void TObsoleteFiles::Load(const ISerializerContainerPtr& spContainer) -{ - InitColumns(spContainer); + void TObsoleteFiles::Load(const ISerializerContainerPtr& spContainer) + { + InitColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - ObsoleteFileInfo tEntry; - object_id_t oid = 0; - while(spRowReader->Next()) - { - spRowReader->GetValue(_T("id"), oid); - spRowReader->GetValue(_T("path"), tEntry.m_path); - tEntry.m_bAdded = false; + ObsoleteFileInfo tEntry; + object_id_t oid = 0; + while (spRowReader->Next()) + { + spRowReader->GetValue(_T("id"), oid); + spRowReader->GetValue(_T("path"), tEntry.m_path); + tEntry.m_bAdded = false; - m_mapPaths.insert(std::make_pair(oid, tEntry)); - m_oidLast = std::max(m_oidLast, oid); - } + m_mapPaths.insert(std::make_pair(oid, tEntry)); + m_oidLast = std::max(m_oidLast, oid); + } - m_setRemovedObjects.Clear(); + m_setRemovedObjects.Clear(); - // try to delete files - MapPaths::iterator iter = m_mapPaths.begin(); - while(iter != m_mapPaths.end()) - { - BOOL bDeleted = DeleteFile(iter->second.m_path.ToString()); - if(bDeleted || GetLastError() == ERROR_FILE_NOT_FOUND) + // try to delete files + MapPaths::iterator iter = m_mapPaths.begin(); + while (iter != m_mapPaths.end()) { - m_setRemovedObjects.Add(iter->first); - iter = m_mapPaths.erase(iter); + BOOL bDeleted = DeleteFile(iter->second.m_path.ToString()); + if (bDeleted || GetLastError() == ERROR_FILE_NOT_FOUND) + { + m_setRemovedObjects.Add(iter->first); + iter = m_mapPaths.erase(iter); + } + else + ++iter; } - else - ++iter; } -} -void TObsoleteFiles::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) + void TObsoleteFiles::InitColumns(const ISerializerContainerPtr& spContainer) const { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("path"), IColumnsDefinition::eType_path); + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("path"), IColumnsDefinition::eType_path); + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TObsoleteFiles.h =================================================================== diff -u -N -ra99c8baeb8f6c237603df46c0f5c4cf943152c09 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TObsoleteFiles.h (.../TObsoleteFiles.h) (revision a99c8baeb8f6c237603df46c0f5c4cf943152c09) +++ src/libchcore/TObsoleteFiles.h (.../TObsoleteFiles.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,41 +26,40 @@ #include "SerializerDataTypes.h" #include "TRemovedObjects.h" -BEGIN_CHCORE_NAMESPACE - -struct ObsoleteFileInfo +namespace chcore { - ObsoleteFileInfo(); - ObsoleteFileInfo(TSmartPath path, bool bAdded); + struct ObsoleteFileInfo + { + ObsoleteFileInfo(); + ObsoleteFileInfo(TSmartPath path, bool bAdded); - TSmartPath m_path; - mutable bool m_bAdded; -}; + TSmartPath m_path; + mutable bool m_bAdded; + }; -class LIBCHCORE_API TObsoleteFiles -{ -public: - TObsoleteFiles(); - virtual ~TObsoleteFiles(); + class LIBCHCORE_API TObsoleteFiles + { + public: + TObsoleteFiles(); + virtual ~TObsoleteFiles(); - void DeleteObsoleteFile(const TSmartPath& pathToDelete); + void DeleteObsoleteFile(const TSmartPath& pathToDelete); - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); - void InitColumns(const ISerializerContainerPtr& spContainer) const; + void InitColumns(const ISerializerContainerPtr& spContainer) const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - typedef std::map MapPaths; - MapPaths m_mapPaths; + typedef std::map MapPaths; + MapPaths m_mapPaths; #pragma warning(pop) - mutable TRemovedObjects m_setRemovedObjects; - object_id_t m_oidLast; -}; + mutable TRemovedObjects m_setRemovedObjects; + object_id_t m_oidLast; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TOverlappedDataBuffer.cpp =================================================================== diff -u -N -radf2d680643ef85665b042e03fed274ab8f11180 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TOverlappedDataBuffer.cpp (.../TOverlappedDataBuffer.cpp) (revision adf2d680643ef85665b042e03fed274ab8f11180) +++ src/libchcore/TOverlappedDataBuffer.cpp (.../TOverlappedDataBuffer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -32,136 +32,135 @@ #define STATUS_END_OF_FILE 0xc0000011 -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////////////// -// class TOverlappedDataBuffer -VOID CALLBACK OverlappedReadCompleted(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped) +namespace chcore { - TOverlappedDataBuffer* pBuffer = (TOverlappedDataBuffer*) lpOverlapped; + /////////////////////////////////////////////////////////////////////////////////// + // class TOverlappedDataBuffer + VOID CALLBACK OverlappedReadCompleted(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped) + { + TOverlappedDataBuffer* pBuffer = (TOverlappedDataBuffer*)lpOverlapped; - // determine if this is the last packet - bool bEof = (dwErrorCode == ERROR_HANDLE_EOF || - pBuffer->GetStatusCode() == STATUS_END_OF_FILE || - (dwErrorCode == ERROR_SUCCESS && pBuffer->GetBytesTransferred() != pBuffer->GetRequestedDataSize())); + // determine if this is the last packet + bool bEof = (dwErrorCode == ERROR_HANDLE_EOF || + pBuffer->GetStatusCode() == STATUS_END_OF_FILE || + (dwErrorCode == ERROR_SUCCESS && pBuffer->GetBytesTransferred() != pBuffer->GetRequestedDataSize())); - // reset status code and error code if they pointed out to EOF - if (pBuffer->GetStatusCode() == STATUS_END_OF_FILE) - pBuffer->SetStatusCode(0); + // reset status code and error code if they pointed out to EOF + if (pBuffer->GetStatusCode() == STATUS_END_OF_FILE) + pBuffer->SetStatusCode(0); - pBuffer->SetErrorCode(dwErrorCode == ERROR_HANDLE_EOF ? ERROR_SUCCESS : dwErrorCode); + pBuffer->SetErrorCode(dwErrorCode == ERROR_HANDLE_EOF ? ERROR_SUCCESS : dwErrorCode); - pBuffer->SetRealDataSize(dwNumberOfBytesTransfered); - pBuffer->SetLastPart(bEof); + pBuffer->SetRealDataSize(dwNumberOfBytesTransfered); + pBuffer->SetLastPart(bEof); - pBuffer->RequeueAsFull(); -} + pBuffer->RequeueAsFull(); + } -VOID CALLBACK OverlappedWriteCompleted(DWORD dwErrorCode, DWORD /*dwNumberOfBytesTransfered*/, LPOVERLAPPED lpOverlapped) -{ - TOverlappedDataBuffer* pBuffer = (TOverlappedDataBuffer*) lpOverlapped; + VOID CALLBACK OverlappedWriteCompleted(DWORD dwErrorCode, DWORD /*dwNumberOfBytesTransfered*/, LPOVERLAPPED lpOverlapped) + { + TOverlappedDataBuffer* pBuffer = (TOverlappedDataBuffer*)lpOverlapped; - pBuffer->SetErrorCode(dwErrorCode); - pBuffer->RequeueAsFinished(); -} + pBuffer->SetErrorCode(dwErrorCode); + pBuffer->RequeueAsFinished(); + } -TOverlappedDataBuffer::TOverlappedDataBuffer(size_t stBufferSize, IOverlappedDataBufferQueue* pQueue) : - m_pBuffer(NULL), - m_stBufferSize(0), - m_bLastPart(false), - m_pQueue(pQueue), - m_dwRequestedDataSize(0), - m_dwRealDataSize(0) -{ - if (!m_pQueue) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + TOverlappedDataBuffer::TOverlappedDataBuffer(size_t stBufferSize, IOverlappedDataBufferQueue* pQueue) : + m_pBuffer(NULL), + m_stBufferSize(0), + m_bLastPart(false), + m_pQueue(pQueue), + m_dwRequestedDataSize(0), + m_dwRealDataSize(0) + { + if (!m_pQueue) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); - // initialize OVERLAPPED members - Internal = 0; - InternalHigh = 0; - Offset = 0; - OffsetHigh = 0; - hEvent = NULL; + // initialize OVERLAPPED members + Internal = 0; + InternalHigh = 0; + Offset = 0; + OffsetHigh = 0; + hEvent = NULL; - // create buffer - ReinitializeBuffer(stBufferSize); -} + // create buffer + ReinitializeBuffer(stBufferSize); + } -TOverlappedDataBuffer::~TOverlappedDataBuffer() -{ - ReleaseBuffer(); -} - -void TOverlappedDataBuffer::ReinitializeBuffer(size_t stNewBufferSize) -{ - if (stNewBufferSize != m_stBufferSize) + TOverlappedDataBuffer::~TOverlappedDataBuffer() { ReleaseBuffer(); + } - m_pBuffer = VirtualAlloc(NULL, stNewBufferSize, MEM_COMMIT, PAGE_READWRITE); - if (!m_pBuffer) - THROW_CORE_EXCEPTION(eErr_CannotAllocateMemory); - m_stBufferSize = stNewBufferSize; + void TOverlappedDataBuffer::ReinitializeBuffer(size_t stNewBufferSize) + { + if (stNewBufferSize != m_stBufferSize) + { + ReleaseBuffer(); + + m_pBuffer = VirtualAlloc(NULL, stNewBufferSize, MEM_COMMIT, PAGE_READWRITE); + if (!m_pBuffer) + THROW_CORE_EXCEPTION(eErr_CannotAllocateMemory); + m_stBufferSize = stNewBufferSize; + } } -} -void TOverlappedDataBuffer::ReleaseBuffer() -{ - if (m_pBuffer) + void TOverlappedDataBuffer::ReleaseBuffer() { - VirtualFree(m_pBuffer, 0, MEM_RELEASE); - m_stBufferSize = 0; - m_pBuffer = nullptr; + if (m_pBuffer) + { + VirtualFree(m_pBuffer, 0, MEM_RELEASE); + m_stBufferSize = 0; + m_pBuffer = nullptr; + } } -} -LPVOID TOverlappedDataBuffer::GetBufferPtr() -{ - return m_pBuffer; -} + LPVOID TOverlappedDataBuffer::GetBufferPtr() + { + return m_pBuffer; + } -void TOverlappedDataBuffer::RequeueAsEmpty() -{ - m_pQueue->AddEmptyBuffer(this); -} + void TOverlappedDataBuffer::RequeueAsEmpty() + { + m_pQueue->AddEmptyBuffer(this); + } -void TOverlappedDataBuffer::RequeueAsFull() -{ - m_pQueue->AddFullBuffer(this); -} + void TOverlappedDataBuffer::RequeueAsFull() + { + m_pQueue->AddFullBuffer(this); + } -void TOverlappedDataBuffer::RequeueAsFinished() -{ - m_pQueue->AddFinishedBuffer(this); -} + void TOverlappedDataBuffer::RequeueAsFinished() + { + m_pQueue->AddFinishedBuffer(this); + } -void TOverlappedDataBuffer::InitForRead(unsigned long long ullPosition, DWORD dwRequestedSize) -{ - SetRequestedDataSize(dwRequestedSize); - SetFilePosition(ullPosition); - SetRealDataSize(0); - SetLastPart(false); - SetErrorCode(ERROR_SUCCESS); - SetStatusCode(0); - SetBytesTransferred(0); -} + void TOverlappedDataBuffer::InitForRead(unsigned long long ullPosition, DWORD dwRequestedSize) + { + SetRequestedDataSize(dwRequestedSize); + SetFilePosition(ullPosition); + SetRealDataSize(0); + SetLastPart(false); + SetErrorCode(ERROR_SUCCESS); + SetStatusCode(0); + SetBytesTransferred(0); + } -void TOverlappedDataBuffer::InitForWrite() -{ - SetErrorCode(ERROR_SUCCESS); - SetStatusCode(0); - SetBytesTransferred(0); -} + void TOverlappedDataBuffer::InitForWrite() + { + SetErrorCode(ERROR_SUCCESS); + SetStatusCode(0); + SetBytesTransferred(0); + } -void TOverlappedDataBuffer::Reset() -{ - SetRequestedDataSize(0); - SetFilePosition(0); - SetRealDataSize(0); - SetLastPart(false); - SetErrorCode(ERROR_SUCCESS); - SetStatusCode(0); - SetBytesTransferred(0); + void TOverlappedDataBuffer::Reset() + { + SetRequestedDataSize(0); + SetFilePosition(0); + SetRealDataSize(0); + SetLastPart(false); + SetErrorCode(ERROR_SUCCESS); + SetStatusCode(0); + SetBytesTransferred(0); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TOverlappedDataBuffer.h =================================================================== diff -u -N -refe016ef1d0cb0cf1ba379dbe3693e35f6a2361e -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TOverlappedDataBuffer.h (.../TOverlappedDataBuffer.h) (revision efe016ef1d0cb0cf1ba379dbe3693e35f6a2361e) +++ src/libchcore/TOverlappedDataBuffer.h (.../TOverlappedDataBuffer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,85 +25,84 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class IOverlappedDataBufferQueue; - -VOID CALLBACK OverlappedReadCompleted(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped); -VOID CALLBACK OverlappedWriteCompleted(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped); - -class TOverlappedDataBuffer : public OVERLAPPED +namespace chcore { -public: - // construction/destruction - TOverlappedDataBuffer(size_t stBufferSize, IOverlappedDataBufferQueue* pQueue); - TOverlappedDataBuffer(const TOverlappedDataBuffer&) = delete; - TOverlappedDataBuffer(TOverlappedDataBuffer&& rSrc) = delete; + class IOverlappedDataBufferQueue; - ~TOverlappedDataBuffer(); + VOID CALLBACK OverlappedReadCompleted(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped); + VOID CALLBACK OverlappedWriteCompleted(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped); - // operators - TOverlappedDataBuffer& operator=(const TOverlappedDataBuffer&) = delete; - TOverlappedDataBuffer& operator=(TOverlappedDataBuffer&& rSrc) = delete; + class TOverlappedDataBuffer : public OVERLAPPED + { + public: + // construction/destruction + TOverlappedDataBuffer(size_t stBufferSize, IOverlappedDataBufferQueue* pQueue); + TOverlappedDataBuffer(const TOverlappedDataBuffer&) = delete; + TOverlappedDataBuffer(TOverlappedDataBuffer&& rSrc) = delete; - // interface methods - // buffer size management - void ReinitializeBuffer(size_t stNewBufferSize); - LPVOID GetBufferPtr(); + ~TOverlappedDataBuffer(); - size_t GetBufferSize() const { return m_stBufferSize; } + // operators + TOverlappedDataBuffer& operator=(const TOverlappedDataBuffer&) = delete; + TOverlappedDataBuffer& operator=(TOverlappedDataBuffer&& rSrc) = delete; - // members - DWORD GetRequestedDataSize() const { return m_dwRequestedDataSize; } - void SetRequestedDataSize(DWORD dwRequestedSize) { m_dwRequestedDataSize = dwRequestedSize; } + // interface methods + // buffer size management + void ReinitializeBuffer(size_t stNewBufferSize); + LPVOID GetBufferPtr(); - DWORD GetRealDataSize() const { return m_dwRealDataSize; } - void SetRealDataSize(DWORD dwRealDataSize) { m_dwRealDataSize = dwRealDataSize; } + size_t GetBufferSize() const { return m_stBufferSize; } - void SetLastPart(bool bLastPart) { m_bLastPart = bLastPart; } - bool IsLastPart() const { return m_bLastPart; } + // members + DWORD GetRequestedDataSize() const { return m_dwRequestedDataSize; } + void SetRequestedDataSize(DWORD dwRequestedSize) { m_dwRequestedDataSize = dwRequestedSize; } - unsigned long long GetBufferOrder() const { return m_ullBufferOrder; } - void SetBufferOrder(unsigned long long ullOrder) { m_ullBufferOrder = ullOrder; } + DWORD GetRealDataSize() const { return m_dwRealDataSize; } + void SetRealDataSize(DWORD dwRealDataSize) { m_dwRealDataSize = dwRealDataSize; } - DWORD GetErrorCode() const { return m_dwErrorCode; } - void SetErrorCode(DWORD dwErrorCode) { m_dwErrorCode = dwErrorCode; } + void SetLastPart(bool bLastPart) { m_bLastPart = bLastPart; } + bool IsLastPart() const { return m_bLastPart; } - // OVERLAPPED interface - ULONG_PTR GetStatusCode() const { return Internal; } - void SetStatusCode(ULONG_PTR ulStatusCode) { Internal = ulStatusCode; } + unsigned long long GetBufferOrder() const { return m_ullBufferOrder; } + void SetBufferOrder(unsigned long long ullOrder) { m_ullBufferOrder = ullOrder; } - void SetBytesTransferred(ULONG_PTR ulBytes) { InternalHigh = ulBytes; } - ULONG_PTR GetBytesTransferred() const { return InternalHigh; } + DWORD GetErrorCode() const { return m_dwErrorCode; } + void SetErrorCode(DWORD dwErrorCode) { m_dwErrorCode = dwErrorCode; } - unsigned long long GetFilePosition() const { return (unsigned long long)OffsetHigh << 32 | Offset; } - void SetFilePosition(unsigned long long ullPosition) { OffsetHigh = (DWORD) (ullPosition >> 32); Offset = (DWORD) ullPosition; } + // OVERLAPPED interface + ULONG_PTR GetStatusCode() const { return Internal; } + void SetStatusCode(ULONG_PTR ulStatusCode) { Internal = ulStatusCode; } - // queue management - void RequeueAsEmpty(); - void RequeueAsFull(); - void RequeueAsFinished(); + void SetBytesTransferred(ULONG_PTR ulBytes) { InternalHigh = ulBytes; } + ULONG_PTR GetBytesTransferred() const { return InternalHigh; } - // composite initialization - void InitForRead(unsigned long long ullPosition, DWORD dwRequestedSize); - void InitForWrite(); - void Reset(); + unsigned long long GetFilePosition() const { return (unsigned long long)OffsetHigh << 32 | Offset; } + void SetFilePosition(unsigned long long ullPosition) { OffsetHigh = (DWORD)(ullPosition >> 32); Offset = (DWORD)ullPosition; } -private: - void ReleaseBuffer(); + // queue management + void RequeueAsEmpty(); + void RequeueAsFull(); + void RequeueAsFinished(); -private: - LPVOID m_pBuffer; // pointer to the allocated buffer - size_t m_stBufferSize; // total buffer size - DWORD m_dwRequestedDataSize; // part of the buffer that is to be used for data transfer (<= m_stBufferSize) - DWORD m_dwRealDataSize; // data size as reported by read operation - DWORD m_dwErrorCode; // win32 error code - bool m_bLastPart; // marks the last part of the file - unsigned long long m_ullBufferOrder; // marks the order of this buffer + // composite initialization + void InitForRead(unsigned long long ullPosition, DWORD dwRequestedSize); + void InitForWrite(); + void Reset(); - IOverlappedDataBufferQueue* m_pQueue; // pointer to the queue where this object resides -}; + private: + void ReleaseBuffer(); -END_CHCORE_NAMESPACE + private: + LPVOID m_pBuffer; // pointer to the allocated buffer + size_t m_stBufferSize; // total buffer size + DWORD m_dwRequestedDataSize; // part of the buffer that is to be used for data transfer (<= m_stBufferSize) + DWORD m_dwRealDataSize; // data size as reported by read operation + DWORD m_dwErrorCode; // win32 error code + bool m_bLastPart; // marks the last part of the file + unsigned long long m_ullBufferOrder; // marks the order of this buffer + IOverlappedDataBufferQueue* m_pQueue; // pointer to the queue where this object resides + }; +} + #endif Index: src/libchcore/TOverlappedDataBufferQueue.cpp =================================================================== diff -u -N -radf2d680643ef85665b042e03fed274ab8f11180 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TOverlappedDataBufferQueue.cpp (.../TOverlappedDataBufferQueue.cpp) (revision adf2d680643ef85665b042e03fed274ab8f11180) +++ src/libchcore/TOverlappedDataBufferQueue.cpp (.../TOverlappedDataBufferQueue.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,315 +24,314 @@ #include #include -BEGIN_CHCORE_NAMESPACE - -bool CompareBufferPositions::operator()(const TOverlappedDataBuffer* pBufferA, const TOverlappedDataBuffer* pBufferB) +namespace chcore { - return pBufferA->GetBufferOrder() < pBufferB->GetBufferOrder(); -} + bool CompareBufferPositions::operator()(const TOverlappedDataBuffer* pBufferA, const TOverlappedDataBuffer* pBufferB) + { + return pBufferA->GetBufferOrder() < pBufferB->GetBufferOrder(); + } -TOverlappedDataBufferQueue::TOverlappedDataBufferQueue() : - m_eventReadPossible(true, false), - m_eventWritePossible(true, false), - m_eventWriteFinished(true, false), - m_eventAllBuffersAccountedFor(true, true), - m_bDataSourceFinished(false), - m_bDataWritingFinished(false), - m_ullNextReadBufferOrder(0), - m_ullNextWriteBufferOrder(0), - m_ullNextFinishedBufferOrder(0) -{ -} + TOverlappedDataBufferQueue::TOverlappedDataBufferQueue() : + m_eventReadPossible(true, false), + m_eventWritePossible(true, false), + m_eventWriteFinished(true, false), + m_eventAllBuffersAccountedFor(true, true), + m_bDataSourceFinished(false), + m_bDataWritingFinished(false), + m_ullNextReadBufferOrder(0), + m_ullNextWriteBufferOrder(0), + m_ullNextFinishedBufferOrder(0) + { + } -TOverlappedDataBufferQueue::TOverlappedDataBufferQueue(size_t stCount, size_t stBufferSize) : - m_eventReadPossible(true, false), - m_eventWritePossible(true, false), - m_eventWriteFinished(true, false), - m_eventAllBuffersAccountedFor(true, false), - m_bDataSourceFinished(false), - m_bDataWritingFinished(false), - m_ullNextReadBufferOrder(0), - m_ullNextWriteBufferOrder(0), - m_ullNextFinishedBufferOrder(0) -{ - ReinitializeBuffers(stCount, stBufferSize); -} + TOverlappedDataBufferQueue::TOverlappedDataBufferQueue(size_t stCount, size_t stBufferSize) : + m_eventReadPossible(true, false), + m_eventWritePossible(true, false), + m_eventWriteFinished(true, false), + m_eventAllBuffersAccountedFor(true, false), + m_bDataSourceFinished(false), + m_bDataWritingFinished(false), + m_ullNextReadBufferOrder(0), + m_ullNextWriteBufferOrder(0), + m_ullNextFinishedBufferOrder(0) + { + ReinitializeBuffers(stCount, stBufferSize); + } -TOverlappedDataBufferQueue::~TOverlappedDataBufferQueue() -{ -} + TOverlappedDataBufferQueue::~TOverlappedDataBufferQueue() + { + } -TOverlappedDataBuffer* TOverlappedDataBufferQueue::GetEmptyBuffer() -{ - if (!m_listEmptyBuffers.empty()) + TOverlappedDataBuffer* TOverlappedDataBufferQueue::GetEmptyBuffer() { - TOverlappedDataBuffer* pBuffer = m_listEmptyBuffers.front(); - m_listEmptyBuffers.pop_front(); + if (!m_listEmptyBuffers.empty()) + { + TOverlappedDataBuffer* pBuffer = m_listEmptyBuffers.front(); + m_listEmptyBuffers.pop_front(); - pBuffer->SetBufferOrder(m_ullNextReadBufferOrder++); + pBuffer->SetBufferOrder(m_ullNextReadBufferOrder++); - UpdateReadPossibleEvent(); - m_eventAllBuffersAccountedFor.ResetEvent(); + UpdateReadPossibleEvent(); + m_eventAllBuffersAccountedFor.ResetEvent(); - return pBuffer; + return pBuffer; + } + + return nullptr; } - return nullptr; -} + void TOverlappedDataBufferQueue::AddEmptyBuffer(TOverlappedDataBuffer* pBuffer) + { + if (!pBuffer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); -void TOverlappedDataBufferQueue::AddEmptyBuffer(TOverlappedDataBuffer* pBuffer) -{ - if (!pBuffer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + m_listEmptyBuffers.push_back(pBuffer); + UpdateReadPossibleEvent(); + UpdateAllBuffersAccountedFor(); + } - m_listEmptyBuffers.push_back(pBuffer); - UpdateReadPossibleEvent(); - UpdateAllBuffersAccountedFor(); -} + void TOverlappedDataBufferQueue::UpdateReadPossibleEvent() + { + if (!m_listEmptyBuffers.empty() && !m_bDataSourceFinished) + m_eventReadPossible.SetEvent(); + else + m_eventReadPossible.ResetEvent(); + } -void TOverlappedDataBufferQueue::UpdateReadPossibleEvent() -{ - if (!m_listEmptyBuffers.empty() && !m_bDataSourceFinished) - m_eventReadPossible.SetEvent(); - else - m_eventReadPossible.ResetEvent(); -} - -TOverlappedDataBuffer* TOverlappedDataBufferQueue::GetFullBuffer() -{ - if (!m_setFullBuffers.empty()) + TOverlappedDataBuffer* TOverlappedDataBufferQueue::GetFullBuffer() { - TOverlappedDataBuffer* pBuffer = *m_setFullBuffers.begin(); - if (pBuffer->GetBufferOrder() != m_ullNextWriteBufferOrder) - return nullptr; + if (!m_setFullBuffers.empty()) + { + TOverlappedDataBuffer* pBuffer = *m_setFullBuffers.begin(); + if (pBuffer->GetBufferOrder() != m_ullNextWriteBufferOrder) + return nullptr; - m_setFullBuffers.erase(m_setFullBuffers.begin()); + m_setFullBuffers.erase(m_setFullBuffers.begin()); - // if this is the last part - mark that writing is finished, so that no other buffer will be written - if (pBuffer->IsLastPart()) - m_bDataWritingFinished = true; + // if this is the last part - mark that writing is finished, so that no other buffer will be written + if (pBuffer->IsLastPart()) + m_bDataWritingFinished = true; - ++m_ullNextWriteBufferOrder; + ++m_ullNextWriteBufferOrder; - UpdateWritePossibleEvent(); - m_eventAllBuffersAccountedFor.ResetEvent(); + UpdateWritePossibleEvent(); + m_eventAllBuffersAccountedFor.ResetEvent(); - return pBuffer; + return pBuffer; + } + + return nullptr; } - return nullptr; -} + void TOverlappedDataBufferQueue::AddFullBuffer(TOverlappedDataBuffer* pBuffer) + { + if (!pBuffer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); -void TOverlappedDataBufferQueue::AddFullBuffer(TOverlappedDataBuffer* pBuffer) -{ - if (!pBuffer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + std::pair pairInsertInfo = m_setFullBuffers.insert(pBuffer); + if (!pairInsertInfo.second) + THROW_CORE_EXCEPTION(eErr_InvalidOverlappedPosition); - std::pair pairInsertInfo = m_setFullBuffers.insert(pBuffer); - if (!pairInsertInfo.second) - THROW_CORE_EXCEPTION(eErr_InvalidOverlappedPosition); + if (pBuffer->IsLastPart()) + m_bDataSourceFinished = true; - if(pBuffer->IsLastPart()) - m_bDataSourceFinished = true; + UpdateWritePossibleEvent(); + UpdateAllBuffersAccountedFor(); + } - UpdateWritePossibleEvent(); - UpdateAllBuffersAccountedFor(); -} - -void TOverlappedDataBufferQueue::UpdateWritePossibleEvent() -{ - if (m_bDataWritingFinished || m_setFullBuffers.empty()) - m_eventWritePossible.ResetEvent(); - else + void TOverlappedDataBufferQueue::UpdateWritePossibleEvent() { - TOverlappedDataBuffer* pFirstBuffer = *m_setFullBuffers.begin(); - if (pFirstBuffer->GetBufferOrder() == m_ullNextWriteBufferOrder) - m_eventWritePossible.SetEvent(); - else + if (m_bDataWritingFinished || m_setFullBuffers.empty()) m_eventWritePossible.ResetEvent(); + else + { + TOverlappedDataBuffer* pFirstBuffer = *m_setFullBuffers.begin(); + if (pFirstBuffer->GetBufferOrder() == m_ullNextWriteBufferOrder) + m_eventWritePossible.SetEvent(); + else + m_eventWritePossible.ResetEvent(); + } } -} -TOverlappedDataBuffer* TOverlappedDataBufferQueue::GetFinishedBuffer() -{ - if(!m_setFinishedBuffers.empty()) + TOverlappedDataBuffer* TOverlappedDataBufferQueue::GetFinishedBuffer() { - TOverlappedDataBuffer* pBuffer = *m_setFinishedBuffers.begin(); - if(pBuffer->GetBufferOrder() != m_ullNextFinishedBufferOrder) - return nullptr; + if (!m_setFinishedBuffers.empty()) + { + TOverlappedDataBuffer* pBuffer = *m_setFinishedBuffers.begin(); + if (pBuffer->GetBufferOrder() != m_ullNextFinishedBufferOrder) + return nullptr; - m_setFinishedBuffers.erase(m_setFinishedBuffers.begin()); + m_setFinishedBuffers.erase(m_setFinishedBuffers.begin()); - ++m_ullNextFinishedBufferOrder; + ++m_ullNextFinishedBufferOrder; - UpdateWriteFinishedEvent(); - m_eventAllBuffersAccountedFor.ResetEvent(); + UpdateWriteFinishedEvent(); + m_eventAllBuffersAccountedFor.ResetEvent(); - return pBuffer; + return pBuffer; + } + + return nullptr; } - return nullptr; -} + void TOverlappedDataBufferQueue::AddFinishedBuffer(TOverlappedDataBuffer* pBuffer) + { + if (!pBuffer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); -void TOverlappedDataBufferQueue::AddFinishedBuffer(TOverlappedDataBuffer* pBuffer) -{ - if (!pBuffer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + std::pair pairInsertInfo = m_setFinishedBuffers.insert(pBuffer); + if (!pairInsertInfo.second) + THROW_CORE_EXCEPTION(eErr_InvalidOverlappedPosition); - std::pair pairInsertInfo = m_setFinishedBuffers.insert(pBuffer); - if (!pairInsertInfo.second) - THROW_CORE_EXCEPTION(eErr_InvalidOverlappedPosition); + UpdateWriteFinishedEvent(); + UpdateAllBuffersAccountedFor(); + } - UpdateWriteFinishedEvent(); - UpdateAllBuffersAccountedFor(); -} - -void TOverlappedDataBufferQueue::UpdateWriteFinishedEvent() -{ - if (m_setFinishedBuffers.empty()) - m_eventWriteFinished.ResetEvent(); - else + void TOverlappedDataBufferQueue::UpdateWriteFinishedEvent() { - TOverlappedDataBuffer* pFirstBuffer = *m_setFinishedBuffers.begin(); - if (pFirstBuffer->GetBufferOrder() == m_ullNextFinishedBufferOrder) - m_eventWriteFinished.SetEvent(); - else + if (m_setFinishedBuffers.empty()) m_eventWriteFinished.ResetEvent(); + else + { + TOverlappedDataBuffer* pFirstBuffer = *m_setFinishedBuffers.begin(); + if (pFirstBuffer->GetBufferOrder() == m_ullNextFinishedBufferOrder) + m_eventWriteFinished.SetEvent(); + else + m_eventWriteFinished.ResetEvent(); + } } -} -void TOverlappedDataBufferQueue::UpdateAllBuffersAccountedFor() -{ - size_t stCurrentBuffers = m_listEmptyBuffers.size() + m_setFullBuffers.size() + m_setFinishedBuffers.size(); - if (stCurrentBuffers == m_listAllBuffers.size()) - m_eventAllBuffersAccountedFor.SetEvent(); - else - m_eventAllBuffersAccountedFor.ResetEvent(); -} - -void TOverlappedDataBufferQueue::ReinitializeBuffers(size_t stCount, size_t stBufferSize) -{ - // sanity check - if any of the buffers are still in use, we can't change the sizes - if (m_listAllBuffers.size() != m_listEmptyBuffers.size()) - THROW_CORE_EXCEPTION(eErr_InternalProblem); - if (stBufferSize == 0) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); - - if (stBufferSize != GetSingleBufferSize()) + void TOverlappedDataBufferQueue::UpdateAllBuffersAccountedFor() { - // buffer sizes increased - clear current buffers and proceed with creating new ones - m_listAllBuffers.clear(); - m_listEmptyBuffers.clear(); + size_t stCurrentBuffers = m_listEmptyBuffers.size() + m_setFullBuffers.size() + m_setFinishedBuffers.size(); + if (stCurrentBuffers == m_listAllBuffers.size()) + m_eventAllBuffersAccountedFor.SetEvent(); + else + m_eventAllBuffersAccountedFor.ResetEvent(); } - else if (stCount == m_listAllBuffers.size()) - return; // nothing really changed - else if (stCount > m_listAllBuffers.size()) - stCount -= m_listAllBuffers.size(); // allocate only the missing buffers - else if (stCount < m_listAllBuffers.size()) + + void TOverlappedDataBufferQueue::ReinitializeBuffers(size_t stCount, size_t stBufferSize) { - // there are too many buffers - reduce - m_listEmptyBuffers.clear(); + // sanity check - if any of the buffers are still in use, we can't change the sizes + if (m_listAllBuffers.size() != m_listEmptyBuffers.size()) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + if (stBufferSize == 0) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - size_t stCountToRemove = m_listAllBuffers.size() - stCount; + if (stBufferSize != GetSingleBufferSize()) + { + // buffer sizes increased - clear current buffers and proceed with creating new ones + m_listAllBuffers.clear(); + m_listEmptyBuffers.clear(); + } + else if (stCount == m_listAllBuffers.size()) + return; // nothing really changed + else if (stCount > m_listAllBuffers.size()) + stCount -= m_listAllBuffers.size(); // allocate only the missing buffers + else if (stCount < m_listAllBuffers.size()) + { + // there are too many buffers - reduce + m_listEmptyBuffers.clear(); - m_listAllBuffers.erase(m_listAllBuffers.begin(), m_listAllBuffers.begin() + stCountToRemove); - for (const auto& upElement : m_listAllBuffers) + size_t stCountToRemove = m_listAllBuffers.size() - stCount; + + m_listAllBuffers.erase(m_listAllBuffers.begin(), m_listAllBuffers.begin() + stCountToRemove); + for (const auto& upElement : m_listAllBuffers) + { + m_listEmptyBuffers.push_back(upElement.get()); + } + + UpdateReadPossibleEvent(); + UpdateAllBuffersAccountedFor(); + return; + } + + // allocate buffers + while (stCount--) { - m_listEmptyBuffers.push_back(upElement.get()); + auto upBuffer = std::make_unique(stBufferSize, this); + m_listEmptyBuffers.push_back(upBuffer.get()); + m_listAllBuffers.push_back(std::move(upBuffer)); } UpdateReadPossibleEvent(); UpdateAllBuffersAccountedFor(); - return; } - // allocate buffers - while (stCount--) + size_t TOverlappedDataBufferQueue::GetTotalBufferCount() const { - auto upBuffer = std::make_unique(stBufferSize, this); - m_listEmptyBuffers.push_back(upBuffer.get()); - m_listAllBuffers.push_back(std::move(upBuffer)); + return m_listAllBuffers.size(); } - UpdateReadPossibleEvent(); - UpdateAllBuffersAccountedFor(); -} + size_t TOverlappedDataBufferQueue::GetSingleBufferSize() const + { + if (m_listAllBuffers.empty()) + return 0; -size_t TOverlappedDataBufferQueue::GetTotalBufferCount() const -{ - return m_listAllBuffers.size(); -} + return (*m_listAllBuffers.begin())->GetBufferSize(); + } -size_t TOverlappedDataBufferQueue::GetSingleBufferSize() const -{ - if (m_listAllBuffers.empty()) - return 0; + void TOverlappedDataBufferQueue::DataSourceChanged() + { + CleanupBuffers(); - return (*m_listAllBuffers.begin())->GetBufferSize(); -} + if (m_listAllBuffers.size() != m_listEmptyBuffers.size()) + THROW_CORE_EXCEPTION(eErr_InternalProblem); -void TOverlappedDataBufferQueue::DataSourceChanged() -{ - CleanupBuffers(); + m_bDataSourceFinished = false; + m_bDataWritingFinished = false; + m_ullNextReadBufferOrder = 0; + m_ullNextWriteBufferOrder = 0; + m_ullNextFinishedBufferOrder = 0; - if (m_listAllBuffers.size() != m_listEmptyBuffers.size()) - THROW_CORE_EXCEPTION(eErr_InternalProblem); + UpdateReadPossibleEvent(); + m_eventWritePossible.ResetEvent(); + m_eventWriteFinished.ResetEvent(); + } - m_bDataSourceFinished = false; - m_bDataWritingFinished = false; - m_ullNextReadBufferOrder = 0; - m_ullNextWriteBufferOrder = 0; - m_ullNextFinishedBufferOrder = 0; - - UpdateReadPossibleEvent(); - m_eventWritePossible.ResetEvent(); - m_eventWriteFinished.ResetEvent(); -} - -void TOverlappedDataBufferQueue::CleanupBuffers() -{ - // function sanitizes the buffer locations (empty/full/finished) - i.e. when there is full buffer that have no data, is marked eof and we are in the eof state - // then this buffer is really the empty one - if (m_bDataSourceFinished && !m_setFullBuffers.empty()) + void TOverlappedDataBufferQueue::CleanupBuffers() { - auto iterCurrent = m_setFullBuffers.begin(); - while (iterCurrent != m_setFullBuffers.end()) + // function sanitizes the buffer locations (empty/full/finished) - i.e. when there is full buffer that have no data, is marked eof and we are in the eof state + // then this buffer is really the empty one + if (m_bDataSourceFinished && !m_setFullBuffers.empty()) { - if ((*iterCurrent)->IsLastPart()) + auto iterCurrent = m_setFullBuffers.begin(); + while (iterCurrent != m_setFullBuffers.end()) { - m_listEmptyBuffers.push_back(*iterCurrent); - iterCurrent = m_setFullBuffers.erase(iterCurrent); + if ((*iterCurrent)->IsLastPart()) + { + m_listEmptyBuffers.push_back(*iterCurrent); + iterCurrent = m_setFullBuffers.erase(iterCurrent); + } + else + ++iterCurrent; } - else - ++iterCurrent; } } -} -void TOverlappedDataBufferQueue::WaitForMissingBuffers(HANDLE hKillEvent) -{ - enum { eKillThread = 0, eAllBuffersReturned, eHandleCount }; - std::array arrHandles = { hKillEvent, m_eventAllBuffersAccountedFor.Handle() }; - - bool bExit = false; - while (!bExit) + void TOverlappedDataBufferQueue::WaitForMissingBuffers(HANDLE hKillEvent) { - DWORD dwResult = WaitForMultipleObjectsEx(eHandleCount, arrHandles.data(), false, INFINITE, true); - switch (dwResult) + enum { eKillThread = 0, eAllBuffersReturned, eHandleCount }; + std::array arrHandles = { hKillEvent, m_eventAllBuffersAccountedFor.Handle() }; + + bool bExit = false; + while (!bExit) { - case STATUS_USER_APC: - ATLTRACE(_T("STATUS_USER_APC while waiting for missing buffers\n")); - break; + DWORD dwResult = WaitForMultipleObjectsEx(eHandleCount, arrHandles.data(), false, INFINITE, true); + switch (dwResult) + { + case STATUS_USER_APC: + ATLTRACE(_T("STATUS_USER_APC while waiting for missing buffers\n")); + break; - case WAIT_OBJECT_0 + eAllBuffersReturned: - bExit = true; - break; + case WAIT_OBJECT_0 + eAllBuffersReturned: + bExit = true; + break; - case WAIT_OBJECT_0 + eKillThread: - bExit = true; - break; + case WAIT_OBJECT_0 + eKillThread: + bExit = true; + break; + } } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TOverlappedDataBufferQueue.h =================================================================== diff -u -N -radf2d680643ef85665b042e03fed274ab8f11180 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TOverlappedDataBufferQueue.h (.../TOverlappedDataBufferQueue.h) (revision adf2d680643ef85665b042e03fed274ab8f11180) +++ src/libchcore/TOverlappedDataBufferQueue.h (.../TOverlappedDataBufferQueue.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,82 +24,81 @@ #include "TEvent.h" #include "IOverlappedDataBufferQueue.h" -BEGIN_CHCORE_NAMESPACE - -class TOverlappedDataBuffer; - -struct CompareBufferPositions +namespace chcore { - bool operator()(const TOverlappedDataBuffer* rBufferA, const TOverlappedDataBuffer* rBufferB); -}; + class TOverlappedDataBuffer; -class TOverlappedDataBufferQueue : public IOverlappedDataBufferQueue -{ -public: - TOverlappedDataBufferQueue(); - TOverlappedDataBufferQueue(size_t stCount, size_t stBufferSize); - ~TOverlappedDataBufferQueue(); + struct CompareBufferPositions + { + bool operator()(const TOverlappedDataBuffer* rBufferA, const TOverlappedDataBuffer* rBufferB); + }; - void ReinitializeBuffers(size_t stCount, size_t stBufferSize); - size_t GetTotalBufferCount() const; - size_t GetSingleBufferSize() const; + class TOverlappedDataBufferQueue : public IOverlappedDataBufferQueue + { + public: + TOverlappedDataBufferQueue(); + TOverlappedDataBufferQueue(size_t stCount, size_t stBufferSize); + ~TOverlappedDataBufferQueue(); - // buffer management - virtual void AddEmptyBuffer(TOverlappedDataBuffer* pBuffer) override; - virtual TOverlappedDataBuffer* GetEmptyBuffer() override; + void ReinitializeBuffers(size_t stCount, size_t stBufferSize); + size_t GetTotalBufferCount() const; + size_t GetSingleBufferSize() const; - virtual void AddFullBuffer(TOverlappedDataBuffer* pBuffer) override; - virtual TOverlappedDataBuffer* GetFullBuffer() override; + // buffer management + virtual void AddEmptyBuffer(TOverlappedDataBuffer* pBuffer) override; + virtual TOverlappedDataBuffer* GetEmptyBuffer() override; - virtual void AddFinishedBuffer(TOverlappedDataBuffer* pBuffer) override; - virtual TOverlappedDataBuffer* GetFinishedBuffer() override; + virtual void AddFullBuffer(TOverlappedDataBuffer* pBuffer) override; + virtual TOverlappedDataBuffer* GetFullBuffer() override; - // data source change - void DataSourceChanged(); + virtual void AddFinishedBuffer(TOverlappedDataBuffer* pBuffer) override; + virtual TOverlappedDataBuffer* GetFinishedBuffer() override; - // processing info - bool IsDataSourceFinished() const { return m_bDataSourceFinished; } - bool IsDataWritingFinished() const { return m_bDataWritingFinished; } + // data source change + void DataSourceChanged(); - // event access - HANDLE GetEventReadPossibleHandle() const { return m_eventReadPossible.Handle(); } - HANDLE GetEventWritePossibleHandle() const { return m_eventWritePossible.Handle(); } - HANDLE GetEventWriteFinishedHandle() const { return m_eventWriteFinished.Handle(); } - HANDLE GetEventAllBuffersAccountedFor() const { return m_eventAllBuffersAccountedFor.Handle(); } + // processing info + bool IsDataSourceFinished() const { return m_bDataSourceFinished; } + bool IsDataWritingFinished() const { return m_bDataWritingFinished; } - void WaitForMissingBuffers(HANDLE hKillEvent); + // event access + HANDLE GetEventReadPossibleHandle() const { return m_eventReadPossible.Handle(); } + HANDLE GetEventWritePossibleHandle() const { return m_eventWritePossible.Handle(); } + HANDLE GetEventWriteFinishedHandle() const { return m_eventWriteFinished.Handle(); } + HANDLE GetEventAllBuffersAccountedFor() const { return m_eventAllBuffersAccountedFor.Handle(); } -private: - void CleanupBuffers(); - void UpdateReadPossibleEvent(); - void UpdateWritePossibleEvent(); - void UpdateWriteFinishedEvent(); - void UpdateAllBuffersAccountedFor(); + void WaitForMissingBuffers(HANDLE hKillEvent); -private: - std::deque> m_listAllBuffers; + private: + void CleanupBuffers(); + void UpdateReadPossibleEvent(); + void UpdateWritePossibleEvent(); + void UpdateWriteFinishedEvent(); + void UpdateAllBuffersAccountedFor(); - std::list m_listEmptyBuffers; + private: + std::deque> m_listAllBuffers; - using FullBuffersSet = std::set < TOverlappedDataBuffer*, CompareBufferPositions > ; - FullBuffersSet m_setFullBuffers; + std::list m_listEmptyBuffers; - using FinishedBuffersSet = std::set < TOverlappedDataBuffer*, CompareBufferPositions > ; - FinishedBuffersSet m_setFinishedBuffers; + using FullBuffersSet = std::set < TOverlappedDataBuffer*, CompareBufferPositions >; + FullBuffersSet m_setFullBuffers; - bool m_bDataSourceFinished; // input file was already read to the end - bool m_bDataWritingFinished; // output file was already written to the end + using FinishedBuffersSet = std::set < TOverlappedDataBuffer*, CompareBufferPositions >; + FinishedBuffersSet m_setFinishedBuffers; - unsigned long long m_ullNextReadBufferOrder; // next order id for read buffers - unsigned long long m_ullNextWriteBufferOrder; // next order id to be processed when writing - unsigned long long m_ullNextFinishedBufferOrder; // next order id to be processed when finishing writing + bool m_bDataSourceFinished; // input file was already read to the end + bool m_bDataWritingFinished; // output file was already written to the end - TEvent m_eventReadPossible; - TEvent m_eventWritePossible; - TEvent m_eventWriteFinished; - TEvent m_eventAllBuffersAccountedFor; -}; + unsigned long long m_ullNextReadBufferOrder; // next order id for read buffers + unsigned long long m_ullNextWriteBufferOrder; // next order id to be processed when writing + unsigned long long m_ullNextFinishedBufferOrder; // next order id to be processed when finishing writing -END_CHCORE_NAMESPACE + TEvent m_eventReadPossible; + TEvent m_eventWritePossible; + TEvent m_eventWriteFinished; + TEvent m_eventAllBuffersAccountedFor; + }; +} #endif Index: src/libchcore/TPath.h =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TPath.h (.../TPath.h) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/TPath.h (.../TPath.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,111 +22,110 @@ #include "libchcore.h" #include "TString.h" -BEGIN_CHCORE_NAMESPACE - -class TSmartPath; -class TPathContainer; - -class LIBCHCORE_API TSmartPath +namespace chcore { -protected: - BOOST_STATIC_CONSTANT(bool, DefaultCaseSensitivity = false); + class TSmartPath; + class TPathContainer; -public: - // Construction/destruction - TSmartPath(); - TSmartPath(const TSmartPath& spPath); + class LIBCHCORE_API TSmartPath + { + protected: + BOOST_STATIC_CONSTANT(bool, DefaultCaseSensitivity = false); - ~TSmartPath(); + public: + // Construction/destruction + TSmartPath(); + TSmartPath(const TSmartPath& spPath); - // operators - TSmartPath& operator=(const TSmartPath& spPath); + ~TSmartPath(); - bool operator==(const TSmartPath& rPath) const; - bool operator!=(const TSmartPath& rPath) const; - bool operator<(const TSmartPath& rPath) const; - bool operator>(const TSmartPath& rPath) const; + // operators + TSmartPath& operator=(const TSmartPath& spPath); - TSmartPath operator+(const TSmartPath& rPath) const; - TSmartPath& operator+=(const TSmartPath& rPath); + bool operator==(const TSmartPath& rPath) const; + bool operator!=(const TSmartPath& rPath) const; + bool operator<(const TSmartPath& rPath) const; + bool operator>(const TSmartPath& rPath) const; - // from/to string conversions - void FromString(const wchar_t* pszPath); - void FromString(const TString& strPath); + TSmartPath operator+(const TSmartPath& rPath) const; + TSmartPath& operator+=(const TSmartPath& rPath); - const wchar_t* ToString() const; - TString ToWString() const; + // from/to string conversions + void FromString(const wchar_t* pszPath); + void FromString(const TString& strPath); - // other operations - void Clear() throw(); + const wchar_t* ToString() const; + TString ToWString() const; - TSmartPath AppendCopy(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists = true) const; - TSmartPath& Append(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists = true); + // other operations + void Clear() throw(); - void SplitPath(TPathContainer& vComponents) const; + TSmartPath AppendCopy(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists = true) const; + TSmartPath& Append(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists = true); - int Compare(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; - bool IsChildOf(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; + void SplitPath(TPathContainer& vComponents) const; - bool MakeRelativePath(const TSmartPath& rReferenceBasePath, bool bCaseSensitive = DefaultCaseSensitivity); - bool MakeAbsolutePath(const TSmartPath& rReferenceBasePath); + int Compare(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; + bool IsChildOf(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; - void AppendIfNotExists(const wchar_t* pszPostfix, bool bCaseSensitive = DefaultCaseSensitivity); - void CutIfExists(const wchar_t* pszPostfix, bool bCaseSensitive = DefaultCaseSensitivity); + bool MakeRelativePath(const TSmartPath& rReferenceBasePath, bool bCaseSensitive = DefaultCaseSensitivity); + bool MakeAbsolutePath(const TSmartPath& rReferenceBasePath); - bool IsNetworkPath() const; - bool IsRelativePath() const; + void AppendIfNotExists(const wchar_t* pszPostfix, bool bCaseSensitive = DefaultCaseSensitivity); + void CutIfExists(const wchar_t* pszPostfix, bool bCaseSensitive = DefaultCaseSensitivity); - bool IsDrive() const; - bool HasDrive() const; - TSmartPath GetDrive() const; // c: for c:\windows\test.txt - wchar_t GetDriveLetter() const; // 'c' for c:\windows\test.txt, null for non-drive based paths + bool IsNetworkPath() const; + bool IsRelativePath() const; - bool IsServerName() const; - bool HasServerName() const; - TSmartPath GetServerName() const; + bool IsDrive() const; + bool HasDrive() const; + TSmartPath GetDrive() const; // c: for c:\windows\test.txt + wchar_t GetDriveLetter() const; // 'c' for c:\windows\test.txt, null for non-drive based paths - bool HasFileRoot() const; - TSmartPath GetFileRoot() const; // "c:\windows\" for "c:\windows\test.txt" + bool IsServerName() const; + bool HasServerName() const; + TSmartPath GetServerName() const; - bool HasFileDir() const; // \windows\ for c:\windows\test.txt - TSmartPath GetFileDir() const; // \windows\ for c:\windows\test.txt + bool HasFileRoot() const; + TSmartPath GetFileRoot() const; // "c:\windows\" for "c:\windows\test.txt" - bool HasFileTitle() const; // test for c:\windows\test.txt - TSmartPath GetFileTitle() const; // test for c:\windows\test.txt + bool HasFileDir() const; // \windows\ for c:\windows\test.txt + TSmartPath GetFileDir() const; // \windows\ for c:\windows\test.txt - bool HasExtension() const; // txt for c:\windows\test.txt - TSmartPath GetExtension() const; // txt for c:\windows\test.txt + bool HasFileTitle() const; // test for c:\windows\test.txt + TSmartPath GetFileTitle() const; // test for c:\windows\test.txt - bool HasFileName() const; // test.txt for c:\windows\test.txt - TSmartPath GetFileName() const; // test.txt for c:\windows\test.txt - void DeleteFileName(); // c:\windows\ for c:\windows\test.txt + bool HasExtension() const; // txt for c:\windows\test.txt + TSmartPath GetExtension() const; // txt for c:\windows\test.txt - TSmartPath GetParent() const; + bool HasFileName() const; // test.txt for c:\windows\test.txt + TSmartPath GetFileName() const; // test.txt for c:\windows\test.txt + void DeleteFileName(); // c:\windows\ for c:\windows\test.txt - bool EndsWithSeparator() const; - void AppendSeparatorIfDoesNotExist(); - void StripSeparatorAtEnd(); + TSmartPath GetParent() const; - bool StartsWithSeparator() const; - void PrependSeparatorIfDoesNotExist(); - void StripSeparatorAtFront(); + bool EndsWithSeparator() const; + void AppendSeparatorIfDoesNotExist(); + void StripSeparatorAtEnd(); - bool StartsWith(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity); + bool StartsWithSeparator() const; + void PrependSeparatorIfDoesNotExist(); + void StripSeparatorAtFront(); - bool IsEmpty() const; - size_t GetLength() const; + bool StartsWith(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity); -protected: - static bool IsSeparator(wchar_t wchSeparator); + bool IsEmpty() const; + size_t GetLength() const; -protected: - TString m_strPath; -}; + protected: + static bool IsSeparator(wchar_t wchSeparator); -LIBCHCORE_API TSmartPath PathFromString(const wchar_t* pszPath); -LIBCHCORE_API TSmartPath PathFromWString(const TString& strPath); + protected: + TString m_strPath; + }; -END_CHCORE_NAMESPACE + LIBCHCORE_API TSmartPath PathFromString(const wchar_t* pszPath); + LIBCHCORE_API TSmartPath PathFromWString(const TString& strPath); +} #endif Index: src/libchcore/TPathContainer.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TPathContainer.cpp (.../TPathContainer.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TPathContainer.cpp (.../TPathContainer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,200 +22,199 @@ #include "ErrorCodes.h" #include "TStringArray.h" -BEGIN_CHCORE_NAMESPACE - -// ============================================================================ -/// TPathContainer::TPathContainer -/// @date 2009/11/30 -/// -/// @brief Constructs an empty path container object. -// ============================================================================ -TPathContainer::TPathContainer() : -m_vPaths() +namespace chcore { -} + // ============================================================================ + /// TPathContainer::TPathContainer + /// @date 2009/11/30 + /// + /// @brief Constructs an empty path container object. + // ============================================================================ + TPathContainer::TPathContainer() : + m_vPaths() + { + } -// ============================================================================ -/// TPathContainer::TPathContainer -/// @date 2009/11/30 -/// -/// @brief Constructs the path container object from another path container. -/// @param[in] rSrcContainer - path container to copy paths from. -// ============================================================================ -TPathContainer::TPathContainer(const TPathContainer& rSrcContainer) : -m_vPaths(rSrcContainer.m_vPaths) -{ -} + // ============================================================================ + /// TPathContainer::TPathContainer + /// @date 2009/11/30 + /// + /// @brief Constructs the path container object from another path container. + /// @param[in] rSrcContainer - path container to copy paths from. + // ============================================================================ + TPathContainer::TPathContainer(const TPathContainer& rSrcContainer) : + m_vPaths(rSrcContainer.m_vPaths) + { + } -// ============================================================================ -/// TPathContainer::~TPathContainer -/// @date 2009/11/30 -/// -/// @brief Destructs this path container object. -// ============================================================================ -TPathContainer::~TPathContainer() -{ -} + // ============================================================================ + /// TPathContainer::~TPathContainer + /// @date 2009/11/30 + /// + /// @brief Destructs this path container object. + // ============================================================================ + TPathContainer::~TPathContainer() + { + } -// ============================================================================ -/// TPathContainer::operator= -/// @date 2009/11/30 -/// -/// @brief Assigns another path container object to this one. -/// @param[in] rSrcContainer - container with paths to copy from. -/// @return Reference to this object. -// ============================================================================ -TPathContainer& TPathContainer::operator=(const TPathContainer& rSrcContainer) -{ - if(this != &rSrcContainer) - m_vPaths = rSrcContainer.m_vPaths; + // ============================================================================ + /// TPathContainer::operator= + /// @date 2009/11/30 + /// + /// @brief Assigns another path container object to this one. + /// @param[in] rSrcContainer - container with paths to copy from. + /// @return Reference to this object. + // ============================================================================ + TPathContainer& TPathContainer::operator=(const TPathContainer& rSrcContainer) + { + if (this != &rSrcContainer) + m_vPaths = rSrcContainer.m_vPaths; - return *this; -} + return *this; + } -// ============================================================================ -/// TPathContainer::Add -/// @date 2009/11/30 -/// -/// @brief Adds a path to the end of list. -/// @param[in] spPath - path to be added. -// ============================================================================ -void TPathContainer::Add(const TSmartPath& spPath) -{ - m_vPaths.push_back(spPath); -} + // ============================================================================ + /// TPathContainer::Add + /// @date 2009/11/30 + /// + /// @brief Adds a path to the end of list. + /// @param[in] spPath - path to be added. + // ============================================================================ + void TPathContainer::Add(const TSmartPath& spPath) + { + m_vPaths.push_back(spPath); + } -void TPathContainer::Append(const TPathContainer& vPaths) -{ - m_vPaths.insert(m_vPaths.end(), vPaths.m_vPaths.begin(), vPaths.m_vPaths.end()); -} + void TPathContainer::Append(const TPathContainer& vPaths) + { + m_vPaths.insert(m_vPaths.end(), vPaths.m_vPaths.begin(), vPaths.m_vPaths.end()); + } -// ============================================================================ -/// TPathContainer::GetAt -/// @date 2009/11/30 -/// -/// @brief Retrieves path at specified index. -/// @param[in] stIndex - index at which to retrieve item. -/// @return Reference to the path object. -// ============================================================================ -const TSmartPath& TPathContainer::GetAt(size_t stIndex) const -{ - if(stIndex > m_vPaths.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + // ============================================================================ + /// TPathContainer::GetAt + /// @date 2009/11/30 + /// + /// @brief Retrieves path at specified index. + /// @param[in] stIndex - index at which to retrieve item. + /// @return Reference to the path object. + // ============================================================================ + const TSmartPath& TPathContainer::GetAt(size_t stIndex) const + { + if (stIndex > m_vPaths.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - return m_vPaths.at(stIndex); -} + return m_vPaths.at(stIndex); + } -// ============================================================================ -/// TPathContainer::GetAt -/// @date 2009/11/30 -/// -/// @brief Retrieves path at specified index. -/// @param[in] stIndex - index at which to retrieve item. -/// @return Reference to the path object. -// ============================================================================ -TSmartPath& TPathContainer::GetAt(size_t stIndex) -{ - if(stIndex > m_vPaths.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + // ============================================================================ + /// TPathContainer::GetAt + /// @date 2009/11/30 + /// + /// @brief Retrieves path at specified index. + /// @param[in] stIndex - index at which to retrieve item. + /// @return Reference to the path object. + // ============================================================================ + TSmartPath& TPathContainer::GetAt(size_t stIndex) + { + if (stIndex > m_vPaths.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - return m_vPaths.at(stIndex); -} + return m_vPaths.at(stIndex); + } -// ============================================================================ -/// TPathContainer::SetAt -/// @date 2009/11/30 -/// -/// @brief Sets a path at a specified index. -/// @param[in] stIndex - index at which to set the path. -/// @param[in] spPath - path to be set. -// ============================================================================ -void TPathContainer::SetAt(size_t stIndex, const TSmartPath& spPath) -{ - if(stIndex > m_vPaths.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + // ============================================================================ + /// TPathContainer::SetAt + /// @date 2009/11/30 + /// + /// @brief Sets a path at a specified index. + /// @param[in] stIndex - index at which to set the path. + /// @param[in] spPath - path to be set. + // ============================================================================ + void TPathContainer::SetAt(size_t stIndex, const TSmartPath& spPath) + { + if (stIndex > m_vPaths.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - m_vPaths[stIndex] = spPath; -} + m_vPaths[stIndex] = spPath; + } -// ============================================================================ -/// TPathContainer::DeleteAt -/// @date 2009/11/30 -/// -/// @brief Removes a path from container at specified index. -/// @param[in] stIndex - index at which to delete. -// ============================================================================ -void TPathContainer::DeleteAt(size_t stIndex) -{ - if(stIndex > m_vPaths.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + // ============================================================================ + /// TPathContainer::DeleteAt + /// @date 2009/11/30 + /// + /// @brief Removes a path from container at specified index. + /// @param[in] stIndex - index at which to delete. + // ============================================================================ + void TPathContainer::DeleteAt(size_t stIndex) + { + if (stIndex > m_vPaths.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - m_vPaths.erase(m_vPaths.begin() + stIndex); -} + m_vPaths.erase(m_vPaths.begin() + stIndex); + } -// ============================================================================ -/// TPathContainer::Clear -/// @date 2009/11/30 -/// -/// @brief Removes all paths from this container. -// ============================================================================ -void TPathContainer::Clear() -{ - m_vPaths.clear(); -} + // ============================================================================ + /// TPathContainer::Clear + /// @date 2009/11/30 + /// + /// @brief Removes all paths from this container. + // ============================================================================ + void TPathContainer::Clear() + { + m_vPaths.clear(); + } -// ============================================================================ -/// TPathContainer::GetCount -/// @date 2009/11/30 -/// -/// @brief Retrieves count of elements in the container. -/// @return Count of elements. -// ============================================================================ -size_t TPathContainer::GetCount() const -{ - return m_vPaths.size(); -} + // ============================================================================ + /// TPathContainer::GetCount + /// @date 2009/11/30 + /// + /// @brief Retrieves count of elements in the container. + /// @return Count of elements. + // ============================================================================ + size_t TPathContainer::GetCount() const + { + return m_vPaths.size(); + } -// ============================================================================ -/// TPathContainer::GetCount -/// @date 2010/10/12 -/// -/// @brief Retrieves info if this container is empty. -/// @return True if empty, false otherwise. -// ============================================================================ -bool TPathContainer::IsEmpty() const -{ - return m_vPaths.empty(); -} - -void TPathContainer::StoreInConfig(TConfig& rConfig, PCTSTR pszPropName) const -{ - TStringArray vPaths; - - // store as vector of strings (ineffective; should be done better) - BOOST_FOREACH(const TSmartPath& spPath, m_vPaths) + // ============================================================================ + /// TPathContainer::GetCount + /// @date 2010/10/12 + /// + /// @brief Retrieves info if this container is empty. + /// @return True if empty, false otherwise. + // ============================================================================ + bool TPathContainer::IsEmpty() const { - vPaths.Add(spPath.ToWString()); + return m_vPaths.empty(); } - rConfig.SetValue(pszPropName, vPaths); -} + void TPathContainer::StoreInConfig(TConfig& rConfig, PCTSTR pszPropName) const + { + TStringArray vPaths; -bool TPathContainer::ReadFromConfig(const TConfig& rConfig, PCTSTR pszPropName) -{ - m_vPaths.clear(); + // store as vector of strings (ineffective; should be done better) + BOOST_FOREACH(const TSmartPath& spPath, m_vPaths) + { + vPaths.Add(spPath.ToWString()); + } - TStringArray vPaths; - if(rConfig.GetValue(pszPropName, vPaths)) + rConfig.SetValue(pszPropName, vPaths); + } + + bool TPathContainer::ReadFromConfig(const TConfig& rConfig, PCTSTR pszPropName) { - for(size_t stIndex = 0; stIndex < vPaths.GetCount(); ++stIndex) + m_vPaths.clear(); + + TStringArray vPaths; + if (rConfig.GetValue(pszPropName, vPaths)) { - m_vPaths.push_back(PathFromWString(vPaths.GetAt(stIndex))); + for (size_t stIndex = 0; stIndex < vPaths.GetCount(); ++stIndex) + { + m_vPaths.push_back(PathFromWString(vPaths.GetAt(stIndex))); + } + return true; } - return true; + else + return false; } - else - return false; } - -END_CHCORE_NAMESPACE Index: src/libchcore/TPathContainer.h =================================================================== diff -u -N -rb1e03eb232a784d6e2d40f67cbbbb33be0972228 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TPathContainer.h (.../TPathContainer.h) (revision b1e03eb232a784d6e2d40f67cbbbb33be0972228) +++ src/libchcore/TPathContainer.h (.../TPathContainer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,43 +23,42 @@ #include "TPath.h" #include "TConfig.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TPathContainer +namespace chcore { -public: - TPathContainer(); - TPathContainer(const TPathContainer& rSrcContainer); - ~TPathContainer(); + class LIBCHCORE_API TPathContainer + { + public: + TPathContainer(); + TPathContainer(const TPathContainer& rSrcContainer); + ~TPathContainer(); - TPathContainer& operator=(const TPathContainer& rSrcContainer); + TPathContainer& operator=(const TPathContainer& rSrcContainer); - void Add(const TSmartPath& spPath); - void Append(const TPathContainer& vPaths); + void Add(const TSmartPath& spPath); + void Append(const TPathContainer& vPaths); - const TSmartPath& GetAt(size_t stIndex) const; - TSmartPath& GetAt(size_t stIndex); + const TSmartPath& GetAt(size_t stIndex) const; + TSmartPath& GetAt(size_t stIndex); - void SetAt(size_t stIndex, const TSmartPath& spPath); + void SetAt(size_t stIndex, const TSmartPath& spPath); - void DeleteAt(size_t stIndex); - void Clear(); + void DeleteAt(size_t stIndex); + void Clear(); - size_t GetCount() const; - bool IsEmpty() const; + size_t GetCount() const; + bool IsEmpty() const; - void StoreInConfig(TConfig& rConfig, PCTSTR pszPropName) const; - bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszPropName); + void StoreInConfig(TConfig& rConfig, PCTSTR pszPropName) const; + bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszPropName); -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::vector m_vPaths; + std::vector m_vPaths; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - CONFIG_MEMBER_SERIALIZATION(TPathContainer) #endif Index: src/libchcore/TPlainStringPool.cpp =================================================================== diff -u -N -r7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TPlainStringPool.cpp (.../TPlainStringPool.cpp) (revision 7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66) +++ src/libchcore/TPlainStringPool.cpp (.../TPlainStringPool.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,76 +21,75 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -TPlainStringPool::TPlainStringPool() +namespace chcore { -} + TPlainStringPool::TPlainStringPool() + { + } -TPlainStringPool::~TPlainStringPool() -{ - Clear(); -} + TPlainStringPool::~TPlainStringPool() + { + Clear(); + } -wchar_t* TPlainStringPool::Alloc(size_t stCount) -{ - if(stCount > BlockSize) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); - - // find block where the new string would fit - size_t stBlockCount = m_vBlocks.size(); - for(size_t stIndex = 0; stIndex < stBlockCount; ++stIndex) + wchar_t* TPlainStringPool::Alloc(size_t stCount) { - if(m_vBlocks[stIndex].second >= stCount) + if (stCount > BlockSize) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); + + // find block where the new string would fit + size_t stBlockCount = m_vBlocks.size(); + for (size_t stIndex = 0; stIndex < stBlockCount; ++stIndex) { - wchar_t* pszResult = m_vBlocks[stIndex].first + BlockSize - m_vBlocks[stIndex].second; - m_vBlocks[stIndex].second -= stCount; - return pszResult; + if (m_vBlocks[stIndex].second >= stCount) + { + wchar_t* pszResult = m_vBlocks[stIndex].first + BlockSize - m_vBlocks[stIndex].second; + m_vBlocks[stIndex].second -= stCount; + return pszResult; + } } - } - wchar_t* pszBuffer = AllocNewBlock(); - m_vBlocks.back().second -= stCount; + wchar_t* pszBuffer = AllocNewBlock(); + m_vBlocks.back().second -= stCount; - return pszBuffer; -} + return pszBuffer; + } -wchar_t* TPlainStringPool::AllocForString(const wchar_t* pszString) -{ - size_t stLen = wcslen(pszString) + 1; + wchar_t* TPlainStringPool::AllocForString(const wchar_t* pszString) + { + size_t stLen = wcslen(pszString) + 1; - wchar_t* pszBuffer = Alloc(stLen); - wmemcpy_s(pszBuffer, BlockSize, pszString, stLen); + wchar_t* pszBuffer = Alloc(stLen); + wmemcpy_s(pszBuffer, BlockSize, pszString, stLen); - return pszBuffer; -} + return pszBuffer; + } -void TPlainStringPool::Clear(bool bLeaveSingleEmptyBlock) -{ - size_t stBlockCount = m_vBlocks.size(); - for(size_t stIndex = 0; stIndex < stBlockCount; ++stIndex) + void TPlainStringPool::Clear(bool bLeaveSingleEmptyBlock) { - if(!bLeaveSingleEmptyBlock || stIndex != 0) + size_t stBlockCount = m_vBlocks.size(); + for (size_t stIndex = 0; stIndex < stBlockCount; ++stIndex) { - delete [] m_vBlocks[stIndex].first; + if (!bLeaveSingleEmptyBlock || stIndex != 0) + { + delete[] m_vBlocks[stIndex].first; + } } + + if (bLeaveSingleEmptyBlock) + { + if (m_vBlocks.size() > 1) + m_vBlocks.erase(m_vBlocks.begin() + 1, m_vBlocks.end()); + } + else + m_vBlocks.clear(); } - if(bLeaveSingleEmptyBlock) + wchar_t* TPlainStringPool::AllocNewBlock() { - if(m_vBlocks.size() > 1) - m_vBlocks.erase(m_vBlocks.begin() + 1, m_vBlocks.end()); + wchar_t* pszBlock = new wchar_t[BlockSize]; + m_vBlocks.push_back(std::make_pair(pszBlock, BlockSize)); + + return pszBlock; } - else - m_vBlocks.clear(); } - -wchar_t* TPlainStringPool::AllocNewBlock() -{ - wchar_t* pszBlock = new wchar_t[BlockSize]; - m_vBlocks.push_back(std::make_pair(pszBlock, BlockSize)); - - return pszBlock; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TPlainStringPool.h =================================================================== diff -u -N -r7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TPlainStringPool.h (.../TPlainStringPool.h) (revision 7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66) +++ src/libchcore/TPlainStringPool.h (.../TPlainStringPool.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,32 +21,31 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TPlainStringPool +namespace chcore { -public: - static const size_t BlockSize = 256*1024; + class LIBCHCORE_API TPlainStringPool + { + public: + static const size_t BlockSize = 256 * 1024; -public: - TPlainStringPool(); - ~TPlainStringPool(); + public: + TPlainStringPool(); + ~TPlainStringPool(); - wchar_t* Alloc(size_t stCount); - wchar_t* AllocForString(const wchar_t* pszString); + wchar_t* Alloc(size_t stCount); + wchar_t* AllocForString(const wchar_t* pszString); - void Clear(bool bLeaveSingleEmptyBlock = true); + void Clear(bool bLeaveSingleEmptyBlock = true); -private: - wchar_t* AllocNewBlock(); + private: + wchar_t* AllocNewBlock(); -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::vector > m_vBlocks; // memory blocks of size BlockSize => remaining size + std::vector > m_vBlocks; // memory blocks of size BlockSize => remaining size #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TRemovedObjects.cpp =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TRemovedObjects.cpp (.../TRemovedObjects.cpp) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TRemovedObjects.cpp (.../TRemovedObjects.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,44 +21,43 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -TRemovedObjects::TRemovedObjects() +namespace chcore { -} + TRemovedObjects::TRemovedObjects() + { + } -TRemovedObjects::~TRemovedObjects() -{ -} + TRemovedObjects::~TRemovedObjects() + { + } -void TRemovedObjects::Add(object_id_t oidObjectID) -{ - m_setObjects.insert(oidObjectID); -} + void TRemovedObjects::Add(object_id_t oidObjectID) + { + m_setObjects.insert(oidObjectID); + } -size_t TRemovedObjects::GetCount() const -{ - return m_setObjects.size(); -} + size_t TRemovedObjects::GetCount() const + { + return m_setObjects.size(); + } -object_id_t TRemovedObjects::GetAt(size_t stIndex) const -{ - if(stIndex >= m_setObjects.size()) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + object_id_t TRemovedObjects::GetAt(size_t stIndex) const + { + if (stIndex >= m_setObjects.size()) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - std::set::const_iterator iter = m_setObjects.begin(); - std::advance(iter, stIndex); - return *iter; -} + std::set::const_iterator iter = m_setObjects.begin(); + std::advance(iter, stIndex); + return *iter; + } -void TRemovedObjects::Clear() -{ - m_setObjects.clear(); -} + void TRemovedObjects::Clear() + { + m_setObjects.clear(); + } -bool TRemovedObjects::IsEmpty() const -{ - return m_setObjects.empty(); + bool TRemovedObjects::IsEmpty() const + { + return m_setObjects.empty(); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TRemovedObjects.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TRemovedObjects.h (.../TRemovedObjects.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TRemovedObjects.h (.../TRemovedObjects.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,28 +22,27 @@ #include "libchcore.h" #include "SerializerDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TRemovedObjects +namespace chcore { -public: - TRemovedObjects(); - ~TRemovedObjects(); + class LIBCHCORE_API TRemovedObjects + { + public: + TRemovedObjects(); + ~TRemovedObjects(); - void Add(object_id_t oidObjectID); - size_t GetCount() const; - object_id_t GetAt(size_t stIndex) const; - void Clear(); + void Add(object_id_t oidObjectID); + size_t GetCount() const; + object_id_t GetAt(size_t stIndex) const; + void Clear(); - bool IsEmpty() const; + bool IsEmpty() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::set m_setObjects; + std::set m_setObjects; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteColumnDefinition.cpp =================================================================== diff -u -N -r7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteColumnDefinition.cpp (.../TSQLiteColumnDefinition.cpp) (revision 7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66) +++ src/libchcore/TSQLiteColumnDefinition.cpp (.../TSQLiteColumnDefinition.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,71 +21,70 @@ #include "ErrorCodes.h" #include "TCoreException.h" -BEGIN_CHCORE_NAMESPACE - -TSQLiteColumnsDefinition::TSQLiteColumnsDefinition() +namespace chcore { -} + TSQLiteColumnsDefinition::TSQLiteColumnsDefinition() + { + } -TSQLiteColumnsDefinition::~TSQLiteColumnsDefinition() -{ -} + TSQLiteColumnsDefinition::~TSQLiteColumnsDefinition() + { + } -size_t TSQLiteColumnsDefinition::AddColumn(const TString& strColumnName, ETypes eColType) -{ - m_vColumns.push_back(std::make_pair(strColumnName, eColType)); - return m_vColumns.size() - 1; -} + size_t TSQLiteColumnsDefinition::AddColumn(const TString& strColumnName, ETypes eColType) + { + m_vColumns.push_back(std::make_pair(strColumnName, eColType)); + return m_vColumns.size() - 1; + } -void TSQLiteColumnsDefinition::Clear() -{ - m_vColumns.clear(); -} - -size_t TSQLiteColumnsDefinition::GetColumnIndex(const wchar_t* strColumnName) -{ - size_t stPos = 0; - for(VecColumns::const_iterator iterFnd = m_vColumns.begin(); iterFnd != m_vColumns.end(); ++iterFnd) + void TSQLiteColumnsDefinition::Clear() { - if(iterFnd->first == strColumnName) - return stPos; - ++stPos; + m_vColumns.clear(); } - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -} + size_t TSQLiteColumnsDefinition::GetColumnIndex(const wchar_t* strColumnName) + { + size_t stPos = 0; + for (VecColumns::const_iterator iterFnd = m_vColumns.begin(); iterFnd != m_vColumns.end(); ++iterFnd) + { + if (iterFnd->first == strColumnName) + return stPos; + ++stPos; + } -const TString& TSQLiteColumnsDefinition::GetColumnName(size_t stIndex) const -{ - return m_vColumns.at(stIndex).first; -} + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + } -size_t TSQLiteColumnsDefinition::GetCount() const -{ - return m_vColumns.size(); -} + const TString& TSQLiteColumnsDefinition::GetColumnName(size_t stIndex) const + { + return m_vColumns.at(stIndex).first; + } -bool TSQLiteColumnsDefinition::IsEmpty() const -{ - return m_vColumns.empty(); -} + size_t TSQLiteColumnsDefinition::GetCount() const + { + return m_vColumns.size(); + } -TString TSQLiteColumnsDefinition::GetCommaSeparatedColumns() const -{ - TString strColumns; - VecColumns::value_type pairCol; - BOOST_FOREACH(pairCol, m_vColumns) + bool TSQLiteColumnsDefinition::IsEmpty() const { - strColumns += pairCol.first + _T(","); + return m_vColumns.empty(); } - strColumns.TrimRightSelf(_T(",")); - return strColumns; -} + TString TSQLiteColumnsDefinition::GetCommaSeparatedColumns() const + { + TString strColumns; + VecColumns::value_type pairCol; + BOOST_FOREACH(pairCol, m_vColumns) + { + strColumns += pairCol.first + _T(","); + } -IColumnsDefinition::ETypes TSQLiteColumnsDefinition::GetColumnType(size_t stIndex) const -{ - return m_vColumns.at(stIndex).second; -} + strColumns.TrimRightSelf(_T(",")); + return strColumns; + } -END_CHCORE_NAMESPACE + IColumnsDefinition::ETypes TSQLiteColumnsDefinition::GetColumnType(size_t stIndex) const + { + return m_vColumns.at(stIndex).second; + } +} Index: src/libchcore/TSQLiteColumnDefinition.h =================================================================== diff -u -N -r7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteColumnDefinition.h (.../TSQLiteColumnDefinition.h) (revision 7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66) +++ src/libchcore/TSQLiteColumnDefinition.h (.../TSQLiteColumnDefinition.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,33 +24,32 @@ #include #include "IColumnsDefinition.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSQLiteColumnsDefinition : public IColumnsDefinition +namespace chcore { -public: - TSQLiteColumnsDefinition(); - virtual ~TSQLiteColumnsDefinition(); + class LIBCHCORE_API TSQLiteColumnsDefinition : public IColumnsDefinition + { + public: + TSQLiteColumnsDefinition(); + virtual ~TSQLiteColumnsDefinition(); - virtual size_t AddColumn(const TString& strColumnName, ETypes eColType); - virtual void Clear(); + virtual size_t AddColumn(const TString& strColumnName, ETypes eColType); + virtual void Clear(); - virtual size_t GetColumnIndex(const wchar_t* strColumnName); - virtual ETypes GetColumnType(size_t stIndex) const; - virtual const TString& GetColumnName(size_t stIndex) const; - virtual size_t GetCount() const; - virtual bool IsEmpty() const; + virtual size_t GetColumnIndex(const wchar_t* strColumnName); + virtual ETypes GetColumnType(size_t stIndex) const; + virtual const TString& GetColumnName(size_t stIndex) const; + virtual size_t GetCount() const; + virtual bool IsEmpty() const; - virtual TString GetCommaSeparatedColumns() const; + virtual TString GetCommaSeparatedColumns() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - typedef std::vector> VecColumns; - VecColumns m_vColumns; + typedef std::vector> VecColumns; + VecColumns m_vColumns; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteDatabase.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteDatabase.cpp (.../TSQLiteDatabase.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TSQLiteDatabase.cpp (.../TSQLiteDatabase.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,49 +22,48 @@ #include "ErrorCodes.h" #include "TSQLiteException.h" -BEGIN_CHCORE_NAMESPACE - -namespace sqlite +namespace chcore { - TSQLiteDatabase::TSQLiteDatabase(const TSmartPath& pathDatabase) : - m_pDBHandle(NULL), - m_bInTransaction(false), - m_pathDatabase(pathDatabase) + namespace sqlite { - int iResult = sqlite3_open16(m_pathDatabase.ToString(), &m_pDBHandle); - if(iResult != SQLITE_OK) + TSQLiteDatabase::TSQLiteDatabase(const TSmartPath& pathDatabase) : + m_pDBHandle(NULL), + m_bInTransaction(false), + m_pathDatabase(pathDatabase) { - const wchar_t* pszMsg = (const wchar_t*)sqlite3_errmsg16(m_pDBHandle); - THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotOpenDatabase, iResult, pszMsg); + int iResult = sqlite3_open16(m_pathDatabase.ToString(), &m_pDBHandle); + if (iResult != SQLITE_OK) + { + const wchar_t* pszMsg = (const wchar_t*)sqlite3_errmsg16(m_pDBHandle); + THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotOpenDatabase, iResult, pszMsg); + } } - } - TSQLiteDatabase::~TSQLiteDatabase() - { - int iResult = sqlite3_close_v2(m_pDBHandle); // handles properly the NULL DB Handle - iResult; - _ASSERTE(iResult == SQLITE_OK); - } + TSQLiteDatabase::~TSQLiteDatabase() + { + int iResult = sqlite3_close_v2(m_pDBHandle); // handles properly the NULL DB Handle + iResult; + _ASSERTE(iResult == SQLITE_OK); + } - HANDLE TSQLiteDatabase::GetHandle() - { - return m_pDBHandle; - } + HANDLE TSQLiteDatabase::GetHandle() + { + return m_pDBHandle; + } - bool TSQLiteDatabase::GetInTransaction() const - { - return m_bInTransaction; - } + bool TSQLiteDatabase::GetInTransaction() const + { + return m_bInTransaction; + } - void TSQLiteDatabase::SetInTransaction(bool bInTransaction) - { - m_bInTransaction = bInTransaction; - } + void TSQLiteDatabase::SetInTransaction(bool bInTransaction) + { + m_bInTransaction = bInTransaction; + } - TSmartPath TSQLiteDatabase::GetLocation() const - { - return m_pathDatabase; + TSmartPath TSQLiteDatabase::GetLocation() const + { + return m_pathDatabase; + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSQLiteDatabase.h =================================================================== diff -u -N -r9479911a096555a7504c5c8a8eaee83ecb63440c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteDatabase.h (.../TSQLiteDatabase.h) (revision 9479911a096555a7504c5c8a8eaee83ecb63440c) +++ src/libchcore/TSQLiteDatabase.h (.../TSQLiteDatabase.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,36 +24,35 @@ struct sqlite3; -BEGIN_CHCORE_NAMESPACE - -namespace sqlite +namespace chcore { - class TSQLiteDatabase + namespace sqlite { - public: - explicit TSQLiteDatabase(const TSmartPath& strFilename); - ~TSQLiteDatabase(); + class TSQLiteDatabase + { + public: + explicit TSQLiteDatabase(const TSmartPath& strFilename); + ~TSQLiteDatabase(); - HANDLE GetHandle(); + HANDLE GetHandle(); - TSmartPath GetLocation() const; + TSmartPath GetLocation() const; - bool GetInTransaction() const; + bool GetInTransaction() const; - protected: - void SetInTransaction(bool bInTransaction); + protected: + void SetInTransaction(bool bInTransaction); - private: - TSmartPath m_pathDatabase; - sqlite3* m_pDBHandle; - bool m_bInTransaction; // global transaction state + private: + TSmartPath m_pathDatabase; + sqlite3* m_pDBHandle; + bool m_bInTransaction; // global transaction state - friend class TSQLiteTransaction; - }; + friend class TSQLiteTransaction; + }; - typedef boost::shared_ptr TSQLiteDatabasePtr; + typedef boost::shared_ptr TSQLiteDatabasePtr; + } } -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteException.cpp =================================================================== diff -u -N -rb1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteException.cpp (.../TSQLiteException.cpp) (revision b1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0) +++ src/libchcore/TSQLiteException.cpp (.../TSQLiteException.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,26 +19,25 @@ #include "stdafx.h" #include "TSQLiteException.h" -BEGIN_CHCORE_NAMESPACE - -namespace sqlite +namespace chcore { - TSQLiteException::TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), - m_iSQLiteError(iSQLiteError) + namespace sqlite { - } + TSQLiteException::TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), + m_iSQLiteError(iSQLiteError) + { + } - TSQLiteException::TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), - m_iSQLiteError(iSQLiteError) - { - } + TSQLiteException::TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), + m_iSQLiteError(iSQLiteError) + { + } - int TSQLiteException::GetSQLiteError() const - { - return m_iSQLiteError; + int TSQLiteException::GetSQLiteError() const + { + return m_iSQLiteError; + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSQLiteException.h =================================================================== diff -u -N -rb1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteException.h (.../TSQLiteException.h) (revision b1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0) +++ src/libchcore/TSQLiteException.h (.../TSQLiteException.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,23 +25,22 @@ #define THROW_SQLITE_EXCEPTION(error_code, sqlite_error_code, err_msg)\ throw TSQLiteException(error_code, sqlite_error_code, err_msg, __FILEW__, __LINE__, __FUNCTIONW__) -BEGIN_CHCORE_NAMESPACE - -namespace sqlite +namespace chcore { - class TSQLiteException : public TBaseException + namespace sqlite { - public: - TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + class TSQLiteException : public TBaseException + { + public: + TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - int GetSQLiteError() const; + int GetSQLiteError() const; - private: - int m_iSQLiteError; - }; + private: + int m_iSQLiteError; + }; + } } -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteSerializer.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializer.cpp (.../TSQLiteSerializer.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TSQLiteSerializer.cpp (.../TSQLiteSerializer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,85 +26,84 @@ #include "TSimpleTimer.h" #include "SerializerTrace.h" -BEGIN_CHCORE_NAMESPACE - -using namespace sqlite; - -TSQLiteSerializer::TSQLiteSerializer(const TSmartPath& pathDB, const ISerializerSchemaPtr& spSchema) : - m_spDatabase(new TSQLiteDatabase(pathDB)), - m_spSchema(spSchema) +namespace chcore { - if(!m_spDatabase || !m_spSchema) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + using namespace sqlite; - // initialize db params - SetupDBOptions(); + TSQLiteSerializer::TSQLiteSerializer(const TSmartPath& pathDB, const ISerializerSchemaPtr& spSchema) : + m_spDatabase(new TSQLiteDatabase(pathDB)), + m_spSchema(spSchema) + { + if (!m_spDatabase || !m_spSchema) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - m_spSchema->Setup(m_spDatabase); -} + // initialize db params + SetupDBOptions(); -TSQLiteSerializer::~TSQLiteSerializer() -{ - // clear the containers first, so that we can safely get rid of the strings pool - m_mapContainers.clear(); - m_poolStrings.Clear(false); -} + m_spSchema->Setup(m_spDatabase); + } -ISerializerContainerPtr TSQLiteSerializer::GetContainer(const TString& strContainerName) -{ - ContainerMap::iterator iterMap = m_mapContainers.find(strContainerName); - if(iterMap == m_mapContainers.end()) - iterMap = m_mapContainers.insert(std::make_pair( - strContainerName, - TSQLiteSerializerContainerPtr(new TSQLiteSerializerContainer(strContainerName, m_spDatabase, m_poolStrings)))).first; + TSQLiteSerializer::~TSQLiteSerializer() + { + // clear the containers first, so that we can safely get rid of the strings pool + m_mapContainers.clear(); + m_poolStrings.Clear(false); + } - return iterMap->second; -} + ISerializerContainerPtr TSQLiteSerializer::GetContainer(const TString& strContainerName) + { + ContainerMap::iterator iterMap = m_mapContainers.find(strContainerName); + if (iterMap == m_mapContainers.end()) + iterMap = m_mapContainers.insert(std::make_pair( + strContainerName, + TSQLiteSerializerContainerPtr(new TSQLiteSerializerContainer(strContainerName, m_spDatabase, m_poolStrings)))).first; -TSmartPath TSQLiteSerializer::GetLocation() const -{ - return m_spDatabase->GetLocation(); -} + return iterMap->second; + } -void TSQLiteSerializer::Flush() -{ - DBTRACE0(_T(" ## Serializer::Flush() - started\n")); + TSmartPath TSQLiteSerializer::GetLocation() const + { + return m_spDatabase->GetLocation(); + } - TSQLiteTransaction tran(m_spDatabase); + void TSQLiteSerializer::Flush() + { + DBTRACE0(_T(" ## Serializer::Flush() - started\n")); - TSimpleTimer timer(true); + TSQLiteTransaction tran(m_spDatabase); - for(ContainerMap::iterator iterContainer = m_mapContainers.begin(); iterContainer != m_mapContainers.end(); ++iterContainer) - { - iterContainer->second->Flush(); - } + TSimpleTimer timer(true); - unsigned long long ullFlushGatherTime = timer.Checkpoint(); ullFlushGatherTime; + for (ContainerMap::iterator iterContainer = m_mapContainers.begin(); iterContainer != m_mapContainers.end(); ++iterContainer) + { + iterContainer->second->Flush(); + } - tran.Commit(); + unsigned long long ullFlushGatherTime = timer.Checkpoint(); ullFlushGatherTime; - unsigned long long ullFlushCommitTime = timer.Checkpoint(); ullFlushCommitTime; - DBTRACE2(_T(" ## Serializer::Flush() - container flushes: %I64u ms, transaction commit: %I64u ms\n"), ullFlushGatherTime, ullFlushCommitTime); + tran.Commit(); - m_mapContainers.clear(); - m_poolStrings.Clear(); + unsigned long long ullFlushCommitTime = timer.Checkpoint(); ullFlushCommitTime; + DBTRACE2(_T(" ## Serializer::Flush() - container flushes: %I64u ms, transaction commit: %I64u ms\n"), ullFlushGatherTime, ullFlushCommitTime); - unsigned long long ullFlushClearTime = timer.Checkpoint(); ullFlushClearTime; - DBTRACE1(_T(" ## Serializer::Flush() - container clearing: %I64u ms\n"), ullFlushClearTime); -} + m_mapContainers.clear(); + m_poolStrings.Clear(); -void TSQLiteSerializer::SetupDBOptions() -{ -/* - TSQLiteStatement tStatement(m_spDatabase); - tStatement.Prepare(_T("PRAGMA JOURNAL_MODE=WAL")); - TSQLiteStatement::EStepResult eResult = tStatement.Step(); - if(eResult != TSQLiteStatement::eStep_HasRow) - THROW_CORE_EXCEPTION(eErr_CannotSetDatabaseOptions); + unsigned long long ullFlushClearTime = timer.Checkpoint(); ullFlushClearTime; + DBTRACE1(_T(" ## Serializer::Flush() - container clearing: %I64u ms\n"), ullFlushClearTime); + } - TString strResult = tStatement.GetText(0); - if(strResult != _T("wal")) - THROW_CORE_EXCEPTION(eErr_CannotSetDatabaseOptions);*/ -} + void TSQLiteSerializer::SetupDBOptions() + { + /* + TSQLiteStatement tStatement(m_spDatabase); + tStatement.Prepare(_T("PRAGMA JOURNAL_MODE=WAL")); + TSQLiteStatement::EStepResult eResult = tStatement.Step(); + if(eResult != TSQLiteStatement::eStep_HasRow) + THROW_CORE_EXCEPTION(eErr_CannotSetDatabaseOptions); -END_CHCORE_NAMESPACE + TString strResult = tStatement.GetText(0); + if(strResult != _T("wal")) + THROW_CORE_EXCEPTION(eErr_CannotSetDatabaseOptions);*/ + } +} Index: src/libchcore/TSQLiteSerializer.h =================================================================== diff -u -N -r7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializer.h (.../TSQLiteSerializer.h) (revision 7b830c34855c8aaa81aac2c6e0ca0fa6bae95e66) +++ src/libchcore/TSQLiteSerializer.h (.../TSQLiteSerializer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -30,35 +30,34 @@ #include "ISQLiteSerializerSchema.h" #include "TPlainStringPool.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSQLiteSerializer : public ISerializer +namespace chcore { -public: - TSQLiteSerializer(const TSmartPath& pathDB, const ISerializerSchemaPtr& spSchema); - virtual ~TSQLiteSerializer(); + class LIBCHCORE_API TSQLiteSerializer : public ISerializer + { + public: + TSQLiteSerializer(const TSmartPath& pathDB, const ISerializerSchemaPtr& spSchema); + virtual ~TSQLiteSerializer(); - virtual TSmartPath GetLocation() const; + virtual TSmartPath GetLocation() const; - virtual ISerializerContainerPtr GetContainer(const TString& strContainerName); - virtual void Flush(); - void SetupDBOptions(); + virtual ISerializerContainerPtr GetContainer(const TString& strContainerName); + virtual void Flush(); + void SetupDBOptions(); -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - sqlite::TSQLiteDatabasePtr m_spDatabase; - ISerializerSchemaPtr m_spSchema; + sqlite::TSQLiteDatabasePtr m_spDatabase; + ISerializerSchemaPtr m_spSchema; - typedef std::map ContainerMap; - ContainerMap m_mapContainers; + typedef std::map ContainerMap; + ContainerMap m_mapContainers; - TPlainStringPool m_poolStrings; + TPlainStringPool m_poolStrings; #pragma warning(pop) -}; + }; -typedef boost::shared_ptr TSQLiteSerializerPtr; + typedef boost::shared_ptr TSQLiteSerializerPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteSerializerContainer.cpp =================================================================== diff -u -N -rd76d3ce6c8c55fa23009dbb03b8bc06f482c5b72 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializerContainer.cpp (.../TSQLiteSerializerContainer.cpp) (revision d76d3ce6c8c55fa23009dbb03b8bc06f482c5b72) +++ src/libchcore/TSQLiteSerializerContainer.cpp (.../TSQLiteSerializerContainer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -29,169 +29,168 @@ #include #include "TSerializerException.h" -BEGIN_CHCORE_NAMESPACE - -using namespace sqlite; - -TSQLiteSerializerContainer::TSQLiteSerializerContainer(const TString& strName, const sqlite::TSQLiteDatabasePtr& spDB, TPlainStringPool& poolStrings) : - m_strName(strName), - m_spDB(spDB), - m_pPoolRows(NULL), - m_poolStrings(poolStrings) +namespace chcore { -} + using namespace sqlite; -TSQLiteSerializerContainer::~TSQLiteSerializerContainer() -{ - // get rid of all rows first - m_mapRows.clear(); + TSQLiteSerializerContainer::TSQLiteSerializerContainer(const TString& strName, const sqlite::TSQLiteDatabasePtr& spDB, TPlainStringPool& poolStrings) : + m_strName(strName), + m_spDB(spDB), + m_pPoolRows(NULL), + m_poolStrings(poolStrings) + { + } - // now get rid of memory pool - delete m_pPoolRows; -} - -ISerializerRowData& TSQLiteSerializerContainer::GetRow(object_id_t oidRowID, bool bMarkAsAdded) -{ - RowMap::iterator iterFnd = m_mapRows.find(oidRowID); - if(iterFnd == m_mapRows.end()) + TSQLiteSerializerContainer::~TSQLiteSerializerContainer() { - void* pMemoryBlock = GetPool().malloc(); - if(!pMemoryBlock) - THROW_SERIALIZER_EXCEPTION(eErr_InternalProblem, _T("Cannot allocate memory")); + // get rid of all rows first + m_mapRows.clear(); - iterFnd = m_mapRows.insert(std::make_pair(oidRowID, TSQLiteSerializerRowData(oidRowID, m_tColumns, bMarkAsAdded, (unsigned long long*)pMemoryBlock, GetPool().get_requested_size(), m_poolStrings))).first; + // now get rid of memory pool + delete m_pPoolRows; } - else if(bMarkAsAdded) - iterFnd->second.MarkAsAdded(); - return (*iterFnd).second; -} + ISerializerRowData& TSQLiteSerializerContainer::GetRow(object_id_t oidRowID, bool bMarkAsAdded) + { + RowMap::iterator iterFnd = m_mapRows.find(oidRowID); + if (iterFnd == m_mapRows.end()) + { + void* pMemoryBlock = GetPool().malloc(); + if (!pMemoryBlock) + THROW_SERIALIZER_EXCEPTION(eErr_InternalProblem, _T("Cannot allocate memory")); -void TSQLiteSerializerContainer::DeleteRow(object_id_t oidRowID) -{ - RowMap::iterator iterFnd = m_mapRows.find(oidRowID); - if(iterFnd != m_mapRows.end()) - m_mapRows.erase(iterFnd); + iterFnd = m_mapRows.insert(std::make_pair(oidRowID, TSQLiteSerializerRowData(oidRowID, m_tColumns, bMarkAsAdded, (unsigned long long*)pMemoryBlock, GetPool().get_requested_size(), m_poolStrings))).first; + } + else if (bMarkAsAdded) + iterFnd->second.MarkAsAdded(); - m_setDeleteItems.insert(oidRowID); -} + return (*iterFnd).second; + } -void TSQLiteSerializerContainer::DeleteRows(const TRemovedObjects& setObjects) -{ - size_t stCount = setObjects.GetCount(); - while(stCount-- != 0) + void TSQLiteSerializerContainer::DeleteRow(object_id_t oidRowID) { - DeleteRow(setObjects.GetAt(stCount)); + RowMap::iterator iterFnd = m_mapRows.find(oidRowID); + if (iterFnd != m_mapRows.end()) + m_mapRows.erase(iterFnd); + + m_setDeleteItems.insert(oidRowID); } -} -ISerializerRowReaderPtr TSQLiteSerializerContainer::GetRowReader() -{ - TSQLiteSerializerRowReaderPtr spRowReader(new TSQLiteSerializerRowReader(m_spDB, m_tColumns, m_strName)); - return spRowReader; -} + void TSQLiteSerializerContainer::DeleteRows(const TRemovedObjects& setObjects) + { + size_t stCount = setObjects.GetCount(); + while (stCount-- != 0) + { + DeleteRow(setObjects.GetAt(stCount)); + } + } -IColumnsDefinition& TSQLiteSerializerContainer::GetColumnsDefinition() -{ - return m_tColumns; -} - -void TSQLiteSerializerContainer::Flush() -{ - FlushDeletions(); - - // group rows that can be executed with one preparation - std::map> mapGroups; - std::map>::iterator iterMapGroups; - - for(RowMap::iterator iterRows = m_mapRows.begin(); iterRows != m_mapRows.end(); ++iterRows) + ISerializerRowReaderPtr TSQLiteSerializerContainer::GetRowReader() { - unsigned long long rowID = iterRows->second.GetChangeIdentification(); - iterMapGroups = mapGroups.find(rowID); - if(iterMapGroups == mapGroups.end()) - iterMapGroups = mapGroups.insert(std::make_pair(rowID, std::vector())).first; + TSQLiteSerializerRowReaderPtr spRowReader(new TSQLiteSerializerRowReader(m_spDB, m_tColumns, m_strName)); + return spRowReader; + } - iterMapGroups->second.push_back(&iterRows->second); + IColumnsDefinition& TSQLiteSerializerContainer::GetColumnsDefinition() + { + return m_tColumns; } - TSQLiteStatement tStatement(m_spDB); - - for(iterMapGroups = mapGroups.begin(); iterMapGroups != mapGroups.end(); ++iterMapGroups) + void TSQLiteSerializerContainer::Flush() { - if(iterMapGroups->first != 0) + FlushDeletions(); + + // group rows that can be executed with one preparation + std::map> mapGroups; + std::map>::iterator iterMapGroups; + + for (RowMap::iterator iterRows = m_mapRows.begin(); iterRows != m_mapRows.end(); ++iterRows) { - std::vector& rGroupRows = iterMapGroups->second; + unsigned long long rowID = iterRows->second.GetChangeIdentification(); + iterMapGroups = mapGroups.find(rowID); + if (iterMapGroups == mapGroups.end()) + iterMapGroups = mapGroups.insert(std::make_pair(rowID, std::vector())).first; - // query is generated from the first item in a group - TString strQuery = rGroupRows.front()->GetQuery(m_strName); - if(!strQuery.IsEmpty()) - { - DBTRACE2(_T("Preparing query for %lu records: %s\n"), (unsigned long)iterMapGroups->second.size(), strQuery.c_str()); + iterMapGroups->second.push_back(&iterRows->second); + } - tStatement.Prepare(strQuery.c_str()); + TSQLiteStatement tStatement(m_spDB); - for(std::vector::iterator iterRow = iterMapGroups->second.begin(); iterRow != iterMapGroups->second.end(); ++iterRow) + for (iterMapGroups = mapGroups.begin(); iterMapGroups != mapGroups.end(); ++iterMapGroups) + { + if (iterMapGroups->first != 0) + { + std::vector& rGroupRows = iterMapGroups->second; + + // query is generated from the first item in a group + TString strQuery = rGroupRows.front()->GetQuery(m_strName); + if (!strQuery.IsEmpty()) { - (*iterRow)->BindParamsAndExec(tStatement); - tStatement.ClearBindings(); - } + DBTRACE2(_T("Preparing query for %lu records: %s\n"), (unsigned long)iterMapGroups->second.size(), strQuery.c_str()); - tStatement.Close(); + tStatement.Prepare(strQuery.c_str()); + + for (std::vector::iterator iterRow = iterMapGroups->second.begin(); iterRow != iterMapGroups->second.end(); ++iterRow) + { + (*iterRow)->BindParamsAndExec(tStatement); + tStatement.ClearBindings(); + } + + tStatement.Close(); + } } } } -} -void TSQLiteSerializerContainer::FlushDeletions() -{ - // delete from m_strName WHERE id IN (???) - TSQLiteStatement tStatement(m_spDB); + void TSQLiteSerializerContainer::FlushDeletions() + { + // delete from m_strName WHERE id IN (???) + TSQLiteStatement tStatement(m_spDB); - const size_t stMaxToRemoveAtOnce = 10; + const size_t stMaxToRemoveAtOnce = 10; - // delete items in chunks - std::set::const_iterator iterToDelete = m_setDeleteItems.begin(); - while(iterToDelete != m_setDeleteItems.end()) - { - TString strItemsToRemove; - size_t stToRemove = stMaxToRemoveAtOnce; - while(iterToDelete != m_setDeleteItems.end() && (--stToRemove) != 0) + // delete items in chunks + std::set::const_iterator iterToDelete = m_setDeleteItems.begin(); + while (iterToDelete != m_setDeleteItems.end()) { - strItemsToRemove += boost::str(boost::wformat(L"%1%,") % *iterToDelete).c_str(); - ++iterToDelete; - } - strItemsToRemove.TrimRightSelf(_T(",")); + TString strItemsToRemove; + size_t stToRemove = stMaxToRemoveAtOnce; + while (iterToDelete != m_setDeleteItems.end() && (--stToRemove) != 0) + { + strItemsToRemove += boost::str(boost::wformat(L"%1%,") % *iterToDelete).c_str(); + ++iterToDelete; + } + strItemsToRemove.TrimRightSelf(_T(",")); - TString strQuery = boost::str(boost::wformat(L"DELETE FROM %1% WHERE id IN (%2%)") % m_strName % strItemsToRemove).c_str(); - tStatement.Prepare(strQuery.c_str()); + TString strQuery = boost::str(boost::wformat(L"DELETE FROM %1% WHERE id IN (%2%)") % m_strName % strItemsToRemove).c_str(); + tStatement.Prepare(strQuery.c_str()); - DBTRACE1_D(_T("Executing query: %s\n"), strQuery.c_str()); - tStatement.Step(); + DBTRACE1_D(_T("Executing query: %s\n"), strQuery.c_str()); + tStatement.Step(); + } } -} -boost::pool<>& TSQLiteSerializerContainer::GetPool() -{ - if(!m_pPoolRows) - m_pPoolRows = new boost::pool<>(CalculateRowMemorySize()); - else + boost::pool<>& TSQLiteSerializerContainer::GetPool() { - if(m_pPoolRows->get_requested_size() != CalculateRowMemorySize()) - THROW_SERIALIZER_EXCEPTION(eErr_InternalProblem, _T("Column count changed after first use")); + if (!m_pPoolRows) + m_pPoolRows = new boost::pool<>(CalculateRowMemorySize()); + else + { + if (m_pPoolRows->get_requested_size() != CalculateRowMemorySize()) + THROW_SERIALIZER_EXCEPTION(eErr_InternalProblem, _T("Column count changed after first use")); + } + + return *m_pPoolRows; } - return *m_pPoolRows; -} + size_t TSQLiteSerializerContainer::CalculateRowMemorySize() const + { + // assume 64bit column mask (8 bytes) + const size_t stMaskSize = 8; -size_t TSQLiteSerializerContainer::CalculateRowMemorySize() const -{ - // assume 64bit column mask (8 bytes) - const size_t stMaskSize = 8; + // and additionally 64bit for each column (either for storing numbers directly or for allocating string/double) + const size_t stFieldSize = 8; - // and additionally 64bit for each column (either for storing numbers directly or for allocating string/double) - const size_t stFieldSize = 8; - - return stMaskSize + m_tColumns.GetCount() * stFieldSize; + return stMaskSize + m_tColumns.GetCount() * stFieldSize; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSQLiteSerializerContainer.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializerContainer.h (.../TSQLiteSerializerContainer.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TSQLiteSerializerContainer.h (.../TSQLiteSerializerContainer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -30,54 +30,53 @@ #include "TSQLiteSerializerRowData.h" #include -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSQLiteSerializerContainer : public ISerializerContainer +namespace chcore { -private: - TSQLiteSerializerContainer(const TSQLiteSerializerContainer&); - TSQLiteSerializerContainer& operator=(const TSQLiteSerializerContainer&); + class LIBCHCORE_API TSQLiteSerializerContainer : public ISerializerContainer + { + private: + TSQLiteSerializerContainer(const TSQLiteSerializerContainer&); + TSQLiteSerializerContainer& operator=(const TSQLiteSerializerContainer&); -public: - TSQLiteSerializerContainer(const TString& strName, const sqlite::TSQLiteDatabasePtr& spDB, TPlainStringPool& poolStrings); - virtual ~TSQLiteSerializerContainer(); + public: + TSQLiteSerializerContainer(const TString& strName, const sqlite::TSQLiteDatabasePtr& spDB, TPlainStringPool& poolStrings); + virtual ~TSQLiteSerializerContainer(); - virtual IColumnsDefinition& GetColumnsDefinition(); + virtual IColumnsDefinition& GetColumnsDefinition(); - virtual ISerializerRowData& GetRow(object_id_t oidRowID, bool bMarkAsAdded); - virtual void DeleteRow(object_id_t oidRowID); - virtual void DeleteRows(const TRemovedObjects& setObjects); + virtual ISerializerRowData& GetRow(object_id_t oidRowID, bool bMarkAsAdded); + virtual void DeleteRow(object_id_t oidRowID); + virtual void DeleteRows(const TRemovedObjects& setObjects); - virtual ISerializerRowReaderPtr GetRowReader(); + virtual ISerializerRowReaderPtr GetRowReader(); - void Flush(); + void Flush(); -private: - void FlushDeletions(); - boost::pool<>& GetPool(); - size_t CalculateRowMemorySize() const; + private: + void FlushDeletions(); + boost::pool<>& GetPool(); + size_t CalculateRowMemorySize() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - TSQLiteColumnsDefinition m_tColumns; + TSQLiteColumnsDefinition m_tColumns; - boost::pool<>* m_pPoolRows; + boost::pool<>* m_pPoolRows; - typedef boost::container::flat_map RowMap; // maps row id to row data - RowMap m_mapRows; + typedef boost::container::flat_map RowMap; // maps row id to row data + RowMap m_mapRows; - std::set m_setDeleteItems; + std::set m_setDeleteItems; - TString m_strName; - sqlite::TSQLiteDatabasePtr m_spDB; + TString m_strName; + sqlite::TSQLiteDatabasePtr m_spDB; - TPlainStringPool& m_poolStrings; + TPlainStringPool& m_poolStrings; #pragma warning(pop) -}; + }; -typedef boost::shared_ptr TSQLiteSerializerContainerPtr; + typedef boost::shared_ptr TSQLiteSerializerContainerPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteSerializerFactory.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializerFactory.cpp (.../TSQLiteSerializerFactory.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TSQLiteSerializerFactory.cpp (.../TSQLiteSerializerFactory.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -29,71 +29,70 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -TSQLiteSerializerFactory::TSQLiteSerializerFactory(const TSmartPath& pathSerializeDir) : - m_pathSerializeDir(pathSerializeDir) +namespace chcore { -} + TSQLiteSerializerFactory::TSQLiteSerializerFactory(const TSmartPath& pathSerializeDir) : + m_pathSerializeDir(pathSerializeDir) + { + } -TSQLiteSerializerFactory::~TSQLiteSerializerFactory() -{ -} + TSQLiteSerializerFactory::~TSQLiteSerializerFactory() + { + } -ISerializerPtr TSQLiteSerializerFactory::CreateTaskManagerSerializer(bool bForceRecreate) -{ - TSmartPath pathTaskManager = m_pathSerializeDir + PathFromString(_T("tasks.sqlite")); - - if (bForceRecreate) + ISerializerPtr TSQLiteSerializerFactory::CreateTaskManagerSerializer(bool bForceRecreate) { - if (!DeleteFile(pathTaskManager.ToString())) + TSmartPath pathTaskManager = m_pathSerializeDir + PathFromString(_T("tasks.sqlite")); + + if (bForceRecreate) { - DWORD dwLastError = GetLastError(); - if (dwLastError != ERROR_FILE_NOT_FOUND) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotDeleteFile, dwLastError); + if (!DeleteFile(pathTaskManager.ToString())) + { + DWORD dwLastError = GetLastError(); + if (dwLastError != ERROR_FILE_NOT_FOUND) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotDeleteFile, dwLastError); + } } - } - TSQLiteSerializerPtr spSerializer(boost::make_shared( - pathTaskManager, - boost::make_shared())); + TSQLiteSerializerPtr spSerializer(boost::make_shared( + pathTaskManager, + boost::make_shared())); - return spSerializer; -} - -ISerializerPtr TSQLiteSerializerFactory::CreateTaskSerializer(const TString& strNameHint, bool bForceRecreate) -{ - TString strName(strNameHint); - if (strName.IsEmpty()) - { - boost::uuids::random_generator gen; - boost::uuids::uuid u = gen(); - strName = boost::lexical_cast(u).c_str(); + return spSerializer; } - TSmartPath pathTask = PathFromWString(strName); - if (!pathTask.HasFileRoot()) + ISerializerPtr TSQLiteSerializerFactory::CreateTaskSerializer(const TString& strNameHint, bool bForceRecreate) { - if (!strName.EndsWithNoCase(_T(".sqlite"))) - strName += _T(".sqlite"); + TString strName(strNameHint); + if (strName.IsEmpty()) + { + boost::uuids::random_generator gen; + boost::uuids::uuid u = gen(); + strName = boost::lexical_cast(u).c_str(); + } - pathTask = m_pathSerializeDir; - pathTask += PathFromWString(strName); - } + TSmartPath pathTask = PathFromWString(strName); + if (!pathTask.HasFileRoot()) + { + if (!strName.EndsWithNoCase(_T(".sqlite"))) + strName += _T(".sqlite"); - if (bForceRecreate) - { - if (!DeleteFile(pathTask.ToString())) + pathTask = m_pathSerializeDir; + pathTask += PathFromWString(strName); + } + + if (bForceRecreate) { - DWORD dwLastError = GetLastError(); - if (dwLastError != ERROR_FILE_NOT_FOUND) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotDeleteFile, dwLastError); + if (!DeleteFile(pathTask.ToString())) + { + DWORD dwLastError = GetLastError(); + if (dwLastError != ERROR_FILE_NOT_FOUND) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotDeleteFile, dwLastError); + } } - } - TSQLiteSerializerPtr spSerializer(boost::make_shared(pathTask, boost::make_shared())); + TSQLiteSerializerPtr spSerializer(boost::make_shared(pathTask, boost::make_shared())); - return spSerializer; + return spSerializer; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSQLiteSerializerFactory.h =================================================================== diff -u -N -rcdb4c898156398dd4f4bf8abd7c854eff42f6ae2 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializerFactory.h (.../TSQLiteSerializerFactory.h) (revision cdb4c898156398dd4f4bf8abd7c854eff42f6ae2) +++ src/libchcore/TSQLiteSerializerFactory.h (.../TSQLiteSerializerFactory.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,23 +23,22 @@ #include "TPath.h" #include "ISerializerFactory.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSQLiteSerializerFactory : public ISerializerFactory +namespace chcore { -public: - TSQLiteSerializerFactory(const TSmartPath& pathSerializeDir); - virtual ~TSQLiteSerializerFactory(); + class LIBCHCORE_API TSQLiteSerializerFactory : public ISerializerFactory + { + public: + TSQLiteSerializerFactory(const TSmartPath& pathSerializeDir); + virtual ~TSQLiteSerializerFactory(); - virtual ISerializerPtr CreateTaskManagerSerializer(bool bForceRecreate = false) override; - virtual ISerializerPtr CreateTaskSerializer(const TString& strNameHint = _T(""), bool bForceRecreate = false) override; + virtual ISerializerPtr CreateTaskManagerSerializer(bool bForceRecreate = false) override; + virtual ISerializerPtr CreateTaskSerializer(const TString& strNameHint = _T(""), bool bForceRecreate = false) override; -private: - TSmartPath m_pathSerializeDir; -}; + private: + TSmartPath m_pathSerializeDir; + }; -typedef boost::shared_ptr TSQLiteSerializerFactoryPtr; + typedef boost::shared_ptr TSQLiteSerializerFactoryPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteSerializerRowData.cpp =================================================================== diff -u -N -r39864b5fbb931e3b257afbd60cfb7f36f71d146d -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializerRowData.cpp (.../TSQLiteSerializerRowData.cpp) (revision 39864b5fbb931e3b257afbd60cfb7f36f71d146d) +++ src/libchcore/TSQLiteSerializerRowData.cpp (.../TSQLiteSerializerRowData.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,511 +25,510 @@ #include "SerializerTrace.h" #include "TPlainStringPool.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////// -TSQLiteSerializerRowData::TSQLiteSerializerRowData(object_id_t oidRowID, TSQLiteColumnsDefinition& rColumnDefinition, bool bAdded, unsigned long long* pPoolMemory, size_t stPoolMemorySizeInBytes, TPlainStringPool& poolStrings) : - m_rColumns(rColumnDefinition), - m_pPoolMemory(pPoolMemory), - m_poolStrings(poolStrings) +namespace chcore { - if(!m_pPoolMemory) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Null memory provided")); - if(rColumnDefinition.GetCount() > 63) - THROW_SERIALIZER_EXCEPTION(eErr_InternalProblem, _T("Serializer supports up to 63 columns. If more is needed the block header needs to be increased.")); + /////////////////////////////////////////////////////////////////////////// + TSQLiteSerializerRowData::TSQLiteSerializerRowData(object_id_t oidRowID, TSQLiteColumnsDefinition& rColumnDefinition, bool bAdded, unsigned long long* pPoolMemory, size_t stPoolMemorySizeInBytes, TPlainStringPool& poolStrings) : + m_rColumns(rColumnDefinition), + m_pPoolMemory(pPoolMemory), + m_poolStrings(poolStrings) + { + if (!m_pPoolMemory) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Null memory provided")); + if (rColumnDefinition.GetCount() > 63) + THROW_SERIALIZER_EXCEPTION(eErr_InternalProblem, _T("Serializer supports up to 63 columns. If more is needed the block header needs to be increased.")); - // initialize memory - memset((void*)pPoolMemory, 0, stPoolMemorySizeInBytes); + // initialize memory + memset((void*)pPoolMemory, 0, stPoolMemorySizeInBytes); - // set id - size_t stIDIndex = rColumnDefinition.GetColumnIndex(_T("id")); - SetValue(stIDIndex, oidRowID); + // set id + size_t stIDIndex = rColumnDefinition.GetColumnIndex(_T("id")); + SetValue(stIDIndex, oidRowID); - if(bAdded) - MarkAsAdded(); -} + if (bAdded) + MarkAsAdded(); + } -TSQLiteSerializerRowData::TSQLiteSerializerRowData(const TSQLiteSerializerRowData& rSrc) : - m_rColumns(rSrc.m_rColumns), - m_pPoolMemory(rSrc.m_pPoolMemory), - m_poolStrings(rSrc.m_poolStrings) -{ -} + TSQLiteSerializerRowData::TSQLiteSerializerRowData(const TSQLiteSerializerRowData& rSrc) : + m_rColumns(rSrc.m_rColumns), + m_pPoolMemory(rSrc.m_pPoolMemory), + m_poolStrings(rSrc.m_poolStrings) + { + } -TSQLiteSerializerRowData::~TSQLiteSerializerRowData() -{ -} + TSQLiteSerializerRowData::~TSQLiteSerializerRowData() + { + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, bool bValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_bool) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, bool bValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_bool) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - ModifyColumnData(stColIndex) = (bValue ? 1ULL : 0ULL); - return *this; -} + ModifyColumnData(stColIndex) = (bValue ? 1ULL : 0ULL); + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, short siValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_short) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, short siValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_short) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned short*)&siValue; - return *this; -} + ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned short*)&siValue; + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned short usiValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ushort) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned short usiValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ushort) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - ModifyColumnData(stColIndex) = (unsigned long long)usiValue; - return *this; -} + ModifyColumnData(stColIndex) = (unsigned long long)usiValue; + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, int iValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_int) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, int iValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_int) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned int*)&iValue; - return *this; -} + ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned int*)&iValue; + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned int uiValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_uint) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned int uiValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_uint) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - ModifyColumnData(stColIndex) = (unsigned long long)uiValue; - return *this; -} + ModifyColumnData(stColIndex) = (unsigned long long)uiValue; + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, long lValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_long) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, long lValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_long) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned long*)&lValue; - return *this; -} + ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned long*)&lValue; + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned long ulValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ulong) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned long ulValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ulong) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - ModifyColumnData(stColIndex) = (unsigned long long)ulValue; - return *this; -} + ModifyColumnData(stColIndex) = (unsigned long long)ulValue; + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, long long llValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_longlong) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, long long llValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_longlong) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - ModifyColumnData(stColIndex) = *(unsigned long long*)&llValue; - return *this; -} + ModifyColumnData(stColIndex) = *(unsigned long long*)&llValue; + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned long long ullValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ulonglong) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned long long ullValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ulonglong) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - ModifyColumnData(stColIndex) = ullValue; - return *this; -} + ModifyColumnData(stColIndex) = ullValue; + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, double dValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_double) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, double dValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_double) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - BOOST_STATIC_ASSERT(sizeof(double) == sizeof(unsigned long long)); - ModifyColumnData(stColIndex) = *(unsigned long long*)&dValue; - return *this; -} + BOOST_STATIC_ASSERT(sizeof(double) == sizeof(unsigned long long)); + ModifyColumnData(stColIndex) = *(unsigned long long*)&dValue; + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, const TString& strValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_string) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - - if(strValue.IsEmpty()) - ModifyColumnData(stColIndex) = (unsigned long long)0; - else + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, const TString& strValue) { - wchar_t* pszBuffer = m_poolStrings.AllocForString(strValue.c_str()); - ModifyColumnData(stColIndex) = (unsigned long long)(void*)pszBuffer; - } + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_string) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - return *this; -} + if (strValue.IsEmpty()) + ModifyColumnData(stColIndex) = (unsigned long long)0; + else + { + wchar_t* pszBuffer = m_poolStrings.AllocForString(strValue.c_str()); + ModifyColumnData(stColIndex) = (unsigned long long)(void*)pszBuffer; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, const TSmartPath& pathValue) -{ - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_path) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); + return *this; + } - if(pathValue.IsEmpty()) - ModifyColumnData(stColIndex) = (unsigned long long)0; - else + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, const TSmartPath& pathValue) { - wchar_t* pszBuffer = m_poolStrings.AllocForString(pathValue.ToString()); - ModifyColumnData(stColIndex) = (unsigned long long)(void*)pszBuffer; - } + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_path) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid argument type provided")); - return *this; -} + if (pathValue.IsEmpty()) + ModifyColumnData(stColIndex) = (unsigned long long)0; + else + { + wchar_t* pszBuffer = m_poolStrings.AllocForString(pathValue.ToString()); + ModifyColumnData(stColIndex) = (unsigned long long)(void*)pszBuffer; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, bool bValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), bValue); -} + return *this; + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, short iValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), iValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, bool bValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), bValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned short uiValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), uiValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, short iValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), iValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, int iValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), iValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned short uiValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), uiValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned int uiValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), uiValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, int iValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), iValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, long lValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), lValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned int uiValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), uiValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned long ulValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), ulValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, long lValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), lValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, long long llValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), llValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned long ulValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), ulValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned long long llValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), llValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, long long llValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), llValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, double dValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), dValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned long long llValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), llValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, const TString& strValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), strValue); -} + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, double dValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), dValue); + } -ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue) -{ - return SetValue(m_rColumns.GetColumnIndex(strColumnName), pathValue); -} - -void TSQLiteSerializerRowData::BindParamsAndExec(sqlite::TSQLiteStatement& tStatement) -{ - using namespace sqlite; - - if(IsAdded()) + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, const TString& strValue) { - // exec query - int iColumn = 1; - BindParams(tStatement, iColumn); + return SetValue(m_rColumns.GetColumnIndex(strColumnName), strValue); + } - tStatement.Step(); + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), pathValue); } - else if(HasAnyData()) + + void TSQLiteSerializerRowData::BindParamsAndExec(sqlite::TSQLiteStatement& tStatement) { - int iColumn = 1; + using namespace sqlite; - size_t stIDColumnIndex = m_rColumns.GetColumnIndex(_T("id")); + if (IsAdded()) + { + // exec query + int iColumn = 1; + BindParams(tStatement, iColumn); - BindParams(tStatement, iColumn, stIDColumnIndex); + tStatement.Step(); + } + else if (HasAnyData()) + { + int iColumn = 1; - // bind id as the last argument - tStatement.BindValue(iColumn++, GetDataForColumn(stIDColumnIndex)); - tStatement.Step(); + size_t stIDColumnIndex = m_rColumns.GetColumnIndex(_T("id")); - int iChanges = tStatement.Changes(); - _ASSERTE(iChanges == 1); - if(iChanges != 1) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidData, _T("Update query did not update record in the database")); + BindParams(tStatement, iColumn, stIDColumnIndex); + + // bind id as the last argument + tStatement.BindValue(iColumn++, GetDataForColumn(stIDColumnIndex)); + tStatement.Step(); + + int iChanges = tStatement.Changes(); + _ASSERTE(iChanges == 1); + if (iChanges != 1) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidData, _T("Update query did not update record in the database")); + } } -} -TString TSQLiteSerializerRowData::GetQuery(const TString& strContainerName) const -{ - if(IsAdded()) + TString TSQLiteSerializerRowData::GetQuery(const TString& strContainerName) const { - // prepare insert query - TString strQuery = boost::str(boost::wformat(L"INSERT INTO %1%(") % strContainerName).c_str(); - TString strParams; - - size_t stCount = m_rColumns.GetCount(); - for(size_t stIndex = 0; stIndex < stCount; ++stIndex) + if (IsAdded()) { - strQuery += boost::str(boost::wformat(_T("%1%,")) % m_rColumns.GetColumnName(stIndex)).c_str(); - strParams += _T("?,"); - } + // prepare insert query + TString strQuery = boost::str(boost::wformat(L"INSERT INTO %1%(") % strContainerName).c_str(); + TString strParams; - strQuery.TrimRightSelf(_T(",")); - strQuery += _T(") VALUES("); + size_t stCount = m_rColumns.GetCount(); + for (size_t stIndex = 0; stIndex < stCount; ++stIndex) + { + strQuery += boost::str(boost::wformat(_T("%1%,")) % m_rColumns.GetColumnName(stIndex)).c_str(); + strParams += _T("?,"); + } - strParams.TrimRightSelf(_T(",")); - strQuery += strParams; - strQuery += _T(")"); + strQuery.TrimRightSelf(_T(",")); + strQuery += _T(") VALUES("); - return strQuery; - } - else if(HasAnyData()) - { - // prepare update query - TString strQuery = boost::str(boost::wformat(L"UPDATE %1% SET ") % strContainerName).c_str(); + strParams.TrimRightSelf(_T(",")); + strQuery += strParams; + strQuery += _T(")"); - size_t stCountOfAssignments = 0; - size_t stIDColumnIndex = m_rColumns.GetColumnIndex(_T("id")); - size_t stCount = m_rColumns.GetCount(); - for(size_t stIndex = 0; stIndex < stCount; ++stIndex) + return strQuery; + } + else if (HasAnyData()) { - if(stIndex != stIDColumnIndex && HasData(stIndex)) + // prepare update query + TString strQuery = boost::str(boost::wformat(L"UPDATE %1% SET ") % strContainerName).c_str(); + + size_t stCountOfAssignments = 0; + size_t stIDColumnIndex = m_rColumns.GetColumnIndex(_T("id")); + size_t stCount = m_rColumns.GetCount(); + for (size_t stIndex = 0; stIndex < stCount; ++stIndex) { - strQuery += boost::str(boost::wformat(_T("%1%=?,")) % m_rColumns.GetColumnName(stIndex)).c_str(); - ++stCountOfAssignments; + if (stIndex != stIDColumnIndex && HasData(stIndex)) + { + strQuery += boost::str(boost::wformat(_T("%1%=?,")) % m_rColumns.GetColumnName(stIndex)).c_str(); + ++stCountOfAssignments; + } } - } - if(stCountOfAssignments == 0) - return TString(); + if (stCountOfAssignments == 0) + return TString(); - strQuery.TrimRightSelf(_T(",")); - strQuery += _T(" WHERE id=?"); + strQuery.TrimRightSelf(_T(",")); + strQuery += _T(" WHERE id=?"); - return strQuery; + return strQuery; + } + else + return TString(); } - else - return TString(); -} -unsigned long long TSQLiteSerializerRowData::GetChangeIdentification() const -{ - return GetDataHeader(); -} + unsigned long long TSQLiteSerializerRowData::GetChangeIdentification() const + { + return GetDataHeader(); + } -void TSQLiteSerializerRowData::MarkAsAdded() -{ - // first bit is always the "added" bit - m_pPoolMemory[0] |= AddedBit; -} + void TSQLiteSerializerRowData::MarkAsAdded() + { + // first bit is always the "added" bit + m_pPoolMemory[0] |= AddedBit; + } -const unsigned long long& TSQLiteSerializerRowData::GetDataForColumn(size_t stColIndex) const -{ - return (m_pPoolMemory[stColIndex + 1]); -} + const unsigned long long& TSQLiteSerializerRowData::GetDataForColumn(size_t stColIndex) const + { + return (m_pPoolMemory[stColIndex + 1]); + } -unsigned long long& TSQLiteSerializerRowData::ModifyColumnData(size_t stColIndex) -{ - FreeColumnData(stColIndex); + unsigned long long& TSQLiteSerializerRowData::ModifyColumnData(size_t stColIndex) + { + FreeColumnData(stColIndex); - MarkColumnUsage(stColIndex, true); - return (m_pPoolMemory[stColIndex + 1]); -} + MarkColumnUsage(stColIndex, true); + return (m_pPoolMemory[stColIndex + 1]); + } -void TSQLiteSerializerRowData::MarkColumnUsage(size_t stIndex, bool bUsed) -{ - if(stIndex >= m_rColumns.GetCount()) - THROW_SERIALIZER_EXCEPTION(eErr_BoundsExceeded, _T("Wrong column provided")); + void TSQLiteSerializerRowData::MarkColumnUsage(size_t stIndex, bool bUsed) + { + if (stIndex >= m_rColumns.GetCount()) + THROW_SERIALIZER_EXCEPTION(eErr_BoundsExceeded, _T("Wrong column provided")); - unsigned long long ullMask = 2ULL << stIndex; - if(bUsed) - m_pPoolMemory[0] |= ullMask; - else - m_pPoolMemory[0] &= ~ullMask; -} + unsigned long long ullMask = 2ULL << stIndex; + if (bUsed) + m_pPoolMemory[0] |= ullMask; + else + m_pPoolMemory[0] &= ~ullMask; + } -bool TSQLiteSerializerRowData::IsAdded() const -{ - return (m_pPoolMemory[0] & AddedBit) != 0; -} + bool TSQLiteSerializerRowData::IsAdded() const + { + return (m_pPoolMemory[0] & AddedBit) != 0; + } -bool TSQLiteSerializerRowData::HasAnyData() const -{ - return GetDataHeader() != 0; -} + bool TSQLiteSerializerRowData::HasAnyData() const + { + return GetDataHeader() != 0; + } -bool TSQLiteSerializerRowData::HasData(size_t stColumnIndex) const -{ - return (GetDataHeader() & (2ULL << stColumnIndex)) != 0; -} - -void TSQLiteSerializerRowData::BindParams(sqlite::TSQLiteStatement &tStatement, int& iSQLiteColumnNumber, size_t stSkipColumn) -{ - size_t stCount = m_rColumns.GetCount(); - for(size_t stColumn = 0; stColumn < stCount; ++stColumn) + bool TSQLiteSerializerRowData::HasData(size_t stColumnIndex) const { - if(stColumn == stSkipColumn) - continue; + return (GetDataHeader() & (2ULL << stColumnIndex)) != 0; + } - if(HasData(stColumn)) + void TSQLiteSerializerRowData::BindParams(sqlite::TSQLiteStatement &tStatement, int& iSQLiteColumnNumber, size_t stSkipColumn) + { + size_t stCount = m_rColumns.GetCount(); + for (size_t stColumn = 0; stColumn < stCount; ++stColumn) { - switch(m_rColumns.GetColumnType(stColumn)) - { - case IColumnsDefinition::eType_bool: - { - bool bValue = GetDataForColumn(stColumn) != 0 ? true : false; - DBTRACE1_D(_T("- param(bool): %ld\n"), bValue ? 1l : 0l); - tStatement.BindValue(iSQLiteColumnNumber++, bValue); - break; - } + if (stColumn == stSkipColumn) + continue; - case IColumnsDefinition::eType_short: + if (HasData(stColumn)) { - short siValue = *(short*)(unsigned short*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(short): %d\n"), siValue); - tStatement.BindValue(iSQLiteColumnNumber++, siValue); - break; - } + switch (m_rColumns.GetColumnType(stColumn)) + { + case IColumnsDefinition::eType_bool: + { + bool bValue = GetDataForColumn(stColumn) != 0 ? true : false; + DBTRACE1_D(_T("- param(bool): %ld\n"), bValue ? 1l : 0l); + tStatement.BindValue(iSQLiteColumnNumber++, bValue); + break; + } - case IColumnsDefinition::eType_ushort: - { - unsigned short usiValue = (unsigned short)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(ushort): %u\n"), usiValue); - tStatement.BindValue(iSQLiteColumnNumber++, usiValue); - break; - } + case IColumnsDefinition::eType_short: + { + short siValue = *(short*)(unsigned short*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(short): %d\n"), siValue); + tStatement.BindValue(iSQLiteColumnNumber++, siValue); + break; + } - case IColumnsDefinition::eType_int: - { - int iValue = *(int*)(unsigned int*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(int): %ld\n"), iValue); - tStatement.BindValue(iSQLiteColumnNumber++, iValue); - break; - } + case IColumnsDefinition::eType_ushort: + { + unsigned short usiValue = (unsigned short)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(ushort): %u\n"), usiValue); + tStatement.BindValue(iSQLiteColumnNumber++, usiValue); + break; + } - case IColumnsDefinition::eType_uint: - { - unsigned int uiValue = (unsigned int)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(uint): %lu\n"), uiValue); - tStatement.BindValue(iSQLiteColumnNumber++, uiValue); - break; - } + case IColumnsDefinition::eType_int: + { + int iValue = *(int*)(unsigned int*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(int): %ld\n"), iValue); + tStatement.BindValue(iSQLiteColumnNumber++, iValue); + break; + } - case IColumnsDefinition::eType_long: - { - long lValue = *(long*)(unsigned long*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(long): %ld\n"), lValue); - tStatement.BindValue(iSQLiteColumnNumber++, lValue); - break; - } + case IColumnsDefinition::eType_uint: + { + unsigned int uiValue = (unsigned int)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(uint): %lu\n"), uiValue); + tStatement.BindValue(iSQLiteColumnNumber++, uiValue); + break; + } - case IColumnsDefinition::eType_ulong: - { - unsigned long ulValue = (unsigned long)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(ulong): %lu\n"), ulValue); - tStatement.BindValue(iSQLiteColumnNumber++, ulValue); - break; - } + case IColumnsDefinition::eType_long: + { + long lValue = *(long*)(unsigned long*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(long): %ld\n"), lValue); + tStatement.BindValue(iSQLiteColumnNumber++, lValue); + break; + } - case IColumnsDefinition::eType_longlong: - { - long long llValue = *(long long*)(unsigned long long*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(llong): %I64d\n"), llValue); - tStatement.BindValue(iSQLiteColumnNumber++, llValue); - break; - } + case IColumnsDefinition::eType_ulong: + { + unsigned long ulValue = (unsigned long)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(ulong): %lu\n"), ulValue); + tStatement.BindValue(iSQLiteColumnNumber++, ulValue); + break; + } - case IColumnsDefinition::eType_ulonglong: - { - unsigned long long ullValue = GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(ullong): %I64u\n"), ullValue); - tStatement.BindValue(iSQLiteColumnNumber++, ullValue); - break; - } + case IColumnsDefinition::eType_longlong: + { + long long llValue = *(long long*)(unsigned long long*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(llong): %I64d\n"), llValue); + tStatement.BindValue(iSQLiteColumnNumber++, llValue); + break; + } - case IColumnsDefinition::eType_double: - { - double dValue = *(double*)(unsigned long long*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(double): %f\n"), dValue); - tStatement.BindValue(iSQLiteColumnNumber++, dValue); - break; - } + case IColumnsDefinition::eType_ulonglong: + { + unsigned long long ullValue = GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(ullong): %I64u\n"), ullValue); + tStatement.BindValue(iSQLiteColumnNumber++, ullValue); + break; + } - case IColumnsDefinition::eType_string: - { - const wchar_t* pszValue = (const wchar_t*)(unsigned long long*)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(string): %s\n"), pszValue ? pszValue : _T("")); - tStatement.BindValue(iSQLiteColumnNumber++, pszValue ? pszValue : _T("")); - break; - } + case IColumnsDefinition::eType_double: + { + double dValue = *(double*)(unsigned long long*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(double): %f\n"), dValue); + tStatement.BindValue(iSQLiteColumnNumber++, dValue); + break; + } - case IColumnsDefinition::eType_path: - { - const wchar_t* pszValue = (const wchar_t*)(unsigned long long*)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(path): %s\n"), pszValue ? pszValue : _T("")); - tStatement.BindValue(iSQLiteColumnNumber++, pszValue ? PathFromString(pszValue) : TSmartPath()); - break; - } + case IColumnsDefinition::eType_string: + { + const wchar_t* pszValue = (const wchar_t*)(unsigned long long*)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(string): %s\n"), pszValue ? pszValue : _T("")); + tStatement.BindValue(iSQLiteColumnNumber++, pszValue ? pszValue : _T("")); + break; + } - default: - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid type")); + case IColumnsDefinition::eType_path: + { + const wchar_t* pszValue = (const wchar_t*)(unsigned long long*)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(path): %s\n"), pszValue ? pszValue : _T("")); + tStatement.BindValue(iSQLiteColumnNumber++, pszValue ? PathFromString(pszValue) : TSmartPath()); + break; + } + + default: + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("Invalid type")); + } } } } -} -unsigned long long TSQLiteSerializerRowData::GetDataHeader() const -{ - return m_pPoolMemory[0]; -} + unsigned long long TSQLiteSerializerRowData::GetDataHeader() const + { + return m_pPoolMemory[0]; + } -void TSQLiteSerializerRowData::FreeColumnData(size_t stColumnID) -{ - if(!HasData(stColumnID)) - return; - - switch(m_rColumns.GetColumnType(stColumnID)) + void TSQLiteSerializerRowData::FreeColumnData(size_t stColumnID) { - case IColumnsDefinition::eType_path: - case IColumnsDefinition::eType_string: + if (!HasData(stColumnID)) + return; + + switch (m_rColumns.GetColumnType(stColumnID)) { + case IColumnsDefinition::eType_path: + case IColumnsDefinition::eType_string: + { unsigned long long& ullColumnData = m_pPoolMemory[stColumnID + 1]; ullColumnData = 0ULL; - + break; } + } } -} -void TSQLiteSerializerRowData::FreeAllColumnData() -{ - size_t stCount = m_rColumns.GetCount(); - for(size_t stColumn = 0; stColumn < stCount; ++stColumn) + void TSQLiteSerializerRowData::FreeAllColumnData() { - FreeColumnData(stColumn); + size_t stCount = m_rColumns.GetCount(); + for (size_t stColumn = 0; stColumn < stCount; ++stColumn) + { + FreeColumnData(stColumn); + } } -} -TSQLiteSerializerRowData& TSQLiteSerializerRowData::operator=(const TSQLiteSerializerRowData& rSrc) -{ - m_pPoolMemory = rSrc.m_pPoolMemory; + TSQLiteSerializerRowData& TSQLiteSerializerRowData::operator=(const TSQLiteSerializerRowData& rSrc) + { + m_pPoolMemory = rSrc.m_pPoolMemory; - return *this; + return *this; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSQLiteSerializerRowData.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializerRowData.h (.../TSQLiteSerializerRowData.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TSQLiteSerializerRowData.h (.../TSQLiteSerializerRowData.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -29,82 +29,81 @@ #include #include -BEGIN_CHCORE_NAMESPACE - -class TPlainStringPool; - -class LIBCHCORE_API TSQLiteSerializerRowData : public ISerializerRowData +namespace chcore { -private: - static const unsigned long long AddedBit = 1; + class TPlainStringPool; -private: - TSQLiteSerializerRowData(object_id_t oidRowID, TSQLiteColumnsDefinition& rColumnDefinition, bool bAdded, unsigned long long* pPoolMemory, size_t stPoolMemorySizeInBytes, TPlainStringPool& poolStrings); + class LIBCHCORE_API TSQLiteSerializerRowData : public ISerializerRowData + { + private: + static const unsigned long long AddedBit = 1; -public: - TSQLiteSerializerRowData(const TSQLiteSerializerRowData& rSrc); - virtual ~TSQLiteSerializerRowData(); + private: + TSQLiteSerializerRowData(object_id_t oidRowID, TSQLiteColumnsDefinition& rColumnDefinition, bool bAdded, unsigned long long* pPoolMemory, size_t stPoolMemorySizeInBytes, TPlainStringPool& poolStrings); - TSQLiteSerializerRowData& operator=(const TSQLiteSerializerRowData& rSrc); + public: + TSQLiteSerializerRowData(const TSQLiteSerializerRowData& rSrc); + virtual ~TSQLiteSerializerRowData(); - virtual ISerializerRowData& SetValue(size_t stColIndex, bool bValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, short iValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned short uiValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, int iValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned int uiValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, long lValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long ulValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, long long llValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long long llValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, double dValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, const TString& strValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, const TSmartPath& pathValue); + TSQLiteSerializerRowData& operator=(const TSQLiteSerializerRowData& rSrc); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, bool bValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, short iValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned short uiValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, int iValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned int uiValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long lValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long ulValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long long llValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long long llValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, double dValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TString& strValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, bool bValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, short iValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned short uiValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, int iValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned int uiValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, long lValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long ulValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, long long llValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long long llValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, double dValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, const TString& strValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, const TSmartPath& pathValue); - TString GetQuery(const TString& strContainerName) const; - unsigned long long GetChangeIdentification() const; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, bool bValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, short iValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned short uiValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, int iValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned int uiValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long lValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long ulValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long long llValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long long llValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, double dValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TString& strValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue); - void BindParamsAndExec(sqlite::TSQLiteStatement& tStatement); + TString GetQuery(const TString& strContainerName) const; + unsigned long long GetChangeIdentification() const; -private: - const unsigned long long& GetDataForColumn(size_t stColIndex) const; - unsigned long long GetDataHeader() const; - unsigned long long& ModifyColumnData(size_t stColIndex); - void FreeColumnData(size_t stColumnID); - void FreeAllColumnData(); + void BindParamsAndExec(sqlite::TSQLiteStatement& tStatement); - void MarkAsAdded(); - bool IsAdded() const; + private: + const unsigned long long& GetDataForColumn(size_t stColIndex) const; + unsigned long long GetDataHeader() const; + unsigned long long& ModifyColumnData(size_t stColIndex); + void FreeColumnData(size_t stColumnID); + void FreeAllColumnData(); - bool HasAnyData() const; - void MarkColumnUsage(size_t stIndex, bool bUsed); - bool HasData(size_t stColumnIndex) const; + void MarkAsAdded(); + bool IsAdded() const; - void BindParams(sqlite::TSQLiteStatement &tStatement, int& iSQLiteColumnNumber, size_t bSkipColumn = (size_t)-1); + bool HasAnyData() const; + void MarkColumnUsage(size_t stIndex, bool bUsed); + bool HasData(size_t stColumnIndex) const; -private: - unsigned long long* m_pPoolMemory; + void BindParams(sqlite::TSQLiteStatement &tStatement, int& iSQLiteColumnNumber, size_t bSkipColumn = (size_t)-1); - TSQLiteColumnsDefinition& m_rColumns; - TPlainStringPool& m_poolStrings; + private: + unsigned long long* m_pPoolMemory; - friend class TSQLiteSerializerContainer; -}; + TSQLiteColumnsDefinition& m_rColumns; + TPlainStringPool& m_poolStrings; -typedef boost::shared_ptr TSQLiteSerializerRowDataPtr; + friend class TSQLiteSerializerContainer; + }; -END_CHCORE_NAMESPACE + typedef boost::shared_ptr TSQLiteSerializerRowDataPtr; +} #endif Index: src/libchcore/TSQLiteSerializerRowReader.cpp =================================================================== diff -u -N -rd76d3ce6c8c55fa23009dbb03b8bc06f482c5b72 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializerRowReader.cpp (.../TSQLiteSerializerRowReader.cpp) (revision d76d3ce6c8c55fa23009dbb03b8bc06f482c5b72) +++ src/libchcore/TSQLiteSerializerRowReader.cpp (.../TSQLiteSerializerRowReader.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,144 +25,143 @@ #include "TSQLiteStatement.h" #include "SerializerTrace.h" -BEGIN_CHCORE_NAMESPACE - -TSQLiteSerializerRowReader::TSQLiteSerializerRowReader(const sqlite::TSQLiteDatabasePtr& spDatabase, TSQLiteColumnsDefinition& rColumns, const TString& strContainerName) : - m_spStatement(new sqlite::TSQLiteStatement(spDatabase)), - m_rColumns(rColumns), - m_bInitialized(false), - m_strContainerName(strContainerName) +namespace chcore { - if(m_strContainerName.IsEmpty()) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); -} + TSQLiteSerializerRowReader::TSQLiteSerializerRowReader(const sqlite::TSQLiteDatabasePtr& spDatabase, TSQLiteColumnsDefinition& rColumns, const TString& strContainerName) : + m_spStatement(new sqlite::TSQLiteStatement(spDatabase)), + m_rColumns(rColumns), + m_bInitialized(false), + m_strContainerName(strContainerName) + { + if (m_strContainerName.IsEmpty()) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); + } -TSQLiteSerializerRowReader::~TSQLiteSerializerRowReader() -{ -} + TSQLiteSerializerRowReader::~TSQLiteSerializerRowReader() + { + } -bool TSQLiteSerializerRowReader::Next() -{ - if(m_rColumns.IsEmpty()) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); - - if(!m_bInitialized) + bool TSQLiteSerializerRowReader::Next() { - // generate query to retrieve data from db - TString strQuery; - strQuery = boost::str(boost::wformat(L"SELECT %1% FROM %2% ORDER BY id") % m_rColumns.GetCommaSeparatedColumns().c_str() % m_strContainerName.c_str()).c_str(); + if (m_rColumns.IsEmpty()) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); - DBTRACE1_D(_T("Executing query: %s\n"), strQuery.c_str()); - m_spStatement->Prepare(strQuery.c_str()); - m_bInitialized = true; - } + if (!m_bInitialized) + { + // generate query to retrieve data from db + TString strQuery; + strQuery = boost::str(boost::wformat(L"SELECT %1% FROM %2% ORDER BY id") % m_rColumns.GetCommaSeparatedColumns().c_str() % m_strContainerName.c_str()).c_str(); - return m_spStatement->Step() == sqlite::TSQLiteStatement::eStep_HasRow; -} + DBTRACE1_D(_T("Executing query: %s\n"), strQuery.c_str()); + m_spStatement->Prepare(strQuery.c_str()); + m_bInitialized = true; + } -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, bool& bValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + return m_spStatement->Step() == sqlite::TSQLiteStatement::eStep_HasRow; + } - m_spStatement->GetValue(GetColumnIndex(strColName), bValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, bool& bValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, short& iValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), bValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), iValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, short& iValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned short& uiValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), iValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), uiValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned short& uiValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, int& iValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), uiValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), iValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, int& iValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned int& uiValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), iValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), uiValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned int& uiValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, long& lValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), uiValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), lValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, long& lValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned long& ulValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), lValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), ulValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned long& ulValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, long long& llValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), ulValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), llValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, long long& llValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned long long& ullValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), llValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), ullValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned long long& ullValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, double& dValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), ullValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), dValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, double& dValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, TString& strValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), dValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), strValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, TString& strValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -void TSQLiteSerializerRowReader::GetValue(const TString& strColName, TSmartPath& pathValue) -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), strValue); + } - m_spStatement->GetValue(GetColumnIndex(strColName), pathValue); -} + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, TSmartPath& pathValue) + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -int TSQLiteSerializerRowReader::GetColumnIndex(const TString& strColName) const -{ - if(!m_bInitialized) - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + m_spStatement->GetValue(GetColumnIndex(strColName), pathValue); + } - size_t stColumn = m_rColumns.GetColumnIndex(strColName.c_str()); - return boost::numeric_cast(stColumn); -} + int TSQLiteSerializerRowReader::GetColumnIndex(const TString& strColName) const + { + if (!m_bInitialized) + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); -END_CHCORE_NAMESPACE + size_t stColumn = m_rColumns.GetColumnIndex(strColName.c_str()); + return boost::numeric_cast(stColumn); + } +} Index: src/libchcore/TSQLiteSerializerRowReader.h =================================================================== diff -u -N -rfc67a825635691930b3ac00dc95b16e59f3d2fae -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteSerializerRowReader.h (.../TSQLiteSerializerRowReader.h) (revision fc67a825635691930b3ac00dc95b16e59f3d2fae) +++ src/libchcore/TSQLiteSerializerRowReader.h (.../TSQLiteSerializerRowReader.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,48 +24,47 @@ #include "TSQLiteStatement.h" #include "TSQLiteColumnDefinition.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSQLiteSerializerRowReader : public ISerializerRowReader +namespace chcore { -private: - TSQLiteSerializerRowReader(const TSQLiteSerializerRowReader&); - TSQLiteSerializerRowReader& operator=(const TSQLiteSerializerRowReader&); + class LIBCHCORE_API TSQLiteSerializerRowReader : public ISerializerRowReader + { + private: + TSQLiteSerializerRowReader(const TSQLiteSerializerRowReader&); + TSQLiteSerializerRowReader& operator=(const TSQLiteSerializerRowReader&); -public: - TSQLiteSerializerRowReader(const sqlite::TSQLiteDatabasePtr& spDatabase, TSQLiteColumnsDefinition& rColumns, const TString& strContainerName); - virtual ~TSQLiteSerializerRowReader(); + public: + TSQLiteSerializerRowReader(const sqlite::TSQLiteDatabasePtr& spDatabase, TSQLiteColumnsDefinition& rColumns, const TString& strContainerName); + virtual ~TSQLiteSerializerRowReader(); - virtual bool Next(); + virtual bool Next(); - virtual void GetValue(const TString& strColName, bool& bValue); - virtual void GetValue(const TString& strColName, short& iValue); - virtual void GetValue(const TString& strColName, unsigned short& uiValue); - virtual void GetValue(const TString& strColName, int& iValue); - virtual void GetValue(const TString& strColName, unsigned int& uiValue); - virtual void GetValue(const TString& strColName, long& lValue); - virtual void GetValue(const TString& strColName, unsigned long& ulValue); - virtual void GetValue(const TString& strColName, long long& llValue); - virtual void GetValue(const TString& strColName, unsigned long long& ullValue); - virtual void GetValue(const TString& strColName, double& dValue); - virtual void GetValue(const TString& strColName, TString& strValue); - virtual void GetValue(const TString& strColName, TSmartPath& pathValue); + virtual void GetValue(const TString& strColName, bool& bValue); + virtual void GetValue(const TString& strColName, short& iValue); + virtual void GetValue(const TString& strColName, unsigned short& uiValue); + virtual void GetValue(const TString& strColName, int& iValue); + virtual void GetValue(const TString& strColName, unsigned int& uiValue); + virtual void GetValue(const TString& strColName, long& lValue); + virtual void GetValue(const TString& strColName, unsigned long& ulValue); + virtual void GetValue(const TString& strColName, long long& llValue); + virtual void GetValue(const TString& strColName, unsigned long long& ullValue); + virtual void GetValue(const TString& strColName, double& dValue); + virtual void GetValue(const TString& strColName, TString& strValue); + virtual void GetValue(const TString& strColName, TSmartPath& pathValue); -private: - int GetColumnIndex(const TString& strColName) const; + private: + int GetColumnIndex(const TString& strColName) const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - bool m_bInitialized; - sqlite::TSQLiteStatementPtr m_spStatement; - TSQLiteColumnsDefinition& m_rColumns; - TString m_strContainerName; + bool m_bInitialized; + sqlite::TSQLiteStatementPtr m_spStatement; + TSQLiteColumnsDefinition& m_rColumns; + TString m_strContainerName; #pragma warning(pop) -}; + }; -typedef boost::shared_ptr TSQLiteSerializerRowReaderPtr; + typedef boost::shared_ptr TSQLiteSerializerRowReaderPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteStatement.cpp =================================================================== diff -u -N -rd76d3ce6c8c55fa23009dbb03b8bc06f482c5b72 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteStatement.cpp (.../TSQLiteStatement.cpp) (revision d76d3ce6c8c55fa23009dbb03b8bc06f482c5b72) +++ src/libchcore/TSQLiteStatement.cpp (.../TSQLiteStatement.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,326 +23,325 @@ #include "TSQLiteException.h" #include -BEGIN_CHCORE_NAMESPACE - -namespace sqlite +namespace chcore { - TSQLiteStatement::TSQLiteStatement(const TSQLiteDatabasePtr& spDatabase) : - m_pStatement(NULL), - m_spDatabase(spDatabase), - m_bHasRow(false) + namespace sqlite { - if(!m_spDatabase) - THROW_SQLITE_EXCEPTION(eErr_InvalidArgument, 0, _T("Invalid database provided")); - } + TSQLiteStatement::TSQLiteStatement(const TSQLiteDatabasePtr& spDatabase) : + m_pStatement(NULL), + m_spDatabase(spDatabase), + m_bHasRow(false) + { + if (!m_spDatabase) + THROW_SQLITE_EXCEPTION(eErr_InvalidArgument, 0, _T("Invalid database provided")); + } - TSQLiteStatement::~TSQLiteStatement() - { - int iResult = sqlite3_finalize(m_pStatement); - iResult; - _ASSERTE(iResult == SQLITE_OK); - } - - void TSQLiteStatement::Close() - { - if(m_pStatement != NULL) + TSQLiteStatement::~TSQLiteStatement() { int iResult = sqlite3_finalize(m_pStatement); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteFinalizeError, iResult, _T("Cannot finalize statement")); - m_pStatement = NULL; + iResult; + _ASSERTE(iResult == SQLITE_OK); } - m_bHasRow = false; - } - void TSQLiteStatement::Prepare(PCWSTR pszQuery) - { - Close(); + void TSQLiteStatement::Close() + { + if (m_pStatement != NULL) + { + int iResult = sqlite3_finalize(m_pStatement); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteFinalizeError, iResult, _T("Cannot finalize statement")); + m_pStatement = NULL; + } + m_bHasRow = false; + } - int iResult = sqlite3_prepare16_v2((sqlite3*)m_spDatabase->GetHandle(), pszQuery, -1, &m_pStatement, NULL); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLitePrepareError, iResult, (PCTSTR)sqlite3_errmsg16((sqlite3*)m_spDatabase->GetHandle())); - } + void TSQLiteStatement::Prepare(PCWSTR pszQuery) + { + Close(); - TSQLiteStatement::EStepResult TSQLiteStatement::Step() - { - m_bHasRow = false; + int iResult = sqlite3_prepare16_v2((sqlite3*)m_spDatabase->GetHandle(), pszQuery, -1, &m_pStatement, NULL); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLitePrepareError, iResult, (PCTSTR)sqlite3_errmsg16((sqlite3*)m_spDatabase->GetHandle())); + } - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - - int iResult = sqlite3_step(m_pStatement); - switch(iResult) + TSQLiteStatement::EStepResult TSQLiteStatement::Step() { - case SQLITE_ROW: - m_bHasRow = true; - return eStep_HasRow; - case SQLITE_OK: - case SQLITE_DONE: - Reset(); - return eStep_Finished; - default: + m_bHasRow = false; + + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + + int iResult = sqlite3_step(m_pStatement); + switch (iResult) { + case SQLITE_ROW: + m_bHasRow = true; + return eStep_HasRow; + case SQLITE_OK: + case SQLITE_DONE: + Reset(); + return eStep_Finished; + default: + { const wchar_t* pszErrMsg = (const wchar_t*)sqlite3_errmsg16((sqlite3*)m_spDatabase->GetHandle()); const size_t stMaxSize = 1024; wchar_t szText[stMaxSize]; _snwprintf_s(szText, stMaxSize, _TRUNCATE, L"Cannot perform step on the statement. SQLite reported error: %s", pszErrMsg); THROW_SQLITE_EXCEPTION(eErr_SQLiteStepError, iResult, szText); } + } } - } - int TSQLiteStatement::Changes() - { - return sqlite3_changes((sqlite3*)m_spDatabase->GetHandle()); - } + int TSQLiteStatement::Changes() + { + return sqlite3_changes((sqlite3*)m_spDatabase->GetHandle()); + } - void TSQLiteStatement::BindValue(int iColumn, bool bValue) - { - BindValue(iColumn, bValue ? 1 : 0); - } + void TSQLiteStatement::BindValue(int iColumn, bool bValue) + { + BindValue(iColumn, bValue ? 1 : 0); + } - void TSQLiteStatement::BindValue(int iColumn, short siValue) - { - BindValue(iColumn, (int)siValue); - } + void TSQLiteStatement::BindValue(int iColumn, short siValue) + { + BindValue(iColumn, (int)siValue); + } - void TSQLiteStatement::BindValue(int iColumn, unsigned short usiValue) - { - BindValue(iColumn, (unsigned int)usiValue); - } + void TSQLiteStatement::BindValue(int iColumn, unsigned short usiValue) + { + BindValue(iColumn, (unsigned int)usiValue); + } - void TSQLiteStatement::BindValue(int iColumn, int iValue) - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + void TSQLiteStatement::BindValue(int iColumn, int iValue) + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - int iResult = sqlite3_bind_int(m_pStatement, iColumn, iValue); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter")); - } + int iResult = sqlite3_bind_int(m_pStatement, iColumn, iValue); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter")); + } - void TSQLiteStatement::BindValue(int iColumn, unsigned int uiValue) - { - BindValue(iColumn, *(int*)&uiValue); - } + void TSQLiteStatement::BindValue(int iColumn, unsigned int uiValue) + { + BindValue(iColumn, *(int*)&uiValue); + } - void TSQLiteStatement::BindValue(int iColumn, long lValue) - { - BindValue(iColumn, boost::numeric_cast(lValue)); - } + void TSQLiteStatement::BindValue(int iColumn, long lValue) + { + BindValue(iColumn, boost::numeric_cast(lValue)); + } - void TSQLiteStatement::BindValue(int iColumn, unsigned long ulValue) - { - BindValue(iColumn, boost::numeric_cast(ulValue)); - } + void TSQLiteStatement::BindValue(int iColumn, unsigned long ulValue) + { + BindValue(iColumn, boost::numeric_cast(ulValue)); + } - void TSQLiteStatement::BindValue(int iColumn, long long llValue) - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + void TSQLiteStatement::BindValue(int iColumn, long long llValue) + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - int iResult = sqlite3_bind_int64(m_pStatement, iColumn, llValue); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter")); - } + int iResult = sqlite3_bind_int64(m_pStatement, iColumn, llValue); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter")); + } - void TSQLiteStatement::BindValue(int iColumn, unsigned long long ullValue) - { - BindValue(iColumn, *(long long*)&ullValue); - } + void TSQLiteStatement::BindValue(int iColumn, unsigned long long ullValue) + { + BindValue(iColumn, *(long long*)&ullValue); + } - void TSQLiteStatement::BindValue(int iColumn, double dValue) - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + void TSQLiteStatement::BindValue(int iColumn, double dValue) + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - int iResult = sqlite3_bind_double(m_pStatement, iColumn, dValue); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter")); - } + int iResult = sqlite3_bind_double(m_pStatement, iColumn, dValue); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter")); + } - void TSQLiteStatement::BindValue(int iColumn, PCTSTR pszText) - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + void TSQLiteStatement::BindValue(int iColumn, PCTSTR pszText) + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - int iResult = sqlite3_bind_text16(m_pStatement, iColumn, pszText, -1, SQLITE_TRANSIENT); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter")); - } + int iResult = sqlite3_bind_text16(m_pStatement, iColumn, pszText, -1, SQLITE_TRANSIENT); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter")); + } - void TSQLiteStatement::BindValue(int iColumn, const TString& strText) - { - BindValue(iColumn, strText.c_str()); - } + void TSQLiteStatement::BindValue(int iColumn, const TString& strText) + { + BindValue(iColumn, strText.c_str()); + } - void TSQLiteStatement::BindValue(int iColumn, const TSmartPath& path) - { - BindValue(iColumn, path.ToString()); - } + void TSQLiteStatement::BindValue(int iColumn, const TSmartPath& path) + { + BindValue(iColumn, path.ToString()); + } - bool TSQLiteStatement::GetBool(int iCol) - { - return GetInt(iCol) != 0; - } + bool TSQLiteStatement::GetBool(int iCol) + { + return GetInt(iCol) != 0; + } - short TSQLiteStatement::GetShort(int iCol) - { - return boost::numeric_cast(GetInt(iCol)); - } + short TSQLiteStatement::GetShort(int iCol) + { + return boost::numeric_cast(GetInt(iCol)); + } - unsigned short TSQLiteStatement::GetUShort(int iCol) - { - return boost::numeric_cast(GetUInt(iCol)); - } + unsigned short TSQLiteStatement::GetUShort(int iCol) + { + return boost::numeric_cast(GetUInt(iCol)); + } - int TSQLiteStatement::GetInt(int iCol) - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - if(!m_bHasRow) - THROW_SQLITE_EXCEPTION(eErr_SQLiteNoRowAvailable, 0, _T("No row available")); + int TSQLiteStatement::GetInt(int iCol) + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + if (!m_bHasRow) + THROW_SQLITE_EXCEPTION(eErr_SQLiteNoRowAvailable, 0, _T("No row available")); - return sqlite3_column_int(m_pStatement, iCol); - } + return sqlite3_column_int(m_pStatement, iCol); + } - unsigned int TSQLiteStatement::GetUInt(int iCol) - { - int iVal = GetInt(iCol); - return *(unsigned int*)&iVal; - } + unsigned int TSQLiteStatement::GetUInt(int iCol) + { + int iVal = GetInt(iCol); + return *(unsigned int*)&iVal; + } - long TSQLiteStatement::GetLong(int iCol) - { - return boost::numeric_cast(GetInt(iCol)); - } + long TSQLiteStatement::GetLong(int iCol) + { + return boost::numeric_cast(GetInt(iCol)); + } - unsigned long TSQLiteStatement::GetULong(int iCol) - { - return boost::numeric_cast(GetUInt(iCol)); - } + unsigned long TSQLiteStatement::GetULong(int iCol) + { + return boost::numeric_cast(GetUInt(iCol)); + } - long long TSQLiteStatement::GetInt64(int iCol) - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - if(!m_bHasRow) - THROW_SQLITE_EXCEPTION(eErr_SQLiteNoRowAvailable, 0, _T("No row available")); + long long TSQLiteStatement::GetInt64(int iCol) + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + if (!m_bHasRow) + THROW_SQLITE_EXCEPTION(eErr_SQLiteNoRowAvailable, 0, _T("No row available")); - return sqlite3_column_int64(m_pStatement, iCol); - } + return sqlite3_column_int64(m_pStatement, iCol); + } - unsigned long long TSQLiteStatement::GetUInt64(int iCol) - { - long long llVal = GetInt64(iCol); - return *(unsigned long long*)&llVal; - } + unsigned long long TSQLiteStatement::GetUInt64(int iCol) + { + long long llVal = GetInt64(iCol); + return *(unsigned long long*)&llVal; + } - double TSQLiteStatement::GetDouble(int iCol) - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - if(!m_bHasRow) - THROW_SQLITE_EXCEPTION(eErr_SQLiteNoRowAvailable, 0, _T("No row available")); + double TSQLiteStatement::GetDouble(int iCol) + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + if (!m_bHasRow) + THROW_SQLITE_EXCEPTION(eErr_SQLiteNoRowAvailable, 0, _T("No row available")); - return sqlite3_column_double(m_pStatement, iCol); - } + return sqlite3_column_double(m_pStatement, iCol); + } - TString TSQLiteStatement::GetText(int iCol) - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - if(!m_bHasRow) - THROW_SQLITE_EXCEPTION(eErr_SQLiteNoRowAvailable, 0, _T("No row available")); + TString TSQLiteStatement::GetText(int iCol) + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + if (!m_bHasRow) + THROW_SQLITE_EXCEPTION(eErr_SQLiteNoRowAvailable, 0, _T("No row available")); - return TString((const wchar_t*)sqlite3_column_text16(m_pStatement, iCol)); - } + return TString((const wchar_t*)sqlite3_column_text16(m_pStatement, iCol)); + } - TSmartPath TSQLiteStatement::GetPath(int iCol) - { - return PathFromWString(GetText(iCol)); - } + TSmartPath TSQLiteStatement::GetPath(int iCol) + { + return PathFromWString(GetText(iCol)); + } - void TSQLiteStatement::ClearBindings() - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + void TSQLiteStatement::ClearBindings() + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - int iResult = sqlite3_clear_bindings(m_pStatement); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot clear bindings")); - } + int iResult = sqlite3_clear_bindings(m_pStatement); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot clear bindings")); + } - void TSQLiteStatement::Reset() - { - if(!m_pStatement) - THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); + void TSQLiteStatement::Reset() + { + if (!m_pStatement) + THROW_SQLITE_EXCEPTION(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement")); - int iResult = sqlite3_reset(m_pStatement); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot reset statement")); - } + int iResult = sqlite3_reset(m_pStatement); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteBindError, iResult, _T("Cannot reset statement")); + } - void TSQLiteStatement::GetValue(int iCol, bool& bValue) - { - bValue = GetBool(iCol); - } + void TSQLiteStatement::GetValue(int iCol, bool& bValue) + { + bValue = GetBool(iCol); + } - void TSQLiteStatement::GetValue(int iCol, short& iValue) - { - iValue = GetShort(iCol); - } + void TSQLiteStatement::GetValue(int iCol, short& iValue) + { + iValue = GetShort(iCol); + } - void TSQLiteStatement::GetValue(int iCol, unsigned short& uiValue) - { - uiValue = GetUShort(iCol); - } + void TSQLiteStatement::GetValue(int iCol, unsigned short& uiValue) + { + uiValue = GetUShort(iCol); + } - void TSQLiteStatement::GetValue(int iCol, int& iValue) - { - iValue = GetInt(iCol); - } + void TSQLiteStatement::GetValue(int iCol, int& iValue) + { + iValue = GetInt(iCol); + } - void TSQLiteStatement::GetValue(int iCol, unsigned int& uiValue) - { - uiValue = GetUInt(iCol); - } + void TSQLiteStatement::GetValue(int iCol, unsigned int& uiValue) + { + uiValue = GetUInt(iCol); + } - void TSQLiteStatement::GetValue(int iCol, long& lValue) - { - lValue = GetLong(iCol); - } + void TSQLiteStatement::GetValue(int iCol, long& lValue) + { + lValue = GetLong(iCol); + } - void TSQLiteStatement::GetValue(int iCol, unsigned long& ulValue) - { - ulValue = GetULong(iCol); - } + void TSQLiteStatement::GetValue(int iCol, unsigned long& ulValue) + { + ulValue = GetULong(iCol); + } - void TSQLiteStatement::GetValue(int iCol, long long& llValue) - { - llValue = GetInt64(iCol); - } + void TSQLiteStatement::GetValue(int iCol, long long& llValue) + { + llValue = GetInt64(iCol); + } - void TSQLiteStatement::GetValue(int iCol, unsigned long long& ullValue) - { - ullValue = GetUInt64(iCol); - } + void TSQLiteStatement::GetValue(int iCol, unsigned long long& ullValue) + { + ullValue = GetUInt64(iCol); + } - void TSQLiteStatement::GetValue(int iCol, double& dValue) - { - dValue = GetDouble(iCol); - } + void TSQLiteStatement::GetValue(int iCol, double& dValue) + { + dValue = GetDouble(iCol); + } - void TSQLiteStatement::GetValue(int iCol, TString& strValue) - { - strValue = GetText(iCol); - } + void TSQLiteStatement::GetValue(int iCol, TString& strValue) + { + strValue = GetText(iCol); + } - void TSQLiteStatement::GetValue(int iCol, TSmartPath& pathValue) - { - pathValue = GetPath(iCol); + void TSQLiteStatement::GetValue(int iCol, TSmartPath& pathValue) + { + pathValue = GetPath(iCol); + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSQLiteStatement.h =================================================================== diff -u -N -r320c4eb6ba3a38dcd6fbda6a9a12a8350a153e41 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteStatement.h (.../TSQLiteStatement.h) (revision 320c4eb6ba3a38dcd6fbda6a9a12a8350a153e41) +++ src/libchcore/TSQLiteStatement.h (.../TSQLiteStatement.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,84 +25,83 @@ struct sqlite3_stmt; -BEGIN_CHCORE_NAMESPACE - -namespace sqlite +namespace chcore { - typedef boost::shared_ptr SQLiteStatementHandle; - - class TSQLiteStatement + namespace sqlite { - public: - enum EStepResult + typedef boost::shared_ptr SQLiteStatementHandle; + + class TSQLiteStatement { - eStep_Finished, - eStep_HasRow - }; + public: + enum EStepResult + { + eStep_Finished, + eStep_HasRow + }; - public: - TSQLiteStatement(const TSQLiteDatabasePtr& spDatabase); - ~TSQLiteStatement(); + public: + TSQLiteStatement(const TSQLiteDatabasePtr& spDatabase); + ~TSQLiteStatement(); - void Close(); + void Close(); - void Prepare(PCTSTR pszQuery); + void Prepare(PCTSTR pszQuery); - void BindValue(int iColumn, bool bValue); - void BindValue(int iColumn, short siValue); - void BindValue(int iColumn, unsigned short usiValue); - void BindValue(int iColumn, int iValue); - void BindValue(int iColumn, unsigned int uiValue); - void BindValue(int iColumn, long lValue); - void BindValue(int iColumn, unsigned long ulValue); - void BindValue(int iColumn, long long llValue); - void BindValue(int iColumn, unsigned long long ullValue); - void BindValue(int iColumn, double dValue); - void BindValue(int iColumn, PCTSTR pszText); - void BindValue(int iColumn, const TString& strText); - void BindValue(int iColumn, const TSmartPath& path); + void BindValue(int iColumn, bool bValue); + void BindValue(int iColumn, short siValue); + void BindValue(int iColumn, unsigned short usiValue); + void BindValue(int iColumn, int iValue); + void BindValue(int iColumn, unsigned int uiValue); + void BindValue(int iColumn, long lValue); + void BindValue(int iColumn, unsigned long ulValue); + void BindValue(int iColumn, long long llValue); + void BindValue(int iColumn, unsigned long long ullValue); + void BindValue(int iColumn, double dValue); + void BindValue(int iColumn, PCTSTR pszText); + void BindValue(int iColumn, const TString& strText); + void BindValue(int iColumn, const TSmartPath& path); - void ClearBindings(); + void ClearBindings(); - EStepResult Step(); - int Changes(); - void Reset(); + EStepResult Step(); + int Changes(); + void Reset(); - bool GetBool(int iCol); - short GetShort(int iCol); - unsigned short GetUShort(int iCol); - int GetInt(int iCol); - unsigned int GetUInt(int iCol); - long GetLong(int iCol); - unsigned long GetULong(int iCol); - long long GetInt64(int iCol); - unsigned long long GetUInt64(int iCol); - double GetDouble(int iCol); - TString GetText(int iCol); - TSmartPath GetPath(int iCol); + bool GetBool(int iCol); + short GetShort(int iCol); + unsigned short GetUShort(int iCol); + int GetInt(int iCol); + unsigned int GetUInt(int iCol); + long GetLong(int iCol); + unsigned long GetULong(int iCol); + long long GetInt64(int iCol); + unsigned long long GetUInt64(int iCol); + double GetDouble(int iCol); + TString GetText(int iCol); + TSmartPath GetPath(int iCol); - void GetValue(int iCol, bool& bValue); - void GetValue(int iCol, short& iValue); - void GetValue(int iCol, unsigned short& uiValue); - void GetValue(int iCol, int& iValue); - void GetValue(int iCol, unsigned int& uiValue); - void GetValue(int iCol, long& lValue); - void GetValue(int iCol, unsigned long& ulValue); - void GetValue(int iCol, long long& llValue); - void GetValue(int iCol, unsigned long long& ullValue); - void GetValue(int iCol, double& dValue); - void GetValue(int iCol, TString& strValue); - void GetValue(int iCol, TSmartPath& pathValue); + void GetValue(int iCol, bool& bValue); + void GetValue(int iCol, short& iValue); + void GetValue(int iCol, unsigned short& uiValue); + void GetValue(int iCol, int& iValue); + void GetValue(int iCol, unsigned int& uiValue); + void GetValue(int iCol, long& lValue); + void GetValue(int iCol, unsigned long& ulValue); + void GetValue(int iCol, long long& llValue); + void GetValue(int iCol, unsigned long long& ullValue); + void GetValue(int iCol, double& dValue); + void GetValue(int iCol, TString& strValue); + void GetValue(int iCol, TSmartPath& pathValue); - private: - sqlite3_stmt* m_pStatement; - TSQLiteDatabasePtr m_spDatabase; - bool m_bHasRow; - }; + private: + sqlite3_stmt* m_pStatement; + TSQLiteDatabasePtr m_spDatabase; + bool m_bHasRow; + }; - typedef boost::shared_ptr TSQLiteStatementPtr; + typedef boost::shared_ptr TSQLiteStatementPtr; + } } -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteTaskManagerSchema.cpp =================================================================== diff -u -N -ra99c8baeb8f6c237603df46c0f5c4cf943152c09 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteTaskManagerSchema.cpp (.../TSQLiteTaskManagerSchema.cpp) (revision a99c8baeb8f6c237603df46c0f5c4cf943152c09) +++ src/libchcore/TSQLiteTaskManagerSchema.cpp (.../TSQLiteTaskManagerSchema.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,48 +22,47 @@ #include "TSerializerVersion.h" #include "TSQLiteStatement.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + using namespace sqlite; -using namespace sqlite; + TSQLiteTaskManagerSchema::TSQLiteTaskManagerSchema() + { + } -TSQLiteTaskManagerSchema::TSQLiteTaskManagerSchema() -{ -} + TSQLiteTaskManagerSchema::~TSQLiteTaskManagerSchema() + { + } -TSQLiteTaskManagerSchema::~TSQLiteTaskManagerSchema() -{ -} + void TSQLiteTaskManagerSchema::Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) + { + TSQLiteTransaction tTransaction(spDatabase); -void TSQLiteTaskManagerSchema::Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) -{ - TSQLiteTransaction tTransaction(spDatabase); + // check version of the database + TSerializerVersion tVersion(spDatabase); - // check version of the database - TSerializerVersion tVersion(spDatabase); + // if version is 0, then this is the fresh database with (almost) no tables inside + if (tVersion.GetVersion() == 0) + { + TSQLiteStatement tStatement(spDatabase); - // if version is 0, then this is the fresh database with (almost) no tables inside - if(tVersion.GetVersion() == 0) - { - TSQLiteStatement tStatement(spDatabase); + tStatement.Prepare(_T("CREATE TABLE tasks(id BIGINT UNIQUE PRIMARY KEY, task_order INT NOT NULL, path VARCHAR(32768) NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE tasks(id BIGINT UNIQUE PRIMARY KEY, task_order INT NOT NULL, path VARCHAR(32768) NOT NULL)")); - tStatement.Step(); + // and finally set the database version to current one + tVersion.SetVersion(1); + } + if (tVersion.GetVersion() == 1) + { + TSQLiteStatement tStatement(spDatabase); - // and finally set the database version to current one - tVersion.SetVersion(1); - } - if(tVersion.GetVersion() == 1) - { - TSQLiteStatement tStatement(spDatabase); + tStatement.Prepare(_T("CREATE TABLE obsolete_tasks(id BIGINT UNIQUE PRIMARY KEY, path VARCHAR(32768) NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE obsolete_tasks(id BIGINT UNIQUE PRIMARY KEY, path VARCHAR(32768) NOT NULL)")); - tStatement.Step(); + // and finally set the database version to current one + tVersion.SetVersion(2); + } - // and finally set the database version to current one - tVersion.SetVersion(2); + tTransaction.Commit(); } - - tTransaction.Commit(); } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSQLiteTaskManagerSchema.h =================================================================== diff -u -N -rd32a79f0e9220bad2c6eeb5e8a986228b6e832fb -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteTaskManagerSchema.h (.../TSQLiteTaskManagerSchema.h) (revision d32a79f0e9220bad2c6eeb5e8a986228b6e832fb) +++ src/libchcore/TSQLiteTaskManagerSchema.h (.../TSQLiteTaskManagerSchema.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,19 +23,18 @@ #include "TSQLiteDatabase.h" #include "ISQLiteSerializerSchema.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSQLiteTaskManagerSchema : public ISQLiteSerializerSchema +namespace chcore { -public: - TSQLiteTaskManagerSchema(); - virtual ~TSQLiteTaskManagerSchema(); + class LIBCHCORE_API TSQLiteTaskManagerSchema : public ISQLiteSerializerSchema + { + public: + TSQLiteTaskManagerSchema(); + virtual ~TSQLiteTaskManagerSchema(); - virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase); -}; + virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase); + }; -typedef boost::shared_ptr TTaskManagerSchemaPtr; + typedef boost::shared_ptr TTaskManagerSchemaPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSQLiteTaskSchema.cpp =================================================================== diff -u -N -r671f4b1792a20d98b186f4e0a9cc6a620dede019 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteTaskSchema.cpp (.../TSQLiteTaskSchema.cpp) (revision 671f4b1792a20d98b186f4e0a9cc6a620dede019) +++ src/libchcore/TSQLiteTaskSchema.cpp (.../TSQLiteTaskSchema.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,196 +22,195 @@ #include "TSerializerVersion.h" #include "TSQLiteStatement.h" -BEGIN_CHCORE_NAMESPACE - -TSQLiteTaskSchema::TSQLiteTaskSchema() +namespace chcore { -} + TSQLiteTaskSchema::TSQLiteTaskSchema() + { + } -TSQLiteTaskSchema::~TSQLiteTaskSchema() -{ -} + TSQLiteTaskSchema::~TSQLiteTaskSchema() + { + } -void TSQLiteTaskSchema::Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) -{ - sqlite::TSQLiteTransaction tTransaction(spDatabase); + void TSQLiteTaskSchema::Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) + { + sqlite::TSQLiteTransaction tTransaction(spDatabase); - // check version of the database - TSerializerVersion tVersion(spDatabase); + // check version of the database + TSerializerVersion tVersion(spDatabase); - // if version is 0, then this is the fresh database with (almost) no tables inside - // that's why the initialization always creates the latest version of database, whithout going - // through all the intermediate migrations - if(tVersion.GetVersion() == 0) - CreateNewDatabase(spDatabase, tVersion); - else - { - // migrate current database to the newest version - if (tVersion.GetVersion() == 1) - Migrate_001_002(spDatabase, tVersion); + // if version is 0, then this is the fresh database with (almost) no tables inside + // that's why the initialization always creates the latest version of database, whithout going + // through all the intermediate migrations + if (tVersion.GetVersion() == 0) + CreateNewDatabase(spDatabase, tVersion); + else + { + // migrate current database to the newest version + if (tVersion.GetVersion() == 1) + Migrate_001_002(spDatabase, tVersion); - if (tVersion.GetVersion() == 2) - Migrate_002_003(spDatabase, tVersion); + if (tVersion.GetVersion() == 2) + Migrate_002_003(spDatabase, tVersion); - if (tVersion.GetVersion() == 3) - Migrate_003_004(spDatabase, tVersion); + if (tVersion.GetVersion() == 3) + Migrate_003_004(spDatabase, tVersion); + } + + tTransaction.Commit(); } - tTransaction.Commit(); -} + void TSQLiteTaskSchema::CreateNewDatabase(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) + { + sqlite::TSQLiteStatement tStatement(spDatabase); + tStatement.Prepare(_T("CREATE TABLE task(id BIGINT UNIQUE, name varchar(256) NOT NULL, log_path VARCHAR(32768), current_state INT NOT NULL, destination_path varchar(32768) NOT NULL)")); + tStatement.Step(); -void TSQLiteTaskSchema::CreateNewDatabase(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) -{ - sqlite::TSQLiteStatement tStatement(spDatabase); - tStatement.Prepare(_T("CREATE TABLE task(id BIGINT UNIQUE, name varchar(256) NOT NULL, log_path VARCHAR(32768), current_state INT NOT NULL, destination_path varchar(32768) NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE base_paths(id BIGINT UNIQUE, src_path varchar(32768) NOT NULL, skip_processing boolean NOT NULL, dst_path varchar(32768) NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE base_paths(id BIGINT UNIQUE, src_path varchar(32768) NOT NULL, skip_processing boolean NOT NULL, dst_path varchar(32768) NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE scanned_files(id BIGINT UNIQUE, rel_path varchar(32768) NOT NULL, base_path_id BIGINT NOT NULL, attr INT NOT NULL, size BIGINT NOT NULL, time_created BIGINT NOT NULL, time_last_write BIGINT NOT NULL, time_last_access BIGINT NOT NULL, flags INT NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE scanned_files(id BIGINT UNIQUE, rel_path varchar(32768) NOT NULL, base_path_id BIGINT NOT NULL, attr INT NOT NULL, size BIGINT NOT NULL, time_created BIGINT NOT NULL, time_last_write BIGINT NOT NULL, time_last_access BIGINT NOT NULL, flags INT NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE task_config(id BIGINT UNIQUE, name varchar(256) NOT NULL, node_order INT NOT NULL, value varchar(32768) NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE task_config(id BIGINT UNIQUE, name varchar(256) NOT NULL, node_order INT NOT NULL, value varchar(32768) NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE filters(id BIGINT UNIQUE, use_mask INT NOT NULL, mask varchar(32768) NOT NULL, ") + _T("use_exclude_mask INT NOT NULL, exclude_mask varchar(32768) NOT NULL, ") + _T("use_size_1 INT NOT NULL, compare_type_1 INT NOT NULL, size_1 BIGINT NOT NULL, ") + _T("use_size_2 INT NOT NULL, compare_type_2 INT NOT NULL, size_2 BIGINT NOT NULL, ") + _T("date_type INT NOT NULL,") + _T("use_date_time_1 INT NOT NULL, date_compare_type_1 INT NOT NULL, use_date_1 INT NOT NULL, use_time_1 INT NOT NULL, datetime_1 varchar(64) NOT NULL, ") + _T("use_date_time_2 INT NOT NULL, date_compare_type_2 INT NOT NULL, use_date_2 INT NOT NULL, use_time_2 INT NOT NULL, datetime_2 varchar(64) NOT NULL, ") + _T("use_attributes INT NOT NULL, attr_archive INT NOT NULL, attr_ro INT NOT NULL, attr_hidden INT NOT NULL, attr_system INT NOT NULL, attr_directory INT NOT NULL") + _T(")")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE filters(id BIGINT UNIQUE, use_mask INT NOT NULL, mask varchar(32768) NOT NULL, ") - _T("use_exclude_mask INT NOT NULL, exclude_mask varchar(32768) NOT NULL, ") - _T("use_size_1 INT NOT NULL, compare_type_1 INT NOT NULL, size_1 BIGINT NOT NULL, ") - _T("use_size_2 INT NOT NULL, compare_type_2 INT NOT NULL, size_2 BIGINT NOT NULL, ") - _T("date_type INT NOT NULL,") - _T("use_date_time_1 INT NOT NULL, date_compare_type_1 INT NOT NULL, use_date_1 INT NOT NULL, use_time_1 INT NOT NULL, datetime_1 varchar(64) NOT NULL, ") - _T("use_date_time_2 INT NOT NULL, date_compare_type_2 INT NOT NULL, use_date_2 INT NOT NULL, use_time_2 INT NOT NULL, datetime_2 varchar(64) NOT NULL, ") - _T("use_attributes INT NOT NULL, attr_archive INT NOT NULL, attr_ro INT NOT NULL, attr_hidden INT NOT NULL, attr_system INT NOT NULL, attr_directory INT NOT NULL") - _T(")")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE local_stats(id BIGINT UNIQUE, elapsed_time BIGINT NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE local_stats(id BIGINT UNIQUE, elapsed_time BIGINT NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE subtasks(id BIGINT UNIQUE, type INT NOT NULL, is_current boolean NOT NULL, is_estimation boolean NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE subtasks(id BIGINT UNIQUE, type INT NOT NULL, is_current boolean NOT NULL, is_estimation boolean NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE subtasks_info(id BIGINT UNIQUE, operation INT NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE subtasks_info(id BIGINT UNIQUE, operation INT NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE subtask_fastmove(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE subtask_fastmove(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE subtask_delete(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE subtask_delete(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE subtask_copymove(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE subtask_copymove(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("CREATE TABLE feedback(id BIGINT UNIQUE, file_error INT NOT NULL, file_already_exists INT NOT NULL, not_enough_space INT NOT NULL, operation_finished INT NOT NULL, operation_error INT NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE feedback(id BIGINT UNIQUE, file_error INT NOT NULL, file_already_exists INT NOT NULL, not_enough_space INT NOT NULL, operation_finished INT NOT NULL, operation_error INT NOT NULL)")); - tStatement.Step(); + // and finally set the database version to current one + tVersion.SetVersion(4); + } - // and finally set the database version to current one - tVersion.SetVersion(4); -} + void TSQLiteTaskSchema::Migrate_001_002(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) + { + sqlite::TSQLiteStatement tStatement(spDatabase); -void TSQLiteTaskSchema::Migrate_001_002(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) -{ - sqlite::TSQLiteStatement tStatement(spDatabase); + tStatement.Prepare(_T("ALTER TABLE subtask_fastmove ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); + tStatement.Step(); + tStatement.Prepare(_T("ALTER TABLE subtask_delete ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); + tStatement.Step(); + tStatement.Prepare(_T("ALTER TABLE subtask_copymove ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); + tStatement.Step(); - tStatement.Prepare(_T("ALTER TABLE subtask_fastmove ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); - tStatement.Step(); - tStatement.Prepare(_T("ALTER TABLE subtask_delete ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); - tStatement.Step(); - tStatement.Prepare(_T("ALTER TABLE subtask_copymove ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); - tStatement.Step(); + tVersion.SetVersion(2); + } - tVersion.SetVersion(2); -} + void TSQLiteTaskSchema::Migrate_002_003(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) + { + sqlite::TSQLiteStatement tStatement(spDatabase); -void TSQLiteTaskSchema::Migrate_002_003(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) -{ - sqlite::TSQLiteStatement tStatement(spDatabase); + // drop column from fastmove + tStatement.Prepare(_T("CREATE TABLE subtask_fastmove_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); - // drop column from fastmove - tStatement.Prepare(_T("CREATE TABLE subtask_fastmove_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); + tStatement.Prepare(_T("INSERT INTO subtask_fastmove_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, ") + _T("total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") + _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, ") + _T("total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") + _T("FROM subtask_fastmove")); + tStatement.Step(); - tStatement.Prepare(_T("INSERT INTO subtask_fastmove_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, ") - _T("total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") - _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, ") - _T("total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") - _T("FROM subtask_fastmove")); - tStatement.Step(); + tStatement.Prepare(_T("DROP TABLE subtask_fastmove")); + tStatement.Step(); - tStatement.Prepare(_T("DROP TABLE subtask_fastmove")); - tStatement.Step(); + tStatement.Prepare(_T("ALTER TABLE subtask_fastmove_new RENAME TO subtask_fastmove")); + tStatement.Step(); - tStatement.Prepare(_T("ALTER TABLE subtask_fastmove_new RENAME TO subtask_fastmove")); - tStatement.Step(); + // drop column from subtask delete + tStatement.Prepare(_T("CREATE TABLE subtask_delete_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); - // drop column from subtask delete - tStatement.Prepare(_T("CREATE TABLE subtask_delete_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); + //id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume + tStatement.Prepare(_T("INSERT INTO subtask_delete_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") + _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") + _T("FROM subtask_delete")); + tStatement.Step(); - //id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume - tStatement.Prepare(_T("INSERT INTO subtask_delete_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") - _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") - _T("FROM subtask_delete")); - tStatement.Step(); + tStatement.Prepare(_T("DROP TABLE subtask_delete")); + tStatement.Step(); - tStatement.Prepare(_T("DROP TABLE subtask_delete")); - tStatement.Step(); + tStatement.Prepare(_T("ALTER TABLE subtask_delete_new RENAME TO subtask_delete")); + tStatement.Step(); - tStatement.Prepare(_T("ALTER TABLE subtask_delete_new RENAME TO subtask_delete")); - tStatement.Step(); + // drop column from subtask copymove + tStatement.Prepare(_T("CREATE TABLE subtask_copymove_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); - // drop column from subtask copymove - tStatement.Prepare(_T("CREATE TABLE subtask_copymove_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); + //id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume + tStatement.Prepare(_T("INSERT INTO subtask_copymove_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") + _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") + _T("FROM subtask_copymove")); + tStatement.Step(); - //id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume - tStatement.Prepare(_T("INSERT INTO subtask_copymove_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") - _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") - _T("FROM subtask_copymove")); - tStatement.Step(); + tStatement.Prepare(_T("DROP TABLE subtask_copymove")); + tStatement.Step(); - tStatement.Prepare(_T("DROP TABLE subtask_copymove")); - tStatement.Step(); + tStatement.Prepare(_T("ALTER TABLE subtask_copymove_new RENAME TO subtask_copymove")); + tStatement.Step(); - tStatement.Prepare(_T("ALTER TABLE subtask_copymove_new RENAME TO subtask_copymove")); - tStatement.Step(); + tVersion.SetVersion(3); + } - tVersion.SetVersion(3); -} + void TSQLiteTaskSchema::Migrate_003_004(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) + { + sqlite::TSQLiteStatement tStatement(spDatabase); -void TSQLiteTaskSchema::Migrate_003_004(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) -{ - sqlite::TSQLiteStatement tStatement(spDatabase); + tStatement.Prepare(_T("CREATE TABLE feedback(id BIGINT UNIQUE, file_error INT NOT NULL, file_already_exists INT NOT NULL, not_enough_space INT NOT NULL, operation_finished INT NOT NULL, operation_error INT NOT NULL)")); + tStatement.Step(); - tStatement.Prepare(_T("CREATE TABLE feedback(id BIGINT UNIQUE, file_error INT NOT NULL, file_already_exists INT NOT NULL, not_enough_space INT NOT NULL, operation_finished INT NOT NULL, operation_error INT NOT NULL)")); - tStatement.Step(); + // for tasks being migrated we have to insert some defaults for feedback + tStatement.Prepare(_T("INSERT INTO feedback(id, file_error, file_already_exists, not_enough_space, operation_finished, operation_error) VALUES(?1, ?2, ?3, ?4, ?5, ?6)")); + tStatement.BindValue(1, 0); + tStatement.BindValue(2, 0); + tStatement.BindValue(3, 0); + tStatement.BindValue(4, 0); + tStatement.BindValue(5, 0); + tStatement.BindValue(6, 0); - // for tasks being migrated we have to insert some defaults for feedback - tStatement.Prepare(_T("INSERT INTO feedback(id, file_error, file_already_exists, not_enough_space, operation_finished, operation_error) VALUES(?1, ?2, ?3, ?4, ?5, ?6)")); - tStatement.BindValue(1, 0); - tStatement.BindValue(2, 0); - tStatement.BindValue(3, 0); - tStatement.BindValue(4, 0); - tStatement.BindValue(5, 0); - tStatement.BindValue(6, 0); + tStatement.Step(); - tStatement.Step(); - - tVersion.SetVersion(4); + tVersion.SetVersion(4); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSQLiteTaskSchema.h =================================================================== diff -u -N -r671f4b1792a20d98b186f4e0a9cc6a620dede019 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteTaskSchema.h (.../TSQLiteTaskSchema.h) (revision 671f4b1792a20d98b186f4e0a9cc6a620dede019) +++ src/libchcore/TSQLiteTaskSchema.h (.../TSQLiteTaskSchema.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,28 +22,27 @@ #include "libchcore.h" #include "ISQLiteSerializerSchema.h" -BEGIN_CHCORE_NAMESPACE - -class TSerializerVersion; - -class LIBCHCORE_API TSQLiteTaskSchema : public ISQLiteSerializerSchema +namespace chcore { -public: - TSQLiteTaskSchema(); - virtual ~TSQLiteTaskSchema(); + class TSerializerVersion; - virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase); + class LIBCHCORE_API TSQLiteTaskSchema : public ISQLiteSerializerSchema + { + public: + TSQLiteTaskSchema(); + virtual ~TSQLiteTaskSchema(); -private: - void CreateNewDatabase(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); + virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase); - void Migrate_001_002(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); - void Migrate_002_003(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); - void Migrate_003_004(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); -}; + private: + void CreateNewDatabase(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); -typedef boost::shared_ptr TSQLiteTaskSchemaPtr; + void Migrate_001_002(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); + void Migrate_002_003(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); + void Migrate_003_004(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); + }; -END_CHCORE_NAMESPACE + typedef boost::shared_ptr TSQLiteTaskSchemaPtr; +} #endif Index: src/libchcore/TSQLiteTransaction.cpp =================================================================== diff -u -N -rb1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteTransaction.cpp (.../TSQLiteTransaction.cpp) (revision b1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0) +++ src/libchcore/TSQLiteTransaction.cpp (.../TSQLiteTransaction.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,80 +22,79 @@ #include "ErrorCodes.h" #include "sqlite3/sqlite3.h" -BEGIN_CHCORE_NAMESPACE - -namespace sqlite +namespace chcore { - TSQLiteTransaction::TSQLiteTransaction(const TSQLiteDatabasePtr& spDatabase) : - m_spDatabase(spDatabase), - m_bTransactionStarted(false) + namespace sqlite { - if(!m_spDatabase) - THROW_SQLITE_EXCEPTION(eErr_InvalidArgument, 0, _T("Invalid database provided")); - Begin(); - } + TSQLiteTransaction::TSQLiteTransaction(const TSQLiteDatabasePtr& spDatabase) : + m_spDatabase(spDatabase), + m_bTransactionStarted(false) + { + if (!m_spDatabase) + THROW_SQLITE_EXCEPTION(eErr_InvalidArgument, 0, _T("Invalid database provided")); + Begin(); + } - TSQLiteTransaction::~TSQLiteTransaction() - { - // try to rollback the transaction; this is the last resort - if(m_bTransactionStarted && m_spDatabase->GetInTransaction()) + TSQLiteTransaction::~TSQLiteTransaction() { - int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "ROLLBACK TRANSACTION;", NULL, NULL, NULL); - iResult; - _ASSERTE(iResult == SQLITE_OK); - m_spDatabase->SetInTransaction(false); + // try to rollback the transaction; this is the last resort + if (m_bTransactionStarted && m_spDatabase->GetInTransaction()) + { + int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "ROLLBACK TRANSACTION;", NULL, NULL, NULL); + iResult; + _ASSERTE(iResult == SQLITE_OK); + m_spDatabase->SetInTransaction(false); + } } - } - void TSQLiteTransaction::Begin() - { - if(m_spDatabase->GetInTransaction()) - return; + void TSQLiteTransaction::Begin() + { + if (m_spDatabase->GetInTransaction()) + return; - if(m_bTransactionStarted) - THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotBeginTransaction, 0, _T("Transaction already started")); + if (m_bTransactionStarted) + THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotBeginTransaction, 0, _T("Transaction already started")); - int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "BEGIN TRANSACTION", NULL, NULL, NULL); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotBeginTransaction, iResult, _T("Cannot begin transaction")); + int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "BEGIN TRANSACTION", NULL, NULL, NULL); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotBeginTransaction, iResult, _T("Cannot begin transaction")); - m_spDatabase->SetInTransaction(true); - m_bTransactionStarted = true; - } + m_spDatabase->SetInTransaction(true); + m_bTransactionStarted = true; + } - void TSQLiteTransaction::Rollback() - { - // no transactions whatsoever (even on database) - if(!m_bTransactionStarted && !m_spDatabase->GetInTransaction()) - THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotRollbackTransaction, 0, _T("Transaction not started")); + void TSQLiteTransaction::Rollback() + { + // no transactions whatsoever (even on database) + if (!m_bTransactionStarted && !m_spDatabase->GetInTransaction()) + THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotRollbackTransaction, 0, _T("Transaction not started")); - // database has transaction started, but not by this object - if(!m_bTransactionStarted) - return; + // database has transaction started, but not by this object + if (!m_bTransactionStarted) + return; - int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "ROLLBACK TRANSACTION;", NULL, NULL, NULL); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotRollbackTransaction, iResult, _T("Cannot rollback transaction")); - m_spDatabase->SetInTransaction(false); - m_bTransactionStarted = false; - } + int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "ROLLBACK TRANSACTION;", NULL, NULL, NULL); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotRollbackTransaction, iResult, _T("Cannot rollback transaction")); + m_spDatabase->SetInTransaction(false); + m_bTransactionStarted = false; + } - void TSQLiteTransaction::Commit() - { - // no transactions whatsoever (even on database) - if(!m_bTransactionStarted && !m_spDatabase->GetInTransaction()) - THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotRollbackTransaction, 0, _T("Transaction not started")); + void TSQLiteTransaction::Commit() + { + // no transactions whatsoever (even on database) + if (!m_bTransactionStarted && !m_spDatabase->GetInTransaction()) + THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotRollbackTransaction, 0, _T("Transaction not started")); - // database has transaction started, but not by this object - if(!m_bTransactionStarted) - return; + // database has transaction started, but not by this object + if (!m_bTransactionStarted) + return; - int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "COMMIT TRANSACTION;", NULL, NULL, NULL); - if(iResult != SQLITE_OK) - THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotCommitTransaction, iResult, _T("Cannot commit transaction")); - m_spDatabase->SetInTransaction(false); - m_bTransactionStarted = false; + int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "COMMIT TRANSACTION;", NULL, NULL, NULL); + if (iResult != SQLITE_OK) + THROW_SQLITE_EXCEPTION(eErr_SQLiteCannotCommitTransaction, iResult, _T("Cannot commit transaction")); + m_spDatabase->SetInTransaction(false); + m_bTransactionStarted = false; + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSQLiteTransaction.h =================================================================== diff -u -N -r3397fd021739bea537248415a7b4fc2712dd2320 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSQLiteTransaction.h (.../TSQLiteTransaction.h) (revision 3397fd021739bea537248415a7b4fc2712dd2320) +++ src/libchcore/TSQLiteTransaction.h (.../TSQLiteTransaction.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,26 +22,25 @@ #include "libchcore.h" #include "TSQLiteDatabase.h" -BEGIN_CHCORE_NAMESPACE - -namespace sqlite +namespace chcore { - class TSQLiteTransaction + namespace sqlite { - public: - TSQLiteTransaction(const TSQLiteDatabasePtr& spDatabase); - ~TSQLiteTransaction(); + class TSQLiteTransaction + { + public: + TSQLiteTransaction(const TSQLiteDatabasePtr& spDatabase); + ~TSQLiteTransaction(); - void Begin(); - void Rollback(); - void Commit(); + void Begin(); + void Rollback(); + void Commit(); - private: - TSQLiteDatabasePtr m_spDatabase; - bool m_bTransactionStarted; // states if transaction was started by this object - }; + private: + TSQLiteDatabasePtr m_spDatabase; + bool m_bTransactionStarted; // states if transaction was started by this object + }; + } } -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TScopedRunningTimeTracker.cpp =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TScopedRunningTimeTracker.cpp (.../TScopedRunningTimeTracker.cpp) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/TScopedRunningTimeTracker.cpp (.../TScopedRunningTimeTracker.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,57 +19,56 @@ #include "stdafx.h" #include "TScopedRunningTimeTracker.h" -BEGIN_CHCORE_NAMESPACE - -TScopedRunningTimeTracker::TScopedRunningTimeTracker(IRunningTimeControl& rLocalStats) : - m_rLocalStats(rLocalStats), - m_bTimeTrackingPaused(false), - m_bRunningStatePaused(false) +namespace chcore { - rLocalStats.EnableTimeTracking(); - rLocalStats.MarkAsRunning(); -} + TScopedRunningTimeTracker::TScopedRunningTimeTracker(IRunningTimeControl& rLocalStats) : + m_rLocalStats(rLocalStats), + m_bTimeTrackingPaused(false), + m_bRunningStatePaused(false) + { + rLocalStats.EnableTimeTracking(); + rLocalStats.MarkAsRunning(); + } -TScopedRunningTimeTracker::~TScopedRunningTimeTracker() -{ - m_rLocalStats.MarkAsNotRunning(); - m_rLocalStats.DisableTimeTracking(); -} - -void TScopedRunningTimeTracker::PauseTimeTracking() -{ - if (!m_bTimeTrackingPaused) + TScopedRunningTimeTracker::~TScopedRunningTimeTracker() { + m_rLocalStats.MarkAsNotRunning(); m_rLocalStats.DisableTimeTracking(); - m_bTimeTrackingPaused = true; } -} -void TScopedRunningTimeTracker::UnPauseTimeTracking() -{ - if (m_bTimeTrackingPaused) + void TScopedRunningTimeTracker::PauseTimeTracking() { - m_rLocalStats.EnableTimeTracking(); - m_bTimeTrackingPaused = false; + if (!m_bTimeTrackingPaused) + { + m_rLocalStats.DisableTimeTracking(); + m_bTimeTrackingPaused = true; + } } -} -void TScopedRunningTimeTracker::PauseRunningState() -{ - if (!m_bRunningStatePaused) + void TScopedRunningTimeTracker::UnPauseTimeTracking() { - m_rLocalStats.MarkAsNotRunning(); - m_bRunningStatePaused = true; + if (m_bTimeTrackingPaused) + { + m_rLocalStats.EnableTimeTracking(); + m_bTimeTrackingPaused = false; + } } -} -void TScopedRunningTimeTracker::UnPauseRunningState() -{ - if (m_bRunningStatePaused) + void TScopedRunningTimeTracker::PauseRunningState() { - m_rLocalStats.MarkAsRunning(); - m_bRunningStatePaused = false; + if (!m_bRunningStatePaused) + { + m_rLocalStats.MarkAsNotRunning(); + m_bRunningStatePaused = true; + } } -} -END_CHCORE_NAMESPACE + void TScopedRunningTimeTracker::UnPauseRunningState() + { + if (m_bRunningStatePaused) + { + m_rLocalStats.MarkAsRunning(); + m_bRunningStatePaused = false; + } + } +} Index: src/libchcore/TScopedRunningTimeTracker.h =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TScopedRunningTimeTracker.h (.../TScopedRunningTimeTracker.h) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/TScopedRunningTimeTracker.h (.../TScopedRunningTimeTracker.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,30 +22,29 @@ #include "libchcore.h" #include "IRunningTimeControl.h" -BEGIN_CHCORE_NAMESPACE - -class TScopedRunningTimeTracker +namespace chcore { -public: - TScopedRunningTimeTracker(IRunningTimeControl& rStats); - ~TScopedRunningTimeTracker(); + class TScopedRunningTimeTracker + { + public: + TScopedRunningTimeTracker(IRunningTimeControl& rStats); + ~TScopedRunningTimeTracker(); - void PauseTimeTracking(); - void UnPauseTimeTracking(); + void PauseTimeTracking(); + void UnPauseTimeTracking(); - void PauseRunningState(); - void UnPauseRunningState(); + void PauseRunningState(); + void UnPauseRunningState(); -private: - TScopedRunningTimeTracker(const TScopedRunningTimeTracker& rLocalStats) = delete; - TScopedRunningTimeTracker& operator=(const TScopedRunningTimeTracker& rLocalStats) = delete; + private: + TScopedRunningTimeTracker(const TScopedRunningTimeTracker& rLocalStats) = delete; + TScopedRunningTimeTracker& operator=(const TScopedRunningTimeTracker& rLocalStats) = delete; -private: - IRunningTimeControl& m_rLocalStats; - bool m_bTimeTrackingPaused; - bool m_bRunningStatePaused; -}; + private: + IRunningTimeControl& m_rLocalStats; + bool m_bTimeTrackingPaused; + bool m_bRunningStatePaused; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TScopedRunningTimeTrackerPause.cpp =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TScopedRunningTimeTrackerPause.cpp (.../TScopedRunningTimeTrackerPause.cpp) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/TScopedRunningTimeTrackerPause.cpp (.../TScopedRunningTimeTrackerPause.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -20,17 +20,16 @@ #include "TScopedRunningTimeTrackerPause.h" #include "TScopedRunningTimeTracker.h" -BEGIN_CHCORE_NAMESPACE - -TScopedRunningTimeTrackerPause::TScopedRunningTimeTrackerPause(TScopedRunningTimeTracker& rRunningTimeTracker) : - m_rRunningTimeTracker(rRunningTimeTracker) +namespace chcore { - m_rRunningTimeTracker.PauseTimeTracking(); -} + TScopedRunningTimeTrackerPause::TScopedRunningTimeTrackerPause(TScopedRunningTimeTracker& rRunningTimeTracker) : + m_rRunningTimeTracker(rRunningTimeTracker) + { + m_rRunningTimeTracker.PauseTimeTracking(); + } -TScopedRunningTimeTrackerPause::~TScopedRunningTimeTrackerPause() -{ - m_rRunningTimeTracker.UnPauseTimeTracking(); + TScopedRunningTimeTrackerPause::~TScopedRunningTimeTrackerPause() + { + m_rRunningTimeTracker.UnPauseTimeTracking(); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TScopedRunningTimeTrackerPause.h =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TScopedRunningTimeTrackerPause.h (.../TScopedRunningTimeTrackerPause.h) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/TScopedRunningTimeTrackerPause.h (.../TScopedRunningTimeTrackerPause.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,25 +19,22 @@ #ifndef __TSCOPEDRUNNINGTIMETRACKERPAUSE_H__ #define __TSCOPEDRUNNINGTIMETRACKERPAUSE_H__ -#include "libchcore.h" - -BEGIN_CHCORE_NAMESPACE - -class TScopedRunningTimeTracker; - -class TScopedRunningTimeTrackerPause +namespace chcore { -public: - TScopedRunningTimeTrackerPause(TScopedRunningTimeTracker& rRunningTimeTracker); - ~TScopedRunningTimeTrackerPause(); + class TScopedRunningTimeTracker; - TScopedRunningTimeTrackerPause(const TScopedRunningTimeTrackerPause&) = delete; - TScopedRunningTimeTrackerPause& operator=(const TScopedRunningTimeTrackerPause&) = delete; + class TScopedRunningTimeTrackerPause + { + public: + TScopedRunningTimeTrackerPause(TScopedRunningTimeTracker& rRunningTimeTracker); + ~TScopedRunningTimeTrackerPause(); -private: - TScopedRunningTimeTracker& m_rRunningTimeTracker; -}; + TScopedRunningTimeTrackerPause(const TScopedRunningTimeTrackerPause&) = delete; + TScopedRunningTimeTrackerPause& operator=(const TScopedRunningTimeTrackerPause&) = delete; -END_CHCORE_NAMESPACE + private: + TScopedRunningTimeTracker& m_rRunningTimeTracker; + }; +} #endif Index: src/libchcore/TSerializerException.cpp =================================================================== diff -u -N -rb1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSerializerException.cpp (.../TSerializerException.cpp) (revision b1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0) +++ src/libchcore/TSerializerException.cpp (.../TSerializerException.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,16 +19,15 @@ #include "stdafx.h" #include "TSerializerException.h" -BEGIN_CHCORE_NAMESPACE - -TSerializerException::TSerializerException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) +namespace chcore { -} + TSerializerException::TSerializerException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } -TSerializerException::TSerializerException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) -{ + TSerializerException::TSerializerException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSerializerException.h =================================================================== diff -u -N -rb1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSerializerException.h (.../TSerializerException.h) (revision b1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0) +++ src/libchcore/TSerializerException.h (.../TSerializerException.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,15 +25,14 @@ #define THROW_SERIALIZER_EXCEPTION(error_code, err_msg)\ throw TSerializerException(error_code, err_msg, __FILEW__, __LINE__, __FUNCTIONW__) -BEGIN_CHCORE_NAMESPACE - -class TSerializerException : public TBaseException +namespace chcore { -public: - TSerializerException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TSerializerException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); -}; + class TSerializerException : public TBaseException + { + public: + TSerializerException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TSerializerException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSerializerVersion.cpp =================================================================== diff -u -N -r1342b18babc7e88850e74f46cb473a737a68f28a -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSerializerVersion.cpp (.../TSerializerVersion.cpp) (revision 1342b18babc7e88850e74f46cb473a737a68f28a) +++ src/libchcore/TSerializerVersion.cpp (.../TSerializerVersion.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,85 +25,84 @@ #include "TSQLiteException.h" #include "sqlite3\sqlite3.h" -BEGIN_CHCORE_NAMESPACE - -using namespace sqlite; - -TSerializerVersion::TSerializerVersion(const TSQLiteDatabasePtr& spDatabase) : - m_spDatabase(spDatabase), - m_bSetupExecuted(false) +namespace chcore { - if(!spDatabase) - THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("No database provided")); -} + using namespace sqlite; -TSerializerVersion::~TSerializerVersion() -{ -} + TSerializerVersion::TSerializerVersion(const TSQLiteDatabasePtr& spDatabase) : + m_spDatabase(spDatabase), + m_bSetupExecuted(false) + { + if (!spDatabase) + THROW_SERIALIZER_EXCEPTION(eErr_InvalidArgument, _T("No database provided")); + } -void TSerializerVersion::Setup() -{ - if(m_bSetupExecuted) - return; + TSerializerVersion::~TSerializerVersion() + { + } - TSQLiteTransaction tTransaction(m_spDatabase); - TSQLiteStatement tStatement(m_spDatabase); - - tStatement.Prepare(_T("SELECT count(*) FROM sqlite_master WHERE type=?1 AND name=?2")); - tStatement.BindValue(1, _T("table")); - tStatement.BindValue(2, _T("version")); - if(tStatement.Step() != TSQLiteStatement::eStep_HasRow) - THROW_SQLITE_EXCEPTION(eErr_InternalProblem, SQLITE_ERROR, _T("Problem accessing sqlite_master table")); - - int iVersionCount = tStatement.GetInt(0); - if(iVersionCount == 0) + void TSerializerVersion::Setup() { - // create table - tStatement.Prepare(_T("CREATE TABLE IF NOT EXISTS version(db_version INT NOT NULL)")); - tStatement.Step(); + if (m_bSetupExecuted) + return; - tStatement.Prepare(_T("INSERT INTO version(db_version) VALUES(?1)")); - tStatement.BindValue(1, 0); - tStatement.Step(); - } + TSQLiteTransaction tTransaction(m_spDatabase); + TSQLiteStatement tStatement(m_spDatabase); - tTransaction.Commit(); + tStatement.Prepare(_T("SELECT count(*) FROM sqlite_master WHERE type=?1 AND name=?2")); + tStatement.BindValue(1, _T("table")); + tStatement.BindValue(2, _T("version")); + if (tStatement.Step() != TSQLiteStatement::eStep_HasRow) + THROW_SQLITE_EXCEPTION(eErr_InternalProblem, SQLITE_ERROR, _T("Problem accessing sqlite_master table")); - m_bSetupExecuted = true; -} + int iVersionCount = tStatement.GetInt(0); + if (iVersionCount == 0) + { + // create table + tStatement.Prepare(_T("CREATE TABLE IF NOT EXISTS version(db_version INT NOT NULL)")); + tStatement.Step(); -int TSerializerVersion::GetVersion() -{ - Setup(); + tStatement.Prepare(_T("INSERT INTO version(db_version) VALUES(?1)")); + tStatement.BindValue(1, 0); + tStatement.Step(); + } - TSQLiteTransaction tTransaction(m_spDatabase); - TSQLiteStatement tStatement(m_spDatabase); + tTransaction.Commit(); - // when table does not exist the sqlite error is just SQLITE_ERROR when preparing statement - tStatement.Prepare(_T("SELECT db_version FROM version")); - if(tStatement.Step() == TSQLiteStatement::eStep_HasRow) + m_bSetupExecuted = true; + } + + int TSerializerVersion::GetVersion() { + Setup(); + + TSQLiteTransaction tTransaction(m_spDatabase); + TSQLiteStatement tStatement(m_spDatabase); + + // when table does not exist the sqlite error is just SQLITE_ERROR when preparing statement + tStatement.Prepare(_T("SELECT db_version FROM version")); + if (tStatement.Step() == TSQLiteStatement::eStep_HasRow) + { + tTransaction.Commit(); + return tStatement.GetInt(0); + } + tTransaction.Commit(); - return tStatement.GetInt(0); + return 0; } - tTransaction.Commit(); - return 0; -} + void TSerializerVersion::SetVersion(int iNewVersion) + { + Setup(); -void TSerializerVersion::SetVersion(int iNewVersion) -{ - Setup(); + TSQLiteTransaction tTransaction(m_spDatabase); + TSQLiteStatement tStatement(m_spDatabase); - TSQLiteTransaction tTransaction(m_spDatabase); - TSQLiteStatement tStatement(m_spDatabase); + // create table + tStatement.Prepare(_T("UPDATE version SET db_version=?1")); + tStatement.BindValue(1, iNewVersion); + tStatement.Step(); - // create table - tStatement.Prepare(_T("UPDATE version SET db_version=?1")); - tStatement.BindValue(1, iNewVersion); - tStatement.Step(); - - tTransaction.Commit(); + tTransaction.Commit(); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSerializerVersion.h =================================================================== diff -u -N -r1342b18babc7e88850e74f46cb473a737a68f28a -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSerializerVersion.h (.../TSerializerVersion.h) (revision 1342b18babc7e88850e74f46cb473a737a68f28a) +++ src/libchcore/TSerializerVersion.h (.../TSerializerVersion.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,28 +22,27 @@ #include "libchcore.h" #include "TSQLiteDatabase.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSerializerVersion +namespace chcore { -public: - TSerializerVersion(const sqlite::TSQLiteDatabasePtr& spDatabase); - ~TSerializerVersion(); + class LIBCHCORE_API TSerializerVersion + { + public: + TSerializerVersion(const sqlite::TSQLiteDatabasePtr& spDatabase); + ~TSerializerVersion(); - int GetVersion(); - void SetVersion(int iNewVersion); + int GetVersion(); + void SetVersion(int iNewVersion); -protected: - void Setup(); + protected: + void Setup(); -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - sqlite::TSQLiteDatabasePtr m_spDatabase; + sqlite::TSQLiteDatabasePtr m_spDatabase; #pragma warning(pop) - bool m_bSetupExecuted; -}; + bool m_bSetupExecuted; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSharedMemory.cpp =================================================================== diff -u -N -r68ef7c89b475edd21eac083b8d22660e15f97254 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSharedMemory.cpp (.../TSharedMemory.cpp) (revision 68ef7c89b475edd21eac083b8d22660e15f97254) +++ src/libchcore/TSharedMemory.cpp (.../TSharedMemory.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,237 +26,236 @@ #include "ErrorCodes.h" #include "TCoreException.h" -BEGIN_CHCORE_NAMESPACE - +namespace chcore +{ #define MUTEX_SUFFIX _T("_Mutex") -class TMutexLock -{ -public: - TMutexLock(HANDLE hMutex) : - m_hMutex(hMutex) + class TMutexLock { - if(m_hMutex) + public: + TMutexLock(HANDLE hMutex) : + m_hMutex(hMutex) { - DWORD dwRes = WaitForSingleObject(hMutex, 10000); - if(dwRes != WAIT_OBJECT_0) - THROW_CORE_EXCEPTION(eErr_MutexTimedOut); + if (m_hMutex) + { + DWORD dwRes = WaitForSingleObject(hMutex, 10000); + if (dwRes != WAIT_OBJECT_0) + THROW_CORE_EXCEPTION(eErr_MutexTimedOut); + } } + + ~TMutexLock() + { + if (m_hMutex) + ReleaseMutex(m_hMutex); + } + + private: + HANDLE m_hMutex; + }; + + /////////////////////////////////////////////////////////////////////////////////////// + // TSharedMemory class + + TSharedMemory::TSharedMemory() : + m_hFileMapping(NULL), + m_pMappedMemory(NULL), + m_hMutex(NULL), + m_stSize(0) + { } - ~TMutexLock() + TSharedMemory::~TSharedMemory() { - if(m_hMutex) - ReleaseMutex(m_hMutex); + Close(); } -private: - HANDLE m_hMutex; -}; + void TSharedMemory::Create(const wchar_t* pszName, shm_size_t stSize) + { + if (!pszName || pszName[0] == _T('\0') || stSize == 0) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); -/////////////////////////////////////////////////////////////////////////////////////// -// TSharedMemory class + Close(); -TSharedMemory::TSharedMemory() : - m_hFileMapping(NULL), - m_pMappedMemory(NULL), - m_hMutex(NULL), - m_stSize(0) -{ -} + try + { + std::wstring wstrMutexName = pszName; + wstrMutexName += MUTEX_SUFFIX; -TSharedMemory::~TSharedMemory() -{ - Close(); -} + SECURITY_DESCRIPTOR secDesc; + if (!InitializeSecurityDescriptor(&secDesc, SECURITY_DESCRIPTOR_REVISION)) + THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); -void TSharedMemory::Create(const wchar_t* pszName, shm_size_t stSize) -{ - if(!pszName || pszName[0] == _T('\0') || stSize == 0) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + SECURITY_ATTRIBUTES secAttr; + secAttr.nLength = sizeof(secAttr); + secAttr.bInheritHandle = FALSE; + secAttr.lpSecurityDescriptor = &secDesc; - Close(); + if (!SetSecurityDescriptorDacl(secAttr.lpSecurityDescriptor, TRUE, 0, FALSE)) + THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); - try - { - std::wstring wstrMutexName = pszName; - wstrMutexName += MUTEX_SUFFIX; + m_hMutex = ::CreateMutex(&secAttr, FALSE, wstrMutexName.c_str()); + if (!m_hMutex) + THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); - SECURITY_DESCRIPTOR secDesc; - if(!InitializeSecurityDescriptor(&secDesc, SECURITY_DESCRIPTOR_REVISION)) - THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); + m_hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, boost::numeric_cast(stSize + sizeof(size_t)), pszName); + if (!m_hFileMapping) + THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); + else if (GetLastError() == ERROR_ALREADY_EXISTS) + THROW_CORE_EXCEPTION(eErr_SharedMemoryAlreadyExists); // shared memory already exists - cannot guarantee that the size is correct - SECURITY_ATTRIBUTES secAttr; - secAttr.nLength = sizeof(secAttr); - secAttr.bInheritHandle = FALSE; - secAttr.lpSecurityDescriptor = &secDesc; + // Get a pointer to the file-mapped shared memory. + m_pMappedMemory = (BYTE*)MapViewOfFile(m_hFileMapping, FILE_MAP_WRITE, 0, 0, 0); + if (!m_pMappedMemory) + THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); + } + catch (...) + { + Close(); + throw; + } - if(!SetSecurityDescriptorDacl(secAttr.lpSecurityDescriptor, TRUE, 0, FALSE)) - THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); + TMutexLock lock(m_hMutex); - m_hMutex = ::CreateMutex(&secAttr, FALSE, wstrMutexName.c_str()); - if(!m_hMutex) - THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); - - m_hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, boost::numeric_cast(stSize + sizeof(size_t)), pszName); - if(!m_hFileMapping) - THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); - else if(GetLastError() == ERROR_ALREADY_EXISTS) - THROW_CORE_EXCEPTION(eErr_SharedMemoryAlreadyExists); // shared memory already exists - cannot guarantee that the size is correct - - // Get a pointer to the file-mapped shared memory. - m_pMappedMemory = (BYTE*)MapViewOfFile(m_hFileMapping, FILE_MAP_WRITE, 0, 0, 0); - if(!m_pMappedMemory) - THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); + m_stSize = stSize + sizeof(shm_size_t); + *(shm_size_t*)m_pMappedMemory = sizeof(shm_size_t); // no data inside (set just in case) } - catch(...) + + void TSharedMemory::Create(const wchar_t* pszName, const TString& wstrData) { - Close(); - throw; + Create(pszName, (const BYTE*)wstrData.c_str(), boost::numeric_cast((wstrData.GetLength() + 1) * sizeof(wchar_t))); } - TMutexLock lock(m_hMutex); + void TSharedMemory::Create(const wchar_t* pszName, const BYTE* pbyData, shm_size_t stSize) + { + Create(pszName, stSize); - m_stSize = stSize + sizeof(shm_size_t); - *(shm_size_t*)m_pMappedMemory = sizeof(shm_size_t); // no data inside (set just in case) -} + TMutexLock lock(m_hMutex); -void TSharedMemory::Create(const wchar_t* pszName, const TString& wstrData) -{ - Create(pszName, (const BYTE*)wstrData.c_str(), boost::numeric_cast((wstrData.GetLength() + 1) * sizeof(wchar_t))); -} + *(shm_size_t*)m_pMappedMemory = stSize; + memcpy(m_pMappedMemory + sizeof(shm_size_t), pbyData, stSize); + } -void TSharedMemory::Create(const wchar_t* pszName, const BYTE* pbyData, shm_size_t stSize) -{ - Create(pszName, stSize); + void TSharedMemory::Open(const wchar_t* pszName) + { + Close(); - TMutexLock lock(m_hMutex); + try + { + m_hFileMapping = OpenFileMapping(FILE_MAP_READ, FALSE, pszName); + if (!m_hFileMapping) + THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); - *(shm_size_t*)m_pMappedMemory = stSize; - memcpy(m_pMappedMemory + sizeof(shm_size_t), pbyData, stSize); -} + // Get a pointer to the file-mapped shared memory. + m_pMappedMemory = (BYTE*)MapViewOfFile(m_hFileMapping, FILE_MAP_READ, 0, 0, 0); + if (!m_pMappedMemory) + THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); + } + catch (...) + { + Close(); + throw; + } -void TSharedMemory::Open(const wchar_t* pszName) -{ - Close(); + TMutexLock lock(m_hMutex); - try - { - m_hFileMapping = OpenFileMapping(FILE_MAP_READ, FALSE, pszName); - if(!m_hFileMapping) - THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); - - // Get a pointer to the file-mapped shared memory. - m_pMappedMemory = (BYTE*)MapViewOfFile(m_hFileMapping, FILE_MAP_READ, 0, 0, 0); - if(!m_pMappedMemory) - THROW_CORE_EXCEPTION(eErr_CannotOpenSharedMemory); + m_stSize = *(shm_size_t*)m_pMappedMemory + sizeof(shm_size_t); } - catch(...) - { - Close(); - throw; - } - TMutexLock lock(m_hMutex); - - m_stSize = *(shm_size_t*)m_pMappedMemory + sizeof(shm_size_t); -} - -void TSharedMemory::Close() throw() -{ - try + void TSharedMemory::Close() throw() { - if(m_hMutex) + try { - CloseHandle(m_hMutex); - m_hMutex = NULL; - } + if (m_hMutex) + { + CloseHandle(m_hMutex); + m_hMutex = NULL; + } - if(m_pMappedMemory) - { - UnmapViewOfFile(m_pMappedMemory); - m_pMappedMemory = NULL; - } + if (m_pMappedMemory) + { + UnmapViewOfFile(m_pMappedMemory); + m_pMappedMemory = NULL; + } - // Close the process's handle to the file-mapping object. - if(m_hFileMapping) + // Close the process's handle to the file-mapping object. + if (m_hFileMapping) + { + CloseHandle(m_hFileMapping); + m_hFileMapping = NULL; + } + } + catch (...) { - CloseHandle(m_hFileMapping); - m_hFileMapping = NULL; } } - catch(...) + + void TSharedMemory::Read(TString& wstrData) const { - } -} + if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) + THROW_CORE_EXCEPTION(eErr_SharedMemoryNotOpen); -void TSharedMemory::Read(TString& wstrData) const -{ - if(!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) - THROW_CORE_EXCEPTION(eErr_SharedMemoryNotOpen); + TMutexLock lock(m_hMutex); - TMutexLock lock(m_hMutex); + shm_size_t stByteSize = *(shm_size_t*)m_pMappedMemory; + if ((stByteSize % 2) != 0) + THROW_CORE_EXCEPTION(eErr_SharedMemoryInvalidFormat); - shm_size_t stByteSize = *(shm_size_t*)m_pMappedMemory; - if((stByteSize % 2) != 0) - THROW_CORE_EXCEPTION(eErr_SharedMemoryInvalidFormat); + const wchar_t* pszRealData = (const wchar_t*)(m_pMappedMemory + sizeof(shm_size_t)); + shm_size_t stCharCount = stByteSize / 2; - const wchar_t* pszRealData = (const wchar_t*)(m_pMappedMemory + sizeof(shm_size_t)); - shm_size_t stCharCount = stByteSize / 2; + if (pszRealData[stCharCount - 1] != _T('\0')) + THROW_CORE_EXCEPTION(eErr_SharedMemoryInvalidFormat); - if(pszRealData[stCharCount - 1] != _T('\0')) - THROW_CORE_EXCEPTION(eErr_SharedMemoryInvalidFormat); + wstrData = pszRealData; + } - wstrData = pszRealData; -} + void TSharedMemory::Write(const TString& wstrData) + { + Write((const BYTE*)wstrData.c_str(), boost::numeric_cast((wstrData.GetLength() + 1) * sizeof(wchar_t))); + } -void TSharedMemory::Write(const TString& wstrData) -{ - Write((const BYTE*)wstrData.c_str(), boost::numeric_cast((wstrData.GetLength() + 1) * sizeof(wchar_t))); -} + void TSharedMemory::Write(const BYTE* pbyData, shm_size_t stSize) + { + if (stSize + sizeof(shm_size_t) > m_stSize) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -void TSharedMemory::Write(const BYTE* pbyData, shm_size_t stSize) -{ - if(stSize + sizeof(shm_size_t) > m_stSize) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + TMutexLock lock(m_hMutex); - TMutexLock lock(m_hMutex); + *(shm_size_t*)m_pMappedMemory = stSize; + memcpy(m_pMappedMemory + sizeof(shm_size_t), pbyData, stSize); + } - *(shm_size_t*)m_pMappedMemory = stSize; - memcpy(m_pMappedMemory + sizeof(shm_size_t), pbyData, stSize); -} + const BYTE* TSharedMemory::GetData() const + { + if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) + return NULL; -const BYTE* TSharedMemory::GetData() const -{ - if(!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) - return NULL; + return (BYTE*)m_pMappedMemory + sizeof(shm_size_t); + } - return (BYTE*)m_pMappedMemory + sizeof(shm_size_t); -} + BYTE* TSharedMemory::GetData() + { + if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) + return NULL; -BYTE* TSharedMemory::GetData() -{ - if(!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) - return NULL; + return (BYTE*)m_pMappedMemory + sizeof(shm_size_t); + } - return (BYTE*)m_pMappedMemory + sizeof(shm_size_t); -} + TSharedMemory::shm_size_t TSharedMemory::GetSharedMemorySize() const + { + if (!m_hFileMapping || !m_pMappedMemory) + return 0; + return m_stSize; + } -TSharedMemory::shm_size_t TSharedMemory::GetSharedMemorySize() const -{ - if(!m_hFileMapping || !m_pMappedMemory) - return 0; - return m_stSize; -} + TSharedMemory::shm_size_t TSharedMemory::GetDataSize() const + { + if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) + return 0; -TSharedMemory::shm_size_t TSharedMemory::GetDataSize() const -{ - if(!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) - return 0; + TMutexLock lock(m_hMutex); - TMutexLock lock(m_hMutex); - - return *(shm_size_t*)m_pMappedMemory; + return *(shm_size_t*)m_pMappedMemory; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSharedMemory.h =================================================================== diff -u -N -r68ef7c89b475edd21eac083b8d22660e15f97254 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSharedMemory.h (.../TSharedMemory.h) (revision 68ef7c89b475edd21eac083b8d22660e15f97254) +++ src/libchcore/TSharedMemory.h (.../TSharedMemory.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,43 +25,42 @@ #include "TString.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSharedMemory +namespace chcore { -public: - typedef unsigned int shm_size_t; + class LIBCHCORE_API TSharedMemory + { + public: + typedef unsigned int shm_size_t; -public: - TSharedMemory(); - ~TSharedMemory(); + public: + TSharedMemory(); + ~TSharedMemory(); - void Create(const wchar_t* pszName, shm_size_t stSize); - void Create(const wchar_t* pszName, const TString& wstrData); - void Create(const wchar_t* pszName, const BYTE* pbyData, shm_size_t stSize); + void Create(const wchar_t* pszName, shm_size_t stSize); + void Create(const wchar_t* pszName, const TString& wstrData); + void Create(const wchar_t* pszName, const BYTE* pbyData, shm_size_t stSize); - void Open(const wchar_t* pszName); - void Close() throw(); + void Open(const wchar_t* pszName); + void Close() throw(); - void Read(TString& wstrData) const; - void Write(const TString& wstrData); - void Write(const BYTE* pbyData, shm_size_t stSize); + void Read(TString& wstrData) const; + void Write(const TString& wstrData); + void Write(const BYTE* pbyData, shm_size_t stSize); - // below are the unsafe functions (i.e. not protected with mutex) - const BYTE* GetData() const; - BYTE* GetData(); + // below are the unsafe functions (i.e. not protected with mutex) + const BYTE* GetData() const; + BYTE* GetData(); - shm_size_t GetSharedMemorySize() const; - shm_size_t GetDataSize() const; + shm_size_t GetSharedMemorySize() const; + shm_size_t GetDataSize() const; -private: - HANDLE m_hFileMapping; - BYTE* m_pMappedMemory; - shm_size_t m_stSize; // contains full size of the allocated shared memory (in case we created the memory), size of occupied memory in case we opened the memory. + private: + HANDLE m_hFileMapping; + BYTE* m_pMappedMemory; + shm_size_t m_stSize; // contains full size of the allocated shared memory (in case we created the memory), size of occupied memory in case we opened the memory. - HANDLE m_hMutex; -}; + HANDLE m_hMutex; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSharedModificationTracker.h =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSharedModificationTracker.h (.../TSharedModificationTracker.h) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/TSharedModificationTracker.h (.../TSharedModificationTracker.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,98 +21,97 @@ #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -template -class TSharedModificationTracker +namespace chcore { -public: - typedef T value_type; - -public: - TSharedModificationTracker(Bitset& rBitset) : - m_tValue(), - m_rBitset(rBitset) + template + class TSharedModificationTracker { - MarkAsModified(); - } + public: + typedef T value_type; - TSharedModificationTracker(const TSharedModificationTracker& rSrc) = delete; + public: + TSharedModificationTracker(Bitset& rBitset) : + m_tValue(), + m_rBitset(rBitset) + { + MarkAsModified(); + } - TSharedModificationTracker(const TSharedModificationTracker& rSrc, Bitset& rBitset) : - m_tValue(rSrc.m_tValue), - m_rBitset(rBitset) - { - m_rBitset[ChangeBit] = rSrc.m_rBitset[ChangeBit]; - } + TSharedModificationTracker(const TSharedModificationTracker& rSrc) = delete; - template - TSharedModificationTracker(Bitset& rBitset, const V&... rValues) : - m_tValue(rValues...), - m_rBitset(rBitset) - { - MarkAsModified(); - } - - TSharedModificationTracker& operator=(const TSharedModificationTracker& rValue) - { - if(this != &rValue) + TSharedModificationTracker(const TSharedModificationTracker& rSrc, Bitset& rBitset) : + m_tValue(rSrc.m_tValue), + m_rBitset(rBitset) { - m_tValue = rValue.m_tValue; - m_rBitset[ChangeBit] = rValue.m_rBitset[ChangeBit]; + m_rBitset[ChangeBit] = rSrc.m_rBitset[ChangeBit]; } - return *this; - } - - template - TSharedModificationTracker& operator=(const V& rValue) - { - if(m_tValue != rValue) + template + TSharedModificationTracker(Bitset& rBitset, const V&... rValues) : + m_tValue(rValues...), + m_rBitset(rBitset) { - m_tValue = rValue; MarkAsModified(); } - return *this; - } + TSharedModificationTracker& operator=(const TSharedModificationTracker& rValue) + { + if (this != &rValue) + { + m_tValue = rValue.m_tValue; + m_rBitset[ChangeBit] = rValue.m_rBitset[ChangeBit]; + } - operator const T&() const - { - return m_tValue; - } + return *this; + } - const T& Get() const - { - return m_tValue; - } + template + TSharedModificationTracker& operator=(const V& rValue) + { + if (m_tValue != rValue) + { + m_tValue = rValue; + MarkAsModified(); + } - T& Modify() - { - MarkAsModified(); - return m_tValue; - } + return *this; + } - bool IsModified() const - { - return m_rBitset[ChangeBit]; - } + operator const T&() const + { + return m_tValue; + } - void MarkAsModified() - { - m_rBitset[ChangeBit] = true; - } + const T& Get() const + { + return m_tValue; + } - void MarkAsUnmodified() - { - m_rBitset[ChangeBit] = false; - } + T& Modify() + { + MarkAsModified(); + return m_tValue; + } -private: - T m_tValue; - Bitset& m_rBitset; -}; + bool IsModified() const + { + return m_rBitset[ChangeBit]; + } -END_CHCORE_NAMESPACE + void MarkAsModified() + { + m_rBitset[ChangeBit] = true; + } + void MarkAsUnmodified() + { + m_rBitset[ChangeBit] = false; + } + + private: + T m_tValue; + Bitset& m_rBitset; + }; +} + #endif Index: src/libchcore/TSimpleTimer.cpp =================================================================== diff -u -N -r5693271a6736f524997e3951fc7b7b6323bc6447 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSimpleTimer.cpp (.../TSimpleTimer.cpp) (revision 5693271a6736f524997e3951fc7b7b6323bc6447) +++ src/libchcore/TSimpleTimer.cpp (.../TSimpleTimer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -20,86 +20,85 @@ #include "TSimpleTimer.h" #include "TTimestampProviderTickCount.h" -BEGIN_CHCORE_NAMESPACE - -TSimpleTimer::TSimpleTimer(bool bAutostart, const ITimestampProviderPtr& spTimestampProvider) : - m_spTimestampProvider(spTimestampProvider), - m_bStarted(false), - m_ullLastTime(0), - m_ullTotalTime(0) +namespace chcore { - if(!spTimestampProvider) - m_spTimestampProvider = ITimestampProviderPtr(new TTimestampProviderTickCount); + TSimpleTimer::TSimpleTimer(bool bAutostart, const ITimestampProviderPtr& spTimestampProvider) : + m_spTimestampProvider(spTimestampProvider), + m_bStarted(false), + m_ullLastTime(0), + m_ullTotalTime(0) + { + if (!spTimestampProvider) + m_spTimestampProvider = ITimestampProviderPtr(new TTimestampProviderTickCount); - if(bAutostart) - Start(); -} + if (bAutostart) + Start(); + } -TSimpleTimer::~TSimpleTimer() -{ -} + TSimpleTimer::~TSimpleTimer() + { + } -void TSimpleTimer::Start() -{ - if(!m_bStarted) + void TSimpleTimer::Start() { - m_bStarted = true; - m_ullLastTime = m_spTimestampProvider->GetCurrentTimestamp(); + if (!m_bStarted) + { + m_bStarted = true; + m_ullLastTime = m_spTimestampProvider->GetCurrentTimestamp(); + } } -} -unsigned long long TSimpleTimer::Stop() -{ - if(m_bStarted) + unsigned long long TSimpleTimer::Stop() { - Tick(); - m_bStarted = false; + if (m_bStarted) + { + Tick(); + m_bStarted = false; + } + + return m_ullTotalTime; } - return m_ullTotalTime; -} + unsigned long long TSimpleTimer::Tick() + { + unsigned long long ullCurrent = m_spTimestampProvider->GetCurrentTimestamp(); + if (m_bStarted) + m_ullTotalTime += ullCurrent - m_ullLastTime; + m_ullLastTime = ullCurrent; -unsigned long long TSimpleTimer::Tick() -{ - unsigned long long ullCurrent = m_spTimestampProvider->GetCurrentTimestamp(); - if(m_bStarted) - m_ullTotalTime += ullCurrent - m_ullLastTime; - m_ullLastTime = ullCurrent; + return ullCurrent; + } - return ullCurrent; -} + unsigned long long TSimpleTimer::Checkpoint() + { + if (m_bStarted) + { + Tick(); + unsigned long long ullCurrentTotal = m_ullTotalTime; + m_ullTotalTime = 0; -unsigned long long TSimpleTimer::Checkpoint() -{ - if(m_bStarted) + return ullCurrentTotal; + } + else + return 0; + } + + void TSimpleTimer::Reset() { - Tick(); - unsigned long long ullCurrentTotal = m_ullTotalTime; + m_bStarted = false; + m_ullLastTime = 0; m_ullTotalTime = 0; + } - return ullCurrentTotal; + void TSimpleTimer::Init(unsigned long long ullTotalTime) + { + Stop(); + m_ullTotalTime = ullTotalTime; + m_ullLastTime = 0; } - else - return 0; -} -void TSimpleTimer::Reset() -{ - m_bStarted = false; - m_ullLastTime = 0; - m_ullTotalTime = 0; + bool TSimpleTimer::IsRunning() const + { + return m_bStarted; + } } - -void TSimpleTimer::Init(unsigned long long ullTotalTime) -{ - Stop(); - m_ullTotalTime = ullTotalTime; - m_ullLastTime = 0; -} - -bool TSimpleTimer::IsRunning() const -{ - return m_bStarted; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TSimpleTimer.h =================================================================== diff -u -N -rc8e73b75027d5e17fb8b1e1eb40e64f40fc62547 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSimpleTimer.h (.../TSimpleTimer.h) (revision c8e73b75027d5e17fb8b1e1eb40e64f40fc62547) +++ src/libchcore/TSimpleTimer.h (.../TSimpleTimer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,39 +22,38 @@ #include "libchcore.h" #include "ITimestampProvider.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSimpleTimer +namespace chcore { -public: - TSimpleTimer(bool bAutostart = false, const ITimestampProviderPtr& spTimestampProvider = ITimestampProviderPtr()); - ~TSimpleTimer(); + class LIBCHCORE_API TSimpleTimer + { + public: + TSimpleTimer(bool bAutostart = false, const ITimestampProviderPtr& spTimestampProvider = ITimestampProviderPtr()); + ~TSimpleTimer(); - void Init(unsigned long long ullTotalTime); + void Init(unsigned long long ullTotalTime); - void Start(); - unsigned long long Stop(); // returns total time - unsigned long long Tick(); // returns current timestamp + void Start(); + unsigned long long Stop(); // returns total time + unsigned long long Tick(); // returns current timestamp - unsigned long long Checkpoint(); // returns current total time and restarts the timer + unsigned long long Checkpoint(); // returns current total time and restarts the timer - void Reset(); + void Reset(); - bool IsRunning() const; - unsigned long long GetTotalTime() const { return m_ullTotalTime; } - unsigned long long GetLastTimestamp() const { return m_ullLastTime; } + bool IsRunning() const; + unsigned long long GetTotalTime() const { return m_ullTotalTime; } + unsigned long long GetLastTimestamp() const { return m_ullLastTime; } -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - ITimestampProviderPtr m_spTimestampProvider; + ITimestampProviderPtr m_spTimestampProvider; #pragma warning(pop) - bool m_bStarted; - unsigned long long m_ullTotalTime; // total time measured - unsigned long long m_ullLastTime; // last processed time -}; + bool m_bStarted; + unsigned long long m_ullTotalTime; // total time measured + unsigned long long m_ullLastTime; // last processed time + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSparseRangeMap.cpp =================================================================== diff -u -N -r5efb534fc5440a7ab779d2514a00486ecb58e845 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSparseRangeMap.cpp (.../TSparseRangeMap.cpp) (revision 5efb534fc5440a7ab779d2514a00486ecb58e845) +++ src/libchcore/TSparseRangeMap.cpp (.../TSparseRangeMap.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -21,94 +21,93 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -TSparseRangeMap::TSparseRangeMap() +namespace chcore { -} - -TSparseRangeMap::~TSparseRangeMap() -{ -} - -void TSparseRangeMap::Insert(file_size_t fsRangeStart, file_size_t fsRangeEnd) -{ - if (fsRangeEnd < fsRangeStart) - std::swap(fsRangeStart, fsRangeEnd); - - std::pair pairInsert = m_mapRanges.emplace(std::make_pair(fsRangeStart, fsRangeEnd)); - RangeMap::iterator iterInsertedRange = pairInsert.first; - if (!pairInsert.second) + TSparseRangeMap::TSparseRangeMap() { - // range with fsRangeStart already exists; update it with the increased range (if bigger than the existing one) - if (fsRangeEnd > iterInsertedRange->second) - iterInsertedRange->second = fsRangeEnd; - else - return; // new range overlaps with old one and is smaller; does not change the state of internal map and no reorganization is needed } - else + + TSparseRangeMap::~TSparseRangeMap() { - // element inserted successfully; since it can overlap the previous range in the map, we need to start merging ranges from this previous element - if (iterInsertedRange != m_mapRanges.begin()) - iterInsertedRange = std::prev(iterInsertedRange); - else if(m_mapRanges.size() == 1) - return; // this is the only element currently in the map; no need to process further. } - // merge subsequent ranges - file_size_t fsCurrentRangeEnd = iterInsertedRange->second; - - RangeMap::iterator iterRange = std::next(iterInsertedRange); - - while(iterRange != m_mapRanges.end()) + void TSparseRangeMap::Insert(file_size_t fsRangeStart, file_size_t fsRangeEnd) { - if (iterRange->first <= fsCurrentRangeEnd + 1) + if (fsRangeEnd < fsRangeStart) + std::swap(fsRangeStart, fsRangeEnd); + + std::pair pairInsert = m_mapRanges.emplace(std::make_pair(fsRangeStart, fsRangeEnd)); + RangeMap::iterator iterInsertedRange = pairInsert.first; + if (!pairInsert.second) { - // next range overlaps with the inserted one - merge them - if(iterRange->second > iterInsertedRange->second) - iterInsertedRange->second = iterRange->second; - iterRange = m_mapRanges.erase(iterRange); + // range with fsRangeStart already exists; update it with the increased range (if bigger than the existing one) + if (fsRangeEnd > iterInsertedRange->second) + iterInsertedRange->second = fsRangeEnd; + else + return; // new range overlaps with old one and is smaller; does not change the state of internal map and no reorganization is needed } else - break; - } -} + { + // element inserted successfully; since it can overlap the previous range in the map, we need to start merging ranges from this previous element + if (iterInsertedRange != m_mapRanges.begin()) + iterInsertedRange = std::prev(iterInsertedRange); + else if (m_mapRanges.size() == 1) + return; // this is the only element currently in the map; no need to process further. + } -size_t TSparseRangeMap::GetRangeCount() const -{ - return m_mapRanges.size(); -} + // merge subsequent ranges + file_size_t fsCurrentRangeEnd = iterInsertedRange->second; -void TSparseRangeMap::GetRangeAt(size_t stIndex, file_size_t& rfsRangeStart, file_size_t& rfsRangeEnd) const -{ - if (stIndex >= m_mapRanges.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + RangeMap::iterator iterRange = std::next(iterInsertedRange); - RangeMap::const_iterator iterMap = m_mapRanges.begin(); - std::advance(iterMap, stIndex); + while (iterRange != m_mapRanges.end()) + { + if (iterRange->first <= fsCurrentRangeEnd + 1) + { + // next range overlaps with the inserted one - merge them + if (iterRange->second > iterInsertedRange->second) + iterInsertedRange->second = iterRange->second; + iterRange = m_mapRanges.erase(iterRange); + } + else + break; + } + } - rfsRangeStart = iterMap->first; - rfsRangeEnd = iterMap->second; -} + size_t TSparseRangeMap::GetRangeCount() const + { + return m_mapRanges.size(); + } -bool TSparseRangeMap::OverlapsRange(file_size_t fsRangeStart, file_size_t fsRangeEnd) const -{ - if (fsRangeEnd < fsRangeStart) - std::swap(fsRangeStart, fsRangeEnd); + void TSparseRangeMap::GetRangeAt(size_t stIndex, file_size_t& rfsRangeStart, file_size_t& rfsRangeEnd) const + { + if (stIndex >= m_mapRanges.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - RangeMap::const_iterator iterStart = m_mapRanges.lower_bound(fsRangeStart); - if (iterStart != m_mapRanges.begin()) - iterStart = std::prev(iterStart); + RangeMap::const_iterator iterMap = m_mapRanges.begin(); + std::advance(iterMap, stIndex); - RangeMap::const_iterator iterEnd = m_mapRanges.upper_bound(fsRangeEnd); - while (iterStart != iterEnd) - { - if (fsRangeStart <= iterStart->second && iterStart->first <= fsRangeEnd) - return true; - ++iterStart; + rfsRangeStart = iterMap->first; + rfsRangeEnd = iterMap->second; } - return false; -} + bool TSparseRangeMap::OverlapsRange(file_size_t fsRangeStart, file_size_t fsRangeEnd) const + { + if (fsRangeEnd < fsRangeStart) + std::swap(fsRangeStart, fsRangeEnd); -END_CHCORE_NAMESPACE + RangeMap::const_iterator iterStart = m_mapRanges.lower_bound(fsRangeStart); + if (iterStart != m_mapRanges.begin()) + iterStart = std::prev(iterStart); + + RangeMap::const_iterator iterEnd = m_mapRanges.upper_bound(fsRangeEnd); + while (iterStart != iterEnd) + { + if (fsRangeStart <= iterStart->second && iterStart->first <= fsRangeEnd) + return true; + ++iterStart; + } + + return false; + } +} Index: src/libchcore/TSparseRangeMap.h =================================================================== diff -u -N -r5efb534fc5440a7ab779d2514a00486ecb58e845 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSparseRangeMap.h (.../TSparseRangeMap.h) (revision 5efb534fc5440a7ab779d2514a00486ecb58e845) +++ src/libchcore/TSparseRangeMap.h (.../TSparseRangeMap.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,31 +22,30 @@ #include "libchcore.h" #include "CommonDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSparseRangeMap +namespace chcore { -public: - TSparseRangeMap(); - ~TSparseRangeMap(); + class LIBCHCORE_API TSparseRangeMap + { + public: + TSparseRangeMap(); + ~TSparseRangeMap(); - void Insert(file_size_t fsRangeStart, file_size_t fsRangeEnd); + void Insert(file_size_t fsRangeStart, file_size_t fsRangeEnd); - size_t GetRangeCount() const; - void GetRangeAt(size_t stIndex, file_size_t& rfsRangeStart, file_size_t& rfsRangeEnd) const; + size_t GetRangeCount() const; + void GetRangeAt(size_t stIndex, file_size_t& rfsRangeStart, file_size_t& rfsRangeEnd) const; - bool OverlapsRange(file_size_t fsRangeStart, file_size_t fsRangeEnd) const; + bool OverlapsRange(file_size_t fsRangeStart, file_size_t fsRangeEnd) const; -private: - using RangePair = std::pair; - using RangeMap = std::map; + private: + using RangePair = std::pair; + using RangeMap = std::map; #pragma warning(push) #pragma warning(disable: 4251) - RangeMap m_mapRanges; + RangeMap m_mapRanges; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSpeedTracker.cpp =================================================================== diff -u -N -r2fe97a93f21771d75901d4b6559057d1ea055104 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSpeedTracker.cpp (.../TSpeedTracker.cpp) (revision 2fe97a93f21771d75901d4b6559057d1ea055104) +++ src/libchcore/TSpeedTracker.cpp (.../TSpeedTracker.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -8,236 +8,235 @@ #include #include "TStringArray.h" -BEGIN_CHCORE_NAMESPACE - -TSpeedTracker::TSpeedTracker(unsigned long long ullTrackTime, unsigned long long ullSampleTime) : - m_stRequiredSamples(ullSampleTime ? boost::numeric_cast(ullTrackTime / ullSampleTime) : 0), - m_ullSampleTime(ullSampleTime), - m_dSamplesPerSecond(ullSampleTime != 0 ? 1000.0 / ullSampleTime : 0.0), - m_dPartialSpeedNotInSamples(0), - m_ullTimeIntervalNotInSamples(0), - m_stNextSamplePos(0), - m_ullLastTimestamp(std::numeric_limits::max()), - m_ullZeroIntervalData(0) +namespace chcore { - if(m_ullSampleTime == 0 || m_stRequiredSamples == 0) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); - std::fill_n(std::inserter(m_vSamples, m_vSamples.end()), m_stRequiredSamples, 0.0); -} - -void TSpeedTracker::Clear() -{ - m_dPartialSpeedNotInSamples = 0; - m_ullTimeIntervalNotInSamples = 0; - m_stNextSamplePos = 0; - m_ullLastTimestamp = std::numeric_limits::max(); - m_ullZeroIntervalData = 0; - std::fill(m_vSamples.begin(), m_vSamples.end(), 0.0); -} - -void TSpeedTracker::AddSample(unsigned long long ullValue, unsigned long long ullTimestamp) -{ - // if this is the first sample ever added (after construction or after clear) then - // we don't have time interval yet - just remember the timestamp and ignore value - if(m_ullLastTimestamp == std::numeric_limits::max()) + TSpeedTracker::TSpeedTracker(unsigned long long ullTrackTime, unsigned long long ullSampleTime) : + m_stRequiredSamples(ullSampleTime ? boost::numeric_cast(ullTrackTime / ullSampleTime) : 0), + m_ullSampleTime(ullSampleTime), + m_dSamplesPerSecond(ullSampleTime != 0 ? 1000.0 / ullSampleTime : 0.0), + m_dPartialSpeedNotInSamples(0), + m_ullTimeIntervalNotInSamples(0), + m_stNextSamplePos(0), + m_ullLastTimestamp(std::numeric_limits::max()), + m_ullZeroIntervalData(0) { - m_ullLastTimestamp = ullTimestamp; - return; + if (m_ullSampleTime == 0 || m_stRequiredSamples == 0) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); + std::fill_n(std::inserter(m_vSamples, m_vSamples.end()), m_stRequiredSamples, 0.0); } - // sanity check - make sure the data is valid - if(ullTimestamp < m_ullLastTimestamp) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); - - // calculate the interval since the time last sample was added - unsigned long long ullInterval = ullTimestamp - m_ullLastTimestamp; - m_ullLastTimestamp = ullTimestamp; - - if(ullInterval == 0) // special case 0: if interval is 0 - put the data sample somewhere for future use + void TSpeedTracker::Clear() { - m_ullZeroIntervalData += ullValue; - return; - } - else if(ullInterval >= m_ullSampleTime * m_stRequiredSamples) // special case 1: interval is bigger than what we track - { - m_stNextSamplePos = 0; - m_dPartialSpeedNotInSamples = 0.0; + m_dPartialSpeedNotInSamples = 0; m_ullTimeIntervalNotInSamples = 0; + m_stNextSamplePos = 0; + m_ullLastTimestamp = std::numeric_limits::max(); m_ullZeroIntervalData = 0; - - double dSpeed = NormalizeValueByTime(ullValue, ullInterval, m_ullSampleTime); - std::fill(m_vSamples.begin(), m_vSamples.end(), dSpeed); - return; + std::fill(m_vSamples.begin(), m_vSamples.end(), 0.0); } - else + + void TSpeedTracker::AddSample(unsigned long long ullValue, unsigned long long ullTimestamp) { - // append the data from previous zero-interval samples - ullValue += m_ullZeroIntervalData; - m_ullZeroIntervalData = 0; - } + // if this is the first sample ever added (after construction or after clear) then + // we don't have time interval yet - just remember the timestamp and ignore value + if (m_ullLastTimestamp == std::numeric_limits::max()) + { + m_ullLastTimestamp = ullTimestamp; + return; + } - // calculate speed - double dSpeed = NormalizeValueByTime(ullValue, ullInterval, m_ullSampleTime); + // sanity check - make sure the data is valid + if (ullTimestamp < m_ullLastTimestamp) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - // finalize the incomplete sample and adjust the input data - FinalizeIncompleteSample(dSpeed, ullInterval); + // calculate the interval since the time last sample was added + unsigned long long ullInterval = ullTimestamp - m_ullLastTimestamp; + m_ullLastTimestamp = ullTimestamp; - // deal with the full samples - AddCompleteSamples(dSpeed, ullInterval); + if (ullInterval == 0) // special case 0: if interval is 0 - put the data sample somewhere for future use + { + m_ullZeroIntervalData += ullValue; + return; + } + else if (ullInterval >= m_ullSampleTime * m_stRequiredSamples) // special case 1: interval is bigger than what we track + { + m_stNextSamplePos = 0; + m_dPartialSpeedNotInSamples = 0.0; + m_ullTimeIntervalNotInSamples = 0; + m_ullZeroIntervalData = 0; - // and finally prepare the incomplete sample data for future use - PrepareIncompleteSample(ullInterval, dSpeed); -} - -double TSpeedTracker::GetSpeed() const -{ - double dResult = 0.0; - - if(m_ullTimeIntervalNotInSamples != 0) - { - dResult = CalculateIncompleteSampleNormalizedSpeed(); - - for(size_t stIndex = 0; stIndex < m_vSamples.size(); ++stIndex) + double dSpeed = NormalizeValueByTime(ullValue, ullInterval, m_ullSampleTime); + std::fill(m_vSamples.begin(), m_vSamples.end(), dSpeed); + return; + } + else { - if(stIndex != m_stNextSamplePos) - dResult += m_vSamples[stIndex]; + // append the data from previous zero-interval samples + ullValue += m_ullZeroIntervalData; + m_ullZeroIntervalData = 0; } - } - else - dResult = std::accumulate(m_vSamples.begin(), m_vSamples.end(), 0.0); - return dResult / m_vSamples.size() * m_dSamplesPerSecond; -} + // calculate speed + double dSpeed = NormalizeValueByTime(ullValue, ullInterval, m_ullSampleTime); -void TSpeedTracker::AppendSamples(double dSpeed, size_t stSamplesCount) -{ - if(m_vSamples.size() != m_stRequiredSamples) - THROW_CORE_EXCEPTION(eErr_InternalProblem); + // finalize the incomplete sample and adjust the input data + FinalizeIncompleteSample(dSpeed, ullInterval); - stSamplesCount = std::min(stSamplesCount, m_stRequiredSamples); - while(stSamplesCount--) - { - m_vSamples[GetNextSampleIndexAndIncrease()] = dSpeed; + // deal with the full samples + AddCompleteSamples(dSpeed, ullInterval); + + // and finally prepare the incomplete sample data for future use + PrepareIncompleteSample(ullInterval, dSpeed); } -} -size_t TSpeedTracker::GetNextSampleIndexAndIncrease() -{ - size_t stResult = m_stNextSamplePos++; - if(m_stNextSamplePos >= m_vSamples.size()) - m_stNextSamplePos = 0; - return stResult; -} + double TSpeedTracker::GetSpeed() const + { + double dResult = 0.0; -double TSpeedTracker::NormalizeValueByTime(unsigned long long ullValue, unsigned long long ullTime, unsigned long long ullNormalizeTime) -{ - return Math::Div64(ullNormalizeTime, ullTime) * ullValue; -} + if (m_ullTimeIntervalNotInSamples != 0) + { + dResult = CalculateIncompleteSampleNormalizedSpeed(); -void TSpeedTracker::FinalizeIncompleteSample(double dSpeed, unsigned long long& ullInterval) -{ - if(m_ullTimeIntervalNotInSamples == 0 || m_dPartialSpeedNotInSamples == 0.0 || ullInterval == 0) - return; + for (size_t stIndex = 0; stIndex < m_vSamples.size(); ++stIndex) + { + if (stIndex != m_stNextSamplePos) + dResult += m_vSamples[stIndex]; + } + } + else + dResult = std::accumulate(m_vSamples.begin(), m_vSamples.end(), 0.0); - // how much data do we need? - unsigned long long ullIntervalStillNeeded = m_ullSampleTime - m_ullTimeIntervalNotInSamples; - if(ullInterval < ullIntervalStillNeeded) - { - // we can only add the next partial sample, but cannot finalize - m_ullTimeIntervalNotInSamples += ullInterval; - m_dPartialSpeedNotInSamples += dSpeed * Math::Div64(ullInterval, m_ullSampleTime); - ullInterval = 0; + return dResult / m_vSamples.size() * m_dSamplesPerSecond; } - else + + void TSpeedTracker::AppendSamples(double dSpeed, size_t stSamplesCount) { - // going to finalize sample - m_dPartialSpeedNotInSamples += dSpeed * Math::Div64(ullIntervalStillNeeded, m_ullSampleTime); + if (m_vSamples.size() != m_stRequiredSamples) + THROW_CORE_EXCEPTION(eErr_InternalProblem); - m_vSamples[GetNextSampleIndexAndIncrease()] = m_dPartialSpeedNotInSamples; - ullInterval -= ullIntervalStillNeeded; + stSamplesCount = std::min(stSamplesCount, m_stRequiredSamples); + while (stSamplesCount--) + { + m_vSamples[GetNextSampleIndexAndIncrease()] = dSpeed; + } + } - m_dPartialSpeedNotInSamples = 0.0; - m_ullTimeIntervalNotInSamples = 0; + size_t TSpeedTracker::GetNextSampleIndexAndIncrease() + { + size_t stResult = m_stNextSamplePos++; + if (m_stNextSamplePos >= m_vSamples.size()) + m_stNextSamplePos = 0; + return stResult; } -} -void TSpeedTracker::AddCompleteSamples(double dSpeed, unsigned long long& ullInterval) -{ - size_t stSamplesCount = boost::numeric_cast(std::min(ullInterval / m_ullSampleTime, (unsigned long long)m_stRequiredSamples)); - - // fill the container with full samples - while(stSamplesCount--) + double TSpeedTracker::NormalizeValueByTime(unsigned long long ullValue, unsigned long long ullTime, unsigned long long ullNormalizeTime) { - m_vSamples[GetNextSampleIndexAndIncrease()] = dSpeed; + return Math::Div64(ullNormalizeTime, ullTime) * ullValue; } - ullInterval = ullInterval % m_ullSampleTime; -} + void TSpeedTracker::FinalizeIncompleteSample(double dSpeed, unsigned long long& ullInterval) + { + if (m_ullTimeIntervalNotInSamples == 0 || m_dPartialSpeedNotInSamples == 0.0 || ullInterval == 0) + return; -double TSpeedTracker::CalculateIncompleteSampleNormalizedSpeed() const -{ - // get the speed for incomplete sample - double dIncompleteSamplePercentage = Math::Div64(m_ullTimeIntervalNotInSamples, m_ullSampleTime); - double dResult = m_dPartialSpeedNotInSamples + (1.0 - dIncompleteSamplePercentage) * m_vSamples[m_stNextSamplePos]; + // how much data do we need? + unsigned long long ullIntervalStillNeeded = m_ullSampleTime - m_ullTimeIntervalNotInSamples; + if (ullInterval < ullIntervalStillNeeded) + { + // we can only add the next partial sample, but cannot finalize + m_ullTimeIntervalNotInSamples += ullInterval; + m_dPartialSpeedNotInSamples += dSpeed * Math::Div64(ullInterval, m_ullSampleTime); + ullInterval = 0; + } + else + { + // going to finalize sample + m_dPartialSpeedNotInSamples += dSpeed * Math::Div64(ullIntervalStillNeeded, m_ullSampleTime); - return dResult; -} + m_vSamples[GetNextSampleIndexAndIncrease()] = m_dPartialSpeedNotInSamples; + ullInterval -= ullIntervalStillNeeded; -void TSpeedTracker::PrepareIncompleteSample(unsigned long long ullInterval, double dSpeed) -{ - if(ullInterval > 0) + m_dPartialSpeedNotInSamples = 0.0; + m_ullTimeIntervalNotInSamples = 0; + } + } + + void TSpeedTracker::AddCompleteSamples(double dSpeed, unsigned long long& ullInterval) { - // we can only add the next partial sample, but cannot finalize - m_ullTimeIntervalNotInSamples = ullInterval; - m_dPartialSpeedNotInSamples = dSpeed * Math::Div64(ullInterval, m_ullSampleTime); + size_t stSamplesCount = boost::numeric_cast(std::min(ullInterval / m_ullSampleTime, (unsigned long long)m_stRequiredSamples)); + + // fill the container with full samples + while (stSamplesCount--) + { + m_vSamples[GetNextSampleIndexAndIncrease()] = dSpeed; + } + + ullInterval = ullInterval % m_ullSampleTime; } -} -TString TSpeedTracker::ToString() const -{ - TString strData; - - strData += boost::lexical_cast(m_stNextSamplePos).c_str(); - strData += _T(";"); + double TSpeedTracker::CalculateIncompleteSampleNormalizedSpeed() const + { + // get the speed for incomplete sample + double dIncompleteSamplePercentage = Math::Div64(m_ullTimeIntervalNotInSamples, m_ullSampleTime); + double dResult = m_dPartialSpeedNotInSamples + (1.0 - dIncompleteSamplePercentage) * m_vSamples[m_stNextSamplePos]; - strData += boost::lexical_cast(m_dPartialSpeedNotInSamples).c_str(); - strData += _T(";"); - strData += boost::lexical_cast(m_ullTimeIntervalNotInSamples).c_str(); - strData += _T(";"); - strData += boost::lexical_cast(m_ullZeroIntervalData).c_str(); - strData += _T(";"); + return dResult; + } - BOOST_FOREACH(double dVal, m_vSamples) + void TSpeedTracker::PrepareIncompleteSample(unsigned long long ullInterval, double dSpeed) { - strData += boost::lexical_cast(dVal).c_str(); - strData += _T(";"); + if (ullInterval > 0) + { + // we can only add the next partial sample, but cannot finalize + m_ullTimeIntervalNotInSamples = ullInterval; + m_dPartialSpeedNotInSamples = dSpeed * Math::Div64(ullInterval, m_ullSampleTime); + } } - strData.TrimRightSelf(_T(";")); + TString TSpeedTracker::ToString() const + { + TString strData; - return strData; -} + strData += boost::lexical_cast(m_stNextSamplePos).c_str(); + strData += _T(";"); -void TSpeedTracker::FromString(const TString& strData) -{ - TStringArray arrStrings; - strData.Split(_T(";"), arrStrings); + strData += boost::lexical_cast(m_dPartialSpeedNotInSamples).c_str(); + strData += _T(";"); + strData += boost::lexical_cast(m_ullTimeIntervalNotInSamples).c_str(); + strData += _T(";"); + strData += boost::lexical_cast(m_ullZeroIntervalData).c_str(); + strData += _T(";"); - const size_t SerializedMembers = 4; - if(arrStrings.GetCount() != m_stRequiredSamples + SerializedMembers) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + BOOST_FOREACH(double dVal, m_vSamples) + { + strData += boost::lexical_cast(dVal).c_str(); + strData += _T(";"); + } - Clear(); + strData.TrimRightSelf(_T(";")); - m_stNextSamplePos = boost::lexical_cast(arrStrings.GetAt(0).c_str()); - m_dPartialSpeedNotInSamples = boost::lexical_cast(arrStrings.GetAt(1).c_str()); - m_ullTimeIntervalNotInSamples = boost::lexical_cast(arrStrings.GetAt(2).c_str()); - m_ullZeroIntervalData = boost::lexical_cast((PCTSTR)arrStrings.GetAt(3).c_str()); + return strData; + } - for(size_t stIndex = 4; stIndex < arrStrings.GetCount(); ++stIndex) + void TSpeedTracker::FromString(const TString& strData) { - m_vSamples[stIndex - 4] = boost::lexical_cast(arrStrings.GetAt(stIndex).c_str()); + TStringArray arrStrings; + strData.Split(_T(";"), arrStrings); + + const size_t SerializedMembers = 4; + if (arrStrings.GetCount() != m_stRequiredSamples + SerializedMembers) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); + + Clear(); + + m_stNextSamplePos = boost::lexical_cast(arrStrings.GetAt(0).c_str()); + m_dPartialSpeedNotInSamples = boost::lexical_cast(arrStrings.GetAt(1).c_str()); + m_ullTimeIntervalNotInSamples = boost::lexical_cast(arrStrings.GetAt(2).c_str()); + m_ullZeroIntervalData = boost::lexical_cast((PCTSTR)arrStrings.GetAt(3).c_str()); + + for (size_t stIndex = 4; stIndex < arrStrings.GetCount(); ++stIndex) + { + m_vSamples[stIndex - 4] = boost::lexical_cast(arrStrings.GetAt(stIndex).c_str()); + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSpeedTracker.h =================================================================== diff -u -N -r19925be73ffcadd9f345f10e03e55aadb3f0eeac -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSpeedTracker.h (.../TSpeedTracker.h) (revision 19925be73ffcadd9f345f10e03e55aadb3f0eeac) +++ src/libchcore/TSpeedTracker.h (.../TSpeedTracker.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -4,52 +4,51 @@ #include "libchcore.h" #include "TString.h" -BEGIN_CHCORE_NAMESPACE - -class TSpeedTracker +namespace chcore { -public: - TSpeedTracker(unsigned long long ullTrackTime, unsigned long long ullSampleTime); + class TSpeedTracker + { + public: + TSpeedTracker(unsigned long long ullTrackTime, unsigned long long ullSampleTime); - void AddSample(unsigned long long ullValue, unsigned long long ullTimestamp); - void Clear(); + void AddSample(unsigned long long ullValue, unsigned long long ullTimestamp); + void Clear(); - // retrieves speed per second - double GetSpeed() const; + // retrieves speed per second + double GetSpeed() const; - TString ToString() const; - void FromString(const TString& strData); + TString ToString() const; + void FromString(const TString& strData); -private: - TSpeedTracker(const TSpeedTracker&); - TSpeedTracker& operator=(const TSpeedTracker&); + private: + TSpeedTracker(const TSpeedTracker&); + TSpeedTracker& operator=(const TSpeedTracker&); - static double NormalizeValueByTime(unsigned long long ullValue, unsigned long long ullTime, unsigned long long ullNormalizeTime = 1000); - void AppendSamples(double dSpeed, size_t stSamplesCount); + static double NormalizeValueByTime(unsigned long long ullValue, unsigned long long ullTime, unsigned long long ullNormalizeTime = 1000); + void AppendSamples(double dSpeed, size_t stSamplesCount); - size_t GetNextSampleIndexAndIncrease(); - void FinalizeIncompleteSample(double dSpeed, unsigned long long& ullInterval); - void AddCompleteSamples(double dSpeed, unsigned long long& ullInterval); - void PrepareIncompleteSample( unsigned long long ullInterval, double dSpeed ); - double CalculateIncompleteSampleNormalizedSpeed() const; + size_t GetNextSampleIndexAndIncrease(); + void FinalizeIncompleteSample(double dSpeed, unsigned long long& ullInterval); + void AddCompleteSamples(double dSpeed, unsigned long long& ullInterval); + void PrepareIncompleteSample(unsigned long long ullInterval, double dSpeed); + double CalculateIncompleteSampleNormalizedSpeed() const; -private: - // initialized in constructor (does not change throughout the whole lifetime) - const size_t m_stRequiredSamples; // how many samples of m_ullSampleTime do we want to keep? - const unsigned long long m_ullSampleTime; // interval covered by a single sample - const double m_dSamplesPerSecond; // how many samples fit in one second + private: + // initialized in constructor (does not change throughout the whole lifetime) + const size_t m_stRequiredSamples; // how many samples of m_ullSampleTime do we want to keep? + const unsigned long long m_ullSampleTime; // interval covered by a single sample + const double m_dSamplesPerSecond; // how many samples fit in one second - // vector of samples with pointer to the next element to be filled - std::vector m_vSamples; // speed per sample - size_t m_stNextSamplePos; // points to the element with the oldest sample + // vector of samples with pointer to the next element to be filled + std::vector m_vSamples; // speed per sample + size_t m_stNextSamplePos; // points to the element with the oldest sample - unsigned long long m_ullLastTimestamp; // last time some sample was processed + unsigned long long m_ullLastTimestamp; // last time some sample was processed - double m_dPartialSpeedNotInSamples; // specifies count of data processed in the m_ullTimeIntervalNotInSamples interval - unsigned long long m_ullTimeIntervalNotInSamples; // interval that was not enough to add m_ullDataNotInSamples to samples - unsigned long long m_ullZeroIntervalData; -}; + double m_dPartialSpeedNotInSamples; // specifies count of data processed in the m_ullTimeIntervalNotInSamples interval + unsigned long long m_ullTimeIntervalNotInSamples; // interval that was not enough to add m_ullDataNotInSamples to samples + unsigned long long m_ullZeroIntervalData; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TString.cpp =================================================================== diff -u -N -r2755e12daeccb1935f569e7235e685e566b0b098 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TString.cpp (.../TString.cpp) (revision 2755e12daeccb1935f569e7235e685e566b0b098) +++ src/libchcore/TString.cpp (.../TString.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -38,678 +38,677 @@ ///< Increment value for internal TString buffer #define CHUNK_INCSIZE 64 -BEGIN_CHCORE_NAMESPACE - -/** Standard constructor - allocates the underlying data object - */ -TString::TString() : - m_pszData(NULL), - m_stBufferSize(0) +namespace chcore { -} + /** Standard constructor - allocates the underlying data object + */ + TString::TString() : + m_pszData(NULL), + m_stBufferSize(0) + { + } -/** Constructor allocates the underlying data object and initializes it with - * a given unicode TString. - * \param[in] pszStr - source unicode TString - */ -TString::TString(const wchar_t* pszStr) : - m_pszData(NULL), - m_stBufferSize(0) -{ - SetString(pszStr); -} + /** Constructor allocates the underlying data object and initializes it with + * a given unicode TString. + * \param[in] pszStr - source unicode TString + */ + TString::TString(const wchar_t* pszStr) : + m_pszData(NULL), + m_stBufferSize(0) + { + SetString(pszStr); + } -TString::TString(const wchar_t* pszStart, const wchar_t* pszEnd, size_t stMaxStringSize) : - m_pszData(NULL), - m_stBufferSize(0) -{ - // we support either both arguments != NULL or both == NULL - if(pszEnd != NULL && pszStart == NULL || pszEnd == NULL && pszStart != NULL) - THROW_STRING_EXCEPTION(eErr_InvalidArgument, _T("End of string specified while start is NULL")); + TString::TString(const wchar_t* pszStart, const wchar_t* pszEnd, size_t stMaxStringSize) : + m_pszData(NULL), + m_stBufferSize(0) + { + // we support either both arguments != NULL or both == NULL + if (pszEnd != NULL && pszStart == NULL || pszEnd == NULL && pszStart != NULL) + THROW_STRING_EXCEPTION(eErr_InvalidArgument, _T("End of string specified while start is NULL")); - // sanity check - if(pszEnd < pszStart) - THROW_STRING_EXCEPTION(eErr_InvalidArgument, _T("Paradox: string begins after its end")); + // sanity check + if (pszEnd < pszStart) + THROW_STRING_EXCEPTION(eErr_InvalidArgument, _T("Paradox: string begins after its end")); - size_t stCount = pszEnd - pszStart; - if(stCount > stMaxStringSize) - THROW_STRING_EXCEPTION(eErr_InvalidArgument, _T("Exceeded maximum expected string size")); + size_t stCount = pszEnd - pszStart; + if (stCount > stMaxStringSize) + THROW_STRING_EXCEPTION(eErr_InvalidArgument, _T("Exceeded maximum expected string size")); - SetString(pszStart, stCount); -} + SetString(pszStart, stCount); + } -TString::TString(const wchar_t* pszStart, size_t stCount) : - m_pszData(NULL), - m_stBufferSize(0) -{ - if(!pszStart) - THROW_STRING_EXCEPTION(eErr_InvalidArgument, _T("String not specified")); + TString::TString(const wchar_t* pszStart, size_t stCount) : + m_pszData(NULL), + m_stBufferSize(0) + { + if (!pszStart) + THROW_STRING_EXCEPTION(eErr_InvalidArgument, _T("String not specified")); - if(stCount == 0) - return; + if (stCount == 0) + return; - SetString(pszStart, stCount); -} + SetString(pszStart, stCount); + } -/** Constructor increases the reference count in the parameter's data object - * and copies only the data object address. - * \param[in] rSrc - source TString object - */ -TString::TString(const TString& rSrc) : - m_pszData(NULL), - m_stBufferSize(0) -{ - SetString(rSrc.m_pszData); -} + /** Constructor increases the reference count in the parameter's data object + * and copies only the data object address. + * \param[in] rSrc - source TString object + */ + TString::TString(const TString& rSrc) : + m_pszData(NULL), + m_stBufferSize(0) + { + SetString(rSrc.m_pszData); + } -/** Destructor releases the underlying data object. - */ -TString::~TString() -{ - delete [] m_pszData; - m_pszData = NULL; - m_stBufferSize = 0; -} + /** Destructor releases the underlying data object. + */ + TString::~TString() + { + delete[] m_pszData; + m_pszData = NULL; + m_stBufferSize = 0; + } -/** Operator releases the current data object, stores a pointer to - * the data object from the given TString object and increases a reference - * count. - * \param[in] src - source TString object - * \return A reference to the current TString. - */ -TString& TString::operator=(const TString& rSrc) -{ - if(this != &rSrc) - SetString(rSrc.m_pszData); + /** Operator releases the current data object, stores a pointer to + * the data object from the given TString object and increases a reference + * count. + * \param[in] src - source TString object + * \return A reference to the current TString. + */ + TString& TString::operator=(const TString& rSrc) + { + if (this != &rSrc) + SetString(rSrc.m_pszData); - return *this; -} + return *this; + } -/** Operator makes an own copy of underlying data object (if needed) and copy - * there the given unicode TString. - * \param[in] pszSrc - source unicode TString - * \return A reference to the current TString object. - */ -const TString& TString::operator=(const wchar_t* pszSrc) -{ - if(pszSrc != m_pszData) - SetString(pszSrc); + /** Operator makes an own copy of underlying data object (if needed) and copy + * there the given unicode TString. + * \param[in] pszSrc - source unicode TString + * \return A reference to the current TString object. + */ + const TString& TString::operator=(const wchar_t* pszSrc) + { + if (pszSrc != m_pszData) + SetString(pszSrc); - return *this; -} + return *this; + } -/** Operator concatenates a given TString object with the current content of - * this TString and returns a new TString object. - * \param[in] src - TString object that will be appended - * \return A new TString object with concatenated strings. - */ -TString TString::operator+(const TString& src) const -{ - TString str(*this); - str.Append(src); - - return str; -} + /** Operator concatenates a given TString object with the current content of + * this TString and returns a new TString object. + * \param[in] src - TString object that will be appended + * \return A new TString object with concatenated strings. + */ + TString TString::operator+(const TString& src) const + { + TString str(*this); + str.Append(src); -/** Operator concatenates a given unicode TString with the current content of - * this TString and returns a new TString object. - * \param[in] pszSrc - unicode TString that will be appended - * \return A new TString object with concatenated strings. - */ -TString TString::operator+(const wchar_t* pszSrc) const -{ - TString str(*this); - str.Append(pszSrc); - - return str; -} + return str; + } -/** Operator appends a given TString object to own internal buffer. - * \param[in] src - TString object that will be appended - * \return A reference to this. - */ -const TString& TString::operator+=(const TString& src) -{ - Append(src); - return *this; -} + /** Operator concatenates a given unicode TString with the current content of + * this TString and returns a new TString object. + * \param[in] pszSrc - unicode TString that will be appended + * \return A new TString object with concatenated strings. + */ + TString TString::operator+(const wchar_t* pszSrc) const + { + TString str(*this); + str.Append(pszSrc); -/** Operator appends a given unicode TString to own internal buffer. - * \param[in] pszSrc - unicode TString that will be appended - * \return A reference to this. - */ -const TString& TString::operator+=(const wchar_t* pszSrc) -{ - Append(pszSrc); - return *this; -} + return str; + } -/** Function counts the GetLength of a TString in characters (doesn't matter if the TString - * is unicode or ansi). - * \note All GetLength checks should be done through this function, because of possible future - * update that will store the TString GetLength in the internal member. - * \return The TString GetLength in characters, not including the terminating '\\0' - */ -size_t TString::GetLength() const -{ - return m_pszData ? _tcslen(m_pszData) : 0; -} + /** Operator appends a given TString object to own internal buffer. + * \param[in] src - TString object that will be appended + * \return A reference to this. + */ + const TString& TString::operator+=(const TString& src) + { + Append(src); + return *this; + } -/** Function makes own data object writable and clears it. Does not delete the - * internal buffer - only sets the content to '\\0'. - */ -void TString::Clear() -{ - if(m_pszData) - m_pszData[0] = L'\0'; -} + /** Operator appends a given unicode TString to own internal buffer. + * \param[in] pszSrc - unicode TString that will be appended + * \return A reference to this. + */ + const TString& TString::operator+=(const wchar_t* pszSrc) + { + Append(pszSrc); + return *this; + } -/** Function checks if the TString is empty. - * \return True if this TString is empty, false otherwise. - */ -bool TString::IsEmpty() const -{ - return !m_pszData || m_pszData[0] == L'\0'; -} + /** Function counts the GetLength of a TString in characters (doesn't matter if the TString + * is unicode or ansi). + * \note All GetLength checks should be done through this function, because of possible future + * update that will store the TString GetLength in the internal member. + * \return The TString GetLength in characters, not including the terminating '\\0' + */ + size_t TString::GetLength() const + { + return m_pszData ? _tcslen(m_pszData) : 0; + } -/** Function merges the given unicode TString with the current content of an internal buffer. - * \param[in] pszSrc - unicode TString to append - */ -void TString::Append(const wchar_t* pszSrc) -{ - if(!pszSrc) - return; + /** Function makes own data object writable and clears it. Does not delete the + * internal buffer - only sets the content to '\\0'. + */ + void TString::Clear() + { + if (m_pszData) + m_pszData[0] = L'\0'; + } - size_t stAddLen = wcslen(pszSrc); - size_t stThisLen = GetLength(); + /** Function checks if the TString is empty. + * \return True if this TString is empty, false otherwise. + */ + bool TString::IsEmpty() const + { + return !m_pszData || m_pszData[0] == L'\0'; + } - Reserve(stThisLen + stAddLen + 1); + /** Function merges the given unicode TString with the current content of an internal buffer. + * \param[in] pszSrc - unicode TString to append + */ + void TString::Append(const wchar_t* pszSrc) + { + if (!pszSrc) + return; - wcsncpy_s(m_pszData + stThisLen, m_stBufferSize - stThisLen, pszSrc, stAddLen + 1); -} + size_t stAddLen = wcslen(pszSrc); + size_t stThisLen = GetLength(); -/** Function merges the given TString object with the current content of an internal buffer. - * \param[in] src - TString object to append - */ -void TString::Append(const TString& rSrc) -{ - if(rSrc.IsEmpty()) - return; + Reserve(stThisLen + stAddLen + 1); - size_t stAddLen = rSrc.GetLength(); - size_t stThisLen = GetLength(); + wcsncpy_s(m_pszData + stThisLen, m_stBufferSize - stThisLen, pszSrc, stAddLen + 1); + } - Reserve(stThisLen + stAddLen + 1); + /** Function merges the given TString object with the current content of an internal buffer. + * \param[in] src - TString object to append + */ + void TString::Append(const TString& rSrc) + { + if (rSrc.IsEmpty()) + return; - wcsncpy_s(m_pszData + stThisLen, m_stBufferSize - stThisLen, rSrc.m_pszData, stAddLen + 1); -} + size_t stAddLen = rSrc.GetLength(); + size_t stThisLen = GetLength(); -/** Returns a new TString object with the Left part of this TString object. - * \param[in] tLen - count of characters to copy to the new TString object - * \return The TString with the Left part of the current TString. - */ -TString TString::Left(size_t tLen) const -{ - size_t stThisLen = GetLength(); + Reserve(stThisLen + stAddLen + 1); - if(stThisLen == 0 || tLen == 0) - return TString(); + wcsncpy_s(m_pszData + stThisLen, m_stBufferSize - stThisLen, rSrc.m_pszData, stAddLen + 1); + } - if(tLen >= stThisLen) - return *this; - else - return TString(m_pszData, tLen); -} + /** Returns a new TString object with the Left part of this TString object. + * \param[in] tLen - count of characters to copy to the new TString object + * \return The TString with the Left part of the current TString. + */ + TString TString::Left(size_t tLen) const + { + size_t stThisLen = GetLength(); -/** Returns a new TString object with the Right part of this TString object. - * \param[in] tLen - count of characters to copy to the new TString object - * \return The TString with the Right part of the current TString. - */ -TString TString::Right(size_t tLen) const -{ - size_t stThisLen = GetLength(); + if (stThisLen == 0 || tLen == 0) + return TString(); - if(stThisLen == 0 || tLen == 0) - return TString(); + if (tLen >= stThisLen) + return *this; + else + return TString(m_pszData, tLen); + } - if(tLen >= stThisLen) - return *this; - else - return TString(m_pszData + stThisLen - tLen, tLen); -} + /** Returns a new TString object with the Right part of this TString object. + * \param[in] tLen - count of characters to copy to the new TString object + * \return The TString with the Right part of the current TString. + */ + TString TString::Right(size_t tLen) const + { + size_t stThisLen = GetLength(); -/** Returns a new TString object with the middle part of this TString object. - * \param[in] tStart - position of the first character to copy - * \param[in] tLen - count of chars to copy - * \return The TString with the middle part of the current TString. - */ -TString TString::Mid(size_t tStart, size_t tLen) const -{ - size_t stThisLen = GetLength(); + if (stThisLen == 0 || tLen == 0) + return TString(); - if(stThisLen == 0 || tLen == 0) - return TString(); + if (tLen >= stThisLen) + return *this; + else + return TString(m_pszData + stThisLen - tLen, tLen); + } - if(tStart >= stThisLen) - return TString(); + /** Returns a new TString object with the middle part of this TString object. + * \param[in] tStart - position of the first character to copy + * \param[in] tLen - count of chars to copy + * \return The TString with the middle part of the current TString. + */ + TString TString::Mid(size_t tStart, size_t tLen) const + { + size_t stThisLen = GetLength(); - size_t stRealLength = std::min(tLen, stThisLen - tStart); + if (stThisLen == 0 || tLen == 0) + return TString(); - TString strNew(m_pszData + tStart, stRealLength); - return strNew; -} + if (tStart >= stThisLen) + return TString(); -TString TString::MidRange(size_t tStart, size_t stAfterEndPos) const -{ - if(stAfterEndPos < tStart) - return TString(); - return Mid(tStart, stAfterEndPos - tStart); -} + size_t stRealLength = std::min(tLen, stThisLen - tStart); -/** Makes this TString it's Left part. Much faster than using standard - * Left() function. - * \param[in] tLen - count of characters at the beginning of the TString to be Left in a TString. - * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds - * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). - * \see Left() - */ -void TString::LeftSelf(size_t tLen) -{ - size_t stThisLen = GetLength(); + TString strNew(m_pszData + tStart, stRealLength); + return strNew; + } - // nothing to do if nothing inside - if(stThisLen == 0) - return; + TString TString::MidRange(size_t tStart, size_t stAfterEndPos) const + { + if (stAfterEndPos < tStart) + return TString(); + return Mid(tStart, stAfterEndPos - tStart); + } - if(tLen < stThisLen) // otherwise there is nothing to do - m_pszData[tLen] = _T('\0'); -} + /** Makes this TString it's Left part. Much faster than using standard + * Left() function. + * \param[in] tLen - count of characters at the beginning of the TString to be Left in a TString. + * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds + * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). + * \see Left() + */ + void TString::LeftSelf(size_t tLen) + { + size_t stThisLen = GetLength(); -/** Makes this TString it's Right part. Much faster than using standard - * Right() function. - * \param[in] tLen - count of characters at the end of the TString to be Left in a TString. - * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds - * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). - * \see Right() - */ -void TString::RightSelf(size_t tLen) -{ - size_t stThisLen = GetLength(); + // nothing to do if nothing inside + if (stThisLen == 0) + return; - // nothing to do if nothing inside - if(stThisLen == 0) - return; + if (tLen < stThisLen) // otherwise there is nothing to do + m_pszData[tLen] = _T('\0'); + } - if(tLen < stThisLen) // otherwise there is nothing to do - wmemmove(m_pszData, m_pszData + stThisLen - tLen, tLen + 1); -} + /** Makes this TString it's Right part. Much faster than using standard + * Right() function. + * \param[in] tLen - count of characters at the end of the TString to be Left in a TString. + * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds + * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). + * \see Right() + */ + void TString::RightSelf(size_t tLen) + { + size_t stThisLen = GetLength(); -/** Makes this TString it's middle part. Much faster than using standard - * Mid() function. - * \param[in] tStart - starting position of a text to be Left in a TString - * \param[in] tLen - count of characters at the middle of the TString to be Left in a TString. - * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds - * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). - * \see Mid() - */ -void TString::MidSelf(size_t tStart, size_t tLen) -{ - size_t stThisLen = GetLength(); + // nothing to do if nothing inside + if (stThisLen == 0) + return; - if(stThisLen == 0) - return; + if (tLen < stThisLen) // otherwise there is nothing to do + wmemmove(m_pszData, m_pszData + stThisLen - tLen, tLen + 1); + } - if(tStart >= stThisLen) - Clear(); - else + /** Makes this TString it's middle part. Much faster than using standard + * Mid() function. + * \param[in] tStart - starting position of a text to be Left in a TString + * \param[in] tLen - count of characters at the middle of the TString to be Left in a TString. + * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds + * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). + * \see Mid() + */ + void TString::MidSelf(size_t tStart, size_t tLen) { - size_t stRealNewLength = std::min(tLen, stThisLen - tStart); + size_t stThisLen = GetLength(); - wmemmove(m_pszData, m_pszData + tStart, stRealNewLength); - m_pszData[stRealNewLength] = _T('\0'); + if (stThisLen == 0) + return; + + if (tStart >= stThisLen) + Clear(); + else + { + size_t stRealNewLength = std::min(tLen, stThisLen - tStart); + + wmemmove(m_pszData, m_pszData + tStart, stRealNewLength); + m_pszData[stRealNewLength] = _T('\0'); + } } -} -void TString::TrimRightSelf(const wchar_t* pszElements) -{ - if(!pszElements || pszElements[0] == L'\0') - return; + void TString::TrimRightSelf(const wchar_t* pszElements) + { + if (!pszElements || pszElements[0] == L'\0') + return; - size_t stThisLen = GetLength(); - if(stThisLen == 0) - return; + size_t stThisLen = GetLength(); + if (stThisLen == 0) + return; - size_t stLen = stThisLen; + size_t stLen = stThisLen; - const wchar_t* pszElementsEnd = pszElements + wcslen(pszElements); - while(stLen-- > 0) - { - if(std::find(pszElements, pszElementsEnd, m_pszData[stLen]) != pszElementsEnd) - m_pszData[stLen] = _T('\0'); - else - break; + const wchar_t* pszElementsEnd = pszElements + wcslen(pszElements); + while (stLen-- > 0) + { + if (std::find(pszElements, pszElementsEnd, m_pszData[stLen]) != pszElementsEnd) + m_pszData[stLen] = _T('\0'); + else + break; + } } -} -bool TString::Delete(size_t stIndex, size_t stCount) -{ - size_t stThisLen = GetLength(); + bool TString::Delete(size_t stIndex, size_t stCount) + { + size_t stThisLen = GetLength(); - if(stIndex >= stThisLen || stCount == 0) - return false; + if (stIndex >= stThisLen || stCount == 0) + return false; - bool bResult = true; - if(stIndex + stCount > stThisLen) // in case there is not enough data to delete, then we want to delete what we can, but return false - bResult = false; + bool bResult = true; + if (stIndex + stCount > stThisLen) // in case there is not enough data to delete, then we want to delete what we can, but return false + bResult = false; - size_t stCountToDelete = std::min(stThisLen - stIndex, stCount); + size_t stCountToDelete = std::min(stThisLen - stIndex, stCount); - // should also copy the terminating null character - errno_t err = wmemmove_s(m_pszData + stIndex, stThisLen - stIndex + 1, m_pszData + stIndex + stCountToDelete, stThisLen - stIndex - stCountToDelete + 1); - if(err != 0) - THROW_CORE_EXCEPTION(eErr_InternalProblem); + // should also copy the terminating null character + errno_t err = wmemmove_s(m_pszData + stIndex, stThisLen - stIndex + 1, m_pszData + stIndex + stCountToDelete, stThisLen - stIndex - stCountToDelete + 1); + if (err != 0) + THROW_CORE_EXCEPTION(eErr_InternalProblem); - return bResult; -} + return bResult; + } -void TString::Split(const wchar_t* pszSeparators, TStringArray& rStrings) const -{ - rStrings.Clear(); + void TString::Split(const wchar_t* pszSeparators, TStringArray& rStrings) const + { + rStrings.Clear(); - size_t stThisLen = GetLength(); - if(stThisLen == 0 || !pszSeparators) - return; + size_t stThisLen = GetLength(); + if (stThisLen == 0 || !pszSeparators) + return; - // ugly version - many reallocations due to the usage of stl wstrings - std::vector vStrings; - boost::split(vStrings, m_pszData, boost::is_any_of(pszSeparators)); + // ugly version - many reallocations due to the usage of stl wstrings + std::vector vStrings; + boost::split(vStrings, m_pszData, boost::is_any_of(pszSeparators)); - BOOST_FOREACH(const std::wstring& strPart, vStrings) + BOOST_FOREACH(const std::wstring& strPart, vStrings) + { + rStrings.Add(strPart.c_str()); + } + } + + /** Compares a TString with the given unicode TString. Comparison is case sensitive. + * \param[in] psz - unicode TString to which the TString object will be compared + * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. + */ + int_t TString::Compare(const wchar_t* psz) const { - rStrings.Add(strPart.c_str()); + return wcscmp(m_pszData ? m_pszData : L"", psz ? psz : L""); } -} -/** Compares a TString with the given unicode TString. Comparison is case sensitive. - * \param[in] psz - unicode TString to which the TString object will be compared - * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. - */ -int_t TString::Compare(const wchar_t* psz) const -{ - return wcscmp(m_pszData ? m_pszData : L"", psz ? psz : L""); -} + /** Compares a TString with the given TString object. Comparison is case sensitive. + * \param[in] str - TString object to which internal TString object will be compared + * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. + */ + int_t TString::Compare(const TString& str) const + { + return Compare(str.m_pszData); + } -/** Compares a TString with the given TString object. Comparison is case sensitive. - * \param[in] str - TString object to which internal TString object will be compared - * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. - */ -int_t TString::Compare(const TString& str) const -{ - return Compare(str.m_pszData); -} + /** Compares a TString with the given unicode TString. Comparison is case insensitive. + * \param[in] psz - unicode TString to which internal TString object will be compared + * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. + */ + int_t TString::CompareNoCase(const wchar_t* psz) const + { + return _wcsicmp(m_pszData ? m_pszData : L"", psz ? psz : L""); + } -/** Compares a TString with the given unicode TString. Comparison is case insensitive. - * \param[in] psz - unicode TString to which internal TString object will be compared - * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. - */ -int_t TString::CompareNoCase(const wchar_t* psz) const -{ - return _wcsicmp(m_pszData ? m_pszData : L"", psz ? psz : L""); -} + /** Compares a TString with the given TString object. Comparison is case insensitive. + * \param[in] str - TString object to which internal TString object will be compared + * \return <0 if this TString object is "less" than str, 0 if they are equal and >0 otherwise. + */ + int_t TString::CompareNoCase(const TString& str) const + { + return CompareNoCase(str.m_pszData); + } -/** Compares a TString with the given TString object. Comparison is case insensitive. - * \param[in] str - TString object to which internal TString object will be compared - * \return <0 if this TString object is "less" than str, 0 if they are equal and >0 otherwise. - */ -int_t TString::CompareNoCase(const TString& str) const -{ - return CompareNoCase(str.m_pszData); -} + bool TString::StartsWith(const wchar_t* pszText) const + { + if (!m_pszData || !pszText) + return false; -bool TString::StartsWith(const wchar_t* pszText) const -{ - if(!m_pszData || !pszText) - return false; + return boost::starts_with(m_pszData, pszText); + } - return boost::starts_with(m_pszData, pszText); -} + bool TString::StartsWithNoCase(const wchar_t* pszText) const + { + if (!m_pszData || !pszText) + return false; -bool TString::StartsWithNoCase(const wchar_t* pszText) const -{ - if(!m_pszData || !pszText) - return false; + return boost::istarts_with(m_pszData, pszText); + } - return boost::istarts_with(m_pszData, pszText); -} + bool TString::EndsWith(const wchar_t* pszText) const + { + if (!m_pszData || !pszText) + return false; -bool TString::EndsWith(const wchar_t* pszText) const -{ - if(!m_pszData || !pszText) - return false; + return boost::ends_with(m_pszData, pszText); + } - return boost::ends_with(m_pszData, pszText); -} + bool TString::EndsWithNoCase(const wchar_t* pszText) const + { + if (!m_pszData || !pszText) + return false; -bool TString::EndsWithNoCase(const wchar_t* pszText) const -{ - if(!m_pszData || !pszText) - return false; + return boost::iends_with(m_pszData, pszText); + } - return boost::iends_with(m_pszData, pszText); -} + size_t TString::FindFirstOf(const wchar_t* pszChars, size_t stStartFromPos) const + { + if (!m_pszData || !pszChars) + return npos; -size_t TString::FindFirstOf(const wchar_t* pszChars, size_t stStartFromPos) const -{ - if(!m_pszData || !pszChars) + size_t stCurrentLength = GetLength(); + for (size_t stIndex = stStartFromPos; stIndex < stCurrentLength; ++stIndex) + { + if (wcschr(pszChars, m_pszData[stIndex])) + return stIndex; + } + return npos; + } - size_t stCurrentLength = GetLength(); - for(size_t stIndex = stStartFromPos; stIndex < stCurrentLength; ++stIndex) + size_t TString::FindLastOf(const wchar_t* pszChars) const { - if(wcschr(pszChars, m_pszData[stIndex])) - return stIndex; - } + if (!m_pszData || !pszChars) + return npos; - return npos; -} + for (size_t stIndex = GetLength(); stIndex != 0; --stIndex) + { + if (wcschr(pszChars, m_pszData[stIndex - 1])) + return stIndex - 1; + } -size_t TString::FindLastOf(const wchar_t* pszChars) const -{ - if(!m_pszData || !pszChars) return npos; + } - for(size_t stIndex = GetLength(); stIndex != 0; --stIndex) + size_t TString::Find(const wchar_t* pszFindText, size_t stStartPos) { - if(wcschr(pszChars, m_pszData[stIndex - 1])) - return stIndex - 1; - } + size_t stThisLen = GetLength(); + if (!pszFindText || stThisLen == 0) + return npos; - return npos; -} + size_t stFindTextLen = _tcslen(pszFindText); + if (stFindTextLen > stThisLen) + return TString::npos; -size_t TString::Find(const wchar_t* pszFindText, size_t stStartPos) -{ - size_t stThisLen = GetLength(); - if(!pszFindText || stThisLen == 0) - return npos; + if (stStartPos > stThisLen - stFindTextLen) + return TString::npos; - size_t stFindTextLen = _tcslen(pszFindText); - if(stFindTextLen > stThisLen) - return TString::npos; + boost::iterator_range rangeText = boost::make_iterator_range(m_pszData + stStartPos, m_pszData + stThisLen); + boost::iterator_range rangeFind = boost::find_first(rangeText, pszFindText); - if(stStartPos > stThisLen - stFindTextLen) - return TString::npos; + if (rangeFind.begin() != rangeText.end()) + return rangeFind.begin() - rangeText.begin() + stStartPos; + else + return TString::npos; + } - boost::iterator_range rangeText = boost::make_iterator_range(m_pszData + stStartPos, m_pszData + stThisLen); - boost::iterator_range rangeFind = boost::find_first(rangeText, pszFindText); + void TString::Replace(const wchar_t* pszWhat, const wchar_t* pszWithWhat) + { + size_t stThisLen = GetLength(); + if (stThisLen == 0) + return; - if(rangeFind.begin() != rangeText.end()) - return rangeFind.begin() - rangeText.begin() + stStartPos; - else - return TString::npos; -} + if (!pszWhat || !pszWithWhat) + return; -void TString::Replace(const wchar_t* pszWhat, const wchar_t* pszWithWhat) -{ - size_t stThisLen = GetLength(); - if(stThisLen == 0) - return; + // find all occurrences of pszWhat in this string, so we can calculate new required size of the string + size_t stWhatLen = _tcslen(pszWhat); + size_t stWithWhatLen = _tcslen(pszWithWhat); - if(!pszWhat || !pszWithWhat) - return; + size_t stNewLen = stThisLen; - // find all occurrences of pszWhat in this string, so we can calculate new required size of the string - size_t stWhatLen = _tcslen(pszWhat); - size_t stWithWhatLen = _tcslen(pszWithWhat); + // resize internal string if needed + if (stWithWhatLen > stWhatLen) + { + size_t stStartPos = 0; + size_t stFindPos = 0; + size_t stSizeDiff = 0; + while ((stFindPos = Find(pszWhat, stStartPos)) != npos) + { + stSizeDiff += stWithWhatLen - stWhatLen; + stStartPos = stFindPos + stWhatLen; // offset by what_len because we don't replace anything at this point + } - size_t stNewLen = stThisLen; + if (stSizeDiff > 0) + stNewLen = stThisLen + stSizeDiff + 1; + } - // resize internal string if needed - if(stWithWhatLen > stWhatLen) - { + Reserve(stNewLen); + + // replace size_t stStartPos = 0; size_t stFindPos = 0; - size_t stSizeDiff = 0; - while((stFindPos = Find(pszWhat, stStartPos)) != npos) + while ((stFindPos = Find(pszWhat, stStartPos)) != npos) { - stSizeDiff += stWithWhatLen - stWhatLen; - stStartPos = stFindPos + stWhatLen; // offset by what_len because we don't replace anything at this point - } + // Sample string "ABCdddb" (len:6), searching for "dd" (len 2) to replace with "x" (len 1) + // found string pos is: [stFindPos, stFindPos + stWhatLen) -- sample ref: [3, 3 + 2) + // we need to + // - move string from position [stFindPos + stWhatLen, stCurrentLength) to position [stFindPos + stWithWhatLen, stCurrentLength + stWithWhatLen - stWhatLen] -- sample ref: [3+2, 6) to [3+1, 5) + size_t stCountToCopy = stThisLen - stFindPos - stWhatLen + 1; - if(stSizeDiff > 0) - stNewLen = stThisLen + stSizeDiff + 1; - } + memmove_s((void*)(m_pszData + stFindPos + stWithWhatLen), stCountToCopy * sizeof(wchar_t), (void*)(m_pszData + stFindPos + stWhatLen), stCountToCopy * sizeof(wchar_t)); - Reserve(stNewLen); + // - copy pszWithWhat to position (stFindPos + stWhatLen) + memcpy_s((void*)(m_pszData + stFindPos), stWithWhatLen * sizeof(wchar_t), pszWithWhat, stWithWhatLen * sizeof(wchar_t)); - // replace - size_t stStartPos = 0; - size_t stFindPos = 0; - while((stFindPos = Find(pszWhat, stStartPos)) != npos) - { - // Sample string "ABCdddb" (len:6), searching for "dd" (len 2) to replace with "x" (len 1) - // found string pos is: [stFindPos, stFindPos + stWhatLen) -- sample ref: [3, 3 + 2) - // we need to - // - move string from position [stFindPos + stWhatLen, stCurrentLength) to position [stFindPos + stWithWhatLen, stCurrentLength + stWithWhatLen - stWhatLen] -- sample ref: [3+2, 6) to [3+1, 5) - size_t stCountToCopy = stThisLen - stFindPos - stWhatLen + 1; - - memmove_s((void*)(m_pszData + stFindPos + stWithWhatLen), stCountToCopy * sizeof(wchar_t), (void*)(m_pszData + stFindPos + stWhatLen), stCountToCopy * sizeof(wchar_t)); - - // - copy pszWithWhat to position (stFindPos + stWhatLen) - memcpy_s((void*)(m_pszData + stFindPos), stWithWhatLen * sizeof(wchar_t), pszWithWhat, stWithWhatLen * sizeof(wchar_t)); - - stStartPos = stFindPos + stWithWhatLen; // offset by stWithWhatLen because we replaced text + stStartPos = stFindPos + stWithWhatLen; // offset by stWithWhatLen because we replaced text + } } -} -/** Returns a character at a given position. Function is very slow (needs to recalc the size of the TString - * and make a few comparisons), but quite safe - if the index is out of range then -1 is returned. - * Make sure to interpret the returned character according to unicode flag. If the TString is unicode, then the - * character returned is also unicode (and vice versa). - * \param[in] tPos - index of the character to return. - * \return Character code of character on a specified position, or -1 if out of range. - */ -bool TString::GetAt(size_t tPos, wchar_t& wch) const -{ - if(tPos < GetLength()) + /** Returns a character at a given position. Function is very slow (needs to recalc the size of the TString + * and make a few comparisons), but quite safe - if the index is out of range then -1 is returned. + * Make sure to interpret the returned character according to unicode flag. If the TString is unicode, then the + * character returned is also unicode (and vice versa). + * \param[in] tPos - index of the character to return. + * \return Character code of character on a specified position, or -1 if out of range. + */ + bool TString::GetAt(size_t tPos, wchar_t& wch) const { - wch = m_pszData[tPos]; - return true; + if (tPos < GetLength()) + { + wch = m_pszData[tPos]; + return true; + } + else + { + wch = L'\0'; + return false; + } } - else + + wchar_t TString::GetAt(size_t tPos) const { - wch = L'\0'; - return false; + if (tPos < GetLength()) + return m_pszData[tPos]; + else + return L'\0'; } -} -wchar_t TString::GetAt(size_t tPos) const -{ - if(tPos < GetLength()) - return m_pszData[tPos]; - else - return L'\0'; -} + /** Returns a pointer to the unicode internal buffer. If the buffer is in ansi format + * then NULL value is returned. Internal buffer is resized to the specified value + * if currently smaller than requested (if -1 is specified as tMinSize then the buffer + * is not resized, and the return value could be NULL). + * \param[in] tMinSize - requested minimal size of the internal buffer (-1 if the size of the TString should not be changed) + * \return Pointer to the internal unicode buffer. + */ + wchar_t* TString::GetBuffer(size_t tMinSize) + { + Reserve(tMinSize + 1); -/** Returns a pointer to the unicode internal buffer. If the buffer is in ansi format - * then NULL value is returned. Internal buffer is resized to the specified value - * if currently smaller than requested (if -1 is specified as tMinSize then the buffer - * is not resized, and the return value could be NULL). - * \param[in] tMinSize - requested minimal size of the internal buffer (-1 if the size of the TString should not be changed) - * \return Pointer to the internal unicode buffer. - */ -wchar_t* TString::GetBuffer(size_t tMinSize) -{ - Reserve(tMinSize + 1); + return m_pszData; + } - return m_pszData; -} + /** Releases buffer got by user by calling get_bufferx functions. The current + * job of this function is to make sure the TString will terminate with null + * character at the end of the buffer. + */ + void TString::ReleaseBuffer() + { + m_pszData[m_stBufferSize - 1] = L'\0'; + } -/** Releases buffer got by user by calling get_bufferx functions. The current - * job of this function is to make sure the TString will terminate with null - * character at the end of the buffer. - */ -void TString::ReleaseBuffer() -{ - m_pszData[m_stBufferSize - 1] = L'\0'; -} + void TString::ReleaseBufferSetLength(size_t tSize) + { + Reserve(tSize + 1); -void TString::ReleaseBufferSetLength(size_t tSize) -{ - Reserve(tSize + 1); + m_pszData[tSize] = L'\0'; + } - m_pszData[tSize] = L'\0'; -} - -void TString::SetString(const wchar_t* pszStart, size_t stCount) -{ - if(!pszStart || stCount == 0) - Clear(); - else + void TString::SetString(const wchar_t* pszStart, size_t stCount) { - Reserve(stCount + 1); + if (!pszStart || stCount == 0) + Clear(); + else + { + Reserve(stCount + 1); - wcsncpy_s(m_pszData, m_stBufferSize, pszStart, stCount); - m_pszData[stCount] = _T('\0'); + wcsncpy_s(m_pszData, m_stBufferSize, pszStart, stCount); + m_pszData[stCount] = _T('\0'); + } } -} -void TString::SetString(const wchar_t* pszString) -{ - if(!pszString) - Clear(); - else + void TString::SetString(const wchar_t* pszString) { - size_t stLen = _tcslen(pszString); - SetString(pszString, stLen); + if (!pszString) + Clear(); + else + { + size_t stLen = _tcslen(pszString); + SetString(pszString, stLen); + } } -} -void TString::Reserve(size_t stLen) -{ - if(m_stBufferSize < stLen) + void TString::Reserve(size_t stLen) { - size_t stNewLen = stLen;//ROUNDUP(stLen, CHUNK_INCSIZE); + if (m_stBufferSize < stLen) + { + size_t stNewLen = stLen;//ROUNDUP(stLen, CHUNK_INCSIZE); - wchar_t* pszNewBuffer = new wchar_t[stNewLen]; - if(m_pszData && m_pszData[0] != L'\0') - _tcsncpy_s(pszNewBuffer, stNewLen, m_pszData, GetLength() + 1); - else - pszNewBuffer[0] = _T('\0'); + wchar_t* pszNewBuffer = new wchar_t[stNewLen]; + if (m_pszData && m_pszData[0] != L'\0') + _tcsncpy_s(pszNewBuffer, stNewLen, m_pszData, GetLength() + 1); + else + pszNewBuffer[0] = _T('\0'); - delete [] m_pszData; - m_pszData = pszNewBuffer; - m_stBufferSize = stNewLen; + delete[] m_pszData; + m_pszData = pszNewBuffer; + m_stBufferSize = stNewLen; + } } -} -const wchar_t* TString::c_str() const -{ - return m_pszData ? m_pszData : L""; + const wchar_t* TString::c_str() const + { + return m_pszData ? m_pszData : L""; + } } -END_CHCORE_NAMESPACE - chcore::TString operator+(const wchar_t* pszString, const chcore::TString& str) { chcore::TString strNew(pszString); Index: src/libchcore/TString.h =================================================================== diff -u -N -r2755e12daeccb1935f569e7235e685e566b0b098 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TString.h (.../TString.h) (revision 2755e12daeccb1935f569e7235e685e566b0b098) +++ src/libchcore/TString.h (.../TString.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -27,147 +27,146 @@ #include #include -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + class TStringArray; -class TStringArray; + /////////////////////////////////////////////////////////////// + // TString manipulation class + /** \brief String manipulation class + * + * Class allows user to manipulate TString objects (either standard ANSI char_t* + * based strings or UNICODE ones - wchar_t related) with simple functions and + * operators. + */ + class LIBCHCORE_API TString + { + public: + /** \name Construction/destruction */ + /*@{*/ + TString(); ///< Standard constructor + TString(const wchar_t* pszStr); ///< Constructor that takes const wchar_t* as an initial TString + TString(const wchar_t* pszStart, const wchar_t* pszEnd, size_t stMaxStringSize = DefaultMaxStringSize); + TString(const wchar_t* pszStart, size_t stCount); + TString(const TString& str); ///< Standard copy constructor -/////////////////////////////////////////////////////////////// -// TString manipulation class -/** \brief String manipulation class - * - * Class allows user to manipulate TString objects (either standard ANSI char_t* - * based strings or UNICODE ones - wchar_t related) with simple functions and - * operators. - */ -class LIBCHCORE_API TString -{ -public: -/** \name Construction/destruction */ -/*@{*/ - TString(); ///< Standard constructor - TString(const wchar_t* pszStr); ///< Constructor that takes const wchar_t* as an initial TString - TString(const wchar_t* pszStart, const wchar_t* pszEnd, size_t stMaxStringSize = DefaultMaxStringSize); - TString(const wchar_t* pszStart, size_t stCount); - TString(const TString& str); ///< Standard copy constructor - - ~TString(); ///< Standard destructor -/*@}*/ + ~TString(); ///< Standard destructor + /*@}*/ -/** \name Operators */ -/**@{*/ - // assignment - TString& operator=(const TString& src); ///< Assign operator for TString objects - TString operator+(const TString& src) const; ///< Concatenate operator for TString objects - const TString& operator+=(const TString& src); ///< Merge operator for TString objects - - const TString& operator=(const wchar_t* pszSrc); ///< Assign operator from unicode strings - TString operator+(const wchar_t* pszSrc) const; ///< Concatenate operator for unicode strings - const TString& operator+=(const wchar_t* pszSrc); ///< Merge operator for unicode strings - - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator<(const wchar_t* psz) const { return Compare(psz) < 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator<=(const wchar_t* psz) const { return Compare(psz) <= 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator==(const wchar_t* psz) const { return Compare(psz) == 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator>=(const wchar_t* psz) const { return Compare(psz) >= 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator>(const wchar_t* psz) const { return Compare(psz) > 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator!=(const wchar_t* psz) const { return Compare(psz) != 0; }; - - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator<(const TString& str) const { return Compare(str) < 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator<=(const TString& str) const { return Compare(str) <= 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator==(const TString& str) const { return Compare(str) == 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator>=(const TString& str) const { return Compare(str) >= 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator>(const TString& str) const { return Compare(str) >= 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator!=(const TString& str) const { return Compare(str) != 0; }; -/**@}*/ + /** \name Operators */ + /**@{*/ + // assignment + TString& operator=(const TString& src); ///< Assign operator for TString objects + TString operator+(const TString& src) const; ///< Concatenate operator for TString objects + const TString& operator+=(const TString& src); ///< Merge operator for TString objects -/** \name Standard operations */ -/**@{*/ - // appends the given TString to this - void Append(const wchar_t* pszSrc); ///< Appends an unicode TString to the TString object - void Append(const TString& src); ///< Appends a TString object to another TString object - - TString Left(size_t tLen) const; ///< Returns TString with the Left part of a source TString - TString Right(size_t tLen) const; ///< Returns TString with the Right part of a source TString - TString Mid(size_t tStart, size_t tLen = (size_t)-1) const; ///< Returns TString with the middle part of a source TString - TString MidRange(size_t tStart, size_t stAfterEndPos) const; ///< Returns TString with the middle part of a source TString - - void LeftSelf(size_t tLen); ///< Makes this TString it's Left part - void RightSelf(size_t tLen); ///< Makes this TString it's Right part - void MidSelf(size_t tStart, size_t tLen = (size_t)-1); ///< Makes this TString it's middle part - - void TrimRightSelf(const wchar_t* pszElements); + const TString& operator=(const wchar_t* pszSrc); ///< Assign operator from unicode strings + TString operator+(const wchar_t* pszSrc) const; ///< Concatenate operator for unicode strings + const TString& operator+=(const wchar_t* pszSrc); ///< Merge operator for unicode strings - bool Delete(size_t stIndex, size_t stCount); + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator<(const wchar_t* psz) const { return Compare(psz) < 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator<=(const wchar_t* psz) const { return Compare(psz) <= 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator==(const wchar_t* psz) const { return Compare(psz) == 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator>=(const wchar_t* psz) const { return Compare(psz) >= 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator>(const wchar_t* psz) const { return Compare(psz) > 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator!=(const wchar_t* psz) const { return Compare(psz) != 0; }; - void Split(const wchar_t* pszSeparators, TStringArray& rStrings) const; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator<(const TString& str) const { return Compare(str) < 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator<=(const TString& str) const { return Compare(str) <= 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator==(const TString& str) const { return Compare(str) == 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator>=(const TString& str) const { return Compare(str) >= 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator>(const TString& str) const { return Compare(str) >= 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator!=(const TString& str) const { return Compare(str) != 0; }; + /**@}*/ - // compare operations - int_t Compare(const wchar_t* psz) const; ///< Comparison of this TString object with a given unicode TString - int_t Compare(const TString& str) const; ///< Comparison of this TString object with another TString object - - int_t CompareNoCase(const wchar_t* psz) const; ///< Comparison (case insensitive) of this TString object with a given unicode TString - int_t CompareNoCase(const TString& str) const; ///< Comparison (case insensitive) of this TString object with another TString object + /** \name Standard operations */ + /**@{*/ + // appends the given TString to this + void Append(const wchar_t* pszSrc); ///< Appends an unicode TString to the TString object + void Append(const TString& src); ///< Appends a TString object to another TString object - bool StartsWith(const wchar_t* pszText) const; - bool StartsWithNoCase(const wchar_t* pszText) const; + TString Left(size_t tLen) const; ///< Returns TString with the Left part of a source TString + TString Right(size_t tLen) const; ///< Returns TString with the Right part of a source TString + TString Mid(size_t tStart, size_t tLen = (size_t)-1) const; ///< Returns TString with the middle part of a source TString + TString MidRange(size_t tStart, size_t stAfterEndPos) const; ///< Returns TString with the middle part of a source TString - bool EndsWith(const wchar_t* pszText) const; - bool EndsWithNoCase(const wchar_t* pszText) const; + void LeftSelf(size_t tLen); ///< Makes this TString it's Left part + void RightSelf(size_t tLen); ///< Makes this TString it's Right part + void MidSelf(size_t tStart, size_t tLen = (size_t)-1); ///< Makes this TString it's middle part - size_t FindFirstOf(const wchar_t* pszChars, size_t stStartFromPos = 0) const; - size_t FindLastOf(const wchar_t* pszChars) const; + void TrimRightSelf(const wchar_t* pszElements); - size_t Find(const wchar_t* pszText, size_t stStartPos = 0); - void Replace(const wchar_t* pszWhat, const wchar_t* pszWithWhat); + bool Delete(size_t stIndex, size_t stCount); - bool GetAt(size_t tPos, wchar_t& wch) const; ///< Gets a character at a specified position - wchar_t GetAt(size_t tPos) const; + void Split(const wchar_t* pszSeparators, TStringArray& rStrings) const; - const wchar_t* c_str() const; + // compare operations + int_t Compare(const wchar_t* psz) const; ///< Comparison of this TString object with a given unicode TString + int_t Compare(const TString& str) const; ///< Comparison of this TString object with another TString object - wchar_t* GetBuffer(size_t tMinSize); ///< Gives user access to the unicode internal buffer - void ReleaseBuffer(); ///< Releases the buffer get from get_bufferx functions - void ReleaseBufferSetLength(size_t tSize); - - size_t GetLength() const; ///< Returns the GetLength of this TString in chars + int_t CompareNoCase(const wchar_t* psz) const; ///< Comparison (case insensitive) of this TString object with a given unicode TString + int_t CompareNoCase(const TString& str) const; ///< Comparison (case insensitive) of this TString object with another TString object - void Clear(); ///< Clear the contents of the TString object + bool StartsWith(const wchar_t* pszText) const; + bool StartsWithNoCase(const wchar_t* pszText) const; - bool IsEmpty() const; ///< Returns true if the TString is empty -/**@}*/ + bool EndsWith(const wchar_t* pszText) const; + bool EndsWithNoCase(const wchar_t* pszText) const; -protected: - void SetString(const wchar_t* pszStart, size_t stCount); - void SetString(const wchar_t* pszString); - void Reserve(size_t stLen); + size_t FindFirstOf(const wchar_t* pszChars, size_t stStartFromPos = 0) const; + size_t FindLastOf(const wchar_t* pszChars) const; -protected: - wchar_t* m_pszData; // contains the real string inside - size_t m_stBufferSize; // allocated string buffer size + size_t Find(const wchar_t* pszText, size_t stStartPos = 0); + void Replace(const wchar_t* pszWhat, const wchar_t* pszWithWhat); -public: - static const size_t npos = (size_t)-1; - static const size_t DefaultMaxStringSize = 65536; -}; + bool GetAt(size_t tPos, wchar_t& wch) const; ///< Gets a character at a specified position + wchar_t GetAt(size_t tPos) const; -inline std::wostream& operator<<(std::wostream& os, const TString& rString) -{ - return os << std::wstring(rString.c_str()); -} + const wchar_t* c_str() const; -END_CHCORE_NAMESPACE + wchar_t* GetBuffer(size_t tMinSize); ///< Gives user access to the unicode internal buffer + void ReleaseBuffer(); ///< Releases the buffer get from get_bufferx functions + void ReleaseBufferSetLength(size_t tSize); + size_t GetLength() const; ///< Returns the GetLength of this TString in chars + + void Clear(); ///< Clear the contents of the TString object + + bool IsEmpty() const; ///< Returns true if the TString is empty + /**@}*/ + + protected: + void SetString(const wchar_t* pszStart, size_t stCount); + void SetString(const wchar_t* pszString); + void Reserve(size_t stLen); + + protected: + wchar_t* m_pszData; // contains the real string inside + size_t m_stBufferSize; // allocated string buffer size + + public: + static const size_t npos = (size_t)-1; + static const size_t DefaultMaxStringSize = 65536; + }; + + inline std::wostream& operator<<(std::wostream& os, const TString& rString) + { + return os << std::wstring(rString.c_str()); + } +} + LIBCHCORE_API chcore::TString operator+(const wchar_t* pszString, const chcore::TString& str); #endif Index: src/libchcore/TStringArray.cpp =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringArray.cpp (.../TStringArray.cpp) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TStringArray.cpp (.../TStringArray.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,211 +25,210 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// class TStringArrayIterator - -TStringArrayIterator::TStringArrayIterator(std::vector::iterator iterArray) : - m_iterArray(iterArray) +namespace chcore { -} + /////////////////////////////////////////////////////////////////////////////////////////////////////// + // class TStringArrayIterator -TStringArrayIterator::TStringArrayIterator() -{ -} + TStringArrayIterator::TStringArrayIterator(std::vector::iterator iterArray) : + m_iterArray(iterArray) + { + } -TStringArrayIterator::~TStringArrayIterator() -{ -} + TStringArrayIterator::TStringArrayIterator() + { + } -TStringArrayIterator TStringArrayIterator::operator++(int) -{ - TStringArrayIterator iterCurrent = *this; - ++m_iterArray; - return iterCurrent; -} + TStringArrayIterator::~TStringArrayIterator() + { + } -TStringArrayIterator& TStringArrayIterator::operator++() -{ - ++m_iterArray; - return *this; -} + TStringArrayIterator TStringArrayIterator::operator++(int) + { + TStringArrayIterator iterCurrent = *this; + ++m_iterArray; + return iterCurrent; + } -bool TStringArrayIterator::operator==(const TStringArrayIterator& rSrc) const -{ - return m_iterArray == rSrc.m_iterArray; -} + TStringArrayIterator& TStringArrayIterator::operator++() + { + ++m_iterArray; + return *this; + } -bool TStringArrayIterator::operator!=(const TStringArrayIterator& rSrc) const -{ - return m_iterArray != rSrc.m_iterArray; -} + bool TStringArrayIterator::operator==(const TStringArrayIterator& rSrc) const + { + return m_iterArray == rSrc.m_iterArray; + } -TString& TStringArrayIterator::operator*() -{ - return *m_iterArray; -} + bool TStringArrayIterator::operator!=(const TStringArrayIterator& rSrc) const + { + return m_iterArray != rSrc.m_iterArray; + } -const TString& TStringArrayIterator::operator*() const -{ - return *m_iterArray; -} + TString& TStringArrayIterator::operator*() + { + return *m_iterArray; + } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// class TStringArrayConstIterator + const TString& TStringArrayIterator::operator*() const + { + return *m_iterArray; + } -TStringArrayConstIterator::TStringArrayConstIterator(std::vector::const_iterator iterArray) : - m_iterArray(iterArray) -{ -} + /////////////////////////////////////////////////////////////////////////////////////////////////////// + // class TStringArrayConstIterator -TStringArrayConstIterator::TStringArrayConstIterator() -{ -} + TStringArrayConstIterator::TStringArrayConstIterator(std::vector::const_iterator iterArray) : + m_iterArray(iterArray) + { + } -TStringArrayConstIterator::~TStringArrayConstIterator() -{ -} + TStringArrayConstIterator::TStringArrayConstIterator() + { + } -TStringArrayConstIterator TStringArrayConstIterator::operator++(int) -{ - TStringArrayConstIterator iterCurrent = *this; - ++m_iterArray; - return iterCurrent; -} + TStringArrayConstIterator::~TStringArrayConstIterator() + { + } -TStringArrayConstIterator& TStringArrayConstIterator::operator++() -{ - ++m_iterArray; - return *this; -} + TStringArrayConstIterator TStringArrayConstIterator::operator++(int) + { + TStringArrayConstIterator iterCurrent = *this; + ++m_iterArray; + return iterCurrent; + } -bool TStringArrayConstIterator::operator==(const TStringArrayConstIterator& rSrc) const -{ - return m_iterArray == rSrc.m_iterArray; -} + TStringArrayConstIterator& TStringArrayConstIterator::operator++() + { + ++m_iterArray; + return *this; + } -bool TStringArrayConstIterator::operator!=(const TStringArrayConstIterator& rSrc) const -{ - return m_iterArray != rSrc.m_iterArray; -} + bool TStringArrayConstIterator::operator==(const TStringArrayConstIterator& rSrc) const + { + return m_iterArray == rSrc.m_iterArray; + } -const TString& TStringArrayConstIterator::operator*() -{ - return *m_iterArray; -} + bool TStringArrayConstIterator::operator!=(const TStringArrayConstIterator& rSrc) const + { + return m_iterArray != rSrc.m_iterArray; + } -const TString& TStringArrayConstIterator::operator*() const -{ - return *m_iterArray; -} + const TString& TStringArrayConstIterator::operator*() + { + return *m_iterArray; + } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// class TStringArray -TStringArray::TStringArray() -{ -} + const TString& TStringArrayConstIterator::operator*() const + { + return *m_iterArray; + } -TStringArray::~TStringArray() -{ -} + /////////////////////////////////////////////////////////////////////////////////////////////////////// + // class TStringArray + TStringArray::TStringArray() + { + } -void TStringArray::Add(const TString& str) -{ - m_vItems.push_back(str); -} + TStringArray::~TStringArray() + { + } -void TStringArray::InsertAt(size_t stIndex, const TString& str) -{ - if(stIndex >= m_vItems.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + void TStringArray::Add(const TString& str) + { + m_vItems.push_back(str); + } - m_vItems.insert(m_vItems.begin() + stIndex, str); -} + void TStringArray::InsertAt(size_t stIndex, const TString& str) + { + if (stIndex >= m_vItems.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -void TStringArray::SetAt(size_t stIndex, const TString& str) -{ - if(stIndex >= m_vItems.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + m_vItems.insert(m_vItems.begin() + stIndex, str); + } - m_vItems[stIndex] = str; -} + void TStringArray::SetAt(size_t stIndex, const TString& str) + { + if (stIndex >= m_vItems.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -void TStringArray::RemoveAt(size_t stIndex) -{ - if(stIndex >= m_vItems.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + m_vItems[stIndex] = str; + } - m_vItems.erase(m_vItems.begin() + stIndex); -} + void TStringArray::RemoveAt(size_t stIndex) + { + if (stIndex >= m_vItems.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -void TStringArray::Clear() -{ - m_vItems.clear(); -} + m_vItems.erase(m_vItems.begin() + stIndex); + } -const TString& TStringArray::GetAt(size_t stIndex) const -{ - if(stIndex >= m_vItems.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + void TStringArray::Clear() + { + m_vItems.clear(); + } - return m_vItems.at(stIndex); -} + const TString& TStringArray::GetAt(size_t stIndex) const + { + if (stIndex >= m_vItems.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -size_t TStringArray::GetCount() const -{ - return m_vItems.size(); -} + return m_vItems.at(stIndex); + } -TStringArrayIterator TStringArray::Begin() -{ - return TStringArrayIterator(m_vItems.begin()); -} + size_t TStringArray::GetCount() const + { + return m_vItems.size(); + } -TStringArrayIterator TStringArray::End() -{ - return TStringArrayIterator(m_vItems.end()); -} + TStringArrayIterator TStringArray::Begin() + { + return TStringArrayIterator(m_vItems.begin()); + } -TStringArrayConstIterator TStringArray::Begin() const -{ - return TStringArrayConstIterator(m_vItems.begin()); -} + TStringArrayIterator TStringArray::End() + { + return TStringArrayIterator(m_vItems.end()); + } -TStringArrayConstIterator TStringArray::End() const -{ - return TStringArrayConstIterator(m_vItems.end()); -} + TStringArrayConstIterator TStringArray::Begin() const + { + return TStringArrayConstIterator(m_vItems.begin()); + } -bool TStringArray::operator==(const TStringArray& rSrc) const -{ - if(rSrc.GetCount() != GetCount()) - return false; + TStringArrayConstIterator TStringArray::End() const + { + return TStringArrayConstIterator(m_vItems.end()); + } - size_t stCount = GetCount(); - while(stCount-- > 0) + bool TStringArray::operator==(const TStringArray& rSrc) const { - if(m_vItems[stCount] != rSrc.m_vItems[stCount]) + if (rSrc.GetCount() != GetCount()) return false; - } - return true; -} + size_t stCount = GetCount(); + while (stCount-- > 0) + { + if (m_vItems[stCount] != rSrc.m_vItems[stCount]) + return false; + } -bool TStringArray::operator!=(const TStringArray& rSrc) const -{ - if(rSrc.GetCount() != GetCount()) return true; + } - size_t stCount = GetCount(); - while(stCount-- > 0) + bool TStringArray::operator!=(const TStringArray& rSrc) const { - if(m_vItems[stCount] != rSrc.m_vItems[stCount]) + if (rSrc.GetCount() != GetCount()) return true; - } - return false; -} + size_t stCount = GetCount(); + while (stCount-- > 0) + { + if (m_vItems[stCount] != rSrc.m_vItems[stCount]) + return true; + } -END_CHCORE_NAMESPACE + return false; + } +} Index: src/libchcore/TStringArray.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringArray.h (.../TStringArray.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TStringArray.h (.../TStringArray.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,96 +26,95 @@ #include "TString.h" #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TStringArrayIterator +namespace chcore { -protected: - TStringArrayIterator(std::vector::iterator iterArray); + class LIBCHCORE_API TStringArrayIterator + { + protected: + TStringArrayIterator(std::vector::iterator iterArray); -public: - TStringArrayIterator(); - ~TStringArrayIterator(); + public: + TStringArrayIterator(); + ~TStringArrayIterator(); - TStringArrayIterator operator++(int); - TStringArrayIterator& operator++(); + TStringArrayIterator operator++(int); + TStringArrayIterator& operator++(); - bool operator==(const TStringArrayIterator& rSrc) const; - bool operator!=(const TStringArrayIterator& rSrc) const; + bool operator==(const TStringArrayIterator& rSrc) const; + bool operator!=(const TStringArrayIterator& rSrc) const; - TString& operator*(); - const TString& operator*() const; + TString& operator*(); + const TString& operator*() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::vector::iterator m_iterArray; + std::vector::iterator m_iterArray; #pragma warning(pop) - friend class TStringArray; -}; + friend class TStringArray; + }; -class LIBCHCORE_API TStringArrayConstIterator -{ -protected: - TStringArrayConstIterator(std::vector::const_iterator iterArray); + class LIBCHCORE_API TStringArrayConstIterator + { + protected: + TStringArrayConstIterator(std::vector::const_iterator iterArray); -public: - TStringArrayConstIterator(); - ~TStringArrayConstIterator(); + public: + TStringArrayConstIterator(); + ~TStringArrayConstIterator(); - TStringArrayConstIterator operator++(int); - TStringArrayConstIterator& operator++(); + TStringArrayConstIterator operator++(int); + TStringArrayConstIterator& operator++(); - bool operator==(const TStringArrayConstIterator& rSrc) const; - bool operator!=(const TStringArrayConstIterator& rSrc) const; + bool operator==(const TStringArrayConstIterator& rSrc) const; + bool operator!=(const TStringArrayConstIterator& rSrc) const; - const TString& operator*(); - const TString& operator*() const; + const TString& operator*(); + const TString& operator*() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::vector::const_iterator m_iterArray; + std::vector::const_iterator m_iterArray; #pragma warning(pop) - friend class TStringArray; -}; + friend class TStringArray; + }; -class LIBCHCORE_API TStringArray -{ -public: - typedef TStringArrayIterator iterator; - typedef TStringArrayConstIterator const_iterator; + class LIBCHCORE_API TStringArray + { + public: + typedef TStringArrayIterator iterator; + typedef TStringArrayConstIterator const_iterator; -public: - TStringArray(); - ~TStringArray(); + public: + TStringArray(); + ~TStringArray(); - bool operator==(const TStringArray& rSrc) const; - bool operator!=(const TStringArray& rSrc) const; + bool operator==(const TStringArray& rSrc) const; + bool operator!=(const TStringArray& rSrc) const; - void Add(const TString& str); - void InsertAt(size_t stIndex, const TString& str); - void SetAt(size_t stIndex, const TString& str); - void RemoveAt(size_t stIndex); - void Clear(); + void Add(const TString& str); + void InsertAt(size_t stIndex, const TString& str); + void SetAt(size_t stIndex, const TString& str); + void RemoveAt(size_t stIndex); + void Clear(); - const TString& GetAt(size_t stIndex) const; - size_t GetCount() const; + const TString& GetAt(size_t stIndex) const; + size_t GetCount() const; - TStringArrayIterator Begin(); - TStringArrayIterator End(); - TStringArrayConstIterator Begin() const; - TStringArrayConstIterator End() const; + TStringArrayIterator Begin(); + TStringArrayIterator End(); + TStringArrayConstIterator Begin() const; + TStringArrayConstIterator End() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::vector m_vItems; + std::vector m_vItems; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TStringException.cpp =================================================================== diff -u -N -r8e19bdbb52f053c078c1a7f4e6938493374067af -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringException.cpp (.../TStringException.cpp) (revision 8e19bdbb52f053c078c1a7f4e6938493374067af) +++ src/libchcore/TStringException.cpp (.../TStringException.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -1,17 +1,15 @@ #include "stdafx.h" #include "TStringException.h" -BEGIN_CHCORE_NAMESPACE - -TStringException::TStringException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) +namespace chcore { -} + TStringException::TStringException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } -TStringException::TStringException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) -{ + TStringException::TStringException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } } - - -END_CHCORE_NAMESPACE Index: src/libchcore/TStringException.h =================================================================== diff -u -N -r8e19bdbb52f053c078c1a7f4e6938493374067af -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringException.h (.../TStringException.h) (revision 8e19bdbb52f053c078c1a7f4e6938493374067af) +++ src/libchcore/TStringException.h (.../TStringException.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,18 +26,17 @@ #define THROW_STRING_EXCEPTION(error_code, err_msg)\ throw TStringException(error_code, err_msg, __FILEW__, __LINE__, __FUNCTIONW__) -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TStringException : public TBaseException +namespace chcore { -public: - TStringException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TStringException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + class LIBCHCORE_API TStringException : public TBaseException + { + public: + TStringException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TStringException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); -private: - TStringException(); -}; + private: + TStringException(); + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TStringPattern.cpp =================================================================== diff -u -N -r5ccf162f73d05a43bbe5cb7c01d16d07b6b0d4d9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringPattern.cpp (.../TStringPattern.cpp) (revision 5ccf162f73d05a43bbe5cb7c01d16d07b6b0d4d9) +++ src/libchcore/TStringPattern.cpp (.../TStringPattern.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -4,130 +4,129 @@ #include "ErrorCodes.h" #include -BEGIN_CHCORE_NAMESPACE - -namespace +namespace chcore { - bool _tcicmp(TCHAR c1, TCHAR c2) + namespace { - TCHAR ch1[2] = { c1, 0 }, ch2[2] = { c2, 0 }; - return (_tcsicmp(ch1, ch2) == 0); + bool _tcicmp(TCHAR c1, TCHAR c2) + { + TCHAR ch1[2] = { c1, 0 }, ch2[2] = { c2, 0 }; + return (_tcsicmp(ch1, ch2) == 0); + } } -} -TStringPattern::TStringPattern(EPatternType ePatternType) : - m_ePatternType(ePatternType) -{ -} - -TStringPattern::TStringPattern(const TString& strPattern, EPatternType ePatternType) : - m_ePatternType(ePatternType), - m_strPattern(strPattern) -{ -} - -TString TStringPattern::ToSerializedString() const -{ - TString strPrefix; - switch (m_ePatternType) + TStringPattern::TStringPattern(EPatternType ePatternType) : + m_ePatternType(ePatternType) { - case EPatternType::eType_Wildcard: - strPrefix = L"WC;"; - break; - - default: - THROW_CORE_EXCEPTION(eErr_UnhandledCase); } - return TString(strPrefix + m_strPattern); -} - -void TStringPattern::FromSerializedString(const TString& strSerializedPattern) -{ - if (strSerializedPattern.StartsWith(L"WC;")) + TStringPattern::TStringPattern(const TString& strPattern, EPatternType ePatternType) : + m_ePatternType(ePatternType), + m_strPattern(strPattern) { - m_ePatternType = EPatternType::eType_Wildcard; - m_strPattern = strSerializedPattern.Mid(3); } - else - THROW_CORE_EXCEPTION(eErr_UnhandledCase); -} -TStringPattern TStringPattern::CreateFromSerializedString(const TString& strSerializedPattern) -{ - TStringPattern pattern; - pattern.FromSerializedString(strSerializedPattern); - return pattern; -} + TString TStringPattern::ToSerializedString() const + { + TString strPrefix; + switch (m_ePatternType) + { + case EPatternType::eType_Wildcard: + strPrefix = L"WC;"; + break; -bool TStringPattern::MatchMask(LPCTSTR lpszMask, LPCTSTR lpszString) const -{ - bool bMatch = 1; + default: + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } - //iterate and delete '?' and '*' one by one - while (*lpszMask != _T('\0') && bMatch && *lpszString != _T('\0')) + return TString(strPrefix + m_strPattern); + } + + void TStringPattern::FromSerializedString(const TString& strSerializedPattern) { - if (*lpszMask == _T('?')) lpszString++; - else if (*lpszMask == _T('*')) + if (strSerializedPattern.StartsWith(L"WC;")) { - bMatch = Scan(lpszMask, lpszString); - lpszMask--; + m_ePatternType = EPatternType::eType_Wildcard; + m_strPattern = strSerializedPattern.Mid(3); } else - { - bMatch = _tcicmp(*lpszMask, *lpszString); - lpszString++; - } - lpszMask++; + THROW_CORE_EXCEPTION(eErr_UnhandledCase); } - while (*lpszMask == _T('*') && bMatch) lpszMask++; - return bMatch && *lpszString == _T('\0') && *lpszMask == _T('\0'); -} + TStringPattern TStringPattern::CreateFromSerializedString(const TString& strSerializedPattern) + { + TStringPattern pattern; + pattern.FromSerializedString(strSerializedPattern); + return pattern; + } -// scan '?' and '*' -bool TStringPattern::Scan(LPCTSTR& lpszMask, LPCTSTR& lpszString) const -{ - // remove the '?' and '*' - for (lpszMask++; *lpszString != _T('\0') && (*lpszMask == _T('?') || *lpszMask == _T('*')); lpszMask++) - if (*lpszMask == _T('?')) lpszString++; - while (*lpszMask == _T('*')) lpszMask++; - - // if lpszString is empty and lpszMask has more characters or, - // lpszMask is empty, return - if (*lpszString == _T('\0') && *lpszMask != _T('\0')) return false; - if (*lpszString == _T('\0') && *lpszMask == _T('\0')) return true; - // else search substring - else + bool TStringPattern::MatchMask(LPCTSTR lpszMask, LPCTSTR lpszString) const { - LPCTSTR wdsCopy = lpszMask; - LPCTSTR lpszStringCopy = lpszString; - bool bMatch = true; - do + bool bMatch = 1; + + //iterate and delete '?' and '*' one by one + while (*lpszMask != _T('\0') && bMatch && *lpszString != _T('\0')) { - if (!MatchMask(lpszMask, lpszString)) lpszStringCopy++; - lpszMask = wdsCopy; - lpszString = lpszStringCopy; - while (!(_tcicmp(*lpszMask, *lpszString)) && (*lpszString != '\0')) lpszString++; - wdsCopy = lpszMask; - lpszStringCopy = lpszString; - } while ((*lpszString != _T('\0')) ? !MatchMask(lpszMask, lpszString) : (bMatch = false) != false); + if (*lpszMask == _T('?')) lpszString++; + else if (*lpszMask == _T('*')) + { + bMatch = Scan(lpszMask, lpszString); + lpszMask--; + } + else + { + bMatch = _tcicmp(*lpszMask, *lpszString); + lpszString++; + } + lpszMask++; + } + while (*lpszMask == _T('*') && bMatch) lpszMask++; + return bMatch && *lpszString == _T('\0') && *lpszMask == _T('\0'); + } + + // scan '?' and '*' + bool TStringPattern::Scan(LPCTSTR& lpszMask, LPCTSTR& lpszString) const + { + // remove the '?' and '*' + for (lpszMask++; *lpszString != _T('\0') && (*lpszMask == _T('?') || *lpszMask == _T('*')); lpszMask++) + if (*lpszMask == _T('?')) lpszString++; + while (*lpszMask == _T('*')) lpszMask++; + + // if lpszString is empty and lpszMask has more characters or, + // lpszMask is empty, return + if (*lpszString == _T('\0') && *lpszMask != _T('\0')) return false; if (*lpszString == _T('\0') && *lpszMask == _T('\0')) return true; + // else search substring + else + { + LPCTSTR wdsCopy = lpszMask; + LPCTSTR lpszStringCopy = lpszString; + bool bMatch = true; + do + { + if (!MatchMask(lpszMask, lpszString)) lpszStringCopy++; + lpszMask = wdsCopy; + lpszString = lpszStringCopy; + while (!(_tcicmp(*lpszMask, *lpszString)) && (*lpszString != '\0')) lpszString++; + wdsCopy = lpszMask; + lpszStringCopy = lpszString; + } while ((*lpszString != _T('\0')) ? !MatchMask(lpszMask, lpszString) : (bMatch = false) != false); - return bMatch; + if (*lpszString == _T('\0') && *lpszMask == _T('\0')) return true; + + return bMatch; + } } -} -bool TStringPattern::Matches(const TString& strTextToMatch) const -{ - return MatchMask(m_strPattern.c_str(), strTextToMatch.c_str()); -} + bool TStringPattern::Matches(const TString& strTextToMatch) const + { + return MatchMask(m_strPattern.c_str(), strTextToMatch.c_str()); + } -void TStringPattern::SetPattern(const TString& strPattern, EPatternType ePatternType) -{ - m_ePatternType = ePatternType; - m_strPattern = strPattern; + void TStringPattern::SetPattern(const TString& strPattern, EPatternType ePatternType) + { + m_ePatternType = ePatternType; + m_strPattern = strPattern; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TStringPattern.h =================================================================== diff -u -N -r5ccf162f73d05a43bbe5cb7c01d16d07b6b0d4d9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringPattern.h (.../TStringPattern.h) (revision 5ccf162f73d05a43bbe5cb7c01d16d07b6b0d4d9) +++ src/libchcore/TStringPattern.h (.../TStringPattern.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,41 +22,40 @@ #include "libchcore.h" #include "TString.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TStringPattern +namespace chcore { -public: - enum class EPatternType + class LIBCHCORE_API TStringPattern { - eType_Wildcard - }; + public: + enum class EPatternType + { + eType_Wildcard + }; -public: - explicit TStringPattern(EPatternType ePatternType = EPatternType::eType_Wildcard); - TStringPattern(const TString& strPattern, EPatternType ePatternType = EPatternType::eType_Wildcard); + public: + explicit TStringPattern(EPatternType ePatternType = EPatternType::eType_Wildcard); + TStringPattern(const TString& strPattern, EPatternType ePatternType = EPatternType::eType_Wildcard); - void SetPattern(const TString& strPattern, EPatternType ePatternType = EPatternType::eType_Wildcard); - bool Matches(const TString& strTextToMatch) const; + void SetPattern(const TString& strPattern, EPatternType ePatternType = EPatternType::eType_Wildcard); + bool Matches(const TString& strTextToMatch) const; - EPatternType GetPatternType() const { return m_ePatternType; } - TString GetPattern() const { return m_strPattern; } + EPatternType GetPatternType() const { return m_ePatternType; } + TString GetPattern() const { return m_strPattern; } - // serialization - static TStringPattern CreateFromSerializedString(const TString& strSerializedPattern); + // serialization + static TStringPattern CreateFromSerializedString(const TString& strSerializedPattern); - void FromSerializedString(const TString& strSerializedPattern); - TString ToSerializedString() const; + void FromSerializedString(const TString& strSerializedPattern); + TString ToSerializedString() const; -private: - bool MatchMask(LPCTSTR lpszMask, LPCTSTR lpszString) const; - bool Scan(LPCTSTR& lpszMask, LPCTSTR& lpszString) const; + private: + bool MatchMask(LPCTSTR lpszMask, LPCTSTR lpszString) const; + bool Scan(LPCTSTR& lpszMask, LPCTSTR& lpszString) const; -private: - TString m_strPattern; - EPatternType m_ePatternType; -}; + private: + TString m_strPattern; + EPatternType m_ePatternType; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TStringPatternArray.cpp =================================================================== diff -u -N -r5ccf162f73d05a43bbe5cb7c01d16d07b6b0d4d9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringPatternArray.cpp (.../TStringPatternArray.cpp) (revision 5ccf162f73d05a43bbe5cb7c01d16d07b6b0d4d9) +++ src/libchcore/TStringPatternArray.cpp (.../TStringPatternArray.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,104 +22,103 @@ #include "ErrorCodes.h" #include "TStringArray.h" -BEGIN_CHCORE_NAMESPACE - -TStringPatternArray::TStringPatternArray() +namespace chcore { -} + TStringPatternArray::TStringPatternArray() + { + } -TStringPatternArray::~TStringPatternArray() -{ -} + TStringPatternArray::~TStringPatternArray() + { + } -void TStringPatternArray::Add(const TStringPattern& strPattern) -{ - m_vPatterns.push_back(strPattern); -} + void TStringPatternArray::Add(const TStringPattern& strPattern) + { + m_vPatterns.push_back(strPattern); + } -void TStringPatternArray::InsertAt(size_t stIndex, const TStringPattern& strPattern) -{ - if (stIndex > m_vPatterns.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + void TStringPatternArray::InsertAt(size_t stIndex, const TStringPattern& strPattern) + { + if (stIndex > m_vPatterns.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - m_vPatterns.insert(m_vPatterns.begin() + stIndex, strPattern); -} + m_vPatterns.insert(m_vPatterns.begin() + stIndex, strPattern); + } -void TStringPatternArray::SetAt(size_t stIndex, const TStringPattern& strPattern) -{ - if (stIndex >= m_vPatterns.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + void TStringPatternArray::SetAt(size_t stIndex, const TStringPattern& strPattern) + { + if (stIndex >= m_vPatterns.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - m_vPatterns[stIndex] = strPattern; -} + m_vPatterns[stIndex] = strPattern; + } -void TStringPatternArray::RemoveAt(size_t stIndex) -{ - if (stIndex >= m_vPatterns.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + void TStringPatternArray::RemoveAt(size_t stIndex) + { + if (stIndex >= m_vPatterns.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - m_vPatterns.erase(m_vPatterns.begin() + stIndex); -} + m_vPatterns.erase(m_vPatterns.begin() + stIndex); + } -void TStringPatternArray::Clear() -{ - m_vPatterns.clear(); -} + void TStringPatternArray::Clear() + { + m_vPatterns.clear(); + } -const TStringPattern& TStringPatternArray::GetAt(size_t stIndex) const -{ - if (stIndex >= m_vPatterns.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + const TStringPattern& TStringPatternArray::GetAt(size_t stIndex) const + { + if (stIndex >= m_vPatterns.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - return m_vPatterns[stIndex]; -} + return m_vPatterns[stIndex]; + } -size_t TStringPatternArray::GetCount() const -{ - return m_vPatterns.size(); -} - -bool TStringPatternArray::MatchesAny(const TString& strTextToMatch) const -{ - for (const TStringPattern& pattern : m_vPatterns) + size_t TStringPatternArray::GetCount() const { - if (pattern.Matches(strTextToMatch)) - return true; + return m_vPatterns.size(); } - return false; -} - -bool TStringPatternArray::MatchesAll(const TString& strTextToMatch) const -{ - for (const TStringPattern& pattern : m_vPatterns) + bool TStringPatternArray::MatchesAny(const TString& strTextToMatch) const { - if (!pattern.Matches(strTextToMatch)) - return false; + for (const TStringPattern& pattern : m_vPatterns) + { + if (pattern.Matches(strTextToMatch)) + return true; + } + + return false; } - return true; -} + bool TStringPatternArray::MatchesAll(const TString& strTextToMatch) const + { + for (const TStringPattern& pattern : m_vPatterns) + { + if (!pattern.Matches(strTextToMatch)) + return false; + } -void TStringPatternArray::FromStringArray(const TStringArray& arrSerializedPatterns) -{ - m_vPatterns.clear(); + return true; + } - for (size_t stIndex = 0; stIndex < arrSerializedPatterns.GetCount(); ++stIndex) + void TStringPatternArray::FromStringArray(const TStringArray& arrSerializedPatterns) { - m_vPatterns.push_back(TStringPattern::CreateFromSerializedString(arrSerializedPatterns.GetAt(stIndex))); + m_vPatterns.clear(); + + for (size_t stIndex = 0; stIndex < arrSerializedPatterns.GetCount(); ++stIndex) + { + m_vPatterns.push_back(TStringPattern::CreateFromSerializedString(arrSerializedPatterns.GetAt(stIndex))); + } } -} -TStringArray TStringPatternArray::ToStringArray() const -{ - TStringArray arrSerialized; - for (const TStringPattern& pattern : m_vPatterns) + TStringArray TStringPatternArray::ToStringArray() const { - arrSerialized.Add(pattern.ToSerializedString()); - } + TStringArray arrSerialized; + for (const TStringPattern& pattern : m_vPatterns) + { + arrSerialized.Add(pattern.ToSerializedString()); + } - return arrSerialized; + return arrSerialized; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TStringPatternArray.h =================================================================== diff -u -N -r5ccf162f73d05a43bbe5cb7c01d16d07b6b0d4d9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringPatternArray.h (.../TStringPatternArray.h) (revision 5ccf162f73d05a43bbe5cb7c01d16d07b6b0d4d9) +++ src/libchcore/TStringPatternArray.h (.../TStringPatternArray.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,39 +22,38 @@ #include "libchcore.h" #include "TStringPattern.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TStringPatternArray +namespace chcore { -public: - TStringPatternArray(); - ~TStringPatternArray(); + class LIBCHCORE_API TStringPatternArray + { + public: + TStringPatternArray(); + ~TStringPatternArray(); - // general api - void Add(const TStringPattern& strPattern); - void InsertAt(size_t stIndex, const TStringPattern& strPattern); - void SetAt(size_t stIndex, const TStringPattern& strPattern); - void RemoveAt(size_t stIndex); - void Clear(); + // general api + void Add(const TStringPattern& strPattern); + void InsertAt(size_t stIndex, const TStringPattern& strPattern); + void SetAt(size_t stIndex, const TStringPattern& strPattern); + void RemoveAt(size_t stIndex); + void Clear(); - const TStringPattern& GetAt(size_t stIndex) const; - size_t GetCount() const; + const TStringPattern& GetAt(size_t stIndex) const; + size_t GetCount() const; - // pattern api - bool MatchesAny(const TString& strTextToMatch) const; - bool MatchesAll(const TString& strTextToMatch) const; + // pattern api + bool MatchesAny(const TString& strTextToMatch) const; + bool MatchesAll(const TString& strTextToMatch) const; - // serialization - void FromStringArray(const TStringArray& arrSerializedPatterns); - TStringArray ToStringArray() const; + // serialization + void FromStringArray(const TStringArray& arrSerializedPatterns); + TStringArray ToStringArray() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::vector m_vPatterns; + std::vector m_vPatterns; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TStringSet.cpp =================================================================== diff -u -N -rdd61ac70dd276425fe97970b49b6854d02bfcc87 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringSet.cpp (.../TStringSet.cpp) (revision dd61ac70dd276425fe97970b49b6854d02bfcc87) +++ src/libchcore/TStringSet.cpp (.../TStringSet.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,167 +23,166 @@ #include "stdafx.h" #include "TStringSet.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////////////////////// -// class TStringSetIterator - -TStringSetIterator::TStringSetIterator(std::set::iterator iterSet) : - m_iterSet(iterSet) +namespace chcore { -} + /////////////////////////////////////////////////////////////////////////////////////////// + // class TStringSetIterator -TStringSetIterator::TStringSetIterator() -{ + TStringSetIterator::TStringSetIterator(std::set::iterator iterSet) : + m_iterSet(iterSet) + { + } -} + TStringSetIterator::TStringSetIterator() + { -TStringSetIterator::~TStringSetIterator() -{ + } -} + TStringSetIterator::~TStringSetIterator() + { -TStringSetIterator TStringSetIterator::operator++(int) -{ - TStringSetIterator iterCurrent(m_iterSet); - ++m_iterSet; - return iterCurrent; -} + } -TStringSetIterator& TStringSetIterator::operator++() -{ - ++m_iterSet; - return *this; -} + TStringSetIterator TStringSetIterator::operator++(int) + { + TStringSetIterator iterCurrent(m_iterSet); + ++m_iterSet; + return iterCurrent; + } -bool TStringSetIterator::operator==(const TStringSetIterator& rSrc) const -{ - return m_iterSet == rSrc.m_iterSet; -} + TStringSetIterator& TStringSetIterator::operator++() + { + ++m_iterSet; + return *this; + } -bool TStringSetIterator::operator!=(const TStringSetIterator& rSrc) const -{ - return m_iterSet != rSrc.m_iterSet; -} + bool TStringSetIterator::operator==(const TStringSetIterator& rSrc) const + { + return m_iterSet == rSrc.m_iterSet; + } -const TString& TStringSetIterator::operator*() const -{ - return *m_iterSet; -} + bool TStringSetIterator::operator!=(const TStringSetIterator& rSrc) const + { + return m_iterSet != rSrc.m_iterSet; + } -/////////////////////////////////////////////////////////////////////////////////////////// -// class TStringSetConstIterator + const TString& TStringSetIterator::operator*() const + { + return *m_iterSet; + } -TStringSetConstIterator::TStringSetConstIterator(std::set::const_iterator iterSet) : - m_iterSet(iterSet) -{ -} + /////////////////////////////////////////////////////////////////////////////////////////// + // class TStringSetConstIterator -TStringSetConstIterator::TStringSetConstIterator() -{ + TStringSetConstIterator::TStringSetConstIterator(std::set::const_iterator iterSet) : + m_iterSet(iterSet) + { + } -} + TStringSetConstIterator::TStringSetConstIterator() + { -TStringSetConstIterator::~TStringSetConstIterator() -{ + } -} + TStringSetConstIterator::~TStringSetConstIterator() + { -TStringSetConstIterator TStringSetConstIterator::operator++(int) -{ - TStringSetConstIterator iterCurrent(m_iterSet); - ++m_iterSet; - return iterCurrent; -} + } -TStringSetConstIterator& TStringSetConstIterator::operator++() -{ - ++m_iterSet; - return *this; -} + TStringSetConstIterator TStringSetConstIterator::operator++(int) + { + TStringSetConstIterator iterCurrent(m_iterSet); + ++m_iterSet; + return iterCurrent; + } -bool TStringSetConstIterator::operator==(const TStringSetConstIterator& rSrc) const -{ - return m_iterSet == rSrc.m_iterSet; -} + TStringSetConstIterator& TStringSetConstIterator::operator++() + { + ++m_iterSet; + return *this; + } -bool TStringSetConstIterator::operator!=(const TStringSetConstIterator& rSrc) const -{ - return m_iterSet != rSrc.m_iterSet; -} + bool TStringSetConstIterator::operator==(const TStringSetConstIterator& rSrc) const + { + return m_iterSet == rSrc.m_iterSet; + } -const TString& TStringSetConstIterator::operator*() const -{ - return *m_iterSet; -} + bool TStringSetConstIterator::operator!=(const TStringSetConstIterator& rSrc) const + { + return m_iterSet != rSrc.m_iterSet; + } -/////////////////////////////////////////////////////////////////////////////////////////// -// class TStringSet + const TString& TStringSetConstIterator::operator*() const + { + return *m_iterSet; + } -TStringSet::TStringSet() -{ -} + /////////////////////////////////////////////////////////////////////////////////////////// + // class TStringSet -TStringSet::~TStringSet() -{ -} + TStringSet::TStringSet() + { + } -void TStringSet::Insert(const TString& str) -{ - m_setItems.insert(str); -} + TStringSet::~TStringSet() + { + } -void TStringSet::Insert(const TStringSet& setStrings) -{ - m_setItems.insert(setStrings.m_setItems.begin(), setStrings.m_setItems.end()); -} + void TStringSet::Insert(const TString& str) + { + m_setItems.insert(str); + } -void TStringSet::Remove(const TString& str) -{ - std::set::iterator iter = m_setItems.find(str); - if(iter != m_setItems.end()) - m_setItems.erase(iter); -} + void TStringSet::Insert(const TStringSet& setStrings) + { + m_setItems.insert(setStrings.m_setItems.begin(), setStrings.m_setItems.end()); + } -void TStringSet::Clear() -{ - m_setItems.clear(); -} + void TStringSet::Remove(const TString& str) + { + std::set::iterator iter = m_setItems.find(str); + if (iter != m_setItems.end()) + m_setItems.erase(iter); + } -bool TStringSet::HasValue(const TString& str) const -{ - std::set::const_iterator iter = m_setItems.find(str); - return (iter != m_setItems.end()); -} + void TStringSet::Clear() + { + m_setItems.clear(); + } -size_t TStringSet::GetCount() const -{ - return m_setItems.size(); -} + bool TStringSet::HasValue(const TString& str) const + { + std::set::const_iterator iter = m_setItems.find(str); + return (iter != m_setItems.end()); + } -bool TStringSet::IsEmpty() const -{ - return m_setItems.empty(); -} + size_t TStringSet::GetCount() const + { + return m_setItems.size(); + } -TStringSetIterator TStringSet::Begin() -{ - return TStringSetIterator(m_setItems.begin()); -} + bool TStringSet::IsEmpty() const + { + return m_setItems.empty(); + } -TStringSetIterator TStringSet::End() -{ - return TStringSetIterator(m_setItems.end()); -} + TStringSetIterator TStringSet::Begin() + { + return TStringSetIterator(m_setItems.begin()); + } -TStringSetConstIterator TStringSet::Begin() const -{ - return TStringSetConstIterator(m_setItems.begin()); -} + TStringSetIterator TStringSet::End() + { + return TStringSetIterator(m_setItems.end()); + } -TStringSetConstIterator TStringSet::End() const -{ - return TStringSetConstIterator(m_setItems.end()); -} + TStringSetConstIterator TStringSet::Begin() const + { + return TStringSetConstIterator(m_setItems.begin()); + } -END_CHCORE_NAMESPACE + TStringSetConstIterator TStringSet::End() const + { + return TStringSetConstIterator(m_setItems.end()); + } +} Index: src/libchcore/TStringSet.h =================================================================== diff -u -N -rdd61ac70dd276425fe97970b49b6854d02bfcc87 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TStringSet.h (.../TStringSet.h) (revision dd61ac70dd276425fe97970b49b6854d02bfcc87) +++ src/libchcore/TStringSet.h (.../TStringSet.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,91 +26,90 @@ #include "TString.h" #include "libchcore.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TStringSetIterator +namespace chcore { -protected: - TStringSetIterator(std::set::iterator iterSet); + class LIBCHCORE_API TStringSetIterator + { + protected: + TStringSetIterator(std::set::iterator iterSet); -public: - TStringSetIterator(); - ~TStringSetIterator(); + public: + TStringSetIterator(); + ~TStringSetIterator(); - TStringSetIterator operator++(int); - TStringSetIterator& operator++(); + TStringSetIterator operator++(int); + TStringSetIterator& operator++(); - bool operator==(const TStringSetIterator& rSrc) const; - bool operator!=(const TStringSetIterator& rSrc) const; + bool operator==(const TStringSetIterator& rSrc) const; + bool operator!=(const TStringSetIterator& rSrc) const; - const TString& operator*() const; + const TString& operator*() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::set::iterator m_iterSet; + std::set::iterator m_iterSet; #pragma warning(pop) - friend class TStringSet; -}; + friend class TStringSet; + }; -class LIBCHCORE_API TStringSetConstIterator -{ -protected: - TStringSetConstIterator(std::set::const_iterator iterSet); + class LIBCHCORE_API TStringSetConstIterator + { + protected: + TStringSetConstIterator(std::set::const_iterator iterSet); -public: - TStringSetConstIterator(); - ~TStringSetConstIterator(); + public: + TStringSetConstIterator(); + ~TStringSetConstIterator(); - TStringSetConstIterator operator++(int); - TStringSetConstIterator& operator++(); + TStringSetConstIterator operator++(int); + TStringSetConstIterator& operator++(); - bool operator==(const TStringSetConstIterator& rSrc) const; - bool operator!=(const TStringSetConstIterator& rSrc) const; + bool operator==(const TStringSetConstIterator& rSrc) const; + bool operator!=(const TStringSetConstIterator& rSrc) const; - const TString& operator*() const; + const TString& operator*() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::set::const_iterator m_iterSet; + std::set::const_iterator m_iterSet; #pragma warning(pop) - friend class TStringSet; -}; + friend class TStringSet; + }; -class LIBCHCORE_API TStringSet -{ -public: - typedef TStringSetIterator iterator; - typedef TStringSetConstIterator const_iterator; + class LIBCHCORE_API TStringSet + { + public: + typedef TStringSetIterator iterator; + typedef TStringSetConstIterator const_iterator; -public: - TStringSet(); - ~TStringSet(); + public: + TStringSet(); + ~TStringSet(); - void Insert(const TString& str); - void Insert(const TStringSet& setStrings); - void Remove(const TString& str); - void Clear(); + void Insert(const TString& str); + void Insert(const TStringSet& setStrings); + void Remove(const TString& str); + void Clear(); - bool HasValue(const TString& str) const; - size_t GetCount() const; - bool IsEmpty() const; + bool HasValue(const TString& str) const; + size_t GetCount() const; + bool IsEmpty() const; - TStringSetIterator Begin(); - TStringSetIterator End(); - TStringSetConstIterator Begin() const; - TStringSetConstIterator End() const; + TStringSetIterator Begin(); + TStringSetIterator End(); + TStringSetConstIterator Begin() const; + TStringSetConstIterator End() const; -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::set m_setItems; + std::set m_setItems; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSubTaskArray.cpp =================================================================== diff -u -N -r7972b0944e0a947144fbdb93262f7d73ac528dc7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskArray.cpp (.../TSubTaskArray.cpp) (revision 7972b0944e0a947144fbdb93262f7d73ac528dc7) +++ src/libchcore/TSubTaskArray.cpp (.../TSubTaskArray.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -35,54 +35,54 @@ #include "ErrorCodes.h" #include -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////// -// TSubTasksArray - -TSubTasksArray::TSubTasksArray(TSubTaskContext& rSubTaskContext) : - m_rSubTaskContext(rSubTaskContext), - m_eOperationType(m_setModifications, eOperation_None), - m_oidSubOperationIndex(0), - m_oidLastStoredIndex((object_id_t)-1) +namespace chcore { - m_setModifications[eMod_Added] = true; -} + /////////////////////////////////////////////////////////////////////////// + // TSubTasksArray -TSubTasksArray::TSubTasksArray(const TOperationPlan& rOperationPlan, TSubTaskContext& rSubTaskContext) : - m_rSubTaskContext(rSubTaskContext), - m_eOperationType(m_setModifications, eOperation_None), - m_oidSubOperationIndex(0), - m_oidLastStoredIndex((object_id_t)-1) -{ - m_setModifications[eMod_Added] = true; - Init(rOperationPlan); -} + TSubTasksArray::TSubTasksArray(TSubTaskContext& rSubTaskContext) : + m_rSubTaskContext(rSubTaskContext), + m_eOperationType(m_setModifications, eOperation_None), + m_oidSubOperationIndex(0), + m_oidLastStoredIndex((object_id_t)-1) + { + m_setModifications[eMod_Added] = true; + } -TSubTasksArray::~TSubTasksArray() -{ -} + TSubTasksArray::TSubTasksArray(const TOperationPlan& rOperationPlan, TSubTaskContext& rSubTaskContext) : + m_rSubTaskContext(rSubTaskContext), + m_eOperationType(m_setModifications, eOperation_None), + m_oidSubOperationIndex(0), + m_oidLastStoredIndex((object_id_t)-1) + { + m_setModifications[eMod_Added] = true; + Init(rOperationPlan); + } -void TSubTasksArray::Init(const TOperationPlan& rOperationPlan) -{ - m_vSubTasks.clear(); - m_rSubTaskContext.GetFilesCache().Clear(); - m_oidSubOperationIndex.store(0, std::memory_order_release); + TSubTasksArray::~TSubTasksArray() + { + } - m_eOperationType = rOperationPlan.GetOperationType(); - - switch(m_eOperationType) + void TSubTasksArray::Init(const TOperationPlan& rOperationPlan) { - case eOperation_Copy: + m_vSubTasks.clear(); + m_rSubTaskContext.GetFilesCache().Clear(); + m_oidSubOperationIndex.store(0, std::memory_order_release); + + m_eOperationType = rOperationPlan.GetOperationType(); + + switch (m_eOperationType) { + case eOperation_Copy: + { TSubTaskBasePtr spOperation = boost::make_shared(boost::ref(m_rSubTaskContext)); AddSubTask(spOperation, true); spOperation = boost::make_shared(boost::ref(m_rSubTaskContext)); AddSubTask(spOperation, false); break; } - case eOperation_Move: + case eOperation_Move: { TSubTaskBasePtr spOperation = boost::make_shared(boost::ref(m_rSubTaskContext)); AddSubTask(spOperation, true); @@ -95,262 +95,261 @@ break; } - default: - THROW_CORE_EXCEPTION(eErr_UndefinedOperation); + default: + THROW_CORE_EXCEPTION(eErr_UndefinedOperation); + } } -} -void TSubTasksArray::ResetProgressAndStats() -{ - m_oidSubOperationIndex.store(0, std::memory_order_release); - - for(const std::pair& tupleRow : m_vSubTasks) + void TSubTasksArray::ResetProgressAndStats() { - if(tupleRow.first == NULL) - THROW_CORE_EXCEPTION(eErr_InternalProblem); + m_oidSubOperationIndex.store(0, std::memory_order_release); - tupleRow.first->Reset(); + for (const std::pair& tupleRow : m_vSubTasks) + { + if (tupleRow.first == NULL) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + + tupleRow.first->Reset(); + } } -} -TSubTaskBase::ESubOperationResult TSubTasksArray::Execute(const IFeedbackHandlerPtr& spFeedbackHandler, bool bRunOnlyEstimationSubTasks) -{ - TSubTaskBase::ESubOperationResult eResult = TSubTaskBase::eSubResult_Continue; - - object_id_t oidSize = boost::numeric_cast(m_vSubTasks.size()); - object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); - - while(oidIndex < oidSize) + TSubTaskBase::ESubOperationResult TSubTasksArray::Execute(const IFeedbackHandlerPtr& spFeedbackHandler, bool bRunOnlyEstimationSubTasks) { - std::pair& rCurrentSubTask = m_vSubTasks.at(boost::numeric_cast(oidIndex)); - TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; + TSubTaskBase::ESubOperationResult eResult = TSubTaskBase::eSubResult_Continue; - // if we run in estimation mode only, then stop processing and return to the caller - if(bRunOnlyEstimationSubTasks && !rCurrentSubTask.second) + object_id_t oidSize = boost::numeric_cast(m_vSubTasks.size()); + object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); + + while (oidIndex < oidSize) { - eResult = TSubTaskBase::eSubResult_Continue; - break; - } + std::pair& rCurrentSubTask = m_vSubTasks.at(boost::numeric_cast(oidIndex)); + TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; - eResult = spCurrentSubTask->Exec(spFeedbackHandler); - if(eResult != TSubTaskBase::eSubResult_Continue) - break; + // if we run in estimation mode only, then stop processing and return to the caller + if (bRunOnlyEstimationSubTasks && !rCurrentSubTask.second) + { + eResult = TSubTaskBase::eSubResult_Continue; + break; + } - oidIndex = m_oidSubOperationIndex.fetch_add(1, std::memory_order_release) + 1; - } + eResult = spCurrentSubTask->Exec(spFeedbackHandler); + if (eResult != TSubTaskBase::eSubResult_Continue) + break; - return eResult; -} + oidIndex = m_oidSubOperationIndex.fetch_add(1, std::memory_order_release) + 1; + } -void TSubTasksArray::AddSubTask(const TSubTaskBasePtr& spOperation, bool bIsPartOfEstimation) -{ - m_vSubTasks.push_back(std::make_pair(spOperation, bIsPartOfEstimation)); -} + return eResult; + } -void TSubTasksArray::GetStatsSnapshot(TSubTaskArrayStatsSnapshot& rSnapshot) const -{ - rSnapshot.Clear(); + void TSubTasksArray::AddSubTask(const TSubTaskBasePtr& spOperation, bool bIsPartOfEstimation) + { + m_vSubTasks.push_back(std::make_pair(spOperation, bIsPartOfEstimation)); + } - // current task - // ugly const_cast - const method, non-const interlocked intrinsic and we're really not modifying the member... - object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); - rSnapshot.SetCurrentSubtaskIndex(oidIndex); - - // progress - for(size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) + void TSubTasksArray::GetStatsSnapshot(TSubTaskArrayStatsSnapshot& rSnapshot) const { - const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; - TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; + rSnapshot.Clear(); - TSubTaskStatsSnapshotPtr spSubtaskSnapshot(new TSubTaskStatsSnapshot); + // current task + // ugly const_cast - const method, non-const interlocked intrinsic and we're really not modifying the member... + object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); + rSnapshot.SetCurrentSubtaskIndex(oidIndex); - spCurrentSubTask->GetStatsSnapshot(spSubtaskSnapshot); - rSnapshot.AddSubTaskSnapshot(spSubtaskSnapshot); - } -} + // progress + for (size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) + { + const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; + TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; -EOperationType TSubTasksArray::GetOperationType() const -{ - return m_eOperationType; -} + TSubTaskStatsSnapshotPtr spSubtaskSnapshot(new TSubTaskStatsSnapshot); -void TSubTasksArray::Store(const ISerializerPtr& spSerializer) const -{ - bool bAdded = m_setModifications[eMod_Added]; + spCurrentSubTask->GetStatsSnapshot(spSubtaskSnapshot); + rSnapshot.AddSubTaskSnapshot(spSubtaskSnapshot); + } + } - /////////////////////////////////////////////////////////////////////// - if (m_eOperationType.IsModified()) + EOperationType TSubTasksArray::GetOperationType() const { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks_info")); - InitSubtasksInfoColumns(spContainer); - - ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); - - rRow.SetValue(_T("operation"), m_eOperationType.Get()); + return m_eOperationType; } - /////////////////////////////////////////////////////////////////////// + void TSubTasksArray::Store(const ISerializerPtr& spSerializer) const { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks")); - InitSubtasksColumns(spContainer); + bool bAdded = m_setModifications[eMod_Added]; - // base data - object_id_t oidCurrentIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); - - // subtasks are stored only once when added as they don't change (at least in context of their order and type) - if(bAdded) + /////////////////////////////////////////////////////////////////////// + if (m_eOperationType.IsModified()) { - if(m_oidLastStoredIndex != -1) - THROW_CORE_EXCEPTION(eErr_InternalProblem); + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks_info")); + InitSubtasksInfoColumns(spContainer); - for(size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) - { - const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; + ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); - ISerializerRowData& rRow = spContainer->GetRow(boost::numeric_cast(stSubOperationIndex), bAdded); - rRow.SetValue(_T("type"), rCurrentSubTask.first->GetSubOperationType()); - rRow.SetValue(_T("is_current"), false); - rRow.SetValue(_T("is_estimation"), rCurrentSubTask.second); - } + rRow.SetValue(_T("operation"), m_eOperationType.Get()); } - // serialize current index - if(bAdded || oidCurrentIndex != m_oidLastStoredIndex) + /////////////////////////////////////////////////////////////////////// { - // mark subtask at current index as "current"; don't do that if we just finished. - if(boost::numeric_cast(oidCurrentIndex) != m_vSubTasks.size()) + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks")); + InitSubtasksColumns(spContainer); + + // base data + object_id_t oidCurrentIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); + + // subtasks are stored only once when added as they don't change (at least in context of their order and type) + if (bAdded) { - ISerializerRowData& rRow = spContainer->GetRow(oidCurrentIndex, false); - rRow.SetValue(_T("is_current"), true); + if (m_oidLastStoredIndex != -1) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + + for (size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) + { + const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; + + ISerializerRowData& rRow = spContainer->GetRow(boost::numeric_cast(stSubOperationIndex), bAdded); + rRow.SetValue(_T("type"), rCurrentSubTask.first->GetSubOperationType()); + rRow.SetValue(_T("is_current"), false); + rRow.SetValue(_T("is_estimation"), rCurrentSubTask.second); + } } - // unmark the old "current" subtask - if(m_oidLastStoredIndex != -1) + // serialize current index + if (bAdded || oidCurrentIndex != m_oidLastStoredIndex) { - ISerializerRowData& rRow = spContainer->GetRow(m_oidLastStoredIndex, false); - rRow.SetValue(_T("is_current"), false); + // mark subtask at current index as "current"; don't do that if we just finished. + if (boost::numeric_cast(oidCurrentIndex) != m_vSubTasks.size()) + { + ISerializerRowData& rRow = spContainer->GetRow(oidCurrentIndex, false); + rRow.SetValue(_T("is_current"), true); + } + + // unmark the old "current" subtask + if (m_oidLastStoredIndex != -1) + { + ISerializerRowData& rRow = spContainer->GetRow(m_oidLastStoredIndex, false); + rRow.SetValue(_T("is_current"), false); + } } + + m_oidLastStoredIndex = oidCurrentIndex; } - m_oidLastStoredIndex = oidCurrentIndex; - } + m_setModifications.reset(); - m_setModifications.reset(); - - /////////////////////////////////////////////////////////////////////// - // store all the subtasks - for(size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) - { - const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; - rCurrentSubTask.first->Store(spSerializer); + /////////////////////////////////////////////////////////////////////// + // store all the subtasks + for (size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) + { + const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; + rCurrentSubTask.first->Store(spSerializer); + } } -} -void TSubTasksArray::Load(const ISerializerPtr& spSerializer) -{ - /////////////////////////////////////////////////////////////////////// + void TSubTasksArray::Load(const ISerializerPtr& spSerializer) { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks_info")); + /////////////////////////////////////////////////////////////////////// + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks_info")); - InitSubtasksInfoColumns(spContainer); + InitSubtasksInfoColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if(spRowReader->Next()) - spRowReader->GetValue(_T("operation"), *(int*)&m_eOperationType.Modify()); - } + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + spRowReader->GetValue(_T("operation"), *(int*)&m_eOperationType.Modify()); + } - /////////////////////////////////////////////////////////////////////// - { - m_oidLastStoredIndex = (object_id_t)-1; + /////////////////////////////////////////////////////////////////////// + { + m_oidLastStoredIndex = (object_id_t)-1; - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks")); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks")); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - InitSubtasksColumns(spContainer); + InitSubtasksColumns(spContainer); - while(spRowReader->Next()) - { - object_id_t oidID = 0; - int iType = 0; - bool bIsCurrent = false; - bool bIsEstimation = false; + while (spRowReader->Next()) + { + object_id_t oidID = 0; + int iType = 0; + bool bIsCurrent = false; + bool bIsEstimation = false; - spRowReader->GetValue(_T("id"), oidID); - spRowReader->GetValue(_T("type"), iType); - spRowReader->GetValue(_T("is_current"), bIsCurrent); - spRowReader->GetValue(_T("is_estimation"), bIsEstimation); + spRowReader->GetValue(_T("id"), oidID); + spRowReader->GetValue(_T("type"), iType); + spRowReader->GetValue(_T("is_current"), bIsCurrent); + spRowReader->GetValue(_T("is_estimation"), bIsEstimation); - if(bIsCurrent) - { - m_oidSubOperationIndex.store(oidID, std::memory_order_release); - m_oidLastStoredIndex = oidID; - } + if (bIsCurrent) + { + m_oidSubOperationIndex.store(oidID, std::memory_order_release); + m_oidLastStoredIndex = oidID; + } - // create subtask, load it and put into the array - TSubTaskBasePtr spSubTask = CreateSubtask((ESubOperationType)iType, m_rSubTaskContext); - spSubTask->Load(spSerializer); + // create subtask, load it and put into the array + TSubTaskBasePtr spSubTask = CreateSubtask((ESubOperationType)iType, m_rSubTaskContext); + spSubTask->Load(spSerializer); - if(boost::numeric_cast(oidID) != m_vSubTasks.size()) - THROW_CORE_EXCEPTION(eErr_InvalidData); + if (boost::numeric_cast(oidID) != m_vSubTasks.size()) + THROW_CORE_EXCEPTION(eErr_InvalidData); - m_vSubTasks.push_back(std::make_pair(spSubTask, bIsEstimation)); - } + m_vSubTasks.push_back(std::make_pair(spSubTask, bIsEstimation)); + } - if(m_oidLastStoredIndex == -1) - { - m_oidSubOperationIndex.store(boost::numeric_cast(m_vSubTasks.size()), std::memory_order_release); - m_oidLastStoredIndex = boost::numeric_cast(m_vSubTasks.size()); + if (m_oidLastStoredIndex == -1) + { + m_oidSubOperationIndex.store(boost::numeric_cast(m_vSubTasks.size()), std::memory_order_release); + m_oidLastStoredIndex = boost::numeric_cast(m_vSubTasks.size()); + } } + + m_setModifications.reset(); } - m_setModifications.reset(); -} - -TSubTaskBasePtr TSubTasksArray::CreateSubtask(ESubOperationType eType, TSubTaskContext& rContext) -{ - switch(eType) + TSubTaskBasePtr TSubTasksArray::CreateSubtask(ESubOperationType eType, TSubTaskContext& rContext) { - case eSubOperation_FastMove: - return boost::make_shared(boost::ref(rContext)); + switch (eType) + { + case eSubOperation_FastMove: + return boost::make_shared(boost::ref(rContext)); - case eSubOperation_Scanning: - return boost::make_shared(boost::ref(rContext)); + case eSubOperation_Scanning: + return boost::make_shared(boost::ref(rContext)); - case eSubOperation_Copying: - return boost::make_shared(boost::ref(rContext)); + case eSubOperation_Copying: + return boost::make_shared(boost::ref(rContext)); - case eSubOperation_Deleting: - return boost::make_shared(boost::ref(rContext)); + case eSubOperation_Deleting: + return boost::make_shared(boost::ref(rContext)); - default: - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + default: + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } -} -IColumnsDefinition& TSubTasksArray::InitSubtasksColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) + IColumnsDefinition& TSubTasksArray::InitSubtasksColumns(const ISerializerContainerPtr& spContainer) const { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("type"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("is_current"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("is_estimation"), IColumnsDefinition::eType_bool); + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("type"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("is_current"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("is_estimation"), IColumnsDefinition::eType_bool); + } + + return rColumns; } - return rColumns; -} - -IColumnsDefinition& TSubTasksArray::InitSubtasksInfoColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) + IColumnsDefinition& TSubTasksArray::InitSubtasksInfoColumns(const ISerializerContainerPtr& spContainer) const { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("operation"), IColumnsDefinition::eType_int); - } + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("operation"), IColumnsDefinition::eType_int); + } - return rColumns; + return rColumns; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSubTaskArray.h =================================================================== diff -u -N -r7972b0944e0a947144fbdb93262f7d73ac528dc7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskArray.h (.../TSubTaskArray.h) (revision 7972b0944e0a947144fbdb93262f7d73ac528dc7) +++ src/libchcore/TSubTaskArray.h (.../TSubTaskArray.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -32,74 +32,73 @@ #include #include -BEGIN_CHCORE_NAMESPACE - -class TOperationPlan; -class TSubTaskContext; - -/////////////////////////////////////////////////////////////////////////// -// TTaskBasicProgressInfo -class LIBCHCORE_API TSubTasksArray +namespace chcore { -public: - TSubTasksArray(TSubTaskContext& rSubTaskContext); - TSubTasksArray(const TOperationPlan& rOperationPlan, TSubTaskContext& rSubTaskContext); - ~TSubTasksArray(); + class TOperationPlan; + class TSubTaskContext; - void Init(const TOperationPlan& rOperationPlan); - EOperationType GetOperationType() const; + /////////////////////////////////////////////////////////////////////////// + // TTaskBasicProgressInfo + class LIBCHCORE_API TSubTasksArray + { + public: + TSubTasksArray(TSubTaskContext& rSubTaskContext); + TSubTasksArray(const TOperationPlan& rOperationPlan, TSubTaskContext& rSubTaskContext); + ~TSubTasksArray(); - // Stats handling - void GetStatsSnapshot(TSubTaskArrayStatsSnapshot& rSnapshot) const; - void ResetProgressAndStats(); + void Init(const TOperationPlan& rOperationPlan); + EOperationType GetOperationType() const; - // progress handling - void Store(const ISerializerPtr& spSerializer) const; - void Load(const ISerializerPtr& spSerializer); + // Stats handling + void GetStatsSnapshot(TSubTaskArrayStatsSnapshot& rSnapshot) const; + void ResetProgressAndStats(); - TSubTaskBase::ESubOperationResult Execute(const IFeedbackHandlerPtr& spFeedbackHandler, bool bRunOnlyEstimationSubTasks); + // progress handling + void Store(const ISerializerPtr& spSerializer) const; + void Load(const ISerializerPtr& spSerializer); -private: - TSubTasksArray(const TSubTasksArray& rSrc); - TSubTasksArray& operator=(const TSubTasksArray& rSrc); + TSubTaskBase::ESubOperationResult Execute(const IFeedbackHandlerPtr& spFeedbackHandler, bool bRunOnlyEstimationSubTasks); - void AddSubTask(const TSubTaskBasePtr& spOperation, bool bIsPartOfEstimation); - static TSubTaskBasePtr CreateSubtask(ESubOperationType eType, TSubTaskContext& rContext); + private: + TSubTasksArray(const TSubTasksArray& rSrc); + TSubTasksArray& operator=(const TSubTasksArray& rSrc); - IColumnsDefinition& InitSubtasksColumns(const ISerializerContainerPtr& spContainer) const; - IColumnsDefinition& InitSubtasksInfoColumns(const ISerializerContainerPtr& spContainer) const; + void AddSubTask(const TSubTaskBasePtr& spOperation, bool bIsPartOfEstimation); + static TSubTaskBasePtr CreateSubtask(ESubOperationType eType, TSubTaskContext& rContext); -private: - enum EModifications - { - eMod_Added, - eMod_OperationType, + IColumnsDefinition& InitSubtasksColumns(const ISerializerContainerPtr& spContainer) const; + IColumnsDefinition& InitSubtasksInfoColumns(const ISerializerContainerPtr& spContainer) const; - // last element - eMod_Last - }; + private: + enum EModifications + { + eMod_Added, + eMod_OperationType, - typedef std::bitset Bitset; + // last element + eMod_Last + }; - TSubTaskContext& m_rSubTaskContext; + typedef std::bitset Bitset; + TSubTaskContext& m_rSubTaskContext; + #pragma warning(push) #pragma warning(disable: 4251) - mutable Bitset m_setModifications; + mutable Bitset m_setModifications; - TSharedModificationTracker m_eOperationType; + TSharedModificationTracker m_eOperationType; - std::vector > m_vSubTasks; // pointer to the subtask object / is this the part of estimation? + std::vector > m_vSubTasks; // pointer to the subtask object / is this the part of estimation? - mutable std::atomic m_oidSubOperationIndex; // index of sub-operation from TOperationDescription + mutable std::atomic m_oidSubOperationIndex; // index of sub-operation from TOperationDescription #pragma warning(pop) - mutable object_id_t m_oidLastStoredIndex; + mutable object_id_t m_oidLastStoredIndex; - friend class TScopedRunningTimeTracker; -}; + friend class TScopedRunningTimeTracker; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSubTaskArrayStatsSnapshot.cpp =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskArrayStatsSnapshot.cpp (.../TSubTaskArrayStatsSnapshot.cpp) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TSubTaskArrayStatsSnapshot.cpp (.../TSubTaskArrayStatsSnapshot.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,42 +22,41 @@ #include "TCoreException.h" #include -BEGIN_CHCORE_NAMESPACE - -TSubTaskArrayStatsSnapshot::TSubTaskArrayStatsSnapshot() : - m_oidCurrentSubtaskIndex(0) +namespace chcore { -} + TSubTaskArrayStatsSnapshot::TSubTaskArrayStatsSnapshot() : + m_oidCurrentSubtaskIndex(0) + { + } -void TSubTaskArrayStatsSnapshot::Clear() -{ - m_vSubTaskSnapshots.clear(); -} + void TSubTaskArrayStatsSnapshot::Clear() + { + m_vSubTaskSnapshots.clear(); + } -void TSubTaskArrayStatsSnapshot::AddSubTaskSnapshot(const TSubTaskStatsSnapshotPtr& spSnapshot) -{ - m_vSubTaskSnapshots.push_back(spSnapshot); -} + void TSubTaskArrayStatsSnapshot::AddSubTaskSnapshot(const TSubTaskStatsSnapshotPtr& spSnapshot) + { + m_vSubTaskSnapshots.push_back(spSnapshot); + } -TSubTaskStatsSnapshotPtr TSubTaskArrayStatsSnapshot::GetSubTaskSnapshotAt(size_t stIndex) const -{ - if(stIndex >= m_vSubTaskSnapshots.size()) - return TSubTaskStatsSnapshotPtr(); + TSubTaskStatsSnapshotPtr TSubTaskArrayStatsSnapshot::GetSubTaskSnapshotAt(size_t stIndex) const + { + if (stIndex >= m_vSubTaskSnapshots.size()) + return TSubTaskStatsSnapshotPtr(); - return m_vSubTaskSnapshots[stIndex]; -} + return m_vSubTaskSnapshots[stIndex]; + } -TSubTaskStatsSnapshotPtr TSubTaskArrayStatsSnapshot::GetCurrentSubTaskSnapshot() const -{ - if(m_oidCurrentSubtaskIndex >= m_vSubTaskSnapshots.size()) - return TSubTaskStatsSnapshotPtr(); + TSubTaskStatsSnapshotPtr TSubTaskArrayStatsSnapshot::GetCurrentSubTaskSnapshot() const + { + if (m_oidCurrentSubtaskIndex >= m_vSubTaskSnapshots.size()) + return TSubTaskStatsSnapshotPtr(); - return m_vSubTaskSnapshots[boost::numeric_cast(m_oidCurrentSubtaskIndex)]; -} + return m_vSubTaskSnapshots[boost::numeric_cast(m_oidCurrentSubtaskIndex)]; + } -size_t TSubTaskArrayStatsSnapshot::GetSubTaskSnapshotCount() const -{ - return m_vSubTaskSnapshots.size(); + size_t TSubTaskArrayStatsSnapshot::GetSubTaskSnapshotCount() const + { + return m_vSubTaskSnapshots.size(); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSubTaskArrayStatsSnapshot.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskArrayStatsSnapshot.h (.../TSubTaskArrayStatsSnapshot.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TSubTaskArrayStatsSnapshot.h (.../TSubTaskArrayStatsSnapshot.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,31 +23,30 @@ #include "TSubTaskStatsSnapshot.h" #include "SerializerDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSubTaskArrayStatsSnapshot +namespace chcore { -public: - TSubTaskArrayStatsSnapshot(); + class LIBCHCORE_API TSubTaskArrayStatsSnapshot + { + public: + TSubTaskArrayStatsSnapshot(); - void Clear(); + void Clear(); - void AddSubTaskSnapshot(const TSubTaskStatsSnapshotPtr& rSnapshot); - TSubTaskStatsSnapshotPtr GetSubTaskSnapshotAt(size_t stIndex) const; - size_t GetSubTaskSnapshotCount() const; - TSubTaskStatsSnapshotPtr GetCurrentSubTaskSnapshot() const; + void AddSubTaskSnapshot(const TSubTaskStatsSnapshotPtr& rSnapshot); + TSubTaskStatsSnapshotPtr GetSubTaskSnapshotAt(size_t stIndex) const; + size_t GetSubTaskSnapshotCount() const; + TSubTaskStatsSnapshotPtr GetCurrentSubTaskSnapshot() const; - object_id_t GetCurrentSubtaskIndex() const { return m_oidCurrentSubtaskIndex; } - void SetCurrentSubtaskIndex(object_id_t val) { m_oidCurrentSubtaskIndex = val; } + object_id_t GetCurrentSubtaskIndex() const { return m_oidCurrentSubtaskIndex; } + void SetCurrentSubtaskIndex(object_id_t val) { m_oidCurrentSubtaskIndex = val; } -private: - object_id_t m_oidCurrentSubtaskIndex; + private: + object_id_t m_oidCurrentSubtaskIndex; #pragma warning(push) #pragma warning(disable: 4251) - std::vector m_vSubTaskSnapshots; + std::vector m_vSubTaskSnapshots; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSubTaskBase.cpp =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskBase.cpp (.../TSubTaskBase.cpp) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TSubTaskBase.cpp (.../TSubTaskBase.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -31,92 +31,91 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////// -// TSubTaskBase - -TSubTaskBase::TSubTaskBase(TSubTaskContext& rContext) : - m_rContext(rContext) +namespace chcore { -} + /////////////////////////////////////////////////////////////////////////// + // TSubTaskBase -TSubTaskBase::~TSubTaskBase() -{ -} + TSubTaskBase::TSubTaskBase(TSubTaskContext& rContext) : + m_rContext(rContext) + { + } -TSmartPath TSubTaskBase::CalculateDestinationPath(const TFileInfoPtr& spFileInfo, TSmartPath pathDst, int iFlags) -{ - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + TSubTaskBase::~TSubTaskBase() + { + } - if(!spFileInfo) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); - - // iFlags: bit 0-ignore folders; bit 1-force creating directories - if(iFlags & 0x02) + TSmartPath TSubTaskBase::CalculateDestinationPath(const TFileInfoPtr& spFileInfo, TSmartPath pathDst, int iFlags) { - // force create directories - TSmartPath pathCombined = pathDst + spFileInfo->GetFullFilePath().GetFileDir(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - // force create directory - spFilesystem->CreateDirectory(pathCombined, true); + if (!spFileInfo) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - return pathCombined + spFileInfo->GetFullFilePath().GetFileName(); - } - else - { - TBasePathDataPtr spPathData = spFileInfo->GetBasePathData(); + // iFlags: bit 0-ignore folders; bit 1-force creating directories + if (iFlags & 0x02) + { + // force create directories + TSmartPath pathCombined = pathDst + spFileInfo->GetFullFilePath().GetFileDir(); - if(!(iFlags & 0x01) && spPathData) + // force create directory + spFilesystem->CreateDirectory(pathCombined, true); + + return pathCombined + spFileInfo->GetFullFilePath().GetFileName(); + } + else { - // generate new dest name - if(!spPathData->IsDestinationPathSet()) + TBasePathDataPtr spPathData = spFileInfo->GetBasePathData(); + + if (!(iFlags & 0x01) && spPathData) { - // generate something - if dest folder == src folder - search for copy - if(pathDst == spFileInfo->GetFullFilePath().GetFileRoot()) + // generate new dest name + if (!spPathData->IsDestinationPathSet()) { - TSmartPath pathSubst = FindFreeSubstituteName(spFileInfo->GetFullFilePath(), pathDst); - spPathData->SetDestinationPath(pathSubst); + // generate something - if dest folder == src folder - search for copy + if (pathDst == spFileInfo->GetFullFilePath().GetFileRoot()) + { + TSmartPath pathSubst = FindFreeSubstituteName(spFileInfo->GetFullFilePath(), pathDst); + spPathData->SetDestinationPath(pathSubst); + } + else + spPathData->SetDestinationPath(spFileInfo->GetFullFilePath().GetFileName()); } - else - spPathData->SetDestinationPath(spFileInfo->GetFullFilePath().GetFileName()); - } - return pathDst + spPathData->GetDestinationPath() + spFileInfo->GetFilePath(); + return pathDst + spPathData->GetDestinationPath() + spFileInfo->GetFilePath(); + } + else + return pathDst + spFileInfo->GetFullFilePath().GetFileName(); } - else - return pathDst + spFileInfo->GetFullFilePath().GetFileName(); } -} -// finds another name for a copy of src file(folder) in dest location -TSmartPath TSubTaskBase::FindFreeSubstituteName(TSmartPath pathSrcPath, TSmartPath pathDstPath) const -{ - const TConfig& rConfig = GetContext().GetConfig(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + // finds another name for a copy of src file(folder) in dest location + TSmartPath TSubTaskBase::FindFreeSubstituteName(TSmartPath pathSrcPath, TSmartPath pathDstPath) const + { + const TConfig& rConfig = GetContext().GetConfig(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - // get the name from src path - pathSrcPath.StripSeparatorAtEnd(); + // get the name from src path + pathSrcPath.StripSeparatorAtEnd(); - TSmartPath pathFilename = pathSrcPath.GetFileName(); + TSmartPath pathFilename = pathSrcPath.GetFileName(); - // set the dest path - TString strCheckPath = GetTaskPropValue(rConfig); - strCheckPath.Replace(_T("%name"), pathFilename.ToString()); - TSmartPath pathCheckPath(PathFromWString(strCheckPath)); + // set the dest path + TString strCheckPath = GetTaskPropValue(rConfig); + strCheckPath.Replace(_T("%name"), pathFilename.ToString()); + TSmartPath pathCheckPath(PathFromWString(strCheckPath)); - // when adding to strDstPath check if the path already exists - if so - try again - int iCounter = 1; - TString strFmt = GetTaskPropValue(rConfig); - while(spFilesystem->PathExist(pathDstPath + pathCheckPath)) - { - strCheckPath = strFmt; - strCheckPath.Replace(_t("%name"), pathFilename.ToString()); - strCheckPath.Replace(_t("%count"), boost::lexical_cast(++iCounter).c_str()); - pathCheckPath.FromString(strCheckPath); - } + // when adding to strDstPath check if the path already exists - if so - try again + int iCounter = 1; + TString strFmt = GetTaskPropValue(rConfig); + while (spFilesystem->PathExist(pathDstPath + pathCheckPath)) + { + strCheckPath = strFmt; + strCheckPath.Replace(_t("%name"), pathFilename.ToString()); + strCheckPath.Replace(_t("%count"), boost::lexical_cast(++iCounter).c_str()); + pathCheckPath.FromString(strCheckPath); + } - return pathCheckPath; + return pathCheckPath; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSubTaskBase.h =================================================================== diff -u -N -r6103ac74583f2136b821dc67515ed8469abd8155 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskBase.h (.../TSubTaskBase.h) (revision 6103ac74583f2136b821dc67515ed8469abd8155) +++ src/libchcore/TSubTaskBase.h (.../TSubTaskBase.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -30,62 +30,61 @@ #include "ISerializer.h" #include "IFeedbackHandler.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + class TSubTaskContext; + class TFileInfo; + typedef boost::shared_ptr TFileInfoPtr; -class TSubTaskContext; -class TFileInfo; -typedef boost::shared_ptr TFileInfoPtr; + /////////////////////////////////////////////////////////////////////////// + // TSubTaskBase -/////////////////////////////////////////////////////////////////////////// -// TSubTaskBase - -class LIBCHCORE_API TSubTaskBase -{ -public: - enum ESubOperationResult + class LIBCHCORE_API TSubTaskBase { - eSubResult_Continue, - eSubResult_KillRequest, - eSubResult_Error, - eSubResult_CancelRequest, - eSubResult_PauseRequest, - eSubResult_Retry, - }; + public: + enum ESubOperationResult + { + eSubResult_Continue, + eSubResult_KillRequest, + eSubResult_Error, + eSubResult_CancelRequest, + eSubResult_PauseRequest, + eSubResult_Retry, + }; -public: - TSubTaskBase(TSubTaskContext& rContext); - virtual ~TSubTaskBase(); + public: + TSubTaskBase(TSubTaskContext& rContext); + virtual ~TSubTaskBase(); - virtual void Reset() = 0; + virtual void Reset() = 0; - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) = 0; - virtual ESubOperationType GetSubOperationType() const = 0; + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) = 0; + virtual ESubOperationType GetSubOperationType() const = 0; - // serialization - virtual void Store(const ISerializerPtr& spSerializer) const = 0; - virtual void Load(const ISerializerPtr& spSerializer) = 0; + // serialization + virtual void Store(const ISerializerPtr& spSerializer) const = 0; + virtual void Load(const ISerializerPtr& spSerializer) = 0; - // stats - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const = 0; + // stats + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const = 0; -protected: - // some common operations - TSubTaskContext& GetContext() { return m_rContext; } - const TSubTaskContext& GetContext() const { return m_rContext; } + protected: + // some common operations + TSubTaskContext& GetContext() { return m_rContext; } + const TSubTaskContext& GetContext() const { return m_rContext; } - TSmartPath CalculateDestinationPath(const TFileInfoPtr& spFileInfo, TSmartPath pathDst, int iFlags); - TSmartPath FindFreeSubstituteName(TSmartPath pathSrcPath, TSmartPath pathDstPath) const; + TSmartPath CalculateDestinationPath(const TFileInfoPtr& spFileInfo, TSmartPath pathDst, int iFlags); + TSmartPath FindFreeSubstituteName(TSmartPath pathSrcPath, TSmartPath pathDstPath) const; -private: - TSubTaskBase(const TSubTaskBase&); - TSubTaskBase& operator=(const TSubTaskBase&); + private: + TSubTaskBase(const TSubTaskBase&); + TSubTaskBase& operator=(const TSubTaskBase&); -private: - TSubTaskContext& m_rContext; -}; + private: + TSubTaskContext& m_rContext; + }; -typedef boost::shared_ptr TSubTaskBasePtr; + typedef boost::shared_ptr TSubTaskBasePtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSubTaskContext.cpp =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskContext.cpp (.../TSubTaskContext.cpp) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TSubTaskContext.cpp (.../TSubTaskContext.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,118 +26,117 @@ #include "TCoreException.h" #include "TFileFiltersArray.h" -BEGIN_CHCORE_NAMESPACE - -TSubTaskContext::TSubTaskContext(TConfig& rConfig, const TBasePathDataContainerPtr& spBasePaths, - const TFileFiltersArray& rFilters, - TTaskConfigTracker& rCfgTracker, icpf::log_file& rLog, - TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem) : - m_rConfig(rConfig), - m_eOperationType(eOperation_None), - m_spBasePaths(spBasePaths), - m_pathDestination(), - m_rCfgTracker(rCfgTracker), - m_rLog(rLog), - m_rThreadController(rThreadController), - m_spFilesystem(spFilesystem), - m_rFilters(rFilters) +namespace chcore { - if (!spFilesystem) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); -} + TSubTaskContext::TSubTaskContext(TConfig& rConfig, const TBasePathDataContainerPtr& spBasePaths, + const TFileFiltersArray& rFilters, + TTaskConfigTracker& rCfgTracker, icpf::log_file& rLog, + TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem) : + m_rConfig(rConfig), + m_eOperationType(eOperation_None), + m_spBasePaths(spBasePaths), + m_pathDestination(), + m_rCfgTracker(rCfgTracker), + m_rLog(rLog), + m_rThreadController(rThreadController), + m_spFilesystem(spFilesystem), + m_rFilters(rFilters) + { + if (!spFilesystem) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); + } -TSubTaskContext::~TSubTaskContext() -{ -} + TSubTaskContext::~TSubTaskContext() + { + } -TConfig& TSubTaskContext::GetConfig() -{ - return m_rConfig; -} + TConfig& TSubTaskContext::GetConfig() + { + return m_rConfig; + } -const TConfig& TSubTaskContext::GetConfig() const -{ - return m_rConfig; -} + const TConfig& TSubTaskContext::GetConfig() const + { + return m_rConfig; + } -EOperationType TSubTaskContext::GetOperationType() const -{ - return m_eOperationType; -} + EOperationType TSubTaskContext::GetOperationType() const + { + return m_eOperationType; + } -void TSubTaskContext::SetOperationType(EOperationType eOperationType) -{ - m_eOperationType = eOperationType; -} + void TSubTaskContext::SetOperationType(EOperationType eOperationType) + { + m_eOperationType = eOperationType; + } -TBasePathDataContainerPtr TSubTaskContext::GetBasePaths() const -{ - return m_spBasePaths; -} + TBasePathDataContainerPtr TSubTaskContext::GetBasePaths() const + { + return m_spBasePaths; + } -TFileInfoArray& TSubTaskContext::GetFilesCache() -{ - return m_tFilesCache; -} + TFileInfoArray& TSubTaskContext::GetFilesCache() + { + return m_tFilesCache; + } -const TFileInfoArray& TSubTaskContext::GetFilesCache() const -{ - return m_tFilesCache; -} + const TFileInfoArray& TSubTaskContext::GetFilesCache() const + { + return m_tFilesCache; + } -TSmartPath TSubTaskContext::GetDestinationPath() const -{ - return m_pathDestination; -} + TSmartPath TSubTaskContext::GetDestinationPath() const + { + return m_pathDestination; + } -void TSubTaskContext::SetDestinationPath(const TSmartPath& pathDestination) -{ - m_pathDestination = pathDestination; -} + void TSubTaskContext::SetDestinationPath(const TSmartPath& pathDestination) + { + m_pathDestination = pathDestination; + } -TTaskConfigTracker& TSubTaskContext::GetCfgTracker() -{ - return m_rCfgTracker; -} + TTaskConfigTracker& TSubTaskContext::GetCfgTracker() + { + return m_rCfgTracker; + } -const TTaskConfigTracker& TSubTaskContext::GetCfgTracker() const -{ - return m_rCfgTracker; -} + const TTaskConfigTracker& TSubTaskContext::GetCfgTracker() const + { + return m_rCfgTracker; + } -icpf::log_file& TSubTaskContext::GetLog() -{ - return m_rLog; -} + icpf::log_file& TSubTaskContext::GetLog() + { + return m_rLog; + } -const icpf::log_file& TSubTaskContext::GetLog() const -{ - return m_rLog; -} + const icpf::log_file& TSubTaskContext::GetLog() const + { + return m_rLog; + } -TWorkerThreadController& TSubTaskContext::GetThreadController() -{ - return m_rThreadController; -} + TWorkerThreadController& TSubTaskContext::GetThreadController() + { + return m_rThreadController; + } -const TWorkerThreadController& TSubTaskContext::GetThreadController() const -{ - return m_rThreadController; -} + const TWorkerThreadController& TSubTaskContext::GetThreadController() const + { + return m_rThreadController; + } -IFilesystemPtr TSubTaskContext::GetLocalFilesystem() -{ - return m_spFilesystem; -} + IFilesystemPtr TSubTaskContext::GetLocalFilesystem() + { + return m_spFilesystem; + } -const IFilesystemPtr TSubTaskContext::GetLocalFilesystem() const -{ - return m_spFilesystem; -} + const IFilesystemPtr TSubTaskContext::GetLocalFilesystem() const + { + return m_spFilesystem; + } -const TFileFiltersArray& TSubTaskContext::GetFilters() const -{ - return m_rFilters; + const TFileFiltersArray& TSubTaskContext::GetFilters() const + { + return m_rFilters; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSubTaskContext.h =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskContext.h (.../TSubTaskContext.h) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TSubTaskContext.h (.../TSubTaskContext.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -36,91 +36,90 @@ class log_file; } -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + class TWorkerThreadController; + class TTaskConfigTracker; + class TLocalFilesystem; + class TConfig; + class TFileFiltersArray; -class TWorkerThreadController; -class TTaskConfigTracker; -class TLocalFilesystem; -class TConfig; -class TFileFiltersArray; + /////////////////////////////////////////////////////////////////////////// + // TSubTaskContext -/////////////////////////////////////////////////////////////////////////// -// TSubTaskContext + class LIBCHCORE_API TSubTaskContext + { + public: + TSubTaskContext(TConfig& rConfig, const TBasePathDataContainerPtr& spBasePaths, + const TFileFiltersArray& rFilters, + TTaskConfigTracker& rCfgTracker, icpf::log_file& rLog, + TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem); + ~TSubTaskContext(); -class LIBCHCORE_API TSubTaskContext -{ -public: - TSubTaskContext(TConfig& rConfig, const TBasePathDataContainerPtr& spBasePaths, - const TFileFiltersArray& rFilters, - TTaskConfigTracker& rCfgTracker, icpf::log_file& rLog, - TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem); - ~TSubTaskContext(); + TConfig& GetConfig(); + const TConfig& GetConfig() const; - TConfig& GetConfig(); - const TConfig& GetConfig() const; + EOperationType GetOperationType() const; + void SetOperationType(EOperationType eOperationType); - EOperationType GetOperationType() const; - void SetOperationType(EOperationType eOperationType); + TBasePathDataContainerPtr GetBasePaths() const; - TBasePathDataContainerPtr GetBasePaths() const; + const TFileFiltersArray& GetFilters() const; + TFileInfoArray& GetFilesCache(); + const TFileInfoArray& GetFilesCache() const; - const TFileFiltersArray& GetFilters() const; - TFileInfoArray& GetFilesCache(); - const TFileInfoArray& GetFilesCache() const; + TSmartPath GetDestinationPath() const; + void SetDestinationPath(const TSmartPath& pathDestination); - TSmartPath GetDestinationPath() const; - void SetDestinationPath(const TSmartPath& pathDestination); + TTaskConfigTracker& GetCfgTracker(); + const TTaskConfigTracker& GetCfgTracker() const; - TTaskConfigTracker& GetCfgTracker(); - const TTaskConfigTracker& GetCfgTracker() const; + icpf::log_file& GetLog(); + const icpf::log_file& GetLog() const; - icpf::log_file& GetLog(); - const icpf::log_file& GetLog() const; + TWorkerThreadController& GetThreadController(); + const TWorkerThreadController& GetThreadController() const; - TWorkerThreadController& GetThreadController(); - const TWorkerThreadController& GetThreadController() const; + IFilesystemPtr GetLocalFilesystem(); + const IFilesystemPtr GetLocalFilesystem() const; - IFilesystemPtr GetLocalFilesystem(); - const IFilesystemPtr GetLocalFilesystem() const; + private: + TSubTaskContext(const TSubTaskContext& rSrc); + TSubTaskContext& operator=(const TSubTaskContext& rSrc); -private: - TSubTaskContext(const TSubTaskContext& rSrc); - TSubTaskContext& operator=(const TSubTaskContext& rSrc); + private: + TConfig& m_rConfig; -private: - TConfig& m_rConfig; + EOperationType m_eOperationType; - EOperationType m_eOperationType; - - // information about input paths + // information about input paths #pragma warning(push) #pragma warning(disable: 4251) - TBasePathDataContainerPtr m_spBasePaths; + TBasePathDataContainerPtr m_spBasePaths; #pragma warning(pop) - const TFileFiltersArray& m_rFilters; + const TFileFiltersArray& m_rFilters; - // data on which to operate - TFileInfoArray m_tFilesCache; + // data on which to operate + TFileInfoArray m_tFilesCache; - TSmartPath m_pathDestination; + TSmartPath m_pathDestination; - // configuration changes tracking - TTaskConfigTracker& m_rCfgTracker; + // configuration changes tracking + TTaskConfigTracker& m_rCfgTracker; - // local filesystem access functions + // local filesystem access functions #pragma warning(push) #pragma warning(disable: 4251) - IFilesystemPtr m_spFilesystem; + IFilesystemPtr m_spFilesystem; #pragma warning(pop) - // additional data - icpf::log_file& m_rLog; + // additional data + icpf::log_file& m_rLog; - // thread control - TWorkerThreadController& m_rThreadController; -}; + // thread control + TWorkerThreadController& m_rThreadController; + }; +} -END_CHCORE_NAMESPACE - #endif // __TSUBTASKCONTEXT_H__ Index: src/libchcore/TSubTaskCopyMove.cpp =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskCopyMove.cpp (.../TSubTaskCopyMove.cpp) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/TSubTaskCopyMove.cpp (.../TSubTaskCopyMove.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -46,348 +46,308 @@ #include #include "TTaskConfigBufferSizes.h" -BEGIN_CHCORE_NAMESPACE - -struct CUSTOM_COPY_PARAMS +namespace chcore { - TFileInfoPtr spSrcFile; // CFileInfo - src file - TSmartPath pathDstFile; // dest path with filename + struct CUSTOM_COPY_PARAMS + { + TFileInfoPtr spSrcFile; // CFileInfo - src file + TSmartPath pathDstFile; // dest path with filename - TBufferSizes tBufferSizes; - TOverlappedDataBufferQueue dbBuffer; // buffer handling - bool bOnlyCreate; // flag from configuration - skips real copying - only create - bool bProcessed; // has the element been processed ? (false if skipped) -}; + TBufferSizes tBufferSizes; + TOverlappedDataBufferQueue dbBuffer; // buffer handling + bool bOnlyCreate; // flag from configuration - skips real copying - only create + bool bProcessed; // has the element been processed ? (false if skipped) + }; -/////////////////////////////////////////////////////////////////////////////////////////////////// -// class TSubTaskCopyMove + /////////////////////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskCopyMove -TSubTaskCopyMove::TSubTaskCopyMove(TSubTaskContext& tSubTaskContext) : - TSubTaskBase(tSubTaskContext), - m_tSubTaskStats(eSubOperation_Copying) -{ -} + TSubTaskCopyMove::TSubTaskCopyMove(TSubTaskContext& tSubTaskContext) : + TSubTaskBase(tSubTaskContext), + m_tSubTaskStats(eSubOperation_Copying) + { + } -void TSubTaskCopyMove::Reset() -{ - m_tSubTaskStats.Clear(); -} + void TSubTaskCopyMove::Reset() + { + m_tSubTaskStats.Clear(); + } -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::Exec(const IFeedbackHandlerPtr& spFeedback) -{ - TScopedRunningTimeTracker guard(m_tSubTaskStats); - TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(spFeedback, guard)); + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::Exec(const IFeedbackHandlerPtr& spFeedback) + { + TScopedRunningTimeTracker guard(m_tSubTaskStats); + TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(spFeedback, guard)); - icpf::log_file& rLog = GetContext().GetLog(); - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - TTaskConfigTracker& rCfgTracker = GetContext().GetCfgTracker(); - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - const TConfig& rConfig = GetContext().GetConfig(); - TSmartPath pathDestination = GetContext().GetDestinationPath(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + icpf::log_file& rLog = GetContext().GetLog(); + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + TTaskConfigTracker& rCfgTracker = GetContext().GetCfgTracker(); + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + const TConfig& rConfig = GetContext().GetConfig(); + TSmartPath pathDestination = GetContext().GetDestinationPath(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - // log - rLog.logi(_T("Processing files/folders (ProcessFiles)")); + // log + rLog.logi(_T("Processing files/folders (ProcessFiles)")); - // initialize stats if not resuming (when resuming we have already initialized - // the stats once - it is being restored in Load() too). - if (!m_tSubTaskStats.IsInitialized()) - m_tSubTaskStats.Init(TBufferSizes::eBuffer_Default, rFilesCache.GetSize(), 0, rFilesCache.CalculateTotalSize(), rFilesCache.CalculatePartialSize(m_tSubTaskStats.GetCurrentIndex()), TString()); - else - { - _ASSERTE(rFilesCache.GetSize() == m_tSubTaskStats.GetTotalCount()); - if (rFilesCache.GetSize() != m_tSubTaskStats.GetTotalCount()) - THROW_CORE_EXCEPTION(eErr_InternalProblem); - } + // initialize stats if not resuming (when resuming we have already initialized + // the stats once - it is being restored in Load() too). + if (!m_tSubTaskStats.IsInitialized()) + m_tSubTaskStats.Init(TBufferSizes::eBuffer_Default, rFilesCache.GetSize(), 0, rFilesCache.CalculateTotalSize(), rFilesCache.CalculatePartialSize(m_tSubTaskStats.GetCurrentIndex()), TString()); + else + { + _ASSERTE(rFilesCache.GetSize() == m_tSubTaskStats.GetTotalCount()); + if (rFilesCache.GetSize() != m_tSubTaskStats.GetTotalCount()) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } - // now it's time to check if there is enough space on destination device - TSubTaskBase::ESubOperationResult eResult = CheckForFreeSpaceFB(spFeedbackHandler); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; + // now it's time to check if there is enough space on destination device + TSubTaskBase::ESubOperationResult eResult = CheckForFreeSpaceFB(spFeedbackHandler); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; - // begin at index which wasn't processed previously - file_count_t fcSize = rFilesCache.GetSize(); - file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); - unsigned long long ullCurrentItemProcessedSize = m_tSubTaskStats.GetCurrentItemProcessedSize(); - bool bCurrentFileSilentResume = m_tSubTaskStats.CanCurrentItemSilentResume(); + // begin at index which wasn't processed previously + file_count_t fcSize = rFilesCache.GetSize(); + file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); + unsigned long long ullCurrentItemProcessedSize = m_tSubTaskStats.GetCurrentItemProcessedSize(); + bool bCurrentFileSilentResume = m_tSubTaskStats.CanCurrentItemSilentResume(); - bool bIgnoreFolders = GetTaskPropValue(rConfig); - bool bForceDirectories = GetTaskPropValue(rConfig); + bool bIgnoreFolders = GetTaskPropValue(rConfig); + bool bForceDirectories = GetTaskPropValue(rConfig); - // create a buffer of size m_nBufferSize - CUSTOM_COPY_PARAMS ccp; - ccp.bProcessed = false; - ccp.bOnlyCreate = GetTaskPropValue(rConfig); + // create a buffer of size m_nBufferSize + CUSTOM_COPY_PARAMS ccp; + ccp.bProcessed = false; + ccp.bOnlyCreate = GetTaskPropValue(rConfig); - // remove changes in buffer sizes to avoid re-creation later - rCfgTracker.RemoveModificationSet(TOptionsSet() % eTO_DefaultBufferSize % eTO_OneDiskBufferSize % eTO_TwoDisksBufferSize % eTO_CDBufferSize % eTO_LANBufferSize % eTO_UseOnlyDefaultBuffer % eTO_BufferQueueDepth); + // remove changes in buffer sizes to avoid re-creation later + rCfgTracker.RemoveModificationSet(TOptionsSet() % eTO_DefaultBufferSize % eTO_OneDiskBufferSize % eTO_TwoDisksBufferSize % eTO_CDBufferSize % eTO_LANBufferSize % eTO_UseOnlyDefaultBuffer % eTO_BufferQueueDepth); - AdjustBufferIfNeeded(ccp.dbBuffer, ccp.tBufferSizes, true); + AdjustBufferIfNeeded(ccp.dbBuffer, ccp.tBufferSizes, true); - // log - TString strFormat; - strFormat = _T("Processing files/folders (ProcessFiles):\r\n\tOnlyCreate: %create\r\n\tFiles/folders count: %filecount\r\n\tIgnore Folders: %ignorefolders\r\n\tDest path: %dstpath\r\n\tCurrent index (0-based): %currindex"); - strFormat.Replace(_T("%create"), boost::lexical_cast(ccp.bOnlyCreate).c_str()); - strFormat.Replace(_T("%filecount"), boost::lexical_cast(fcSize).c_str()); - strFormat.Replace(_T("%ignorefolders"), boost::lexical_cast(bIgnoreFolders).c_str()); - strFormat.Replace(_T("%dstpath"), pathDestination.ToString()); - strFormat.Replace(_T("%currindex"), boost::lexical_cast(fcIndex).c_str()); + // log + TString strFormat; + strFormat = _T("Processing files/folders (ProcessFiles):\r\n\tOnlyCreate: %create\r\n\tFiles/folders count: %filecount\r\n\tIgnore Folders: %ignorefolders\r\n\tDest path: %dstpath\r\n\tCurrent index (0-based): %currindex"); + strFormat.Replace(_T("%create"), boost::lexical_cast(ccp.bOnlyCreate).c_str()); + strFormat.Replace(_T("%filecount"), boost::lexical_cast(fcSize).c_str()); + strFormat.Replace(_T("%ignorefolders"), boost::lexical_cast(bIgnoreFolders).c_str()); + strFormat.Replace(_T("%dstpath"), pathDestination.ToString()); + strFormat.Replace(_T("%currindex"), boost::lexical_cast(fcIndex).c_str()); - rLog.logi(strFormat.c_str()); + rLog.logi(strFormat.c_str()); - for(; fcIndex < fcSize; fcIndex++) - { - // should we kill ? - if(rThreadController.KillRequested()) + for(; fcIndex < fcSize; fcIndex++) { - // log - rLog.logi(_T("Kill request while processing file in ProcessFiles")); - return TSubTaskBase::eSubResult_KillRequest; - } + // should we kill ? + if(rThreadController.KillRequested()) + { + // log + rLog.logi(_T("Kill request while processing file in ProcessFiles")); + return TSubTaskBase::eSubResult_KillRequest; + } - // next file to be copied - TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcIndex); - TSmartPath pathCurrent = spFileInfo->GetFullFilePath(); + // next file to be copied + TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcIndex); + TSmartPath pathCurrent = spFileInfo->GetFullFilePath(); - // new stats - m_tSubTaskStats.SetCurrentIndex(fcIndex); - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); - m_tSubTaskStats.SetCurrentItemProcessedSize(ullCurrentItemProcessedSize); // preserve the processed size for the first item - ullCurrentItemProcessedSize = 0; - m_tSubTaskStats.SetCurrentItemTotalSize(spFileInfo->GetLength64()); - m_tSubTaskStats.SetCurrentItemSilentResume(bCurrentFileSilentResume); - bCurrentFileSilentResume = false; + // new stats + m_tSubTaskStats.SetCurrentIndex(fcIndex); + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); + m_tSubTaskStats.SetCurrentItemProcessedSize(ullCurrentItemProcessedSize); // preserve the processed size for the first item + ullCurrentItemProcessedSize = 0; + m_tSubTaskStats.SetCurrentItemTotalSize(spFileInfo->GetLength64()); + m_tSubTaskStats.SetCurrentItemSilentResume(bCurrentFileSilentResume); + bCurrentFileSilentResume = false; - // set dest path with filename - ccp.pathDstFile = CalculateDestinationPath(spFileInfo, pathDestination, ((int)bForceDirectories) << 1 | (int)bIgnoreFolders); + // set dest path with filename + ccp.pathDstFile = CalculateDestinationPath(spFileInfo, pathDestination, ((int)bForceDirectories) << 1 | (int)bIgnoreFolders); - // are the files/folders lie on the same partition ? - bool bMove = GetContext().GetOperationType() == eOperation_Move; + // are the files/folders lie on the same partition ? + bool bMove = GetContext().GetOperationType() == eOperation_Move; - // if folder - create it - if(spFileInfo->IsDirectory()) - { - eResult = CreateDirectoryFB(spFeedbackHandler, ccp.pathDstFile); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; + // if folder - create it + if(spFileInfo->IsDirectory()) + { + eResult = CreateDirectoryFB(spFeedbackHandler, ccp.pathDstFile); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; - // new stats - m_tSubTaskStats.IncreaseProcessedSize(spFileInfo->GetLength64()); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(spFileInfo->GetLength64()); + // new stats + m_tSubTaskStats.IncreaseProcessedSize(spFileInfo->GetLength64()); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(spFileInfo->GetLength64()); - spFileInfo->MarkAsProcessed(true); - } - else - { - // start copying/moving file - ccp.spSrcFile = spFileInfo; - ccp.bProcessed = false; + spFileInfo->MarkAsProcessed(true); + } + else + { + // start copying/moving file + ccp.spSrcFile = spFileInfo; + ccp.bProcessed = false; - // copy data - eResult = CustomCopyFileFB(spFeedbackHandler, &ccp); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; + // copy data + eResult = CustomCopyFileFB(spFeedbackHandler, &ccp); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; - spFileInfo->MarkAsProcessed(ccp.bProcessed); + spFileInfo->MarkAsProcessed(ccp.bProcessed); - // if moving - delete file (only if config flag is set) - if(bMove && spFileInfo->IsProcessed() && !GetTaskPropValue(rConfig)) - { - if(!GetTaskPropValue(rConfig)) - spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), FILE_ATTRIBUTE_NORMAL); - spFilesystem->DeleteFile(spFileInfo->GetFullFilePath()); // there will be another try later, so we don't check - // if succeeded + // if moving - delete file (only if config flag is set) + if(bMove && spFileInfo->IsProcessed() && !GetTaskPropValue(rConfig)) + { + if(!GetTaskPropValue(rConfig)) + spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), FILE_ATTRIBUTE_NORMAL); + spFilesystem->DeleteFile(spFileInfo->GetFullFilePath()); // there will be another try later, so we don't check + // if succeeded + } } - } - // set a time - if(GetTaskPropValue(rConfig)) - spFilesystem->SetFileDirectoryTime(ccp.pathDstFile, spFileInfo->GetCreationTime(), spFileInfo->GetLastAccessTime(), spFileInfo->GetLastWriteTime()); // no error checking (but most probably it should be checked) + // set a time + if(GetTaskPropValue(rConfig)) + spFilesystem->SetFileDirectoryTime(ccp.pathDstFile, spFileInfo->GetCreationTime(), spFileInfo->GetLastAccessTime(), spFileInfo->GetLastWriteTime()); // no error checking (but most probably it should be checked) - // attributes - if(GetTaskPropValue(rConfig)) - spFilesystem->SetAttributes(ccp.pathDstFile, spFileInfo->GetAttributes()); // as above - } + // attributes + if(GetTaskPropValue(rConfig)) + spFilesystem->SetAttributes(ccp.pathDstFile, spFileInfo->GetAttributes()); // as above + } - m_tSubTaskStats.SetCurrentIndex(fcIndex); + m_tSubTaskStats.SetCurrentIndex(fcIndex); - // new stats - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(TString()); + // new stats + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(TString()); - // log - rLog.logi(_T("Finished processing in ProcessFiles")); + // log + rLog.logi(_T("Finished processing in ProcessFiles")); - return TSubTaskBase::eSubResult_Continue; -} + return TSubTaskBase::eSubResult_Continue; + } -void TSubTaskCopyMove::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const -{ - m_tSubTaskStats.GetSnapshot(spStats); - // if this subtask is not started yet, try to get the most fresh information for processing - if(!spStats->IsRunning() && spStats->GetTotalCount() == 0 && spStats->GetTotalSize() == 0) + void TSubTaskCopyMove::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const { - spStats->SetTotalCount(GetContext().GetFilesCache().GetSize()); - spStats->SetTotalSize(GetContext().GetFilesCache().CalculateTotalSize()); + m_tSubTaskStats.GetSnapshot(spStats); + // if this subtask is not started yet, try to get the most fresh information for processing + if(!spStats->IsRunning() && spStats->GetTotalCount() == 0 && spStats->GetTotalSize() == 0) + { + spStats->SetTotalCount(GetContext().GetFilesCache().GetSize()); + spStats->SetTotalSize(GetContext().GetFilesCache().CalculateTotalSize()); + } } -} -TBufferSizes::EBufferType TSubTaskCopyMove::GetBufferIndex(const TBufferSizes& rBufferSizes, const TFileInfoPtr& spFileInfo) -{ - if(rBufferSizes.IsOnlyDefault()) - return TBufferSizes::eBuffer_Default; + TBufferSizes::EBufferType TSubTaskCopyMove::GetBufferIndex(const TBufferSizes& rBufferSizes, const TFileInfoPtr& spFileInfo) + { + if(rBufferSizes.IsOnlyDefault()) + return TBufferSizes::eBuffer_Default; - if(!spFileInfo) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + if(!spFileInfo) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - TSmartPath pathSource = spFileInfo->GetFullFilePath(); - TSmartPath pathDestination = GetContext().GetDestinationPath(); + TSmartPath pathSource = spFileInfo->GetFullFilePath(); + TSmartPath pathDestination = GetContext().GetDestinationPath(); - TLocalFilesystem::EPathsRelation eRelation = GetContext().GetLocalFilesystem()->GetPathsRelation(pathSource, pathDestination); - switch(eRelation) - { - case TLocalFilesystem::eRelation_Network: - return TBufferSizes::eBuffer_LAN; + TLocalFilesystem::EPathsRelation eRelation = GetContext().GetLocalFilesystem()->GetPathsRelation(pathSource, pathDestination); + switch(eRelation) + { + case TLocalFilesystem::eRelation_Network: + return TBufferSizes::eBuffer_LAN; - case TLocalFilesystem::eRelation_CDRom: - return TBufferSizes::eBuffer_CD; + case TLocalFilesystem::eRelation_CDRom: + return TBufferSizes::eBuffer_CD; - case TLocalFilesystem::eRelation_TwoPhysicalDisks: - return TBufferSizes::eBuffer_TwoDisks; + case TLocalFilesystem::eRelation_TwoPhysicalDisks: + return TBufferSizes::eBuffer_TwoDisks; - case TLocalFilesystem::eRelation_SinglePhysicalDisk: - return TBufferSizes::eBuffer_OneDisk; + case TLocalFilesystem::eRelation_SinglePhysicalDisk: + return TBufferSizes::eBuffer_OneDisk; - //case eRelation_Other: - default: - return TBufferSizes::eBuffer_Default; + //case eRelation_Other: + default: + return TBufferSizes::eBuffer_Default; + } } -} -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::CustomCopyFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, CUSTOM_COPY_PARAMS* pData) -{ - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - icpf::log_file& rLog = GetContext().GetLog(); - const TConfig& rConfig = GetContext().GetConfig(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::CustomCopyFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, CUSTOM_COPY_PARAMS* pData) + { + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + icpf::log_file& rLog = GetContext().GetLog(); + const TConfig& rConfig = GetContext().GetConfig(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - IFilesystemFilePtr fileSrc = spFilesystem->CreateFileObject(pData->spSrcFile->GetFullFilePath()); - IFilesystemFilePtr fileDst = spFilesystem->CreateFileObject(pData->pathDstFile); + IFilesystemFilePtr fileSrc = spFilesystem->CreateFileObject(pData->spSrcFile->GetFullFilePath()); + IFilesystemFilePtr fileDst = spFilesystem->CreateFileObject(pData->pathDstFile); - TString strFormat; - TSubTaskBase::ESubOperationResult eResult = TSubTaskBase::eSubResult_Continue; + TString strFormat; + TSubTaskBase::ESubOperationResult eResult = TSubTaskBase::eSubResult_Continue; - // calculate if we want to disable buffering for file transfer - // NOTE: we are using here the file size read when scanning directories for files; it might be - // outdated at this point, but at present we don't want to re-read file size since it - // will cost additional disk access - bool bNoBuffer = (GetTaskPropValue(rConfig) && - pData->spSrcFile->GetLength64() >= GetTaskPropValue(rConfig)); + // calculate if we want to disable buffering for file transfer + // NOTE: we are using here the file size read when scanning directories for files; it might be + // outdated at this point, but at present we don't want to re-read file size since it + // will cost additional disk access + bool bNoBuffer = (GetTaskPropValue(rConfig) && + pData->spSrcFile->GetLength64() >= GetTaskPropValue(rConfig)); - bool bSkip = false; - eResult = OpenSrcAndDstFilesFB(spFeedbackHandler, pData, fileSrc, fileDst, bNoBuffer, bSkip); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if(bSkip) - return TSubTaskBase::eSubResult_Continue; + bool bSkip = false; + eResult = OpenSrcAndDstFilesFB(spFeedbackHandler, pData, fileSrc, fileDst, bNoBuffer, bSkip); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if(bSkip) + return TSubTaskBase::eSubResult_Continue; - // let the buffer queue know that we change the data source - pData->dbBuffer.DataSourceChanged(); + // let the buffer queue know that we change the data source + pData->dbBuffer.DataSourceChanged(); - // recreate buffer if needed - AdjustBufferIfNeeded(pData->dbBuffer, pData->tBufferSizes); + // recreate buffer if needed + AdjustBufferIfNeeded(pData->dbBuffer, pData->tBufferSizes); - ATLTRACE(_T("CustomCopyFile: %s\n"), pData->spSrcFile->GetFullFilePath().ToString()); + ATLTRACE(_T("CustomCopyFile: %s\n"), pData->spSrcFile->GetFullFilePath().ToString()); - // establish count of data to read - TBufferSizes::EBufferType eBufferIndex = GetBufferIndex(pData->tBufferSizes, pData->spSrcFile); - m_tSubTaskStats.SetCurrentBufferIndex(eBufferIndex); + // establish count of data to read + TBufferSizes::EBufferType eBufferIndex = GetBufferIndex(pData->tBufferSizes, pData->spSrcFile); + m_tSubTaskStats.SetCurrentBufferIndex(eBufferIndex); - DWORD dwToRead = RoundUp(pData->tBufferSizes.GetSizeByType(eBufferIndex), IFilesystemFile::MaxSectorSize); + DWORD dwToRead = RoundUp(pData->tBufferSizes.GetSizeByType(eBufferIndex), IFilesystemFile::MaxSectorSize); - // read data from file to buffer - enum { eKillThread = 0, eWriteFinished, eWritePossible, eReadPossible, eHandleCount }; - std::array arrHandles = { - rThreadController.GetKillThreadHandle(), - pData->dbBuffer.GetEventWriteFinishedHandle(), - pData->dbBuffer.GetEventWritePossibleHandle(), - pData->dbBuffer.GetEventReadPossibleHandle() - }; + // read data from file to buffer + enum { eKillThread = 0, eWriteFinished, eWritePossible, eReadPossible, eHandleCount }; + std::array arrHandles = { + rThreadController.GetKillThreadHandle(), + pData->dbBuffer.GetEventWriteFinishedHandle(), + pData->dbBuffer.GetEventWritePossibleHandle(), + pData->dbBuffer.GetEventReadPossibleHandle() + }; - // #bug: always starting at the beginning of file instead of the position that OpenSrcAndDstFilesFB set the files to - unsigned long long ullNextReadPos = 0; + // #bug: always starting at the beginning of file instead of the position that OpenSrcAndDstFilesFB set the files to + unsigned long long ullNextReadPos = 0; - bool bStopProcessing = false; - while(!bStopProcessing) - { - DWORD dwResult = WaitForMultipleObjectsEx(eHandleCount, arrHandles.data(), false, INFINITE, true); - switch(dwResult) + bool bStopProcessing = false; + while(!bStopProcessing) { - case STATUS_USER_APC: - break; - - case WAIT_OBJECT_0 + eKillThread: + DWORD dwResult = WaitForMultipleObjectsEx(eHandleCount, arrHandles.data(), false, INFINITE, true); + switch(dwResult) { - // log - strFormat = _T("Kill request while main copying file %srcpath -> %dstpath"); - strFormat.Replace(_T("%srcpath"), pData->spSrcFile->GetFullFilePath().ToString()); - strFormat.Replace(_T("%dstpath"), pData->pathDstFile.ToString()); - rLog.logi(strFormat.c_str()); - return TSubTaskBase::eSubResult_KillRequest; - } + case STATUS_USER_APC: + break; - case WAIT_OBJECT_0 + eReadPossible: - { - TOverlappedDataBuffer* pBuffer = pData->dbBuffer.GetEmptyBuffer(); - if (!pBuffer) - THROW_CORE_EXCEPTION(eErr_InternalProblem); - - pBuffer->InitForRead(ullNextReadPos, dwToRead); - ullNextReadPos += dwToRead; - - eResult = ReadFileFB(spFeedbackHandler, fileSrc, *pBuffer, pData->spSrcFile->GetFullFilePath(), bSkip); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if(bSkip) + case WAIT_OBJECT_0 + eKillThread: { - // new stats - m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - - pData->bProcessed = false; - return TSubTaskBase::eSubResult_Continue; + // log + strFormat = _T("Kill request while main copying file %srcpath -> %dstpath"); + strFormat.Replace(_T("%srcpath"), pData->spSrcFile->GetFullFilePath().ToString()); + strFormat.Replace(_T("%dstpath"), pData->pathDstFile.ToString()); + rLog.logi(strFormat.c_str()); + return TSubTaskBase::eSubResult_KillRequest; } - break; - } - case WAIT_OBJECT_0 + eWritePossible: - { - TOverlappedDataBuffer* pBuffer = pData->dbBuffer.GetFullBuffer(); - if (!pBuffer) - THROW_CORE_EXCEPTION(eErr_InternalProblem); - // was there an error reported? - if(pBuffer->GetErrorCode() != ERROR_SUCCESS) + case WAIT_OBJECT_0 + eReadPossible: { - // read error encountered - handle it - eResult = HandleReadError(spFeedbackHandler, *pBuffer, pData->spSrcFile->GetFullFilePath(), bSkip); - if(eResult == TSubTaskBase::eSubResult_Retry) - { - // re-request read of the same data - eResult = ReadFileFB(spFeedbackHandler, fileSrc, *pBuffer, pData->spSrcFile->GetFullFilePath(), bSkip); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if(bSkip) - { - // new stats - m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); + TOverlappedDataBuffer* pBuffer = pData->dbBuffer.GetEmptyBuffer(); + if (!pBuffer) + THROW_CORE_EXCEPTION(eErr_InternalProblem); - pData->bProcessed = false; - return TSubTaskBase::eSubResult_Continue; - } - } - else if(eResult != TSubTaskBase::eSubResult_Continue) + pBuffer->InitForRead(ullNextReadPos, dwToRead); + ullNextReadPos += dwToRead; + + eResult = ReadFileFB(spFeedbackHandler, fileSrc, *pBuffer, pData->spSrcFile->GetFullFilePath(), bSkip); + if(eResult != TSubTaskBase::eSubResult_Continue) return eResult; else if(bSkip) { @@ -398,39 +358,51 @@ pData->bProcessed = false; return TSubTaskBase::eSubResult_Continue; } + break; } - else + case WAIT_OBJECT_0 + eWritePossible: { - pBuffer->InitForWrite(); + TOverlappedDataBuffer* pBuffer = pData->dbBuffer.GetFullBuffer(); + if (!pBuffer) + THROW_CORE_EXCEPTION(eErr_InternalProblem); - eResult = WriteFileFB(spFeedbackHandler, fileDst, *pBuffer, pData->pathDstFile, bSkip); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if(bSkip) + // was there an error reported? + if(pBuffer->GetErrorCode() != ERROR_SUCCESS) { - // new stats - m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); + // read error encountered - handle it + eResult = HandleReadError(spFeedbackHandler, *pBuffer, pData->spSrcFile->GetFullFilePath(), bSkip); + if(eResult == TSubTaskBase::eSubResult_Retry) + { + // re-request read of the same data + eResult = ReadFileFB(spFeedbackHandler, fileSrc, *pBuffer, pData->spSrcFile->GetFullFilePath(), bSkip); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if(bSkip) + { + // new stats + m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - pData->bProcessed = false; - return TSubTaskBase::eSubResult_Continue; - } - } + pData->bProcessed = false; + return TSubTaskBase::eSubResult_Continue; + } + } + else if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if(bSkip) + { + // new stats + m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - break; - } - - case WAIT_OBJECT_0 + eWriteFinished: - { - TOverlappedDataBuffer* pBuffer = pData->dbBuffer.GetFinishedBuffer(); - if (!pBuffer) - THROW_CORE_EXCEPTION(eErr_InternalProblem); - - if(pBuffer->GetErrorCode() != ERROR_SUCCESS) - { - eResult = HandleWriteError(spFeedbackHandler, *pBuffer, pData->spSrcFile->GetFullFilePath(), bSkip); - if(eResult == TSubTaskBase::eSubResult_Retry) + pData->bProcessed = false; + return TSubTaskBase::eSubResult_Continue; + } + } + else { + pBuffer->InitForWrite(); + eResult = WriteFileFB(spFeedbackHandler, fileDst, *pBuffer, pData->pathDstFile, bSkip); if(eResult != TSubTaskBase::eSubResult_Continue) return eResult; @@ -444,148 +416,123 @@ return TSubTaskBase::eSubResult_Continue; } } - else if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if(bSkip) - { - // new stats - m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - pData->bProcessed = false; - return TSubTaskBase::eSubResult_Continue; - } + break; } - else + + case WAIT_OBJECT_0 + eWriteFinished: { - eResult = FinalizeFileFB(spFeedbackHandler, fileDst, *pBuffer, pData->pathDstFile, bSkip); - if (eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if (bSkip) + TOverlappedDataBuffer* pBuffer = pData->dbBuffer.GetFinishedBuffer(); + if (!pBuffer) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + + if(pBuffer->GetErrorCode() != ERROR_SUCCESS) { - // new stats - m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); + eResult = HandleWriteError(spFeedbackHandler, *pBuffer, pData->spSrcFile->GetFullFilePath(), bSkip); + if(eResult == TSubTaskBase::eSubResult_Retry) + { + eResult = WriteFileFB(spFeedbackHandler, fileDst, *pBuffer, pData->pathDstFile, bSkip); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if(bSkip) + { + // new stats + m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - pData->bProcessed = false; - return TSubTaskBase::eSubResult_Continue; + pData->bProcessed = false; + return TSubTaskBase::eSubResult_Continue; + } + } + else if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if(bSkip) + { + // new stats + m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); + + pData->bProcessed = false; + return TSubTaskBase::eSubResult_Continue; + } } + else + { + eResult = FinalizeFileFB(spFeedbackHandler, fileDst, *pBuffer, pData->pathDstFile, bSkip); + if (eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if (bSkip) + { + // new stats + m_tSubTaskStats.IncreaseProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize()); - unsigned long long ullCITotalSize = m_tSubTaskStats.GetCurrentItemTotalSize(); - unsigned long long ullCIProcessedSize = m_tSubTaskStats.GetCurrentItemProcessedSize(); + pData->bProcessed = false; + return TSubTaskBase::eSubResult_Continue; + } - unsigned long long ullWritten = pBuffer->GetBytesTransferred(); - if(ullCIProcessedSize + ullWritten > ullCITotalSize) - { - // total size changed - pData->spSrcFile->SetLength64(ullCIProcessedSize + ullWritten); - m_tSubTaskStats.IncreaseCurrentItemTotalSize(ullCIProcessedSize + ullWritten - ullCITotalSize); - m_tSubTaskStats.IncreaseTotalSize(ullCIProcessedSize + ullWritten - ullCITotalSize); - } + unsigned long long ullCITotalSize = m_tSubTaskStats.GetCurrentItemTotalSize(); + unsigned long long ullCIProcessedSize = m_tSubTaskStats.GetCurrentItemProcessedSize(); - // new stats - m_tSubTaskStats.IncreaseProcessedSize(ullWritten); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullWritten); + unsigned long long ullWritten = pBuffer->GetBytesTransferred(); + if(ullCIProcessedSize + ullWritten > ullCITotalSize) + { + // total size changed + pData->spSrcFile->SetLength64(ullCIProcessedSize + ullWritten); + m_tSubTaskStats.IncreaseCurrentItemTotalSize(ullCIProcessedSize + ullWritten - ullCITotalSize); + m_tSubTaskStats.IncreaseTotalSize(ullCIProcessedSize + ullWritten - ullCITotalSize); + } - // stop iterating through file - bStopProcessing = pBuffer->IsLastPart(); - pBuffer->RequeueAsEmpty(); + // new stats + m_tSubTaskStats.IncreaseProcessedSize(ullWritten); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullWritten); + + // stop iterating through file + bStopProcessing = pBuffer->IsLastPart(); + pBuffer->RequeueAsEmpty(); + } + + break; } - break; + default: + THROW_CORE_EXCEPTION(eErr_UnhandledCase); } + } - default: - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + // fix the stats for files shorter than expected + unsigned long long ullCITotalSize = m_tSubTaskStats.GetCurrentItemTotalSize(); + unsigned long long ullCIProcessedSize = m_tSubTaskStats.GetCurrentItemProcessedSize(); + if(ullCIProcessedSize < ullCITotalSize) + { + pData->spSrcFile->SetLength64(ullCIProcessedSize); + m_tSubTaskStats.DecreaseCurrentItemTotalSize(ullCITotalSize - ullCIProcessedSize); + m_tSubTaskStats.DecreaseTotalSize(ullCITotalSize - ullCIProcessedSize); } - } - // fix the stats for files shorter than expected - unsigned long long ullCITotalSize = m_tSubTaskStats.GetCurrentItemTotalSize(); - unsigned long long ullCIProcessedSize = m_tSubTaskStats.GetCurrentItemProcessedSize(); - if(ullCIProcessedSize < ullCITotalSize) - { - pData->spSrcFile->SetLength64(ullCIProcessedSize); - m_tSubTaskStats.DecreaseCurrentItemTotalSize(ullCITotalSize - ullCIProcessedSize); - m_tSubTaskStats.DecreaseTotalSize(ullCITotalSize - ullCIProcessedSize); - } + pData->bProcessed = true; + m_tSubTaskStats.SetCurrentItemProcessedSize(0); - pData->bProcessed = true; - m_tSubTaskStats.SetCurrentItemProcessedSize(0); + pData->dbBuffer.WaitForMissingBuffers(rThreadController.GetKillThreadHandle()); - pData->dbBuffer.WaitForMissingBuffers(rThreadController.GetKillThreadHandle()); - - return TSubTaskBase::eSubResult_Continue; -} - -TSubTaskCopyMove::ESubOperationResult TSubTaskCopyMove::OpenSrcAndDstFilesFB(const IFeedbackHandlerPtr& spFeedbackHandler, CUSTOM_COPY_PARAMS* pData, - const IFilesystemFilePtr& spFileSrc, const IFilesystemFilePtr& spFileDst, bool bNoBuffer, bool& bSkip) -{ - const TConfig& rConfig = GetContext().GetConfig(); - - bSkip = false; - - // first open the source file and handle any failures - TSubTaskCopyMove::ESubOperationResult eResult = OpenSourceFileFB(spFeedbackHandler, spFileSrc, bNoBuffer); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if(!spFileSrc->IsOpen()) - { - // invalid handle = operation skipped by user - unsigned long long ullDiff = pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize(); - - m_tSubTaskStats.IncreaseProcessedSize(ullDiff); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullDiff); - - pData->bProcessed = false; - bSkip = true; return TSubTaskBase::eSubResult_Continue; } - // update the source file size (it might differ from the time this file was originally scanned). - // NOTE: this kind of update could be also done when copying chunks of data beyond the original end-of-file, - // but it would require frequent total size updates and thus - serializations). - // NOTE2: the by-chunk corrections of stats are still applied when copying to ensure even further size - // matching; this update however still allows for better serialization management. - unsigned long long ullNewSize = spFileSrc->GetFileSize(); - unsigned long long ullOldSize = pData->spSrcFile->GetLength64(); - if(ullNewSize != ullOldSize) + TSubTaskCopyMove::ESubOperationResult TSubTaskCopyMove::OpenSrcAndDstFilesFB(const IFeedbackHandlerPtr& spFeedbackHandler, CUSTOM_COPY_PARAMS* pData, + const IFilesystemFilePtr& spFileSrc, const IFilesystemFilePtr& spFileDst, bool bNoBuffer, bool& bSkip) { - if(ullNewSize > ullOldSize) - { - m_tSubTaskStats.IncreaseTotalSize(ullNewSize - ullOldSize); - m_tSubTaskStats.IncreaseCurrentItemTotalSize(ullNewSize - ullOldSize); - } - else - { - m_tSubTaskStats.DecreaseTotalSize(ullOldSize - ullNewSize); - m_tSubTaskStats.DecreaseCurrentItemTotalSize(ullOldSize - ullNewSize); - } + const TConfig& rConfig = GetContext().GetConfig(); - pData->spSrcFile->SetLength64(ullNewSize); - } + bSkip = false; - // change attributes of a dest file - // NOTE: probably should be removed from here and report problems with read-only files - // directly to the user (as feedback request) - if(!GetTaskPropValue(rConfig)) - SetFileAttributes(pData->pathDstFile.ToString(), FILE_ATTRIBUTE_NORMAL); - - // open destination file, handle the failures and possibly existence of the destination file - unsigned long long ullProcessedSize = m_tSubTaskStats.GetCurrentItemProcessedSize(); - unsigned long long ullSeekTo = 0; - bool bDstFileFreshlyCreated = false; - - if (!m_tSubTaskStats.CanCurrentItemSilentResume()) - { - // open destination file for case, when we start operation on this file (i.e. it is not resume of the - // old operation) - eResult = OpenDestinationFileFB(spFeedbackHandler, spFileDst, bNoBuffer, pData->spSrcFile, ullSeekTo, bDstFileFreshlyCreated); + // first open the source file and handle any failures + TSubTaskCopyMove::ESubOperationResult eResult = OpenSourceFileFB(spFeedbackHandler, spFileSrc, bNoBuffer); if(eResult != TSubTaskBase::eSubResult_Continue) return eResult; - else if(!spFileDst->IsOpen()) + else if(!spFileSrc->IsOpen()) { - unsigned long long ullDiff = pData->spSrcFile->GetLength64() - ullProcessedSize; + // invalid handle = operation skipped by user + unsigned long long ullDiff = pData->spSrcFile->GetLength64() - m_tSubTaskStats.GetCurrentItemProcessedSize(); m_tSubTaskStats.IncreaseProcessedSize(ullDiff); m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullDiff); @@ -594,248 +541,361 @@ bSkip = true; return TSubTaskBase::eSubResult_Continue; } - } - else - { - // we are resuming previous operation - eResult = OpenExistingDestinationFileFB(spFeedbackHandler, spFileDst, bNoBuffer); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if(!spFileDst->IsOpen()) + + // update the source file size (it might differ from the time this file was originally scanned). + // NOTE: this kind of update could be also done when copying chunks of data beyond the original end-of-file, + // but it would require frequent total size updates and thus - serializations). + // NOTE2: the by-chunk corrections of stats are still applied when copying to ensure even further size + // matching; this update however still allows for better serialization management. + unsigned long long ullNewSize = spFileSrc->GetFileSize(); + unsigned long long ullOldSize = pData->spSrcFile->GetLength64(); + if(ullNewSize != ullOldSize) { - unsigned long long ullDiff = pData->spSrcFile->GetLength64() - ullProcessedSize; + if(ullNewSize > ullOldSize) + { + m_tSubTaskStats.IncreaseTotalSize(ullNewSize - ullOldSize); + m_tSubTaskStats.IncreaseCurrentItemTotalSize(ullNewSize - ullOldSize); + } + else + { + m_tSubTaskStats.DecreaseTotalSize(ullOldSize - ullNewSize); + m_tSubTaskStats.DecreaseCurrentItemTotalSize(ullOldSize - ullNewSize); + } - m_tSubTaskStats.IncreaseProcessedSize(ullDiff); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullDiff); - - pData->bProcessed = false; - bSkip = true; - return TSubTaskBase::eSubResult_Continue; + pData->spSrcFile->SetLength64(ullNewSize); } - } - if(pData->bOnlyCreate) - { - // we don't copy contents, but need to increase processed size - unsigned long long ullDiff = pData->spSrcFile->GetLength64() - ullProcessedSize; + // change attributes of a dest file + // NOTE: probably should be removed from here and report problems with read-only files + // directly to the user (as feedback request) + if(!GetTaskPropValue(rConfig)) + SetFileAttributes(pData->pathDstFile.ToString(), FILE_ATTRIBUTE_NORMAL); - m_tSubTaskStats.IncreaseProcessedSize(ullDiff); - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullDiff); + // open destination file, handle the failures and possibly existence of the destination file + unsigned long long ullProcessedSize = m_tSubTaskStats.GetCurrentItemProcessedSize(); + unsigned long long ullSeekTo = 0; + bool bDstFileFreshlyCreated = false; - return TSubTaskBase::eSubResult_Continue; - } - - // seek to the position where copying will start - ULONGLONG ullMove = (bNoBuffer ? RoundDown(ullSeekTo, IFilesystemFile::MaxSectorSize) : ullSeekTo);; - if(ullMove != 0) // src and dst files exists, requested resume at the specified index - { - // adjust the stats for the difference between what was already processed and what will now be considered processed - if (ullMove > ullProcessedSize) + if (!m_tSubTaskStats.CanCurrentItemSilentResume()) { - unsigned long long ullDiff = ullMove - ullProcessedSize; - m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullDiff); - m_tSubTaskStats.IncreaseProcessedSize(ullDiff); + // open destination file for case, when we start operation on this file (i.e. it is not resume of the + // old operation) + eResult = OpenDestinationFileFB(spFeedbackHandler, spFileDst, bNoBuffer, pData->spSrcFile, ullSeekTo, bDstFileFreshlyCreated); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if(!spFileDst->IsOpen()) + { + unsigned long long ullDiff = pData->spSrcFile->GetLength64() - ullProcessedSize; + + m_tSubTaskStats.IncreaseProcessedSize(ullDiff); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullDiff); + + pData->bProcessed = false; + bSkip = true; + return TSubTaskBase::eSubResult_Continue; + } } - else if (ullMove < ullProcessedSize) + else { - unsigned long long ullDiff = ullProcessedSize - ullMove; - m_tSubTaskStats.DecreaseCurrentItemProcessedSize(ullDiff); - m_tSubTaskStats.DecreaseProcessedSize(ullDiff); + // we are resuming previous operation + eResult = OpenExistingDestinationFileFB(spFeedbackHandler, spFileDst, bNoBuffer); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if(!spFileDst->IsOpen()) + { + unsigned long long ullDiff = pData->spSrcFile->GetLength64() - ullProcessedSize; + + m_tSubTaskStats.IncreaseProcessedSize(ullDiff); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullDiff); + + pData->bProcessed = false; + bSkip = true; + return TSubTaskBase::eSubResult_Continue; + } } - } - // if the destination file already exists - truncate it to the current file position - if(!bDstFileFreshlyCreated) - { - // if destination file was opened (as opposed to newly created) - eResult = TruncateFileFB(spFeedbackHandler, spFileDst, ullMove, pData->pathDstFile, bSkip); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if(bSkip) + if(pData->bOnlyCreate) { - pData->bProcessed = false; + // we don't copy contents, but need to increase processed size + unsigned long long ullDiff = pData->spSrcFile->GetLength64() - ullProcessedSize; + + m_tSubTaskStats.IncreaseProcessedSize(ullDiff); + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullDiff); + return TSubTaskBase::eSubResult_Continue; } - } - // at this point user already decided that he want to write data into destination file; - // so if we're to resume copying after this point, we don't have to ask user for overwriting existing file - m_tSubTaskStats.SetCurrentItemSilentResume(true); + // seek to the position where copying will start + ULONGLONG ullMove = (bNoBuffer ? RoundDown(ullSeekTo, IFilesystemFile::MaxSectorSize) : ullSeekTo);; + if(ullMove != 0) // src and dst files exists, requested resume at the specified index + { + // adjust the stats for the difference between what was already processed and what will now be considered processed + if (ullMove > ullProcessedSize) + { + unsigned long long ullDiff = ullMove - ullProcessedSize; + m_tSubTaskStats.IncreaseCurrentItemProcessedSize(ullDiff); + m_tSubTaskStats.IncreaseProcessedSize(ullDiff); + } + else if (ullMove < ullProcessedSize) + { + unsigned long long ullDiff = ullProcessedSize - ullMove; + m_tSubTaskStats.DecreaseCurrentItemProcessedSize(ullDiff); + m_tSubTaskStats.DecreaseProcessedSize(ullDiff); + } + } - return eResult; -} + // if the destination file already exists - truncate it to the current file position + if(!bDstFileFreshlyCreated) + { + // if destination file was opened (as opposed to newly created) + eResult = TruncateFileFB(spFeedbackHandler, spFileDst, ullMove, pData->pathDstFile, bSkip); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if(bSkip) + { + pData->bProcessed = false; + return TSubTaskBase::eSubResult_Continue; + } + } -bool TSubTaskCopyMove::AdjustBufferIfNeeded(TOverlappedDataBufferQueue& rBuffer, TBufferSizes& rBufferSizes, bool bForce) -{ - const TConfig& rConfig = GetContext().GetConfig(); - TTaskConfigTracker& rCfgTracker = GetContext().GetCfgTracker(); - icpf::log_file& rLog = GetContext().GetLog(); + // at this point user already decided that he want to write data into destination file; + // so if we're to resume copying after this point, we don't have to ask user for overwriting existing file + m_tSubTaskStats.SetCurrentItemSilentResume(true); - if(bForce || (rCfgTracker.IsModified() && rCfgTracker.IsModified(TOptionsSet() % eTO_DefaultBufferSize % eTO_OneDiskBufferSize % eTO_TwoDisksBufferSize % eTO_CDBufferSize % eTO_LANBufferSize % eTO_UseOnlyDefaultBuffer % eTO_BufferQueueDepth, true))) + return eResult; + } + + bool TSubTaskCopyMove::AdjustBufferIfNeeded(TOverlappedDataBufferQueue& rBuffer, TBufferSizes& rBufferSizes, bool bForce) { - rBufferSizes = GetTaskPropBufferSizes(rConfig); + const TConfig& rConfig = GetContext().GetConfig(); + TTaskConfigTracker& rCfgTracker = GetContext().GetCfgTracker(); + icpf::log_file& rLog = GetContext().GetLog(); - // log - TString strFormat; - strFormat = _T("Changing buffer size to [Def:%defsize2, One:%onesize2, Two:%twosize2, CD:%cdsize2, LAN:%lansize2, Count:%cnt]"); + if(bForce || (rCfgTracker.IsModified() && rCfgTracker.IsModified(TOptionsSet() % eTO_DefaultBufferSize % eTO_OneDiskBufferSize % eTO_TwoDisksBufferSize % eTO_CDBufferSize % eTO_LANBufferSize % eTO_UseOnlyDefaultBuffer % eTO_BufferQueueDepth, true))) + { + rBufferSizes = GetTaskPropBufferSizes(rConfig); - strFormat.Replace(_T("%defsize2"), boost::lexical_cast(rBufferSizes.GetDefaultSize()).c_str()); - strFormat.Replace(_T("%onesize2"), boost::lexical_cast(rBufferSizes.GetOneDiskSize()).c_str()); - strFormat.Replace(_T("%twosize2"), boost::lexical_cast(rBufferSizes.GetTwoDisksSize()).c_str()); - strFormat.Replace(_T("%cdsize2"), boost::lexical_cast(rBufferSizes.GetCDSize()).c_str()); - strFormat.Replace(_T("%lansize2"), boost::lexical_cast(rBufferSizes.GetLANSize()).c_str()); - strFormat.Replace(_T("%cnt"), boost::lexical_cast(rBufferSizes.GetBufferCount()).c_str()); + // log + TString strFormat; + strFormat = _T("Changing buffer size to [Def:%defsize2, One:%onesize2, Two:%twosize2, CD:%cdsize2, LAN:%lansize2, Count:%cnt]"); - rLog.logi(strFormat.c_str()); + strFormat.Replace(_T("%defsize2"), boost::lexical_cast(rBufferSizes.GetDefaultSize()).c_str()); + strFormat.Replace(_T("%onesize2"), boost::lexical_cast(rBufferSizes.GetOneDiskSize()).c_str()); + strFormat.Replace(_T("%twosize2"), boost::lexical_cast(rBufferSizes.GetTwoDisksSize()).c_str()); + strFormat.Replace(_T("%cdsize2"), boost::lexical_cast(rBufferSizes.GetCDSize()).c_str()); + strFormat.Replace(_T("%lansize2"), boost::lexical_cast(rBufferSizes.GetLANSize()).c_str()); + strFormat.Replace(_T("%cnt"), boost::lexical_cast(rBufferSizes.GetBufferCount()).c_str()); - rBuffer.ReinitializeBuffers(rBufferSizes.GetBufferCount(), rBufferSizes.GetMaxSize()); + rLog.logi(strFormat.c_str()); - return true; // buffer adjusted - } + rBuffer.ReinitializeBuffers(rBufferSizes.GetBufferCount(), rBufferSizes.GetMaxSize()); - return false; // buffer did not need adjusting -} + return true; // buffer adjusted + } -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::OpenSourceFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileSrc, bool bNoBuffering) -{ - icpf::log_file& rLog = GetContext().GetLog(); + return false; // buffer did not need adjusting + } - bool bRetry = false; + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::OpenSourceFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileSrc, bool bNoBuffering) + { + icpf::log_file& rLog = GetContext().GetLog(); - fileSrc->Close(); + bool bRetry = false; - do - { - bRetry = false; + fileSrc->Close(); - if(!fileSrc->OpenExistingForReading(bNoBuffering)) + do { - DWORD dwLastError = GetLastError(); + bRetry = false; - EFeedbackResult frResult = spFeedbackHandler->FileError(fileSrc->GetFilePath().ToWString(), TString(), EFileError::eCreateError, dwLastError); - switch(frResult) + if(!fileSrc->OpenExistingForReading(bNoBuffering)) { - case EFeedbackResult::eResult_Skip: - break; // will return INVALID_HANDLE_VALUE + DWORD dwLastError = GetLastError(); - case EFeedbackResult::eResult_Cancel: + EFeedbackResult frResult = spFeedbackHandler->FileError(fileSrc->GetFilePath().ToWString(), TString(), EFileError::eCreateError, dwLastError); + switch(frResult) { - // log - TString strFormat = _T("Cancel request [error %errno] while opening source file %path (OpenSourceFileFB)"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), fileSrc->GetFilePath().ToString()); - rLog.loge(strFormat.c_str()); + case EFeedbackResult::eResult_Skip: + break; // will return INVALID_HANDLE_VALUE - return TSubTaskBase::eSubResult_CancelRequest; - } + case EFeedbackResult::eResult_Cancel: + { + // log + TString strFormat = _T("Cancel request [error %errno] while opening source file %path (OpenSourceFileFB)"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), fileSrc->GetFilePath().ToString()); + rLog.loge(strFormat.c_str()); - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + return TSubTaskBase::eSubResult_CancelRequest; + } - case EFeedbackResult::eResult_Retry: - { - // log - TString strFormat = _T("Retrying [error %errno] to open source file %path (OpenSourceFileFB)"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), fileSrc->GetFilePath().ToString()); - rLog.loge(strFormat.c_str()); + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; - bRetry = true; - break; - } + case EFeedbackResult::eResult_Retry: + { + // log + TString strFormat = _T("Retrying [error %errno] to open source file %path (OpenSourceFileFB)"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), fileSrc->GetFilePath().ToString()); + rLog.loge(strFormat.c_str()); - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + bRetry = true; + break; + } + + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; } - while(bRetry); - return TSubTaskBase::eSubResult_Continue; -} + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::OpenDestinationFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileDst, bool bNoBuffering, const TFileInfoPtr& spSrcFileInfo, unsigned long long& ullSeekTo, bool& bFreshlyCreated) + { + icpf::log_file& rLog = GetContext().GetLog(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::OpenDestinationFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileDst, bool bNoBuffering, const TFileInfoPtr& spSrcFileInfo, unsigned long long& ullSeekTo, bool& bFreshlyCreated) -{ - icpf::log_file& rLog = GetContext().GetLog(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + bool bRetry = false; - bool bRetry = false; + ullSeekTo = 0; + bFreshlyCreated = true; - ullSeekTo = 0; - bFreshlyCreated = true; - - fileDst->Close(); - do - { - bRetry = false; - - if(!fileDst->CreateNewForWriting(bNoBuffering)) + fileDst->Close(); + do { - DWORD dwLastError = GetLastError(); - if(dwLastError == ERROR_FILE_EXISTS) + bRetry = false; + + if(!fileDst->CreateNewForWriting(bNoBuffering)) { - bFreshlyCreated = false; + DWORD dwLastError = GetLastError(); + if(dwLastError == ERROR_FILE_EXISTS) + { + bFreshlyCreated = false; - // pass it to the specialized method - TSubTaskBase::ESubOperationResult eResult = OpenExistingDestinationFileFB(spFeedbackHandler, fileDst, bNoBuffering); - if(eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - else if(!fileDst->IsOpen()) - return TSubTaskBase::eSubResult_Continue; + // pass it to the specialized method + TSubTaskBase::ESubOperationResult eResult = OpenExistingDestinationFileFB(spFeedbackHandler, fileDst, bNoBuffering); + if(eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + else if(!fileDst->IsOpen()) + return TSubTaskBase::eSubResult_Continue; - // read info about the existing destination file, - // NOTE: it is not known which one would be faster - reading file parameters - // by using spDstFileInfo->Create() (which uses FindFirstFile()) or by - // reading parameters using opened handle; need to be tested in the future - TFileInfoPtr spDstFileInfo(boost::make_shared()); + // read info about the existing destination file, + // NOTE: it is not known which one would be faster - reading file parameters + // by using spDstFileInfo->Create() (which uses FindFirstFile()) or by + // reading parameters using opened handle; need to be tested in the future + TFileInfoPtr spDstFileInfo(boost::make_shared()); - if(!spFilesystem->GetFileInfo(fileDst->GetFilePath(), spDstFileInfo)) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotGetFileInfo, GetLastError()); + if(!spFilesystem->GetFileInfo(fileDst->GetFilePath(), spDstFileInfo)) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotGetFileInfo, GetLastError()); - // src and dst files are the same - EFeedbackResult frResult = spFeedbackHandler->FileAlreadyExists(spSrcFileInfo, spDstFileInfo); - switch(frResult) - { - case EFeedbackResult::eResult_Overwrite: - ullSeekTo = 0; - break; + // src and dst files are the same + EFeedbackResult frResult = spFeedbackHandler->FileAlreadyExists(spSrcFileInfo, spDstFileInfo); + switch(frResult) + { + case EFeedbackResult::eResult_Overwrite: + ullSeekTo = 0; + break; - case EFeedbackResult::eResult_CopyRest: - ullSeekTo = spDstFileInfo->GetLength64(); - break; + case EFeedbackResult::eResult_CopyRest: + ullSeekTo = spDstFileInfo->GetLength64(); + break; - case EFeedbackResult::eResult_Skip: - return TSubTaskBase::eSubResult_Continue; + case EFeedbackResult::eResult_Skip: + return TSubTaskBase::eSubResult_Continue; - case EFeedbackResult::eResult_Cancel: - { - // log - TString strFormat = _T("Cancel request while checking result of dialog before opening source file %path (CustomCopyFileFB)"); - strFormat.Replace(_T("%path"), fileDst->GetFilePath().ToString()); - rLog.logi(strFormat.c_str()); + case EFeedbackResult::eResult_Cancel: + { + // log + TString strFormat = _T("Cancel request while checking result of dialog before opening source file %path (CustomCopyFileFB)"); + strFormat.Replace(_T("%path"), fileDst->GetFilePath().ToString()); + rLog.logi(strFormat.c_str()); - return TSubTaskBase::eSubResult_CancelRequest; + return TSubTaskBase::eSubResult_CancelRequest; + } + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); } - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + } + else + { + EFeedbackResult frResult = spFeedbackHandler->FileError(fileDst->GetFilePath().ToWString(), TString(), EFileError::eCreateError, dwLastError); + switch(frResult) + { + case EFeedbackResult::eResult_Retry: + { + // log + TString strFormat = _T("Retrying [error %errno] to open destination file %path (CustomCopyFileFB)"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), fileDst->GetFilePath().ToString()); + rLog.loge(strFormat.c_str()); - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + bRetry = true; + + break; + } + case EFeedbackResult::eResult_Cancel: + { + // log + TString strFormat = _T("Cancel request [error %errno] while opening destination file %path (CustomCopyFileFB)"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), fileDst->GetFilePath().ToString()); + rLog.loge(strFormat.c_str()); + + return TSubTaskBase::eSubResult_CancelRequest; + } + + case EFeedbackResult::eResult_Skip: + break; // will return invalid handle value + + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } } - else + } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::OpenExistingDestinationFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileDst, bool bNoBuffering) + { + icpf::log_file& rLog = GetContext().GetLog(); + + bool bRetry = false; + + fileDst->Close(); + + do + { + bRetry = false; + + if(!fileDst->OpenExistingForWriting(bNoBuffering)) { + DWORD dwLastError = GetLastError(); + EFeedbackResult frResult = spFeedbackHandler->FileError(fileDst->GetFilePath().ToWString(), TString(), EFileError::eCreateError, dwLastError); - switch(frResult) + switch (frResult) { case EFeedbackResult::eResult_Retry: { // log TString strFormat = _T("Retrying [error %errno] to open destination file %path (CustomCopyFileFB)"); strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), fileDst->GetFilePath().ToString()); + strFormat.Replace(_t("%path"), fileDst->GetFilePath().ToString()); rLog.loge(strFormat.c_str()); bRetry = true; @@ -865,470 +925,409 @@ } } } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; } - while(bRetry); - return TSubTaskBase::eSubResult_Continue; -} - -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::OpenExistingDestinationFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileDst, bool bNoBuffering) -{ - icpf::log_file& rLog = GetContext().GetLog(); - - bool bRetry = false; - - fileDst->Close(); - - do + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::TruncateFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& spFile, long long llNewSize, + const TSmartPath& pathFile, bool& bSkip) { - bRetry = false; + icpf::log_file& rLog = GetContext().GetLog(); - if(!fileDst->OpenExistingForWriting(bNoBuffering)) - { - DWORD dwLastError = GetLastError(); + bSkip = false; - EFeedbackResult frResult = spFeedbackHandler->FileError(fileDst->GetFilePath().ToWString(), TString(), EFileError::eCreateError, dwLastError); - switch (frResult) + bool bRetry = false; + do + { + if(!spFile->Truncate(llNewSize)) { - case EFeedbackResult::eResult_Retry: - { - // log - TString strFormat = _T("Retrying [error %errno] to open destination file %path (CustomCopyFileFB)"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_t("%path"), fileDst->GetFilePath().ToString()); - rLog.loge(strFormat.c_str()); + // log + DWORD dwLastError = GetLastError(); - bRetry = true; + TString strFormat = _T("Error %errno while truncating file %path to 0"); + strFormat.Replace(_t("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_t("%path"), pathFile.ToString()); + rLog.loge(strFormat.c_str()); - break; - } - case EFeedbackResult::eResult_Cancel: + EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eResizeError, dwLastError); + switch(frResult) { - // log - TString strFormat = _T("Cancel request [error %errno] while opening destination file %path (CustomCopyFileFB)"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), fileDst->GetFilePath().ToString()); - rLog.loge(strFormat.c_str()); - + case EFeedbackResult::eResult_Cancel: return TSubTaskBase::eSubResult_CancelRequest; - } - case EFeedbackResult::eResult_Skip: - break; // will return invalid handle value + case EFeedbackResult::eResult_Retry: + bRetry = true; - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + case EFeedbackResult::eResult_Skip: + bSkip = true; + return TSubTaskBase::eSubResult_Continue; + + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; } - while(bRetry); - return TSubTaskBase::eSubResult_Continue; -} - -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::TruncateFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& spFile, long long llNewSize, - const TSmartPath& pathFile, bool& bSkip) -{ - icpf::log_file& rLog = GetContext().GetLog(); - - bSkip = false; - - bool bRetry = false; - do + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::ReadFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& spFile, + TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip) { - if(!spFile->Truncate(llNewSize)) + icpf::log_file& rLog = GetContext().GetLog(); + + bSkip = false; + bool bRetry = false; + do { - // log - DWORD dwLastError = GetLastError(); + bRetry = false; - TString strFormat = _T("Error %errno while truncating file %path to 0"); - strFormat.Replace(_t("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_t("%path"), pathFile.ToString()); - rLog.loge(strFormat.c_str()); - - EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eResizeError, dwLastError); - switch(frResult) + if(!spFile->ReadFile(rBuffer)) { - case EFeedbackResult::eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; + TString strFormat = _T("Error %errno while requesting read of %count bytes from source file %path (CustomCopyFileFB)"); + strFormat.Replace(_t("%errno"), boost::lexical_cast(GetLastError()).c_str()); + strFormat.Replace(_t("%count"), boost::lexical_cast(rBuffer.GetRequestedDataSize()).c_str()); + strFormat.Replace(_t("%path"), pathFile.ToString()); + rLog.loge(strFormat.c_str()); - case EFeedbackResult::eResult_Retry: - bRetry = true; + EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eReadError, GetLastError()); + switch(frResult) + { + case EFeedbackResult::eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + case EFeedbackResult::eResult_Retry: + bRetry = true; + break; - case EFeedbackResult::eResult_Skip: - bSkip = true; - return TSubTaskBase::eSubResult_Continue; + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + case EFeedbackResult::eResult_Skip: + bSkip = true; + return TSubTaskBase::eSubResult_Continue; + + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; } - while(bRetry); - return TSubTaskBase::eSubResult_Continue; -} + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::HandleReadError(const IFeedbackHandlerPtr& spFeedbackHandler, + TOverlappedDataBuffer& rBuffer, + const TSmartPath& pathFile, + bool& bSkip) + { + icpf::log_file& rLog = GetContext().GetLog(); + DWORD dwLastError = rBuffer.GetErrorCode(); -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::ReadFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& spFile, - TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip) -{ - icpf::log_file& rLog = GetContext().GetLog(); + bSkip = false; - bSkip = false; - bool bRetry = false; - do - { - bRetry = false; + // log + TString strFormat = _T("Error %errno while requesting read of %count bytes from source file %path (CustomCopyFileFB)"); + strFormat.Replace(_t("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_t("%count"), boost::lexical_cast(rBuffer.GetRequestedDataSize()).c_str()); + strFormat.Replace(_t("%path"), pathFile.ToString()); + rLog.loge(strFormat.c_str()); - if(!spFile->ReadFile(rBuffer)) + EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eReadError, dwLastError); + switch(frResult) { - TString strFormat = _T("Error %errno while requesting read of %count bytes from source file %path (CustomCopyFileFB)"); - strFormat.Replace(_t("%errno"), boost::lexical_cast(GetLastError()).c_str()); - strFormat.Replace(_t("%count"), boost::lexical_cast(rBuffer.GetRequestedDataSize()).c_str()); - strFormat.Replace(_t("%path"), pathFile.ToString()); - rLog.loge(strFormat.c_str()); + case EFeedbackResult::eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; - EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eReadError, GetLastError()); - switch(frResult) - { - case EFeedbackResult::eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; + case EFeedbackResult::eResult_Retry: + return TSubTaskBase::eSubResult_Retry; - case EFeedbackResult::eResult_Retry: - bRetry = true; - break; + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + case EFeedbackResult::eResult_Skip: + bSkip = true; + return TSubTaskBase::eSubResult_Continue; - case EFeedbackResult::eResult_Skip: - bSkip = true; - return TSubTaskBase::eSubResult_Continue; - - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); - } + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); } } - while(bRetry); - return TSubTaskBase::eSubResult_Continue; -} + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::WriteFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& spFile, + TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip) + { + icpf::log_file& rLog = GetContext().GetLog(); -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::HandleReadError(const IFeedbackHandlerPtr& spFeedbackHandler, - TOverlappedDataBuffer& rBuffer, - const TSmartPath& pathFile, - bool& bSkip) -{ - icpf::log_file& rLog = GetContext().GetLog(); - DWORD dwLastError = rBuffer.GetErrorCode(); + bSkip = false; - bSkip = false; + bool bRetry = false; + do + { + bRetry = false; - // log - TString strFormat = _T("Error %errno while requesting read of %count bytes from source file %path (CustomCopyFileFB)"); - strFormat.Replace(_t("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_t("%count"), boost::lexical_cast(rBuffer.GetRequestedDataSize()).c_str()); - strFormat.Replace(_t("%path"), pathFile.ToString()); - rLog.loge(strFormat.c_str()); + if(!spFile->WriteFile(rBuffer)) + { + // log + DWORD dwLastError = GetLastError(); - EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eReadError, dwLastError); - switch(frResult) - { - case EFeedbackResult::eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; + TString strFormat = _T("Error %errno while trying to write %count bytes to destination file %path (CustomCopyFileFB)"); + strFormat.Replace(_t("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_t("%count"), boost::lexical_cast(rBuffer.GetBytesTransferred()).c_str()); + strFormat.Replace(_t("%path"), pathFile.ToString()); + rLog.loge(strFormat.c_str()); - case EFeedbackResult::eResult_Retry: - return TSubTaskBase::eSubResult_Retry; + EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eWriteError, dwLastError); + switch(frResult) + { + case EFeedbackResult::eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + case EFeedbackResult::eResult_Retry: + bRetry = true; + break; - case EFeedbackResult::eResult_Skip: - bSkip = true; - return TSubTaskBase::eSubResult_Continue; + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); - } -} + case EFeedbackResult::eResult_Skip: + bSkip = true; + return TSubTaskBase::eSubResult_Continue; -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::WriteFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& spFile, - TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip) -{ - icpf::log_file& rLog = GetContext().GetLog(); + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } + } + } + while(bRetry); - bSkip = false; + return TSubTaskBase::eSubResult_Continue; + } - bool bRetry = false; - do + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::HandleWriteError(const IFeedbackHandlerPtr& spFeedbackHandler, + TOverlappedDataBuffer& rBuffer, + const TSmartPath& pathFile, + bool& bSkip) { - bRetry = false; + icpf::log_file& rLog = GetContext().GetLog(); + DWORD dwLastError = rBuffer.GetErrorCode(); - if(!spFile->WriteFile(rBuffer)) - { - // log - DWORD dwLastError = GetLastError(); + bSkip = false; - TString strFormat = _T("Error %errno while trying to write %count bytes to destination file %path (CustomCopyFileFB)"); - strFormat.Replace(_t("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_t("%count"), boost::lexical_cast(rBuffer.GetBytesTransferred()).c_str()); - strFormat.Replace(_t("%path"), pathFile.ToString()); - rLog.loge(strFormat.c_str()); + // log + TString strFormat = _T("Error %errno while trying to write %count bytes to destination file %path (CustomCopyFileFB)"); + strFormat.Replace(_t("%errno"), boost::lexical_cast(rBuffer.GetErrorCode()).c_str()); + strFormat.Replace(_t("%count"), boost::lexical_cast(rBuffer.GetBytesTransferred()).c_str()); + strFormat.Replace(_t("%path"), pathFile.ToString()); + rLog.loge(strFormat.c_str()); - EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eWriteError, dwLastError); - switch(frResult) - { - case EFeedbackResult::eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; + EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eWriteError, dwLastError); + switch(frResult) + { + case EFeedbackResult::eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; - case EFeedbackResult::eResult_Retry: - bRetry = true; - break; + case EFeedbackResult::eResult_Retry: + return TSubTaskBase::eSubResult_Retry; - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; - case EFeedbackResult::eResult_Skip: - bSkip = true; - return TSubTaskBase::eSubResult_Continue; + case EFeedbackResult::eResult_Skip: + bSkip = true; + return TSubTaskBase::eSubResult_Continue; - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); - } + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); } } - while(bRetry); - return TSubTaskBase::eSubResult_Continue; -} + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::FinalizeFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& spFile, + TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip) + { + icpf::log_file& rLog = GetContext().GetLog(); -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::HandleWriteError(const IFeedbackHandlerPtr& spFeedbackHandler, - TOverlappedDataBuffer& rBuffer, - const TSmartPath& pathFile, - bool& bSkip) -{ - icpf::log_file& rLog = GetContext().GetLog(); - DWORD dwLastError = rBuffer.GetErrorCode(); + bSkip = false; - bSkip = false; + bool bRetry = false; + do + { + bRetry = false; - // log - TString strFormat = _T("Error %errno while trying to write %count bytes to destination file %path (CustomCopyFileFB)"); - strFormat.Replace(_t("%errno"), boost::lexical_cast(rBuffer.GetErrorCode()).c_str()); - strFormat.Replace(_t("%count"), boost::lexical_cast(rBuffer.GetBytesTransferred()).c_str()); - strFormat.Replace(_t("%path"), pathFile.ToString()); - rLog.loge(strFormat.c_str()); + if (!spFile->FinalizeFile(rBuffer)) + { + // log + DWORD dwLastError = GetLastError(); - EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eWriteError, dwLastError); - switch(frResult) - { - case EFeedbackResult::eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; + TString strFormat = _T("Error %errno while trying to finalize file %path (CustomCopyFileFB)"); + strFormat.Replace(_t("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_t("%path"), pathFile.ToString()); + rLog.loge(strFormat.c_str()); - case EFeedbackResult::eResult_Retry: - return TSubTaskBase::eSubResult_Retry; + EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eFinalizeError, dwLastError); + switch (frResult) + { + case EFeedbackResult::eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + case EFeedbackResult::eResult_Retry: + bRetry = true; + break; - case EFeedbackResult::eResult_Skip: - bSkip = true; - return TSubTaskBase::eSubResult_Continue; + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); - } -} + case EFeedbackResult::eResult_Skip: + bSkip = true; + return TSubTaskBase::eSubResult_Continue; -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::FinalizeFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& spFile, - TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip) -{ - icpf::log_file& rLog = GetContext().GetLog(); + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } + } + } + while (bRetry); - bSkip = false; + return TSubTaskBase::eSubResult_Continue; + } - bool bRetry = false; - do + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::CreateDirectoryFB(const IFeedbackHandlerPtr& spFeedbackHandler, const TSmartPath& pathDirectory) { - bRetry = false; + icpf::log_file& rLog = GetContext().GetLog(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - if (!spFile->FinalizeFile(rBuffer)) + bool bRetry = true; + DWORD dwLastError = ERROR_SUCCESS; + while(bRetry && !spFilesystem->CreateDirectory(pathDirectory, false) && (dwLastError = GetLastError()) != ERROR_ALREADY_EXISTS) { // log - DWORD dwLastError = GetLastError(); - - TString strFormat = _T("Error %errno while trying to finalize file %path (CustomCopyFileFB)"); - strFormat.Replace(_t("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_t("%path"), pathFile.ToString()); + TString strFormat; + strFormat = _T("Error %errno while calling CreateDirectory %path (ProcessFiles)"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), pathDirectory.ToString()); rLog.loge(strFormat.c_str()); - EFeedbackResult frResult = spFeedbackHandler->FileError(pathFile.ToWString(), TString(), EFileError::eFinalizeError, dwLastError); - switch (frResult) + EFeedbackResult frResult = spFeedbackHandler->FileError(pathDirectory.ToWString(), TString(), EFileError::eCreateError, dwLastError); + switch(frResult) { case EFeedbackResult::eResult_Cancel: return TSubTaskBase::eSubResult_CancelRequest; case EFeedbackResult::eResult_Retry: - bRetry = true; + bRetry = false; break; case EFeedbackResult::eResult_Pause: return TSubTaskBase::eSubResult_PauseRequest; case EFeedbackResult::eResult_Skip: - bSkip = true; - return TSubTaskBase::eSubResult_Continue; + bRetry = false; + break; // just do nothing default: BOOST_ASSERT(FALSE); // unknown result THROW_CORE_EXCEPTION(eErr_UnhandledCase); } } + + return TSubTaskBase::eSubResult_Continue; } - while (bRetry); - return TSubTaskBase::eSubResult_Continue; -} - -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::CreateDirectoryFB(const IFeedbackHandlerPtr& spFeedbackHandler, const TSmartPath& pathDirectory) -{ - icpf::log_file& rLog = GetContext().GetLog(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - - bool bRetry = true; - DWORD dwLastError = ERROR_SUCCESS; - while(bRetry && !spFilesystem->CreateDirectory(pathDirectory, false) && (dwLastError = GetLastError()) != ERROR_ALREADY_EXISTS) + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::CheckForFreeSpaceFB(const IFeedbackHandlerPtr& spFeedbackHandler) { - // log - TString strFormat; - strFormat = _T("Error %errno while calling CreateDirectory %path (ProcessFiles)"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), pathDirectory.ToString()); - rLog.loge(strFormat.c_str()); + icpf::log_file& rLog = GetContext().GetLog(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + TBasePathDataContainerPtr spSrcPaths = GetContext().GetBasePaths(); + TSmartPath pathDestination = GetContext().GetDestinationPath(); - EFeedbackResult frResult = spFeedbackHandler->FileError(pathDirectory.ToWString(), TString(), EFileError::eCreateError, dwLastError); - switch(frResult) - { - case EFeedbackResult::eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; + ull_t ullNeededSize = 0, ullAvailableSize = 0; + bool bRetry = false; - case EFeedbackResult::eResult_Retry: + do + { bRetry = false; - break; - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + rLog.logi(_T("Checking for free space on destination disk...")); - case EFeedbackResult::eResult_Skip: - bRetry = false; - break; // just do nothing + ullNeededSize = rFilesCache.CalculateTotalSize() - rFilesCache.CalculatePartialSize(m_tSubTaskStats.GetCurrentIndex()); // it'd be nice to round up to take cluster size into consideration - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); - } - } - - return TSubTaskBase::eSubResult_Continue; -} - -TSubTaskBase::ESubOperationResult TSubTaskCopyMove::CheckForFreeSpaceFB(const IFeedbackHandlerPtr& spFeedbackHandler) -{ - icpf::log_file& rLog = GetContext().GetLog(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - TBasePathDataContainerPtr spSrcPaths = GetContext().GetBasePaths(); - TSmartPath pathDestination = GetContext().GetDestinationPath(); - - ull_t ullNeededSize = 0, ullAvailableSize = 0; - bool bRetry = false; - - do - { - bRetry = false; - - rLog.logi(_T("Checking for free space on destination disk...")); - - ullNeededSize = rFilesCache.CalculateTotalSize() - rFilesCache.CalculatePartialSize(m_tSubTaskStats.GetCurrentIndex()); // it'd be nice to round up to take cluster size into consideration - - // get free space - bool bResult = spFilesystem->GetDynamicFreeSpace(pathDestination, ullAvailableSize); - if(bResult && ullNeededSize > ullAvailableSize) - { - TString strFormat = _T("Not enough free space on disk - needed %needsize bytes for data, available: %availablesize bytes."); - strFormat.Replace(_t("%needsize"), boost::lexical_cast(ullNeededSize).c_str()); - strFormat.Replace(_t("%availablesize"), boost::lexical_cast(ullAvailableSize).c_str()); - rLog.logw(strFormat.c_str()); - - if(!spSrcPaths->IsEmpty()) + // get free space + bool bResult = spFilesystem->GetDynamicFreeSpace(pathDestination, ullAvailableSize); + if(bResult && ullNeededSize > ullAvailableSize) { - EFeedbackResult frResult = spFeedbackHandler->NotEnoughSpace(spSrcPaths->GetAt(0)->GetSrcPath().ToWString(), pathDestination.ToWString(), ullNeededSize); - switch(frResult) + TString strFormat = _T("Not enough free space on disk - needed %needsize bytes for data, available: %availablesize bytes."); + strFormat.Replace(_t("%needsize"), boost::lexical_cast(ullNeededSize).c_str()); + strFormat.Replace(_t("%availablesize"), boost::lexical_cast(ullAvailableSize).c_str()); + rLog.logw(strFormat.c_str()); + + if(!spSrcPaths->IsEmpty()) { - case EFeedbackResult::eResult_Cancel: - rLog.logi(_T("Cancel request while checking for free space on disk.")); - return TSubTaskBase::eSubResult_CancelRequest; + EFeedbackResult frResult = spFeedbackHandler->NotEnoughSpace(spSrcPaths->GetAt(0)->GetSrcPath().ToWString(), pathDestination.ToWString(), ullNeededSize); + switch(frResult) + { + case EFeedbackResult::eResult_Cancel: + rLog.logi(_T("Cancel request while checking for free space on disk.")); + return TSubTaskBase::eSubResult_CancelRequest; - case EFeedbackResult::eResult_Retry: - rLog.logi(_T("Retrying to read drive's free space...")); - bRetry = true; - break; + case EFeedbackResult::eResult_Retry: + rLog.logi(_T("Retrying to read drive's free space...")); + bRetry = true; + break; - case EFeedbackResult::eResult_Ignore: - rLog.logi(_T("Ignored warning about not enough place on disk to copy data.")); - return TSubTaskBase::eSubResult_Continue; + case EFeedbackResult::eResult_Ignore: + rLog.logi(_T("Ignored warning about not enough place on disk to copy data.")); + return TSubTaskBase::eSubResult_Continue; - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } } } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; } - while(bRetry); - return TSubTaskBase::eSubResult_Continue; -} + void TSubTaskCopyMove::Store(const ISerializerPtr& spSerializer) const + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_copymove")); + InitColumns(spContainer); -void TSubTaskCopyMove::Store(const ISerializerPtr& spSerializer) const -{ - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_copymove")); - InitColumns(spContainer); + ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); - ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); + m_tSubTaskStats.Store(rRow); + } - m_tSubTaskStats.Store(rRow); -} + void TSubTaskCopyMove::Load(const ISerializerPtr& spSerializer) + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_copymove")); -void TSubTaskCopyMove::Load(const ISerializerPtr& spSerializer) -{ - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_copymove")); + InitColumns(spContainer); - InitColumns(spContainer); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if(spRowReader->Next()) + m_tSubTaskStats.Load(spRowReader); + } - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if(spRowReader->Next()) - m_tSubTaskStats.Load(spRowReader); + void TSubTaskCopyMove::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if(rColumns.IsEmpty()) + TSubTaskStatsInfo::InitColumns(rColumns); + } } - -void TSubTaskCopyMove::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) - TSubTaskStatsInfo::InitColumns(rColumns); -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TSubTaskCopyMove.h =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskCopyMove.h (.../TSubTaskCopyMove.h) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/TSubTaskCopyMove.h (.../TSubTaskCopyMove.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -29,76 +29,75 @@ #include "TBufferSizes.h" #include "IFilesystemFile.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + class TLocalFilesystemFile; + typedef boost::shared_ptr TFileInfoPtr; + struct CUSTOM_COPY_PARAMS; -class TLocalFilesystemFile; -typedef boost::shared_ptr TFileInfoPtr; -struct CUSTOM_COPY_PARAMS; + class TDataBufferManager; + class TSimpleDataBuffer; + class TBufferSizes; + class TOverlappedDataBufferQueue; + class TOverlappedDataBuffer; -class TDataBufferManager; -class TSimpleDataBuffer; -class TBufferSizes; -class TOverlappedDataBufferQueue; -class TOverlappedDataBuffer; + class LIBCHCORE_API TSubTaskCopyMove : public TSubTaskBase + { + public: + TSubTaskCopyMove(TSubTaskContext& tSubTaskContext); -class LIBCHCORE_API TSubTaskCopyMove : public TSubTaskBase -{ -public: - TSubTaskCopyMove(TSubTaskContext& tSubTaskContext); + virtual void Reset(); - virtual void Reset(); + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; + virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Copying; } - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; - virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Copying; } + virtual void Store(const ISerializerPtr& spSerializer) const; + virtual void Load(const ISerializerPtr& spSerializer); - virtual void Store(const ISerializerPtr& spSerializer) const; - virtual void Load(const ISerializerPtr& spSerializer); + void InitColumns(const ISerializerContainerPtr& spContainer) const; - void InitColumns(const ISerializerContainerPtr& spContainer) const; + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const; - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const; + private: + TBufferSizes::EBufferType GetBufferIndex(const TBufferSizes& rBufferSizes, const TFileInfoPtr& spFileInfo); + bool AdjustBufferIfNeeded(TOverlappedDataBufferQueue& rBuffer, TBufferSizes& rBufferSizes, bool bForce = false); -private: - TBufferSizes::EBufferType GetBufferIndex(const TBufferSizes& rBufferSizes, const TFileInfoPtr& spFileInfo); - bool AdjustBufferIfNeeded(TOverlappedDataBufferQueue& rBuffer, TBufferSizes& rBufferSizes, bool bForce = false); + ESubOperationResult CustomCopyFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, CUSTOM_COPY_PARAMS* pData); - ESubOperationResult CustomCopyFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, CUSTOM_COPY_PARAMS* pData); + ESubOperationResult OpenSrcAndDstFilesFB(const IFeedbackHandlerPtr& spFeedbackHandler, CUSTOM_COPY_PARAMS* pData, + const IFilesystemFilePtr& spFileSrc, const IFilesystemFilePtr& spFileDst, bool bNoBuffer, bool& bSkip); - ESubOperationResult OpenSrcAndDstFilesFB(const IFeedbackHandlerPtr& spFeedbackHandler, CUSTOM_COPY_PARAMS* pData, - const IFilesystemFilePtr& spFileSrc, const IFilesystemFilePtr& spFileDst, bool bNoBuffer, bool& bSkip); + ESubOperationResult OpenSourceFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileSrc, bool bNoBuffering); + ESubOperationResult OpenDestinationFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileDst, bool bNoBuffering, const TFileInfoPtr& spSrcFileInfo, + unsigned long long& ullSeekTo, bool& bFreshlyCreated); + ESubOperationResult OpenExistingDestinationFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileDst, bool bNoBuffering); - ESubOperationResult OpenSourceFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileSrc, bool bNoBuffering); - ESubOperationResult OpenDestinationFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileDst, bool bNoBuffering, const TFileInfoPtr& spSrcFileInfo, - unsigned long long& ullSeekTo, bool& bFreshlyCreated); - ESubOperationResult OpenExistingDestinationFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& fileDst, bool bNoBuffering); + ESubOperationResult TruncateFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& file, long long llNewSize, + const TSmartPath& pathFile, bool& bSkip); - ESubOperationResult TruncateFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& file, long long llNewSize, - const TSmartPath& pathFile, bool& bSkip); + ESubOperationResult ReadFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& file, + TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip); + ESubOperationResult HandleReadError(const IFeedbackHandlerPtr& spFeedbackHandler, TOverlappedDataBuffer& rBuffer, + const TSmartPath& pathFile, bool& bSkip); - ESubOperationResult ReadFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& file, - TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip); - ESubOperationResult HandleReadError(const IFeedbackHandlerPtr& spFeedbackHandler, TOverlappedDataBuffer& rBuffer, - const TSmartPath& pathFile, bool& bSkip); + ESubOperationResult WriteFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& file, + TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip); + ESubOperationResult HandleWriteError(const IFeedbackHandlerPtr& spFeedbackHandler, TOverlappedDataBuffer& rBuffer, + const TSmartPath& pathFile, bool& bSkip); - ESubOperationResult WriteFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& file, - TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip); - ESubOperationResult HandleWriteError(const IFeedbackHandlerPtr& spFeedbackHandler, TOverlappedDataBuffer& rBuffer, - const TSmartPath& pathFile, bool& bSkip); + ESubOperationResult FinalizeFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& file, + TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip); - ESubOperationResult FinalizeFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemFilePtr& file, - TOverlappedDataBuffer& rBuffer, const TSmartPath& pathFile, bool& bSkip); + ESubOperationResult CreateDirectoryFB(const IFeedbackHandlerPtr& spFeedbackHandler, const TSmartPath& pathDirectory); - ESubOperationResult CreateDirectoryFB(const IFeedbackHandlerPtr& spFeedbackHandler, const TSmartPath& pathDirectory); + ESubOperationResult CheckForFreeSpaceFB(const IFeedbackHandlerPtr& spFeedbackHandler); - ESubOperationResult CheckForFreeSpaceFB(const IFeedbackHandlerPtr& spFeedbackHandler); - -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - TSubTaskStatsInfo m_tSubTaskStats; + TSubTaskStatsInfo m_tSubTaskStats; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSubTaskDelete.cpp =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskDelete.cpp (.../TSubTaskDelete.cpp) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TSubTaskDelete.cpp (.../TSubTaskDelete.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -39,174 +39,173 @@ #include #include "TBufferSizes.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// class TSubTaskDelete - -TSubTaskDelete::TSubTaskDelete(TSubTaskContext& rContext) : - TSubTaskBase(rContext), - m_tSubTaskStats(eSubOperation_Deleting) +namespace chcore { -} + /////////////////////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskDelete -void TSubTaskDelete::Reset() -{ - m_tSubTaskStats.Clear(); -} + TSubTaskDelete::TSubTaskDelete(TSubTaskContext& rContext) : + TSubTaskBase(rContext), + m_tSubTaskStats(eSubOperation_Deleting) + { + } -TSubTaskBase::ESubOperationResult TSubTaskDelete::Exec(const IFeedbackHandlerPtr& spFeedback) -{ - TScopedRunningTimeTracker guard(m_tSubTaskStats); - TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(spFeedback, guard)); + void TSubTaskDelete::Reset() + { + m_tSubTaskStats.Clear(); + } - // log - icpf::log_file& rLog = GetContext().GetLog(); - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - const TConfig& rConfig = GetContext().GetConfig(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + TSubTaskBase::ESubOperationResult TSubTaskDelete::Exec(const IFeedbackHandlerPtr& spFeedback) + { + TScopedRunningTimeTracker guard(m_tSubTaskStats); + TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(spFeedback, guard)); - // log - rLog.logi(_T("Deleting files (DeleteFiles)...")); + // log + icpf::log_file& rLog = GetContext().GetLog(); + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + const TConfig& rConfig = GetContext().GetConfig(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - // new stats - m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); - m_tSubTaskStats.SetTotalCount(rFilesCache.GetSize()); - m_tSubTaskStats.SetProcessedCount(0); - m_tSubTaskStats.SetTotalSize(0); - m_tSubTaskStats.SetProcessedSize(0); - m_tSubTaskStats.SetCurrentPath(TString()); + // log + rLog.logi(_T("Deleting files (DeleteFiles)...")); - // current processed path - BOOL bSuccess; - TFileInfoPtr spFileInfo; - TString strFormat; + // new stats + m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); + m_tSubTaskStats.SetTotalCount(rFilesCache.GetSize()); + m_tSubTaskStats.SetProcessedCount(0); + m_tSubTaskStats.SetTotalSize(0); + m_tSubTaskStats.SetProcessedSize(0); + m_tSubTaskStats.SetCurrentPath(TString()); - // index points to 0 or next item to process - file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); - while(fcIndex < rFilesCache.GetSize()) - { - spFileInfo = rFilesCache.GetAt(rFilesCache.GetSize() - fcIndex - 1); + // current processed path + BOOL bSuccess; + TFileInfoPtr spFileInfo; + TString strFormat; - m_tSubTaskStats.SetCurrentIndex(fcIndex); + // index points to 0 or next item to process + file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); + while (fcIndex < rFilesCache.GetSize()) + { + spFileInfo = rFilesCache.GetAt(rFilesCache.GetSize() - fcIndex - 1); - // new stats - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(spFileInfo->GetFullFilePath().ToString()); + m_tSubTaskStats.SetCurrentIndex(fcIndex); - // check for kill flag - if(rThreadController.KillRequested()) - { - // log - rLog.logi(_T("Kill request while deleting files (Delete Files)")); - return TSubTaskBase::eSubResult_KillRequest; - } + // new stats + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(spFileInfo->GetFullFilePath().ToString()); - // current processed element - if(!spFileInfo->IsProcessed()) - { - ++fcIndex; - continue; - } + // check for kill flag + if (rThreadController.KillRequested()) + { + // log + rLog.logi(_T("Kill request while deleting files (Delete Files)")); + return TSubTaskBase::eSubResult_KillRequest; + } - // delete data - if(spFileInfo->IsDirectory()) - { - if(!GetTaskPropValue(rConfig)) - spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_DIRECTORY); - bSuccess = spFilesystem->RemoveDirectory(spFileInfo->GetFullFilePath()); - } - else - { - // set files attributes to normal - it'd slow processing a bit, but it's better. - if(!GetTaskPropValue(rConfig)) - spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), FILE_ATTRIBUTE_NORMAL); - bSuccess = spFilesystem->DeleteFile(spFileInfo->GetFullFilePath()); - } + // current processed element + if (!spFileInfo->IsProcessed()) + { + ++fcIndex; + continue; + } - // operation failed - DWORD dwLastError = GetLastError(); - if(!bSuccess && dwLastError != ERROR_PATH_NOT_FOUND && dwLastError != ERROR_FILE_NOT_FOUND) - { - // log - strFormat = _T("Error #%errno while deleting file/folder %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); - rLog.loge(strFormat.c_str()); + // delete data + if (spFileInfo->IsDirectory()) + { + if (!GetTaskPropValue(rConfig)) + spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_DIRECTORY); + bSuccess = spFilesystem->RemoveDirectory(spFileInfo->GetFullFilePath()); + } + else + { + // set files attributes to normal - it'd slow processing a bit, but it's better. + if (!GetTaskPropValue(rConfig)) + spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), FILE_ATTRIBUTE_NORMAL); + bSuccess = spFilesystem->DeleteFile(spFileInfo->GetFullFilePath()); + } - EFeedbackResult frResult = spFeedbackHandler->FileError(spFileInfo->GetFullFilePath().ToWString(), TString(), EFileError::eDeleteError, dwLastError); - switch(frResult) + // operation failed + DWORD dwLastError = GetLastError(); + if (!bSuccess && dwLastError != ERROR_PATH_NOT_FOUND && dwLastError != ERROR_FILE_NOT_FOUND) { - case EFeedbackResult::eResult_Cancel: - rLog.logi(_T("Cancel request while deleting file.")); - return TSubTaskBase::eSubResult_CancelRequest; + // log + strFormat = _T("Error #%errno while deleting file/folder %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); + rLog.loge(strFormat.c_str()); - case EFeedbackResult::eResult_Retry: - continue; // no fcIndex bump, since we are trying again + EFeedbackResult frResult = spFeedbackHandler->FileError(spFileInfo->GetFullFilePath().ToWString(), TString(), EFileError::eDeleteError, dwLastError); + switch (frResult) + { + case EFeedbackResult::eResult_Cancel: + rLog.logi(_T("Cancel request while deleting file.")); + return TSubTaskBase::eSubResult_CancelRequest; - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + case EFeedbackResult::eResult_Retry: + continue; // no fcIndex bump, since we are trying again - case EFeedbackResult::eResult_Skip: - break; // just do nothing + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + case EFeedbackResult::eResult_Skip: + break; // just do nothing + + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } - } - ++fcIndex; - }//while + ++fcIndex; + }//while - m_tSubTaskStats.SetCurrentIndex(fcIndex); - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(TString()); + m_tSubTaskStats.SetCurrentIndex(fcIndex); + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(TString()); - // log - rLog.logi(_T("Deleting files finished")); + // log + rLog.logi(_T("Deleting files finished")); - return TSubTaskBase::eSubResult_Continue; -} + return TSubTaskBase::eSubResult_Continue; + } -void TSubTaskDelete::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const -{ - m_tSubTaskStats.GetSnapshot(spStats); - // if this subtask is not started yet, try to get the most fresh information for processing - if(!spStats->IsRunning() && spStats->GetTotalCount() == 0 && spStats->GetTotalSize() == 0) + void TSubTaskDelete::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const { - spStats->SetTotalCount(GetContext().GetFilesCache().GetSize()); - spStats->SetTotalSize(0); + m_tSubTaskStats.GetSnapshot(spStats); + // if this subtask is not started yet, try to get the most fresh information for processing + if (!spStats->IsRunning() && spStats->GetTotalCount() == 0 && spStats->GetTotalSize() == 0) + { + spStats->SetTotalCount(GetContext().GetFilesCache().GetSize()); + spStats->SetTotalSize(0); + } } -} -void TSubTaskDelete::Store(const ISerializerPtr& spSerializer) const -{ - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_delete")); - InitColumns(spContainer); + void TSubTaskDelete::Store(const ISerializerPtr& spSerializer) const + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_delete")); + InitColumns(spContainer); - ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); + ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); - m_tSubTaskStats.Store(rRow); -} + m_tSubTaskStats.Store(rRow); + } -void TSubTaskDelete::Load(const ISerializerPtr& spSerializer) -{ - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_delete")); + void TSubTaskDelete::Load(const ISerializerPtr& spSerializer) + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_delete")); - InitColumns(spContainer); + InitColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if(spRowReader->Next()) - m_tSubTaskStats.Load(spRowReader); -} + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + m_tSubTaskStats.Load(spRowReader); + } -void TSubTaskDelete::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) - TSubTaskStatsInfo::InitColumns(rColumns); + void TSubTaskDelete::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TSubTaskStatsInfo::InitColumns(rColumns); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSubTaskDelete.h =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskDelete.h (.../TSubTaskDelete.h) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/TSubTaskDelete.h (.../TSubTaskDelete.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,35 +26,34 @@ #include "libchcore.h" #include "TSubTaskBase.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////// -// TSubTaskDelete - -class LIBCHCORE_API TSubTaskDelete : public TSubTaskBase +namespace chcore { -public: - TSubTaskDelete(TSubTaskContext& rContext); + /////////////////////////////////////////////////////////////////////////// + // TSubTaskDelete - virtual void Reset(); + class LIBCHCORE_API TSubTaskDelete : public TSubTaskBase + { + public: + TSubTaskDelete(TSubTaskContext& rContext); - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; - virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Deleting; } + virtual void Reset(); - virtual void Store(const ISerializerPtr& spSerializer) const; - virtual void Load(const ISerializerPtr& spSerializer); + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; + virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Deleting; } - void InitColumns(const ISerializerContainerPtr& spContainer) const; + virtual void Store(const ISerializerPtr& spSerializer) const; + virtual void Load(const ISerializerPtr& spSerializer); - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const; + void InitColumns(const ISerializerContainerPtr& spContainer) const; -private: + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const; + + private: #pragma warning(push) #pragma warning(disable: 4251) - TSubTaskStatsInfo m_tSubTaskStats; + TSubTaskStatsInfo m_tSubTaskStats; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSubTaskFastMove.cpp =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskFastMove.cpp (.../TSubTaskFastMove.cpp) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TSubTaskFastMove.cpp (.../TSubTaskFastMove.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -40,232 +40,229 @@ #include "TFeedbackHandlerWrapper.h" #include "TBufferSizes.h" -BEGIN_CHCORE_NAMESPACE - -TSubTaskFastMove::TSubTaskFastMove(TSubTaskContext& rContext) : - TSubTaskBase(rContext), - m_tSubTaskStats(eSubOperation_FastMove) +namespace chcore { -} + TSubTaskFastMove::TSubTaskFastMove(TSubTaskContext& rContext) : + TSubTaskBase(rContext), + m_tSubTaskStats(eSubOperation_FastMove) + { + } -TSubTaskFastMove::~TSubTaskFastMove() -{ -} + TSubTaskFastMove::~TSubTaskFastMove() + { + } -void TSubTaskFastMove::Reset() -{ - m_tSubTaskStats.Clear(); -} + void TSubTaskFastMove::Reset() + { + m_tSubTaskStats.Clear(); + } -TSubTaskFastMove::ESubOperationResult TSubTaskFastMove::Exec(const IFeedbackHandlerPtr& spFeedback) -{ - TScopedRunningTimeTracker guard(m_tSubTaskStats); - TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(spFeedback, guard)); + TSubTaskFastMove::ESubOperationResult TSubTaskFastMove::Exec(const IFeedbackHandlerPtr& spFeedback) + { + TScopedRunningTimeTracker guard(m_tSubTaskStats); + TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(spFeedback, guard)); - // log - icpf::log_file& rLog = GetContext().GetLog(); - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); - const TConfig& rConfig = GetContext().GetConfig(); - TSmartPath pathDestination = GetContext().GetDestinationPath(); - const TFileFiltersArray& rafFilters = GetContext().GetFilters(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + // log + icpf::log_file& rLog = GetContext().GetLog(); + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); + const TConfig& rConfig = GetContext().GetConfig(); + TSmartPath pathDestination = GetContext().GetDestinationPath(); + const TFileFiltersArray& rafFilters = GetContext().GetFilters(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - rLog.logi(_T("Performing initial fast-move operation...")); + rLog.logi(_T("Performing initial fast-move operation...")); - // new stats - m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); - m_tSubTaskStats.SetTotalCount(spBasePaths->GetCount()); - m_tSubTaskStats.SetProcessedCount(0); - m_tSubTaskStats.SetTotalSize(0); - m_tSubTaskStats.SetProcessedSize(0); - m_tSubTaskStats.SetCurrentPath(TString()); + // new stats + m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); + m_tSubTaskStats.SetTotalCount(spBasePaths->GetCount()); + m_tSubTaskStats.SetProcessedCount(0); + m_tSubTaskStats.SetTotalSize(0); + m_tSubTaskStats.SetProcessedSize(0); + m_tSubTaskStats.SetCurrentPath(TString()); - bool bIgnoreDirs = GetTaskPropValue(rConfig); - bool bForceDirectories = GetTaskPropValue(rConfig); + bool bIgnoreDirs = GetTaskPropValue(rConfig); + bool bForceDirectories = GetTaskPropValue(rConfig); - // when using special options with move operation, we don't want to use fast-moving, since most probably - // some searching and special processing needs to be done - if(bIgnoreDirs || bForceDirectories) - return eSubResult_Continue; + // when using special options with move operation, we don't want to use fast-moving, since most probably + // some searching and special processing needs to be done + if (bIgnoreDirs || bForceDirectories) + return eSubResult_Continue; - // add everything - TString strFormat; - bool bRetry = true; - bool bSkipInputPath = false; + // add everything + TString strFormat; + bool bRetry = true; + bool bSkipInputPath = false; - file_count_t fcSize = spBasePaths->GetCount(); - file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); - for(; fcIndex < fcSize ; fcIndex++) - { - TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); - TSmartPath pathCurrent = spBasePath->GetSrcPath(); + file_count_t fcSize = spBasePaths->GetCount(); + file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); + for (; fcIndex < fcSize; fcIndex++) + { + TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); + TSmartPath pathCurrent = spBasePath->GetSrcPath(); - // store currently processed index - m_tSubTaskStats.SetCurrentIndex(fcIndex); + // store currently processed index + m_tSubTaskStats.SetCurrentIndex(fcIndex); - // new stats - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); + // new stats + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); - // retrieve base path data - // check if we want to process this path at all - if(spBasePath->GetSkipFurtherProcessing()) - continue; + // retrieve base path data + // check if we want to process this path at all + if (spBasePath->GetSkipFurtherProcessing()) + continue; - TFileInfoPtr spFileInfo(boost::make_shared()); - bSkipInputPath = false; - // try to get some info about the input path; let user know if the path does not exist. - do - { - bRetry = false; - - // read attributes of src file/folder - bool bExists = spFilesystem->GetFileInfo(pathCurrent, spFileInfo, spBasePath); - if(!bExists) + TFileInfoPtr spFileInfo(boost::make_shared()); + bSkipInputPath = false; + // try to get some info about the input path; let user know if the path does not exist. + do { - EFeedbackResult frResult = spFeedbackHandler->FileError(pathCurrent.ToWString(), TString(), EFileError::eFastMoveError, ERROR_FILE_NOT_FOUND); - switch(frResult) + bRetry = false; + + // read attributes of src file/folder + bool bExists = spFilesystem->GetFileInfo(pathCurrent, spFileInfo, spBasePath); + if (!bExists) { - case EFeedbackResult::eResult_Cancel: - return eSubResult_CancelRequest; + EFeedbackResult frResult = spFeedbackHandler->FileError(pathCurrent.ToWString(), TString(), EFileError::eFastMoveError, ERROR_FILE_NOT_FOUND); + switch (frResult) + { + case EFeedbackResult::eResult_Cancel: + return eSubResult_CancelRequest; - case EFeedbackResult::eResult_Retry: - bRetry = true; - break; + case EFeedbackResult::eResult_Retry: + bRetry = true; + break; - case EFeedbackResult::eResult_Pause: - return eSubResult_PauseRequest; + case EFeedbackResult::eResult_Pause: + return eSubResult_PauseRequest; - case EFeedbackResult::eResult_Skip: - bSkipInputPath = true; - break; // just do nothing + case EFeedbackResult::eResult_Skip: + bSkipInputPath = true; + break; // just do nothing - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } - } - } - while(bRetry); + } while (bRetry); - // if we have chosen to skip the input path then there's nothing to do - if(bSkipInputPath) - continue; + // if we have chosen to skip the input path then there's nothing to do + if (bSkipInputPath) + continue; - // does it match the input filter? - if(!spFileInfo->IsDirectory() && !rafFilters.Match(spFileInfo)) - { - spBasePath->SetSkipFurtherProcessing(true); - continue; - } - - // try to fast move - bRetry = true; - bool bResult = true; - do - { - TSmartPath pathDestinationPath = CalculateDestinationPath(spFileInfo, pathDestination, 0); - TSmartPath pathSrc = spBasePath->GetSrcPath(); - bResult = spFilesystem->FastMove(pathSrc, pathDestinationPath); - if(!bResult) + // does it match the input filter? + if (!spFileInfo->IsDirectory() && !rafFilters.Match(spFileInfo)) { - DWORD dwLastError = GetLastError(); + spBasePath->SetSkipFurtherProcessing(true); + continue; + } - // check if this is one of the errors, that will just cause fast move to skip - if(dwLastError == ERROR_ACCESS_DENIED || dwLastError == ERROR_ALREADY_EXISTS) + // try to fast move + bRetry = true; + bool bResult = true; + do + { + TSmartPath pathDestinationPath = CalculateDestinationPath(spFileInfo, pathDestination, 0); + TSmartPath pathSrc = spBasePath->GetSrcPath(); + bResult = spFilesystem->FastMove(pathSrc, pathDestinationPath); + if (!bResult) { - bRetry = false; - bResult = true; - } - else - { - //log - strFormat = _T("Error %errno while calling fast move %srcpath -> %dstpath (TSubTaskFastMove)"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%srcpath"), spFileInfo->GetFullFilePath().ToString()); - strFormat.Replace(_T("%dstpath"), pathDestination.ToString()); - rLog.loge(strFormat.c_str()); + DWORD dwLastError = GetLastError(); - EFeedbackResult frResult = spFeedbackHandler->FileError(pathSrc.ToWString(), pathDestinationPath.ToWString(), EFileError::eFastMoveError, dwLastError); - switch(frResult) + // check if this is one of the errors, that will just cause fast move to skip + if (dwLastError == ERROR_ACCESS_DENIED || dwLastError == ERROR_ALREADY_EXISTS) { - case EFeedbackResult::eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; + bRetry = false; + bResult = true; + } + else + { + //log + strFormat = _T("Error %errno while calling fast move %srcpath -> %dstpath (TSubTaskFastMove)"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%srcpath"), spFileInfo->GetFullFilePath().ToString()); + strFormat.Replace(_T("%dstpath"), pathDestination.ToString()); + rLog.loge(strFormat.c_str()); - case EFeedbackResult::eResult_Retry: - continue; + EFeedbackResult frResult = spFeedbackHandler->FileError(pathSrc.ToWString(), pathDestinationPath.ToWString(), EFileError::eFastMoveError, dwLastError); + switch (frResult) + { + case EFeedbackResult::eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; - case EFeedbackResult::eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; + case EFeedbackResult::eResult_Retry: + continue; - case EFeedbackResult::eResult_Skip: - //bSkipInputPath = true; // not needed, since we will break the loop anyway and there is no other processing for this path either - bRetry = false; - break; // just do nothing + case EFeedbackResult::eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + case EFeedbackResult::eResult_Skip: + //bSkipInputPath = true; // not needed, since we will break the loop anyway and there is no other processing for this path either + bRetry = false; + break; // just do nothing + + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } } + else + spBasePath->SetSkipFurtherProcessing(true); // mark that this path should not be processed any further + } while (!bResult && bRetry); + + // check for kill need + if (rThreadController.KillRequested()) + { + // log + rLog.logi(_T("Kill request while adding data to files array (RecurseDirectories)")); + return eSubResult_KillRequest; } - else - spBasePath->SetSkipFurtherProcessing(true); // mark that this path should not be processed any further } - while(!bResult && bRetry); - // check for kill need - if(rThreadController.KillRequested()) - { - // log - rLog.logi(_T("Kill request while adding data to files array (RecurseDirectories)")); - return eSubResult_KillRequest; - } - } + m_tSubTaskStats.SetCurrentIndex(fcIndex); + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(TString()); - m_tSubTaskStats.SetCurrentIndex(fcIndex); - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(TString()); + // log + rLog.logi(_T("Fast moving finished")); - // log - rLog.logi(_T("Fast moving finished")); + return eSubResult_Continue; + } - return eSubResult_Continue; -} + void TSubTaskFastMove::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const + { + m_tSubTaskStats.GetSnapshot(spStats); + } -void TSubTaskFastMove::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const -{ - m_tSubTaskStats.GetSnapshot(spStats); -} + void TSubTaskFastMove::Store(const ISerializerPtr& spSerializer) const + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_fastmove")); -void TSubTaskFastMove::Store(const ISerializerPtr& spSerializer) const -{ - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_fastmove")); + InitColumns(spContainer); - InitColumns(spContainer); + ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); - ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); + m_tSubTaskStats.Store(rRow); + } - m_tSubTaskStats.Store(rRow); -} + void TSubTaskFastMove::Load(const ISerializerPtr& spSerializer) + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_fastmove")); -void TSubTaskFastMove::Load(const ISerializerPtr& spSerializer) -{ - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_fastmove")); + InitColumns(spContainer); - InitColumns(spContainer); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + m_tSubTaskStats.Load(spRowReader); + } - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if(spRowReader->Next()) - m_tSubTaskStats.Load(spRowReader); + void TSubTaskFastMove::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TSubTaskStatsInfo::InitColumns(rColumns); + } } - -void TSubTaskFastMove::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) - TSubTaskStatsInfo::InitColumns(rColumns); -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TSubTaskFastMove.h =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskFastMove.h (.../TSubTaskFastMove.h) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/TSubTaskFastMove.h (.../TSubTaskFastMove.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -28,41 +28,40 @@ #include "TPath.h" #include "CommonDataTypes.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + class TFileFiltersArray; -class TFileFiltersArray; + /////////////////////////////////////////////////////////////////////////// + // TSubTaskFastMove -/////////////////////////////////////////////////////////////////////////// -// TSubTaskFastMove + class LIBCHCORE_API TSubTaskFastMove : public TSubTaskBase + { + public: + TSubTaskFastMove(TSubTaskContext& rContext); + virtual ~TSubTaskFastMove(); -class LIBCHCORE_API TSubTaskFastMove : public TSubTaskBase -{ -public: - TSubTaskFastMove(TSubTaskContext& rContext); - virtual ~TSubTaskFastMove(); + virtual void Reset(); - virtual void Reset(); + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; + virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_FastMove; } - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; - virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_FastMove; } + virtual void Store(const ISerializerPtr& spSerializer) const; + virtual void Load(const ISerializerPtr& spSerializer); - virtual void Store(const ISerializerPtr& spSerializer) const; - virtual void Load(const ISerializerPtr& spSerializer); + void InitColumns(const ISerializerContainerPtr& spContainer) const; - void InitColumns(const ISerializerContainerPtr& spContainer) const; + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const; - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const; + private: + int ScanDirectory(TSmartPath pathDirName, size_t stSrcIndex, bool bRecurse, bool bIncludeDirs, TFileFiltersArray& afFilters); -private: - int ScanDirectory(TSmartPath pathDirName, size_t stSrcIndex, bool bRecurse, bool bIncludeDirs, TFileFiltersArray& afFilters); - -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - TSubTaskStatsInfo m_tSubTaskStats; + TSubTaskStatsInfo m_tSubTaskStats; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSubTaskScanDirectory.cpp =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskScanDirectory.cpp (.../TSubTaskScanDirectory.cpp) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TSubTaskScanDirectory.cpp (.../TSubTaskScanDirectory.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -39,243 +39,241 @@ #include "TFeedbackHandlerWrapper.h" #include "TBufferSizes.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// class TSubTaskScanDirectories -TSubTaskScanDirectories::TSubTaskScanDirectories(TSubTaskContext& rContext) : - TSubTaskBase(rContext), - m_tSubTaskStats(eSubOperation_Scanning) +namespace chcore { -} + /////////////////////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskScanDirectories + TSubTaskScanDirectories::TSubTaskScanDirectories(TSubTaskContext& rContext) : + TSubTaskBase(rContext), + m_tSubTaskStats(eSubOperation_Scanning) + { + } -TSubTaskScanDirectories::~TSubTaskScanDirectories() -{ -} + TSubTaskScanDirectories::~TSubTaskScanDirectories() + { + } -void TSubTaskScanDirectories::Reset() -{ - m_tSubTaskStats.Clear(); -} + void TSubTaskScanDirectories::Reset() + { + m_tSubTaskStats.Clear(); + } -TSubTaskScanDirectories::ESubOperationResult TSubTaskScanDirectories::Exec(const IFeedbackHandlerPtr& spFeedback) -{ - TScopedRunningTimeTracker guard(m_tSubTaskStats); - TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(spFeedback, guard)); + TSubTaskScanDirectories::ESubOperationResult TSubTaskScanDirectories::Exec(const IFeedbackHandlerPtr& spFeedback) + { + TScopedRunningTimeTracker guard(m_tSubTaskStats); + TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(spFeedback, guard)); - // log - icpf::log_file& rLog = GetContext().GetLog(); - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); - const TConfig& rConfig = GetContext().GetConfig(); - const TFileFiltersArray& rafFilters = GetContext().GetFilters(); - const IFilesystemPtr& spFilesystem = GetContext().GetLocalFilesystem(); + // log + icpf::log_file& rLog = GetContext().GetLog(); + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); + const TConfig& rConfig = GetContext().GetConfig(); + const TFileFiltersArray& rafFilters = GetContext().GetFilters(); + const IFilesystemPtr& spFilesystem = GetContext().GetLocalFilesystem(); - rLog.logi(_T("Searching for files...")); + rLog.logi(_T("Searching for files...")); - // reset progress - rFilesCache.SetComplete(false); + // reset progress + rFilesCache.SetComplete(false); - // new stats - m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); - m_tSubTaskStats.SetTotalCount(spBasePaths->GetCount()); - m_tSubTaskStats.SetProcessedCount(0); - m_tSubTaskStats.SetTotalSize(0); - m_tSubTaskStats.SetProcessedSize(0); - m_tSubTaskStats.SetCurrentPath(TString()); + // new stats + m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); + m_tSubTaskStats.SetTotalCount(spBasePaths->GetCount()); + m_tSubTaskStats.SetProcessedCount(0); + m_tSubTaskStats.SetTotalSize(0); + m_tSubTaskStats.SetProcessedSize(0); + m_tSubTaskStats.SetCurrentPath(TString()); - // delete the content of rFilesCache - rFilesCache.Clear(); + // delete the content of rFilesCache + rFilesCache.Clear(); - bool bIgnoreDirs = GetTaskPropValue(rConfig); - bool bForceDirectories = GetTaskPropValue(rConfig); + bool bIgnoreDirs = GetTaskPropValue(rConfig); + bool bForceDirectories = GetTaskPropValue(rConfig); - // add everything - TString strFormat; - bool bRetry = true; - bool bSkipInputPath = false; + // add everything + TString strFormat; + bool bRetry = true; + bool bSkipInputPath = false; - file_count_t fcSize = spBasePaths->GetCount(); - // NOTE: in theory, we should resume the scanning, but in practice we are always restarting scanning if interrupted. - file_count_t fcIndex = 0; // m_tSubTaskStats.GetCurrentIndex() - for(; fcIndex < fcSize; fcIndex++) - { - TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); - TSmartPath pathCurrent = spBasePath->GetSrcPath(); + file_count_t fcSize = spBasePaths->GetCount(); + // NOTE: in theory, we should resume the scanning, but in practice we are always restarting scanning if interrupted. + file_count_t fcIndex = 0; // m_tSubTaskStats.GetCurrentIndex() + for (; fcIndex < fcSize; fcIndex++) + { + TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); + TSmartPath pathCurrent = spBasePath->GetSrcPath(); - m_tSubTaskStats.SetCurrentIndex(fcIndex); + m_tSubTaskStats.SetCurrentIndex(fcIndex); - // new stats - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); + // new stats + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); - bSkipInputPath = false; - TFileInfoPtr spFileInfo(boost::make_shared()); + bSkipInputPath = false; + TFileInfoPtr spFileInfo(boost::make_shared()); - // check if we want to process this path at all (might be already fast moved) - if(spBasePath->GetSkipFurtherProcessing()) - continue; + // check if we want to process this path at all (might be already fast moved) + if (spBasePath->GetSkipFurtherProcessing()) + continue; - // try to get some info about the input path; let user know if the path does not exist. - do - { - bRetry = false; - - // read attributes of src file/folder - bool bExists = spFilesystem->GetFileInfo(pathCurrent, spFileInfo, spBasePath); - if(!bExists) + // try to get some info about the input path; let user know if the path does not exist. + do { - EFeedbackResult frResult = spFeedbackHandler->FileError(pathCurrent.ToWString(), TString(), EFileError::eFastMoveError, ERROR_FILE_NOT_FOUND); - switch(frResult) + bRetry = false; + + // read attributes of src file/folder + bool bExists = spFilesystem->GetFileInfo(pathCurrent, spFileInfo, spBasePath); + if (!bExists) { - case EFeedbackResult::eResult_Cancel: - rFilesCache.Clear(); - return eSubResult_CancelRequest; + EFeedbackResult frResult = spFeedbackHandler->FileError(pathCurrent.ToWString(), TString(), EFileError::eFastMoveError, ERROR_FILE_NOT_FOUND); + switch (frResult) + { + case EFeedbackResult::eResult_Cancel: + rFilesCache.Clear(); + return eSubResult_CancelRequest; - case EFeedbackResult::eResult_Retry: - bRetry = true; - break; + case EFeedbackResult::eResult_Retry: + bRetry = true; + break; - case EFeedbackResult::eResult_Pause: - rFilesCache.Clear(); - return eSubResult_PauseRequest; + case EFeedbackResult::eResult_Pause: + rFilesCache.Clear(); + return eSubResult_PauseRequest; - case EFeedbackResult::eResult_Skip: - bSkipInputPath = true; - break; // just do nothing + case EFeedbackResult::eResult_Skip: + bSkipInputPath = true; + break; // just do nothing - default: - BOOST_ASSERT(FALSE); // unknown result - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + default: + BOOST_ASSERT(FALSE); // unknown result + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } } - } - } - while(bRetry); + } while (bRetry); - // if we have chosen to skip the input path then there's nothing to do - if(bSkipInputPath) - continue; + // if we have chosen to skip the input path then there's nothing to do + if (bSkipInputPath) + continue; - // log - strFormat = _T("Adding file/folder (clipboard) : %path ..."); - strFormat.Replace(_T("%path"), pathCurrent.ToString()); - rLog.logi(strFormat.c_str()); + // log + strFormat = _T("Adding file/folder (clipboard) : %path ..."); + strFormat.Replace(_T("%path"), pathCurrent.ToString()); + rLog.logi(strFormat.c_str()); - // add if needed - if(spFileInfo->IsDirectory()) - { - // add if folder's aren't ignored - if(!bIgnoreDirs && !bForceDirectories) + // add if needed + if (spFileInfo->IsDirectory()) { - // add directory info; it is not to be filtered with afFilters - rFilesCache.AddFileInfo(spFileInfo); + // add if folder's aren't ignored + if (!bIgnoreDirs && !bForceDirectories) + { + // add directory info; it is not to be filtered with afFilters + rFilesCache.AddFileInfo(spFileInfo); + // log + strFormat = _T("Added folder %path"); + strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); + rLog.logi(strFormat.c_str()); + } + + // don't add folder contents when moving inside one disk boundary // log - strFormat = _T("Added folder %path"); - strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); + strFormat = _T("Recursing folder %path"); + strFormat.Replace(_t("%path"), spFileInfo->GetFullFilePath().ToString()); rLog.logi(strFormat.c_str()); - } - // don't add folder contents when moving inside one disk boundary - // log - strFormat = _T("Recursing folder %path"); - strFormat.Replace(_t("%path"), spFileInfo->GetFullFilePath().ToString()); - rLog.logi(strFormat.c_str()); + ScanDirectory(spFileInfo->GetFullFilePath(), spBasePath, true, !bIgnoreDirs || bForceDirectories, rafFilters); - ScanDirectory(spFileInfo->GetFullFilePath(), spBasePath, true, !bIgnoreDirs || bForceDirectories, rafFilters); - - // check for kill need - if(rThreadController.KillRequested()) + // check for kill need + if (rThreadController.KillRequested()) + { + // log + rLog.logi(_T("Kill request while adding data to files array (RecurseDirectories)")); + rFilesCache.Clear(); + return eSubResult_KillRequest; + } + } + else { + // add file info if passes filters + if (rafFilters.Match(spFileInfo)) + rFilesCache.AddFileInfo(spFileInfo); + // log - rLog.logi(_T("Kill request while adding data to files array (RecurseDirectories)")); - rFilesCache.Clear(); - return eSubResult_KillRequest; + strFormat = _T("Added file %path"); + strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); + rLog.logi(strFormat.c_str()); } } - else - { - // add file info if passes filters - if(rafFilters.Match(spFileInfo)) - rFilesCache.AddFileInfo(spFileInfo); - // log - strFormat = _T("Added file %path"); - strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); - rLog.logi(strFormat.c_str()); - } - } + // update stats + m_tSubTaskStats.SetCurrentIndex(fcIndex); + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(TString()); - // update stats - m_tSubTaskStats.SetCurrentIndex(fcIndex); - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(TString()); + rFilesCache.SetComplete(true); - rFilesCache.SetComplete(true); + // log + rLog.logi(_T("Searching for files finished")); - // log - rLog.logi(_T("Searching for files finished")); + return eSubResult_Continue; + } - return eSubResult_Continue; -} + void TSubTaskScanDirectories::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const + { + m_tSubTaskStats.GetSnapshot(spStats); + } -void TSubTaskScanDirectories::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const -{ - m_tSubTaskStats.GetSnapshot(spStats); -} - -int TSubTaskScanDirectories::ScanDirectory(TSmartPath pathDirName, const TBasePathDataPtr& spBasePathData, - bool bRecurse, bool bIncludeDirs, const TFileFiltersArray& afFilters) -{ - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); - const IFilesystemPtr& spFilesystem = GetContext().GetLocalFilesystem(); - - IFilesystemFindPtr spFinder = spFilesystem->CreateFinderObject(pathDirName, PathFromString(_T("*"))); - TFileInfoPtr spFileInfo(boost::make_shared()); - - while(spFinder->FindNext(spFileInfo)) + int TSubTaskScanDirectories::ScanDirectory(TSmartPath pathDirName, const TBasePathDataPtr& spBasePathData, + bool bRecurse, bool bIncludeDirs, const TFileFiltersArray& afFilters) { - if(rThreadController.KillRequested()) - break; + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); + const IFilesystemPtr& spFilesystem = GetContext().GetLocalFilesystem(); - if(!spFileInfo->IsDirectory()) + IFilesystemFindPtr spFinder = spFilesystem->CreateFinderObject(pathDirName, PathFromString(_T("*"))); + TFileInfoPtr spFileInfo(boost::make_shared()); + + while (spFinder->FindNext(spFileInfo)) { - if(afFilters.Match(spFileInfo)) + if (rThreadController.KillRequested()) + break; + + if (!spFileInfo->IsDirectory()) { - spFileInfo->SetParentObject(spBasePathData); - rFilesCache.AddFileInfo(spFileInfo); - spFileInfo = boost::make_shared(); + if (afFilters.Match(spFileInfo)) + { + spFileInfo->SetParentObject(spBasePathData); + rFilesCache.AddFileInfo(spFileInfo); + spFileInfo = boost::make_shared(); + } } - } - else - { - TSmartPath pathCurrent = spFileInfo->GetFullFilePath(); - if(bIncludeDirs) + else { - spFileInfo->SetParentObject(spBasePathData); - rFilesCache.AddFileInfo(spFileInfo); - spFileInfo = boost::make_shared(); - } + TSmartPath pathCurrent = spFileInfo->GetFullFilePath(); + if (bIncludeDirs) + { + spFileInfo->SetParentObject(spBasePathData); + rFilesCache.AddFileInfo(spFileInfo); + spFileInfo = boost::make_shared(); + } - if(bRecurse) - ScanDirectory(pathCurrent, spBasePathData, bRecurse, bIncludeDirs, afFilters); + if (bRecurse) + ScanDirectory(pathCurrent, spBasePathData, bRecurse, bIncludeDirs, afFilters); + } } + + return 0; } - return 0; -} + void TSubTaskScanDirectories::Store(const ISerializerPtr& spSerializer) const + { + spSerializer; + } -void TSubTaskScanDirectories::Store(const ISerializerPtr& spSerializer) const -{ - spSerializer; + void TSubTaskScanDirectories::Load(const ISerializerPtr& spSerializer) + { + spSerializer; + } } - -void TSubTaskScanDirectories::Load(const ISerializerPtr& spSerializer) -{ - spSerializer; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TSubTaskScanDirectory.h =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskScanDirectory.h (.../TSubTaskScanDirectory.h) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/TSubTaskScanDirectory.h (.../TSubTaskScanDirectory.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -29,40 +29,39 @@ #include "TBasePathData.h" #include "CommonDataTypes.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + class TFileFiltersArray; -class TFileFiltersArray; + /////////////////////////////////////////////////////////////////////////// + // TSubTaskScanDirectories -/////////////////////////////////////////////////////////////////////////// -// TSubTaskScanDirectories + class LIBCHCORE_API TSubTaskScanDirectories : public TSubTaskBase + { + public: + TSubTaskScanDirectories(TSubTaskContext& rContext); + virtual ~TSubTaskScanDirectories(); -class LIBCHCORE_API TSubTaskScanDirectories : public TSubTaskBase -{ -public: - TSubTaskScanDirectories(TSubTaskContext& rContext); - virtual ~TSubTaskScanDirectories(); + virtual void Reset(); - virtual void Reset(); + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; + virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Scanning; } - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; - virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Scanning; } + virtual void Store(const ISerializerPtr& spSerializer) const; + virtual void Load(const ISerializerPtr& spSerializer); - virtual void Store(const ISerializerPtr& spSerializer) const; - virtual void Load(const ISerializerPtr& spSerializer); + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const; - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const; + private: + int ScanDirectory(TSmartPath pathDirName, const TBasePathDataPtr& spBasePathData, + bool bRecurse, bool bIncludeDirs, const TFileFiltersArray& afFilters); -private: - int ScanDirectory(TSmartPath pathDirName, const TBasePathDataPtr& spBasePathData, - bool bRecurse, bool bIncludeDirs, const TFileFiltersArray& afFilters); - -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - TSubTaskStatsInfo m_tSubTaskStats; + TSubTaskStatsInfo m_tSubTaskStats; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSubTaskStatsInfo.cpp =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskStatsInfo.cpp (.../TSubTaskStatsInfo.cpp) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/TSubTaskStatsInfo.cpp (.../TSubTaskStatsInfo.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -28,455 +28,454 @@ #include "ErrorCodes.h" #include "SerializerDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////////////// -// class TSubTaskStatsInfo - -TSubTaskStatsInfo::TSubTaskStatsInfo(ESubOperationType eSubTaskType) : - m_eSubOperationType(eSubTaskType), - m_bSubTaskIsRunning(m_setModifications, false), - m_ullTotalSize(m_setModifications, 0), - m_ullProcessedSize(m_setModifications, 0), - m_fcTotalCount(m_setModifications, 0), - m_fcProcessedCount(m_setModifications, 0), - m_iCurrentBufferIndex(m_setModifications, 0), - m_strCurrentPath(m_setModifications), - m_tSizeSpeed(m_setModifications, DefaultSpeedTrackTime, DefaultSpeedSampleTime), - m_tCountSpeed(m_setModifications, DefaultSpeedTrackTime, DefaultSpeedSampleTime), - m_ullCurrentItemProcessedSize(m_setModifications, 0), - m_ullCurrentItemTotalSize(m_setModifications, 0), - m_tTimer(m_setModifications), - m_bIsInitialized(m_setModifications, false), - m_fcCurrentIndex(m_setModifications, 0), - m_bCurrentItemSilentResume(m_setModifications, false) +namespace chcore { - m_setModifications[eMod_Added] = true; -} + /////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskStatsInfo -void TSubTaskStatsInfo::Clear() -{ - m_bSubTaskIsRunning = false; - m_ullTotalSize = 0; - m_ullProcessedSize = 0; - m_fcTotalCount = 0UL; - m_fcProcessedCount = 0UL; - m_iCurrentBufferIndex = 0; - m_strCurrentPath.Modify().Clear(); - m_tTimer.Modify().Reset(); - m_tSizeSpeed.Modify().Clear(); - m_tCountSpeed.Modify().Clear(); - m_ullCurrentItemProcessedSize = 0; - m_ullCurrentItemTotalSize = 0; - m_bIsInitialized = false; - m_fcCurrentIndex = 0UL; - m_bCurrentItemSilentResume = false; -} + TSubTaskStatsInfo::TSubTaskStatsInfo(ESubOperationType eSubTaskType) : + m_eSubOperationType(eSubTaskType), + m_bSubTaskIsRunning(m_setModifications, false), + m_ullTotalSize(m_setModifications, 0), + m_ullProcessedSize(m_setModifications, 0), + m_fcTotalCount(m_setModifications, 0), + m_fcProcessedCount(m_setModifications, 0), + m_iCurrentBufferIndex(m_setModifications, 0), + m_strCurrentPath(m_setModifications), + m_tSizeSpeed(m_setModifications, DefaultSpeedTrackTime, DefaultSpeedSampleTime), + m_tCountSpeed(m_setModifications, DefaultSpeedTrackTime, DefaultSpeedSampleTime), + m_ullCurrentItemProcessedSize(m_setModifications, 0), + m_ullCurrentItemTotalSize(m_setModifications, 0), + m_tTimer(m_setModifications), + m_bIsInitialized(m_setModifications, false), + m_fcCurrentIndex(m_setModifications, 0), + m_bCurrentItemSilentResume(m_setModifications, false) + { + m_setModifications[eMod_Added] = true; + } -void TSubTaskStatsInfo::GetSnapshot(TSubTaskStatsSnapshotPtr& spStatsSnapshot) const -{ - if(!spStatsSnapshot) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + void TSubTaskStatsInfo::Clear() + { + m_bSubTaskIsRunning = false; + m_ullTotalSize = 0; + m_ullProcessedSize = 0; + m_fcTotalCount = 0UL; + m_fcProcessedCount = 0UL; + m_iCurrentBufferIndex = 0; + m_strCurrentPath.Modify().Clear(); + m_tTimer.Modify().Reset(); + m_tSizeSpeed.Modify().Clear(); + m_tCountSpeed.Modify().Clear(); + m_ullCurrentItemProcessedSize = 0; + m_ullCurrentItemTotalSize = 0; + m_bIsInitialized = false; + m_fcCurrentIndex = 0UL; + m_bCurrentItemSilentResume = false; + } - spStatsSnapshot->Clear(); + void TSubTaskStatsInfo::GetSnapshot(TSubTaskStatsSnapshotPtr& spStatsSnapshot) const + { + if (!spStatsSnapshot) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - boost::upgrade_lock lock(m_lock); - if(m_bSubTaskIsRunning) - UpdateTime(lock); + spStatsSnapshot->Clear(); - spStatsSnapshot->SetRunning(m_bSubTaskIsRunning); - spStatsSnapshot->SetProcessedCount(m_fcProcessedCount); - spStatsSnapshot->SetTotalCount(m_fcTotalCount); - spStatsSnapshot->SetProcessedSize(m_ullProcessedSize); - spStatsSnapshot->SetTotalSize(m_ullTotalSize); - spStatsSnapshot->SetCurrentBufferIndex(m_iCurrentBufferIndex); - spStatsSnapshot->SetCurrentPath(m_strCurrentPath); - spStatsSnapshot->SetTimeElapsed(m_tTimer.Get().GetTotalTime()); - spStatsSnapshot->SetSizeSpeed(m_tSizeSpeed.Get().GetSpeed()); - spStatsSnapshot->SetCountSpeed(m_tCountSpeed.Get().GetSpeed()); - spStatsSnapshot->SetCurrentItemProcessedSize(m_ullCurrentItemProcessedSize); - spStatsSnapshot->SetCurrentItemTotalSize(m_ullCurrentItemTotalSize); - spStatsSnapshot->SetSubOperationType(m_eSubOperationType); - spStatsSnapshot->SetCurrentIndex(m_fcCurrentIndex); -} + boost::upgrade_lock lock(m_lock); + if (m_bSubTaskIsRunning) + UpdateTime(lock); -// is running? -void TSubTaskStatsInfo::MarkAsRunning() -{ - boost::unique_lock lock(m_lock); - m_bSubTaskIsRunning = true; -} + spStatsSnapshot->SetRunning(m_bSubTaskIsRunning); + spStatsSnapshot->SetProcessedCount(m_fcProcessedCount); + spStatsSnapshot->SetTotalCount(m_fcTotalCount); + spStatsSnapshot->SetProcessedSize(m_ullProcessedSize); + spStatsSnapshot->SetTotalSize(m_ullTotalSize); + spStatsSnapshot->SetCurrentBufferIndex(m_iCurrentBufferIndex); + spStatsSnapshot->SetCurrentPath(m_strCurrentPath); + spStatsSnapshot->SetTimeElapsed(m_tTimer.Get().GetTotalTime()); + spStatsSnapshot->SetSizeSpeed(m_tSizeSpeed.Get().GetSpeed()); + spStatsSnapshot->SetCountSpeed(m_tCountSpeed.Get().GetSpeed()); + spStatsSnapshot->SetCurrentItemProcessedSize(m_ullCurrentItemProcessedSize); + spStatsSnapshot->SetCurrentItemTotalSize(m_ullCurrentItemTotalSize); + spStatsSnapshot->SetSubOperationType(m_eSubOperationType); + spStatsSnapshot->SetCurrentIndex(m_fcCurrentIndex); + } -void TSubTaskStatsInfo::MarkAsNotRunning() -{ - boost::unique_lock lock(m_lock); - m_bSubTaskIsRunning = false; -} + // is running? + void TSubTaskStatsInfo::MarkAsRunning() + { + boost::unique_lock lock(m_lock); + m_bSubTaskIsRunning = true; + } -void TSubTaskStatsInfo::IncreaseProcessedCount(file_count_t fcIncreaseBy) -{ - boost::unique_lock lock(m_lock); - m_fcProcessedCount.Modify() += fcIncreaseBy; + void TSubTaskStatsInfo::MarkAsNotRunning() + { + boost::unique_lock lock(m_lock); + m_bSubTaskIsRunning = false; + } - m_tCountSpeed.Modify().AddSample(fcIncreaseBy, m_tTimer.Modify().Tick()); + void TSubTaskStatsInfo::IncreaseProcessedCount(file_count_t fcIncreaseBy) + { + boost::unique_lock lock(m_lock); + m_fcProcessedCount.Modify() += fcIncreaseBy; - _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); - if(m_fcProcessedCount > m_fcTotalCount) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + m_tCountSpeed.Modify().AddSample(fcIncreaseBy, m_tTimer.Modify().Tick()); -void TSubTaskStatsInfo::SetProcessedCount(file_count_t fcProcessedCount) -{ - boost::unique_lock lock(m_lock); + _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); + if (m_fcProcessedCount > m_fcTotalCount) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } - m_tCountSpeed.Modify().AddSample(fcProcessedCount > m_fcProcessedCount ? fcProcessedCount - m_fcProcessedCount : 0, m_tTimer.Modify().Tick()); + void TSubTaskStatsInfo::SetProcessedCount(file_count_t fcProcessedCount) + { + boost::unique_lock lock(m_lock); - m_fcProcessedCount = fcProcessedCount; + m_tCountSpeed.Modify().AddSample(fcProcessedCount > m_fcProcessedCount ? fcProcessedCount - m_fcProcessedCount : 0, m_tTimer.Modify().Tick()); - _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); - if(m_fcProcessedCount > m_fcTotalCount) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + m_fcProcessedCount = fcProcessedCount; -void TSubTaskStatsInfo::SetTotalCount(file_count_t fcCount) -{ - boost::unique_lock lock(m_lock); - m_fcTotalCount = fcCount; - _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); - if(m_fcProcessedCount > m_fcTotalCount) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); + if (m_fcProcessedCount > m_fcTotalCount) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } -file_count_t TSubTaskStatsInfo::GetTotalCount() const -{ - boost::shared_lock lock(m_lock); - return m_fcTotalCount; -} + void TSubTaskStatsInfo::SetTotalCount(file_count_t fcCount) + { + boost::unique_lock lock(m_lock); + m_fcTotalCount = fcCount; + _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); + if (m_fcProcessedCount > m_fcTotalCount) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } -void TSubTaskStatsInfo::IncreaseProcessedSize(unsigned long long ullIncreaseBy) -{ - boost::unique_lock lock(m_lock); - m_ullProcessedSize.Modify() += ullIncreaseBy; + file_count_t TSubTaskStatsInfo::GetTotalCount() const + { + boost::shared_lock lock(m_lock); + return m_fcTotalCount; + } - m_tSizeSpeed.Modify().AddSample(ullIncreaseBy, m_tTimer.Modify().Tick()); + void TSubTaskStatsInfo::IncreaseProcessedSize(unsigned long long ullIncreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullProcessedSize.Modify() += ullIncreaseBy; - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if(m_ullProcessedSize > m_ullTotalSize) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + m_tSizeSpeed.Modify().AddSample(ullIncreaseBy, m_tTimer.Modify().Tick()); -void TSubTaskStatsInfo::DecreaseProcessedSize(unsigned long long ullDecreaseBy) -{ - boost::unique_lock lock(m_lock); - m_ullProcessedSize.Modify() -= ullDecreaseBy; + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } - // we didn't process anything here - hence the 0-sized sample - m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Modify().Tick()); + void TSubTaskStatsInfo::DecreaseProcessedSize(unsigned long long ullDecreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullProcessedSize.Modify() -= ullDecreaseBy; - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if(m_ullProcessedSize > m_ullTotalSize) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + // we didn't process anything here - hence the 0-sized sample + m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Modify().Tick()); -void TSubTaskStatsInfo::SetProcessedSize(unsigned long long ullProcessedSize) -{ - boost::unique_lock lock(m_lock); + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } - m_tSizeSpeed.Modify().AddSample(ullProcessedSize > m_ullProcessedSize ? ullProcessedSize - m_ullProcessedSize : 0, m_tTimer.Modify().Tick()); + void TSubTaskStatsInfo::SetProcessedSize(unsigned long long ullProcessedSize) + { + boost::unique_lock lock(m_lock); - m_ullProcessedSize = ullProcessedSize; - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if(m_ullProcessedSize > m_ullTotalSize) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + m_tSizeSpeed.Modify().AddSample(ullProcessedSize > m_ullProcessedSize ? ullProcessedSize - m_ullProcessedSize : 0, m_tTimer.Modify().Tick()); -void TSubTaskStatsInfo::SetTotalSize(unsigned long long ullTotalSize) -{ - boost::unique_lock lock(m_lock); - m_ullTotalSize = ullTotalSize; - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if(m_ullProcessedSize > m_ullTotalSize) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + m_ullProcessedSize = ullProcessedSize; + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } -// current item -void TSubTaskStatsInfo::IncreaseCurrentItemProcessedSize(unsigned long long ullIncreaseBy) -{ - boost::unique_lock lock(m_lock); - m_ullCurrentItemProcessedSize.Modify() += ullIncreaseBy; + void TSubTaskStatsInfo::SetTotalSize(unsigned long long ullTotalSize) + { + boost::unique_lock lock(m_lock); + m_ullTotalSize = ullTotalSize; + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } - _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); - if(m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + // current item + void TSubTaskStatsInfo::IncreaseCurrentItemProcessedSize(unsigned long long ullIncreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullCurrentItemProcessedSize.Modify() += ullIncreaseBy; -void TSubTaskStatsInfo::DecreaseCurrentItemProcessedSize(unsigned long long ullDecreaseBy) -{ - boost::unique_lock lock(m_lock); - m_ullCurrentItemProcessedSize.Modify() -= ullDecreaseBy; + _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); + if (m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } - _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); - if(m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + void TSubTaskStatsInfo::DecreaseCurrentItemProcessedSize(unsigned long long ullDecreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullCurrentItemProcessedSize.Modify() -= ullDecreaseBy; -void TSubTaskStatsInfo::SetCurrentItemProcessedSize(unsigned long long ullProcessedSize) -{ - boost::unique_lock lock(m_lock); + _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); + if (m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } - m_ullCurrentItemProcessedSize = ullProcessedSize; - _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); - if(m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + void TSubTaskStatsInfo::SetCurrentItemProcessedSize(unsigned long long ullProcessedSize) + { + boost::unique_lock lock(m_lock); -void TSubTaskStatsInfo::SetCurrentItemTotalSize(unsigned long long ullTotalSize) -{ - boost::unique_lock lock(m_lock); - m_ullCurrentItemTotalSize = ullTotalSize; - _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); - if(m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) - THROW_CORE_EXCEPTION(eErr_InternalProblem); -} + m_ullCurrentItemProcessedSize = ullProcessedSize; + _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); + if (m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } -// buffer index -void TSubTaskStatsInfo::SetCurrentBufferIndex(int iCurrentIndex) -{ - boost::unique_lock lock(m_lock); - m_iCurrentBufferIndex = iCurrentIndex; -} -// current path -void TSubTaskStatsInfo::SetCurrentPath(const TString& strPath) -{ - boost::unique_lock lock(m_lock); - m_strCurrentPath = strPath; -} + void TSubTaskStatsInfo::SetCurrentItemTotalSize(unsigned long long ullTotalSize) + { + boost::unique_lock lock(m_lock); + m_ullCurrentItemTotalSize = ullTotalSize; + _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); + if (m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) + THROW_CORE_EXCEPTION(eErr_InternalProblem); + } -// time -void TSubTaskStatsInfo::EnableTimeTracking() -{ - boost::unique_lock lock(m_lock); - m_tTimer.Modify().Start(); -} + // buffer index + void TSubTaskStatsInfo::SetCurrentBufferIndex(int iCurrentIndex) + { + boost::unique_lock lock(m_lock); + m_iCurrentBufferIndex = iCurrentIndex; + } + // current path + void TSubTaskStatsInfo::SetCurrentPath(const TString& strPath) + { + boost::unique_lock lock(m_lock); + m_strCurrentPath = strPath; + } -void TSubTaskStatsInfo::DisableTimeTracking() -{ - boost::unique_lock lock(m_lock); - m_tTimer.Modify().Stop(); -} + // time + void TSubTaskStatsInfo::EnableTimeTracking() + { + boost::unique_lock lock(m_lock); + m_tTimer.Modify().Start(); + } -void TSubTaskStatsInfo::UpdateTime(boost::upgrade_lock& lock) const -{ - boost::upgrade_to_unique_lock lock_upgraded(lock); - if (m_tTimer.Get().IsRunning()) + void TSubTaskStatsInfo::DisableTimeTracking() { - m_tTimer.Modify().Tick(); - m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Get().GetLastTimestamp()); - m_tCountSpeed.Modify().AddSample(0, m_tTimer.Get().GetLastTimestamp()); + boost::unique_lock lock(m_lock); + m_tTimer.Modify().Stop(); } -} -void TSubTaskStatsInfo::Store(ISerializerRowData& rRowData) const -{ - boost::shared_lock lock(m_lock); + void TSubTaskStatsInfo::UpdateTime(boost::upgrade_lock& lock) const + { + boost::upgrade_to_unique_lock lock_upgraded(lock); + if (m_tTimer.Get().IsRunning()) + { + m_tTimer.Modify().Tick(); + m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Get().GetLastTimestamp()); + m_tCountSpeed.Modify().AddSample(0, m_tTimer.Get().GetLastTimestamp()); + } + } - if(m_bSubTaskIsRunning.IsModified()) - rRowData.SetValue(_T("is_running"), m_bSubTaskIsRunning); - if(m_bIsInitialized.IsModified()) - rRowData.SetValue(_T("is_initialized"), m_bIsInitialized); + void TSubTaskStatsInfo::Store(ISerializerRowData& rRowData) const + { + boost::shared_lock lock(m_lock); - if(m_ullTotalSize.IsModified()) - rRowData.SetValue(_T("total_size"), m_ullTotalSize); + if (m_bSubTaskIsRunning.IsModified()) + rRowData.SetValue(_T("is_running"), m_bSubTaskIsRunning); + if (m_bIsInitialized.IsModified()) + rRowData.SetValue(_T("is_initialized"), m_bIsInitialized); - if(m_ullProcessedSize.IsModified()) - rRowData.SetValue(_T("processed_size"), m_ullProcessedSize); - if(m_tSizeSpeed.IsModified()) - rRowData.SetValue(_T("size_speed"), m_tSizeSpeed.Get().ToString()); + if (m_ullTotalSize.IsModified()) + rRowData.SetValue(_T("total_size"), m_ullTotalSize); - if(m_fcTotalCount.IsModified()) - rRowData.SetValue(_T("total_count"), m_fcTotalCount); - if(m_ullProcessedSize.IsModified()) - rRowData.SetValue(_T("processed_count"), m_fcProcessedCount); - if(m_tSizeSpeed.IsModified()) - rRowData.SetValue(_T("count_speed"), m_tCountSpeed.Get().ToString()); + if (m_ullProcessedSize.IsModified()) + rRowData.SetValue(_T("processed_size"), m_ullProcessedSize); + if (m_tSizeSpeed.IsModified()) + rRowData.SetValue(_T("size_speed"), m_tSizeSpeed.Get().ToString()); - if(m_ullCurrentItemProcessedSize.IsModified()) - rRowData.SetValue(_T("ci_processed_size"), m_ullCurrentItemProcessedSize); - if(m_ullCurrentItemTotalSize.IsModified()) - rRowData.SetValue(_T("ci_total_size"), m_ullCurrentItemTotalSize); - if (m_bCurrentItemSilentResume.IsModified()) - rRowData.SetValue(_T("ci_silent_resume"), m_bCurrentItemSilentResume); - if(m_fcCurrentIndex.IsModified()) - rRowData.SetValue(_T("current_index"), m_fcCurrentIndex); + if (m_fcTotalCount.IsModified()) + rRowData.SetValue(_T("total_count"), m_fcTotalCount); + if (m_ullProcessedSize.IsModified()) + rRowData.SetValue(_T("processed_count"), m_fcProcessedCount); + if (m_tSizeSpeed.IsModified()) + rRowData.SetValue(_T("count_speed"), m_tCountSpeed.Get().ToString()); - if(m_tTimer.IsModified()) - rRowData.SetValue(_T("timer"), m_tTimer.Get().GetTotalTime()); + if (m_ullCurrentItemProcessedSize.IsModified()) + rRowData.SetValue(_T("ci_processed_size"), m_ullCurrentItemProcessedSize); + if (m_ullCurrentItemTotalSize.IsModified()) + rRowData.SetValue(_T("ci_total_size"), m_ullCurrentItemTotalSize); + if (m_bCurrentItemSilentResume.IsModified()) + rRowData.SetValue(_T("ci_silent_resume"), m_bCurrentItemSilentResume); + if (m_fcCurrentIndex.IsModified()) + rRowData.SetValue(_T("current_index"), m_fcCurrentIndex); - if(m_iCurrentBufferIndex.IsModified()) - rRowData.SetValue(_T("buffer_index"), m_iCurrentBufferIndex); + if (m_tTimer.IsModified()) + rRowData.SetValue(_T("timer"), m_tTimer.Get().GetTotalTime()); - if(m_strCurrentPath.IsModified()) - rRowData.SetValue(_T("current_path"), m_strCurrentPath); + if (m_iCurrentBufferIndex.IsModified()) + rRowData.SetValue(_T("buffer_index"), m_iCurrentBufferIndex); - m_setModifications.reset(); -} + if (m_strCurrentPath.IsModified()) + rRowData.SetValue(_T("current_path"), m_strCurrentPath); -void TSubTaskStatsInfo::InitColumns(IColumnsDefinition& rColumnDefs) -{ - rColumnDefs.AddColumn(_T("id"), ColumnType::value); - rColumnDefs.AddColumn(_T("is_running"), IColumnsDefinition::eType_bool); - rColumnDefs.AddColumn(_T("is_initialized"), IColumnsDefinition::eType_bool); - rColumnDefs.AddColumn(_T("total_size"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("processed_size"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("size_speed"), IColumnsDefinition::eType_string); - rColumnDefs.AddColumn(_T("total_count"), ColumnType::value); - rColumnDefs.AddColumn(_T("processed_count"), ColumnType::value); - rColumnDefs.AddColumn(_T("count_speed"), IColumnsDefinition::eType_string); - rColumnDefs.AddColumn(_T("ci_processed_size"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("ci_total_size"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("ci_silent_resume"), IColumnsDefinition::eType_bool); - rColumnDefs.AddColumn(_T("current_index"), ColumnType::value); - rColumnDefs.AddColumn(_T("timer"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("buffer_index"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("current_path"), IColumnsDefinition::eType_string); -} + m_setModifications.reset(); + } -void TSubTaskStatsInfo::Load(const ISerializerRowReaderPtr& spRowReader) -{ - boost::unique_lock lock(m_lock); + void TSubTaskStatsInfo::InitColumns(IColumnsDefinition& rColumnDefs) + { + rColumnDefs.AddColumn(_T("id"), ColumnType::value); + rColumnDefs.AddColumn(_T("is_running"), IColumnsDefinition::eType_bool); + rColumnDefs.AddColumn(_T("is_initialized"), IColumnsDefinition::eType_bool); + rColumnDefs.AddColumn(_T("total_size"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("processed_size"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("size_speed"), IColumnsDefinition::eType_string); + rColumnDefs.AddColumn(_T("total_count"), ColumnType::value); + rColumnDefs.AddColumn(_T("processed_count"), ColumnType::value); + rColumnDefs.AddColumn(_T("count_speed"), IColumnsDefinition::eType_string); + rColumnDefs.AddColumn(_T("ci_processed_size"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("ci_total_size"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("ci_silent_resume"), IColumnsDefinition::eType_bool); + rColumnDefs.AddColumn(_T("current_index"), ColumnType::value); + rColumnDefs.AddColumn(_T("timer"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("buffer_index"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("current_path"), IColumnsDefinition::eType_string); + } - spRowReader->GetValue(_T("is_running"), m_bSubTaskIsRunning.Modify()); - spRowReader->GetValue(_T("is_initialized"), m_bIsInitialized.Modify()); + void TSubTaskStatsInfo::Load(const ISerializerRowReaderPtr& spRowReader) + { + boost::unique_lock lock(m_lock); - spRowReader->GetValue(_T("total_size"), m_ullTotalSize.Modify()); + spRowReader->GetValue(_T("is_running"), m_bSubTaskIsRunning.Modify()); + spRowReader->GetValue(_T("is_initialized"), m_bIsInitialized.Modify()); - spRowReader->GetValue(_T("processed_size"), m_ullProcessedSize.Modify()); + spRowReader->GetValue(_T("total_size"), m_ullTotalSize.Modify()); - TString strSpeed; - spRowReader->GetValue(_T("size_speed"), strSpeed); - m_tSizeSpeed.Modify().FromString(strSpeed); + spRowReader->GetValue(_T("processed_size"), m_ullProcessedSize.Modify()); - spRowReader->GetValue(_T("total_count"), m_fcTotalCount.Modify()); - spRowReader->GetValue(_T("processed_count"), m_fcProcessedCount.Modify()); + TString strSpeed; + spRowReader->GetValue(_T("size_speed"), strSpeed); + m_tSizeSpeed.Modify().FromString(strSpeed); - spRowReader->GetValue(_T("count_speed"), strSpeed); - m_tCountSpeed.Modify().FromString(strSpeed); + spRowReader->GetValue(_T("total_count"), m_fcTotalCount.Modify()); + spRowReader->GetValue(_T("processed_count"), m_fcProcessedCount.Modify()); - spRowReader->GetValue(_T("ci_processed_size"), m_ullCurrentItemProcessedSize.Modify()); - spRowReader->GetValue(_T("ci_total_size"), m_ullCurrentItemTotalSize.Modify()); - spRowReader->GetValue(_T("ci_silent_resume"), m_bCurrentItemSilentResume.Modify()); - spRowReader->GetValue(_T("current_index"), m_fcCurrentIndex.Modify()); + spRowReader->GetValue(_T("count_speed"), strSpeed); + m_tCountSpeed.Modify().FromString(strSpeed); - unsigned long long ullTimer = 0; - spRowReader->GetValue(_T("timer"), ullTimer); - m_tTimer.Modify().Init(ullTimer); + spRowReader->GetValue(_T("ci_processed_size"), m_ullCurrentItemProcessedSize.Modify()); + spRowReader->GetValue(_T("ci_total_size"), m_ullCurrentItemTotalSize.Modify()); + spRowReader->GetValue(_T("ci_silent_resume"), m_bCurrentItemSilentResume.Modify()); + spRowReader->GetValue(_T("current_index"), m_fcCurrentIndex.Modify()); - spRowReader->GetValue(_T("buffer_index"), m_iCurrentBufferIndex.Modify()); + unsigned long long ullTimer = 0; + spRowReader->GetValue(_T("timer"), ullTimer); + m_tTimer.Modify().Init(ullTimer); - spRowReader->GetValue(_T("current_path"), m_strCurrentPath.Modify()); + spRowReader->GetValue(_T("buffer_index"), m_iCurrentBufferIndex.Modify()); - m_setModifications.reset(); -} + spRowReader->GetValue(_T("current_path"), m_strCurrentPath.Modify()); -void TSubTaskStatsInfo::Init(int iCurrentBufferIndex, file_count_t fcTotalCount, file_count_t fcProcessedCount, unsigned long long ullTotalSize, unsigned long long ullProcessedSize, const TString& strCurrentPath) -{ - boost::unique_lock lock(m_lock); + m_setModifications.reset(); + } - if(m_bIsInitialized) - THROW_CORE_EXCEPTION(eErr_InvalidData); + void TSubTaskStatsInfo::Init(int iCurrentBufferIndex, file_count_t fcTotalCount, file_count_t fcProcessedCount, unsigned long long ullTotalSize, unsigned long long ullProcessedSize, const TString& strCurrentPath) + { + boost::unique_lock lock(m_lock); - m_iCurrentBufferIndex = iCurrentBufferIndex; + if (m_bIsInitialized) + THROW_CORE_EXCEPTION(eErr_InvalidData); - m_fcTotalCount = fcTotalCount; - m_fcProcessedCount = fcProcessedCount; + m_iCurrentBufferIndex = iCurrentBufferIndex; - _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); - if(m_fcProcessedCount > m_fcTotalCount) - THROW_CORE_EXCEPTION(eErr_InternalProblem); + m_fcTotalCount = fcTotalCount; + m_fcProcessedCount = fcProcessedCount; - m_ullTotalSize = ullTotalSize; - m_ullProcessedSize = ullProcessedSize; - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if(m_ullProcessedSize > m_ullTotalSize) - THROW_CORE_EXCEPTION(eErr_InternalProblem); + _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); + if (m_fcProcessedCount > m_fcTotalCount) + THROW_CORE_EXCEPTION(eErr_InternalProblem); - m_strCurrentPath = strCurrentPath; + m_ullTotalSize = ullTotalSize; + m_ullProcessedSize = ullProcessedSize; + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + THROW_CORE_EXCEPTION(eErr_InternalProblem); - m_bIsInitialized = true; -} + m_strCurrentPath = strCurrentPath; -bool TSubTaskStatsInfo::IsInitialized() const -{ - boost::shared_lock lock(m_lock); - bool bInitialized = m_bIsInitialized; + m_bIsInitialized = true; + } - return bInitialized; -} + bool TSubTaskStatsInfo::IsInitialized() const + { + boost::shared_lock lock(m_lock); + bool bInitialized = m_bIsInitialized; -void TSubTaskStatsInfo::SetCurrentIndex(file_count_t fcIndex) -{ - boost::unique_lock lock(m_lock); - m_fcCurrentIndex = fcIndex; -} + return bInitialized; + } -file_count_t TSubTaskStatsInfo::GetCurrentIndex() const -{ - boost::shared_lock lock(m_lock); - return m_fcCurrentIndex.Get(); -} + void TSubTaskStatsInfo::SetCurrentIndex(file_count_t fcIndex) + { + boost::unique_lock lock(m_lock); + m_fcCurrentIndex = fcIndex; + } -unsigned long long TSubTaskStatsInfo::GetCurrentItemProcessedSize() const -{ - boost::shared_lock lock(m_lock); - return m_ullCurrentItemProcessedSize; -} + file_count_t TSubTaskStatsInfo::GetCurrentIndex() const + { + boost::shared_lock lock(m_lock); + return m_fcCurrentIndex.Get(); + } -unsigned long long TSubTaskStatsInfo::GetCurrentItemTotalSize() const -{ - boost::shared_lock lock(m_lock); - return m_ullCurrentItemTotalSize; -} + unsigned long long TSubTaskStatsInfo::GetCurrentItemProcessedSize() const + { + boost::shared_lock lock(m_lock); + return m_ullCurrentItemProcessedSize; + } -bool TSubTaskStatsInfo::CanCurrentItemSilentResume() const -{ - boost::shared_lock lock(m_lock); - return m_bCurrentItemSilentResume; -} + unsigned long long TSubTaskStatsInfo::GetCurrentItemTotalSize() const + { + boost::shared_lock lock(m_lock); + return m_ullCurrentItemTotalSize; + } -void TSubTaskStatsInfo::SetCurrentItemSilentResume(bool bEnableSilentResume) -{ - boost::unique_lock lock(m_lock); - m_bCurrentItemSilentResume = bEnableSilentResume; -} + bool TSubTaskStatsInfo::CanCurrentItemSilentResume() const + { + boost::shared_lock lock(m_lock); + return m_bCurrentItemSilentResume; + } -bool TSubTaskStatsInfo::WasAdded() const -{ - boost::shared_lock lock(m_lock); - return m_setModifications[eMod_Added]; -} + void TSubTaskStatsInfo::SetCurrentItemSilentResume(bool bEnableSilentResume) + { + boost::unique_lock lock(m_lock); + m_bCurrentItemSilentResume = bEnableSilentResume; + } -void TSubTaskStatsInfo::IncreaseTotalSize(unsigned long long ullIncreaseBy) -{ - boost::unique_lock lock(m_lock); - m_ullTotalSize = m_ullTotalSize + ullIncreaseBy; -} + bool TSubTaskStatsInfo::WasAdded() const + { + boost::shared_lock lock(m_lock); + return m_setModifications[eMod_Added]; + } -void TSubTaskStatsInfo::DecreaseTotalSize(unsigned long long ullDecreaseBy) -{ - boost::unique_lock lock(m_lock); - m_ullTotalSize = m_ullTotalSize - ullDecreaseBy; -} + void TSubTaskStatsInfo::IncreaseTotalSize(unsigned long long ullIncreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullTotalSize = m_ullTotalSize + ullIncreaseBy; + } -void TSubTaskStatsInfo::IncreaseCurrentItemTotalSize(unsigned long long ullIncreaseBy) -{ - boost::unique_lock lock(m_lock); - m_ullCurrentItemTotalSize = m_ullCurrentItemTotalSize + ullIncreaseBy; -} + void TSubTaskStatsInfo::DecreaseTotalSize(unsigned long long ullDecreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullTotalSize = m_ullTotalSize - ullDecreaseBy; + } -void TSubTaskStatsInfo::DecreaseCurrentItemTotalSize(unsigned long long ullDecreaseBy) -{ - boost::unique_lock lock(m_lock); - m_ullCurrentItemTotalSize = m_ullCurrentItemTotalSize - ullDecreaseBy; -} + void TSubTaskStatsInfo::IncreaseCurrentItemTotalSize(unsigned long long ullIncreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullCurrentItemTotalSize = m_ullCurrentItemTotalSize + ullIncreaseBy; + } -END_CHCORE_NAMESPACE + void TSubTaskStatsInfo::DecreaseCurrentItemTotalSize(unsigned long long ullDecreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullCurrentItemTotalSize = m_ullCurrentItemTotalSize - ullDecreaseBy; + } +} Index: src/libchcore/TSubTaskStatsInfo.h =================================================================== diff -u -N -rc66b22f786f8434075a09e92de52bba8a53a85db -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskStatsInfo.h (.../TSubTaskStatsInfo.h) (revision c66b22f786f8434075a09e92de52bba8a53a85db) +++ src/libchcore/TSubTaskStatsInfo.h (.../TSubTaskStatsInfo.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -36,150 +36,149 @@ #include "CommonDataTypes.h" #include "IRunningTimeControl.h" -BEGIN_CHCORE_NAMESPACE - -class TSubTaskStatsInfo; -class TSubTaskStatsSnapshot; - -class TSubTaskStatsInfo : public IRunningTimeControl +namespace chcore { -private: - static const unsigned long long DefaultSpeedTrackTime = 1000; // in miliseconds - static const unsigned long long DefaultSpeedSampleTime = 100; // in miliseconds + class TSubTaskStatsInfo; + class TSubTaskStatsSnapshot; -public: - TSubTaskStatsInfo(ESubOperationType eSubTaskType); + class TSubTaskStatsInfo : public IRunningTimeControl + { + private: + static const unsigned long long DefaultSpeedTrackTime = 1000; // in miliseconds + static const unsigned long long DefaultSpeedSampleTime = 100; // in miliseconds - void Init(int iCurrentBufferIndex, file_count_t fcTotalCount, file_count_t fcProcessedCount, unsigned long long ullTotalSize, unsigned long long ullProcessedSize, const TString& strCurrentPath); - void Clear(); - bool WasAdded() const; + public: + TSubTaskStatsInfo(ESubOperationType eSubTaskType); - bool IsInitialized() const; + void Init(int iCurrentBufferIndex, file_count_t fcTotalCount, file_count_t fcProcessedCount, unsigned long long ullTotalSize, unsigned long long ullProcessedSize, const TString& strCurrentPath); + void Clear(); + bool WasAdded() const; - void GetSnapshot(TSubTaskStatsSnapshotPtr& spStatsSnapshot) const; + bool IsInitialized() const; - void IncreaseProcessedCount(file_count_t fcIncreaseBy); - void SetProcessedCount(file_count_t fcIndex); + void GetSnapshot(TSubTaskStatsSnapshotPtr& spStatsSnapshot) const; - void SetTotalCount(file_count_t fcCount); - file_count_t GetTotalCount() const; + void IncreaseProcessedCount(file_count_t fcIncreaseBy); + void SetProcessedCount(file_count_t fcIndex); - // size stats - void IncreaseProcessedSize(unsigned long long ullIncreaseBy); - void DecreaseProcessedSize(unsigned long long ullDecreaseBy); - void SetProcessedSize(unsigned long long ullProcessedSize); + void SetTotalCount(file_count_t fcCount); + file_count_t GetTotalCount() const; - void IncreaseTotalSize(unsigned long long ullIncreaseBy); - void DecreaseTotalSize(unsigned long long ullDecreaseBy); - void SetTotalSize(unsigned long long ullTotalSize); + // size stats + void IncreaseProcessedSize(unsigned long long ullIncreaseBy); + void DecreaseProcessedSize(unsigned long long ullDecreaseBy); + void SetProcessedSize(unsigned long long ullProcessedSize); - // current item - void IncreaseCurrentItemProcessedSize(unsigned long long ullIncreaseBy); - void DecreaseCurrentItemProcessedSize(unsigned long long ullDecreaseBy); - void SetCurrentItemProcessedSize(unsigned long long ullProcessedSize); + void IncreaseTotalSize(unsigned long long ullIncreaseBy); + void DecreaseTotalSize(unsigned long long ullDecreaseBy); + void SetTotalSize(unsigned long long ullTotalSize); - void IncreaseCurrentItemTotalSize(unsigned long long ullIncreaseBy); - void DecreaseCurrentItemTotalSize(unsigned long long ullDecreaseBy); - void SetCurrentItemTotalSize(unsigned long long ullTotalSize); + // current item + void IncreaseCurrentItemProcessedSize(unsigned long long ullIncreaseBy); + void DecreaseCurrentItemProcessedSize(unsigned long long ullDecreaseBy); + void SetCurrentItemProcessedSize(unsigned long long ullProcessedSize); - unsigned long long GetCurrentItemProcessedSize() const; - unsigned long long GetCurrentItemTotalSize() const; + void IncreaseCurrentItemTotalSize(unsigned long long ullIncreaseBy); + void DecreaseCurrentItemTotalSize(unsigned long long ullDecreaseBy); + void SetCurrentItemTotalSize(unsigned long long ullTotalSize); - bool CanCurrentItemSilentResume() const; - void SetCurrentItemSilentResume(bool bEnableSilentResume); + unsigned long long GetCurrentItemProcessedSize() const; + unsigned long long GetCurrentItemTotalSize() const; - // current index - void SetCurrentIndex(file_count_t fcIndex); - file_count_t GetCurrentIndex() const; + bool CanCurrentItemSilentResume() const; + void SetCurrentItemSilentResume(bool bEnableSilentResume); - // buffer index - void SetCurrentBufferIndex(int iCurrentIndex); + // current index + void SetCurrentIndex(file_count_t fcIndex); + file_count_t GetCurrentIndex() const; - // current path - void SetCurrentPath(const TString& strPath); + // buffer index + void SetCurrentBufferIndex(int iCurrentIndex); - ESubOperationType GetSubOperationType() const { return m_eSubOperationType; } + // current path + void SetCurrentPath(const TString& strPath); - // serialization - void Store(ISerializerRowData& rRowData) const; - static void InitColumns(IColumnsDefinition& rColumnDefs); - void Load(const ISerializerRowReaderPtr& spRowReader); + ESubOperationType GetSubOperationType() const { return m_eSubOperationType; } -private: - TSubTaskStatsInfo(const TSubTaskStatsInfo&) = delete; - TSubTaskStatsInfo& operator=(const TSubTaskStatsInfo&) = delete; + // serialization + void Store(ISerializerRowData& rRowData) const; + static void InitColumns(IColumnsDefinition& rColumnDefs); + void Load(const ISerializerRowReaderPtr& spRowReader); - // is running? - virtual void MarkAsRunning() override; - virtual void MarkAsNotRunning() override; + private: + TSubTaskStatsInfo(const TSubTaskStatsInfo&) = delete; + TSubTaskStatsInfo& operator=(const TSubTaskStatsInfo&) = delete; - // time tracking - virtual void EnableTimeTracking() override; - virtual void DisableTimeTracking() override; + // is running? + virtual void MarkAsRunning() override; + virtual void MarkAsNotRunning() override; - void UpdateTime(boost::upgrade_lock& lock) const; + // time tracking + virtual void EnableTimeTracking() override; + virtual void DisableTimeTracking() override; -private: - enum EModifications - { - eMod_Added = 0, - eMod_IsRunning, - eMod_TotalSize, - eMod_ProcessedSize, - eMod_SizeSpeed, - eMod_TotalCount, - eMod_ProcessedCount, - eMod_CountSpeed, - eMod_CurrentItemProcessedSize, - eMod_CurrentItemTotalSize, - eMod_Timer, - eMod_CurrentBufferIndex, - eMod_CurrentPath, - eMod_IsInitialized, - eMod_CurrentItemIndex, - eMod_CurrentItemCanResumeSilently, + void UpdateTime(boost::upgrade_lock& lock) const; - // last item - eMod_Last - }; + private: + enum EModifications + { + eMod_Added = 0, + eMod_IsRunning, + eMod_TotalSize, + eMod_ProcessedSize, + eMod_SizeSpeed, + eMod_TotalCount, + eMod_ProcessedCount, + eMod_CountSpeed, + eMod_CurrentItemProcessedSize, + eMod_CurrentItemTotalSize, + eMod_Timer, + eMod_CurrentBufferIndex, + eMod_CurrentPath, + eMod_IsInitialized, + eMod_CurrentItemIndex, + eMod_CurrentItemCanResumeSilently, - typedef std::bitset Bitset; - mutable Bitset m_setModifications; + // last item + eMod_Last + }; - TSharedModificationTracker m_bSubTaskIsRunning; + typedef std::bitset Bitset; + mutable Bitset m_setModifications; - TSharedModificationTracker m_ullTotalSize; - TSharedModificationTracker m_ullProcessedSize; - mutable TSharedModificationTracker m_tSizeSpeed; + TSharedModificationTracker m_bSubTaskIsRunning; - TSharedModificationTracker m_fcTotalCount; - TSharedModificationTracker m_fcProcessedCount; - mutable TSharedModificationTracker m_tCountSpeed; + TSharedModificationTracker m_ullTotalSize; + TSharedModificationTracker m_ullProcessedSize; + mutable TSharedModificationTracker m_tSizeSpeed; - TSharedModificationTracker m_fcCurrentIndex; + TSharedModificationTracker m_fcTotalCount; + TSharedModificationTracker m_fcProcessedCount; + mutable TSharedModificationTracker m_tCountSpeed; - TSharedModificationTracker m_ullCurrentItemProcessedSize; - TSharedModificationTracker m_ullCurrentItemTotalSize; - TSharedModificationTracker m_bCurrentItemSilentResume; + TSharedModificationTracker m_fcCurrentIndex; - mutable TSharedModificationTracker m_tTimer; + TSharedModificationTracker m_ullCurrentItemProcessedSize; + TSharedModificationTracker m_ullCurrentItemTotalSize; + TSharedModificationTracker m_bCurrentItemSilentResume; - TSharedModificationTracker m_iCurrentBufferIndex; + mutable TSharedModificationTracker m_tTimer; - TSharedModificationTracker m_strCurrentPath; // currently processed path + TSharedModificationTracker m_iCurrentBufferIndex; - TSharedModificationTracker m_bIsInitialized; + TSharedModificationTracker m_strCurrentPath; // currently processed path - const ESubOperationType m_eSubOperationType; + TSharedModificationTracker m_bIsInitialized; + const ESubOperationType m_eSubOperationType; + #pragma warning(push) #pragma warning(disable: 4251) - mutable boost::shared_mutex m_lock; + mutable boost::shared_mutex m_lock; #pragma warning(pop) - friend class TSubTaskProcessingGuard; -}; + friend class TSubTaskProcessingGuard; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TSubTaskStatsSnapshot.cpp =================================================================== diff -u -N -rcdc76e1a95383dff63a5254aeb8d37035028512c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskStatsSnapshot.cpp (.../TSubTaskStatsSnapshot.cpp) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/TSubTaskStatsSnapshot.cpp (.../TSubTaskStatsSnapshot.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,98 +26,97 @@ #include "MathFunctions.h" #include "TBufferSizes.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////////////// -// class TSubTaskStats -TSubTaskStatsSnapshot::TSubTaskStatsSnapshot() : - m_bSubTaskIsRunning(false), - m_ullTotalSize(0), - m_ullProcessedSize(0), - m_fcTotalCount(0), - m_fcProcessedCount(0), - m_iCurrentBufferIndex(TBufferSizes::eBuffer_Default), - m_strCurrentPath(0), - m_timeElapsed(0), - m_dSizeSpeed(0), - m_dCountSpeed(0), - m_ullCurrentItemProcessedSize(0), - m_ullCurrentItemTotalSize(0), - m_eSubOperationType(eSubOperation_None), - m_fcCurrentIndex(0) +namespace chcore { -} + /////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskStats + TSubTaskStatsSnapshot::TSubTaskStatsSnapshot() : + m_bSubTaskIsRunning(false), + m_ullTotalSize(0), + m_ullProcessedSize(0), + m_fcTotalCount(0), + m_fcProcessedCount(0), + m_iCurrentBufferIndex(TBufferSizes::eBuffer_Default), + m_strCurrentPath(0), + m_timeElapsed(0), + m_dSizeSpeed(0), + m_dCountSpeed(0), + m_ullCurrentItemProcessedSize(0), + m_ullCurrentItemTotalSize(0), + m_eSubOperationType(eSubOperation_None), + m_fcCurrentIndex(0) + { + } -void TSubTaskStatsSnapshot::Clear() -{ - m_bSubTaskIsRunning = false; - m_ullTotalSize = 0; - m_ullProcessedSize = 0; - m_fcTotalCount = 0; - m_fcProcessedCount = 0; - m_iCurrentBufferIndex = TBufferSizes::eBuffer_Default; - m_strCurrentPath = 0; - m_timeElapsed = 0; - m_dSizeSpeed = 0; - m_dCountSpeed = 0; - m_ullCurrentItemProcessedSize = 0; - m_ullCurrentItemTotalSize = 0; - m_eSubOperationType = eSubOperation_None; - m_fcCurrentIndex = 0; -} + void TSubTaskStatsSnapshot::Clear() + { + m_bSubTaskIsRunning = false; + m_ullTotalSize = 0; + m_ullProcessedSize = 0; + m_fcTotalCount = 0; + m_fcProcessedCount = 0; + m_iCurrentBufferIndex = TBufferSizes::eBuffer_Default; + m_strCurrentPath = 0; + m_timeElapsed = 0; + m_dSizeSpeed = 0; + m_dCountSpeed = 0; + m_ullCurrentItemProcessedSize = 0; + m_ullCurrentItemTotalSize = 0; + m_eSubOperationType = eSubOperation_None; + m_fcCurrentIndex = 0; + } -double TSubTaskStatsSnapshot::CalculateProgress() const -{ - // we're treating each of the items as 512B object to process - // to have some balance between items' count and items' size in - // progress information - unsigned long long ullProcessed = 512ULL * m_fcProcessedCount + m_ullProcessedSize; - unsigned long long ullTotal = 512ULL * m_fcTotalCount + m_ullTotalSize; + double TSubTaskStatsSnapshot::CalculateProgress() const + { + // we're treating each of the items as 512B object to process + // to have some balance between items' count and items' size in + // progress information + unsigned long long ullProcessed = 512ULL * m_fcProcessedCount + m_ullProcessedSize; + unsigned long long ullTotal = 512ULL * m_fcTotalCount + m_ullTotalSize; - if(ullTotal != 0) - return Math::Div64(ullProcessed, ullTotal); - else - return 0.0; -} + if (ullTotal != 0) + return Math::Div64(ullProcessed, ullTotal); + else + return 0.0; + } -unsigned long long TSubTaskStatsSnapshot::GetEstimatedTotalTime() const -{ - double dProgress = CalculateProgress(); - if(dProgress == 0.0) - return std::numeric_limits::max(); - else - return (unsigned long long)(m_timeElapsed * (1.0 / dProgress)); -} + unsigned long long TSubTaskStatsSnapshot::GetEstimatedTotalTime() const + { + double dProgress = CalculateProgress(); + if (dProgress == 0.0) + return std::numeric_limits::max(); + else + return (unsigned long long)(m_timeElapsed * (1.0 / dProgress)); + } -void TSubTaskStatsSnapshot::SetSizeSpeed(double dSizeSpeed) -{ - m_dSizeSpeed = dSizeSpeed; -} + void TSubTaskStatsSnapshot::SetSizeSpeed(double dSizeSpeed) + { + m_dSizeSpeed = dSizeSpeed; + } -void TSubTaskStatsSnapshot::SetCountSpeed(double dCountSpeed) -{ - m_dCountSpeed = dCountSpeed; -} + void TSubTaskStatsSnapshot::SetCountSpeed(double dCountSpeed) + { + m_dCountSpeed = dCountSpeed; + } -double TSubTaskStatsSnapshot::GetAvgSizeSpeed() const -{ - if(m_timeElapsed) - return Math::Div64(m_ullProcessedSize, m_timeElapsed / 1000); - else - return 0.0; -} + double TSubTaskStatsSnapshot::GetAvgSizeSpeed() const + { + if (m_timeElapsed) + return Math::Div64(m_ullProcessedSize, m_timeElapsed / 1000); + else + return 0.0; + } -double TSubTaskStatsSnapshot::GetAvgCountSpeed() const -{ - if(m_timeElapsed) - return Math::Div64(m_fcProcessedCount, m_timeElapsed / 1000); - else - return 0.0; -} + double TSubTaskStatsSnapshot::GetAvgCountSpeed() const + { + if (m_timeElapsed) + return Math::Div64(m_fcProcessedCount, m_timeElapsed / 1000); + else + return 0.0; + } -double TSubTaskStatsSnapshot::GetCombinedProgress() const -{ - return CalculateProgress(); + double TSubTaskStatsSnapshot::GetCombinedProgress() const + { + return CalculateProgress(); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TSubTaskStatsSnapshot.h =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TSubTaskStatsSnapshot.h (.../TSubTaskStatsSnapshot.h) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TSubTaskStatsSnapshot.h (.../TSubTaskStatsSnapshot.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -28,105 +28,104 @@ #include "ESubTaskTypes.h" #include "CommonDataTypes.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TSubTaskStatsSnapshot +namespace chcore { -public: - TSubTaskStatsSnapshot(); + class LIBCHCORE_API TSubTaskStatsSnapshot + { + public: + TSubTaskStatsSnapshot(); - void Clear(); + void Clear(); - // is running? - void SetRunning(bool bRunning) { m_bSubTaskIsRunning = bRunning; } - bool IsRunning() const { return m_bSubTaskIsRunning; } + // is running? + void SetRunning(bool bRunning) { m_bSubTaskIsRunning = bRunning; } + bool IsRunning() const { return m_bSubTaskIsRunning; } - // count stats - void SetProcessedCount(file_count_t fcIndex) { m_fcProcessedCount = fcIndex; } - file_count_t GetProcessedCount() const { return m_fcProcessedCount; } + // count stats + void SetProcessedCount(file_count_t fcIndex) { m_fcProcessedCount = fcIndex; } + file_count_t GetProcessedCount() const { return m_fcProcessedCount; } - void SetTotalCount(file_count_t fcCount) { m_fcTotalCount = fcCount; } - file_count_t GetTotalCount() const { return m_fcTotalCount; } + void SetTotalCount(file_count_t fcCount) { m_fcTotalCount = fcCount; } + file_count_t GetTotalCount() const { return m_fcTotalCount; } - // size stats - void SetProcessedSize(unsigned long long ullProcessedSize) { m_ullProcessedSize = ullProcessedSize; } - unsigned long long GetProcessedSize() const { return m_ullProcessedSize; } + // size stats + void SetProcessedSize(unsigned long long ullProcessedSize) { m_ullProcessedSize = ullProcessedSize; } + unsigned long long GetProcessedSize() const { return m_ullProcessedSize; } - void SetTotalSize(unsigned long long ullTotalSize) { m_ullTotalSize = ullTotalSize; } - unsigned long long GetTotalSize() const { return m_ullTotalSize; } + void SetTotalSize(unsigned long long ullTotalSize) { m_ullTotalSize = ullTotalSize; } + unsigned long long GetTotalSize() const { return m_ullTotalSize; } - // current file - void SetCurrentItemProcessedSize(unsigned long long ullProcessedSize) { m_ullCurrentItemProcessedSize = ullProcessedSize; } - unsigned long long GetCurrentItemProcessedSize() const { return m_ullCurrentItemProcessedSize; } + // current file + void SetCurrentItemProcessedSize(unsigned long long ullProcessedSize) { m_ullCurrentItemProcessedSize = ullProcessedSize; } + unsigned long long GetCurrentItemProcessedSize() const { return m_ullCurrentItemProcessedSize; } - void SetCurrentItemTotalSize(unsigned long long ullTotalSize) { m_ullCurrentItemTotalSize = ullTotalSize; } - unsigned long long GetCurrentItemTotalSize() const { return m_ullCurrentItemTotalSize; } + void SetCurrentItemTotalSize(unsigned long long ullTotalSize) { m_ullCurrentItemTotalSize = ullTotalSize; } + unsigned long long GetCurrentItemTotalSize() const { return m_ullCurrentItemTotalSize; } - void SetCurrentIndex(file_count_t fcCurrentIndex) { m_fcCurrentIndex = fcCurrentIndex; } - file_count_t GetCurrentIndex() const { return m_fcCurrentIndex; } + void SetCurrentIndex(file_count_t fcCurrentIndex) { m_fcCurrentIndex = fcCurrentIndex; } + file_count_t GetCurrentIndex() const { return m_fcCurrentIndex; } - // progress in percent - double GetCombinedProgress() const; // returns progress [0.0, 1.0] + // progress in percent + double GetCombinedProgress() const; // returns progress [0.0, 1.0] - // buffer index - void SetCurrentBufferIndex(int iCurrentIndex) { m_iCurrentBufferIndex = iCurrentIndex; } - int GetCurrentBufferIndex() const { return m_iCurrentBufferIndex; } + // buffer index + void SetCurrentBufferIndex(int iCurrentIndex) { m_iCurrentBufferIndex = iCurrentIndex; } + int GetCurrentBufferIndex() const { return m_iCurrentBufferIndex; } - // current path - void SetCurrentPath(const TString& strPath) { m_strCurrentPath = strPath; } - const TString& GetCurrentPath() const { return m_strCurrentPath; } + // current path + void SetCurrentPath(const TString& strPath) { m_strCurrentPath = strPath; } + const TString& GetCurrentPath() const { return m_strCurrentPath; } - // time - void SetTimeElapsed(unsigned long long timeElapsed) { m_timeElapsed = timeElapsed; } - unsigned long long GetTimeElapsed() { return m_timeElapsed; } + // time + void SetTimeElapsed(unsigned long long timeElapsed) { m_timeElapsed = timeElapsed; } + unsigned long long GetTimeElapsed() { return m_timeElapsed; } - // time estimations - unsigned long long GetEstimatedTotalTime() const; + // time estimations + unsigned long long GetEstimatedTotalTime() const; - // speed - void SetSizeSpeed(double dSizeSpeed); - double GetSizeSpeed() const { return m_dSizeSpeed; } - void SetCountSpeed(double dCountSpeed); - double GetCountSpeed() const { return m_dCountSpeed; } + // speed + void SetSizeSpeed(double dSizeSpeed); + double GetSizeSpeed() const { return m_dSizeSpeed; } + void SetCountSpeed(double dCountSpeed); + double GetCountSpeed() const { return m_dCountSpeed; } - double GetAvgSizeSpeed() const; - double GetAvgCountSpeed() const; + double GetAvgSizeSpeed() const; + double GetAvgCountSpeed() const; - ESubOperationType GetSubOperationType() const { return m_eSubOperationType; } - void SetSubOperationType(ESubOperationType val) { m_eSubOperationType = val; } + ESubOperationType GetSubOperationType() const { return m_eSubOperationType; } + void SetSubOperationType(ESubOperationType val) { m_eSubOperationType = val; } -private: - double CalculateProgress() const; + private: + double CalculateProgress() const; -private: - bool m_bSubTaskIsRunning; + private: + bool m_bSubTaskIsRunning; - // subtask size and size speed per second - unsigned long long m_ullTotalSize; - unsigned long long m_ullProcessedSize; - double m_dSizeSpeed; + // subtask size and size speed per second + unsigned long long m_ullTotalSize; + unsigned long long m_ullProcessedSize; + double m_dSizeSpeed; - // subtask count of items and its speed per second - file_count_t m_fcTotalCount; - file_count_t m_fcProcessedCount; - double m_dCountSpeed; + // subtask count of items and its speed per second + file_count_t m_fcTotalCount; + file_count_t m_fcProcessedCount; + double m_dCountSpeed; - // current item size - unsigned long long m_ullCurrentItemTotalSize; - unsigned long long m_ullCurrentItemProcessedSize; - file_count_t m_fcCurrentIndex; + // current item size + unsigned long long m_ullCurrentItemTotalSize; + unsigned long long m_ullCurrentItemProcessedSize; + file_count_t m_fcCurrentIndex; - ESubOperationType m_eSubOperationType; + ESubOperationType m_eSubOperationType; - int m_iCurrentBufferIndex; + int m_iCurrentBufferIndex; - TString m_strCurrentPath; // currently processed path + TString m_strCurrentPath; // currently processed path - unsigned long long m_timeElapsed; // time really elapsed for the subtask -}; + unsigned long long m_timeElapsed; // time really elapsed for the subtask + }; -typedef boost::shared_ptr TSubTaskStatsSnapshotPtr; + typedef boost::shared_ptr TSubTaskStatsSnapshotPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTask.cpp =================================================================== diff -u -N -r9ebcc7abf1e0e70f0db2d08b2691351a26ef259b -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTask.cpp (.../TTask.cpp) (revision 9ebcc7abf1e0e70f0db2d08b2691351a26ef259b) +++ src/libchcore/TTask.cpp (.../TTask.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -40,628 +40,627 @@ #include #include "TTaskConfigBufferSizes.h" -BEGIN_CHCORE_NAMESPACE - -//////////////////////////////////////////////////////////////////////////// -// TTask members - -TTask::TTask(const ISerializerPtr& spSerializer, const IFeedbackHandlerPtr& spFeedbackHandler) : - m_log(), - m_spInternalFeedbackHandler(spFeedbackHandler), - m_spSrcPaths(new TBasePathDataContainer), - m_bForce(false), - m_bContinue(false), - m_tSubTaskContext(m_tConfiguration, m_spSrcPaths, m_afFilters, - m_cfgTracker, m_log, m_workerThread, - std::make_shared()), - m_tSubTasksArray(m_tSubTaskContext), - m_spSerializer(spSerializer) +namespace chcore { - if(!spFeedbackHandler || !spSerializer) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); -} + //////////////////////////////////////////////////////////////////////////// + // TTask members -TTask::~TTask() -{ - KillThread(); -} + TTask::TTask(const ISerializerPtr& spSerializer, const IFeedbackHandlerPtr& spFeedbackHandler) : + m_log(), + m_spInternalFeedbackHandler(spFeedbackHandler), + m_spSrcPaths(new TBasePathDataContainer), + m_bForce(false), + m_bContinue(false), + m_tSubTaskContext(m_tConfiguration, m_spSrcPaths, m_afFilters, + m_cfgTracker, m_log, m_workerThread, + std::make_shared()), + m_tSubTasksArray(m_tSubTaskContext), + m_spSerializer(spSerializer) + { + if (!spFeedbackHandler || !spSerializer) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + } -void TTask::SetTaskDefinition(const TTaskDefinition& rTaskDefinition) -{ - m_tBaseData.SetDestinationPath(rTaskDefinition.GetDestinationPath()); - m_tConfiguration = rTaskDefinition.GetConfiguration(); - *m_spSrcPaths = rTaskDefinition.GetSourcePaths(); - m_afFilters = rTaskDefinition.GetFilters(); - m_tBaseData.SetTaskName(rTaskDefinition.GetTaskName()); + TTask::~TTask() + { + KillThread(); + } - m_tSubTasksArray.Init(rTaskDefinition.GetOperationPlan()); - m_tSubTaskContext.SetOperationType(m_tSubTasksArray.GetOperationType()); - m_tSubTaskContext.SetDestinationPath(m_tBaseData.GetDestinationPath()); -} + void TTask::SetTaskDefinition(const TTaskDefinition& rTaskDefinition) + { + m_tBaseData.SetDestinationPath(rTaskDefinition.GetDestinationPath()); + m_tConfiguration = rTaskDefinition.GetConfiguration(); + *m_spSrcPaths = rTaskDefinition.GetSourcePaths(); + m_afFilters = rTaskDefinition.GetFilters(); + m_tBaseData.SetTaskName(rTaskDefinition.GetTaskName()); -void TTask::OnRegisterTask() -{ -} + m_tSubTasksArray.Init(rTaskDefinition.GetOperationPlan()); + m_tSubTaskContext.SetOperationType(m_tSubTasksArray.GetOperationType()); + m_tSubTaskContext.SetDestinationPath(m_tBaseData.GetDestinationPath()); + } -void TTask::OnUnregisterTask() -{ -} + void TTask::OnRegisterTask() + { + } -void TTask::SetTaskState(ETaskCurrentState eTaskState) -{ - // NOTE: we could check some transition rules here - boost::unique_lock lock(m_lock); - m_tBaseData.SetCurrentState(eTaskState); -} + void TTask::OnUnregisterTask() + { + } -ETaskCurrentState TTask::GetTaskState() const -{ - boost::shared_lock lock(m_lock); - return m_tBaseData.GetCurrentState(); -} + void TTask::SetTaskState(ETaskCurrentState eTaskState) + { + // NOTE: we could check some transition rules here + boost::unique_lock lock(m_lock); + m_tBaseData.SetCurrentState(eTaskState); + } -void TTask::SetBufferSizes(const TBufferSizes& bsSizes) -{ - m_tConfiguration.DelayNotifications(); + ETaskCurrentState TTask::GetTaskState() const + { + boost::shared_lock lock(m_lock); + return m_tBaseData.GetCurrentState(); + } - SetTaskPropBufferSizes(m_tConfiguration, bsSizes); - m_tConfiguration.ResumeNotifications(); -} + void TTask::SetBufferSizes(const TBufferSizes& bsSizes) + { + m_tConfiguration.DelayNotifications(); -void TTask::GetBufferSizes(TBufferSizes& bsSizes) -{ - bsSizes = GetTaskPropBufferSizes(m_tConfiguration); -} + SetTaskPropBufferSizes(m_tConfiguration, bsSizes); + m_tConfiguration.ResumeNotifications(); + } -// thread -void TTask::SetPriority(int nPriority) -{ - SetTaskPropValue(m_tConfiguration, nPriority); -} + void TTask::GetBufferSizes(TBufferSizes& bsSizes) + { + bsSizes = GetTaskPropBufferSizes(m_tConfiguration); + } -void TTask::Load() -{ - using namespace chcore; + // thread + void TTask::SetPriority(int nPriority) + { + SetTaskPropValue(m_tConfiguration, nPriority); + } - bool bLogPathLoaded = false; - bool bLoadFailed = false; - const size_t stMaxSize = 1024; - wchar_t szErr[stMaxSize]; - - try + void TTask::Load() { - boost::unique_lock lock(m_lock); + using namespace chcore; - ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("task")); - m_tBaseData.Load(spContainer); + bool bLogPathLoaded = false; + bool bLoadFailed = false; + const size_t stMaxSize = 1024; + wchar_t szErr[stMaxSize]; - bLogPathLoaded = true; + try + { + boost::unique_lock lock(m_lock); - spContainer = m_spSerializer->GetContainer(_T("base_paths")); - m_spSrcPaths->Load(spContainer); + ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("task")); + m_tBaseData.Load(spContainer); - spContainer = m_spSerializer->GetContainer(_T("scanned_files")); - m_tSubTaskContext.GetFilesCache().Load(spContainer, m_spSrcPaths); + bLogPathLoaded = true; - spContainer = m_spSerializer->GetContainer(_T("task_config")); - m_tConfiguration.Load(spContainer); + spContainer = m_spSerializer->GetContainer(_T("base_paths")); + m_spSrcPaths->Load(spContainer); - spContainer = m_spSerializer->GetContainer(_T("filters")); - m_afFilters.Load(spContainer); + spContainer = m_spSerializer->GetContainer(_T("scanned_files")); + m_tSubTaskContext.GetFilesCache().Load(spContainer, m_spSrcPaths); - spContainer = m_spSerializer->GetContainer(_T("local_stats")); - m_tLocalStats.Load(spContainer); + spContainer = m_spSerializer->GetContainer(_T("task_config")); + m_tConfiguration.Load(spContainer); - spContainer = m_spSerializer->GetContainer(_T("feedback")); - m_spInternalFeedbackHandler->Load(spContainer); + spContainer = m_spSerializer->GetContainer(_T("filters")); + m_afFilters.Load(spContainer); - m_tSubTasksArray.Load(m_spSerializer); + spContainer = m_spSerializer->GetContainer(_T("local_stats")); + m_tLocalStats.Load(spContainer); - // ensure copy-based context entries are properly updated after loading - m_tSubTaskContext.SetDestinationPath(m_tBaseData.GetDestinationPath()); - m_tSubTaskContext.SetOperationType(m_tSubTasksArray.GetOperationType()); - } - catch(const TBaseException& e) - { - SetTaskState(eTaskState_LoadError); - bLoadFailed = true; + spContainer = m_spSerializer->GetContainer(_T("feedback")); + m_spInternalFeedbackHandler->Load(spContainer); - _tcscpy_s(szErr, stMaxSize, _T("Task load error: ")); - size_t stLen = _tcslen(szErr); + m_tSubTasksArray.Load(m_spSerializer); - e.GetDetailedErrorInfo(szErr + stLen, stMaxSize - stLen); - } - catch(const std::exception& e) - { - SetTaskState(eTaskState_LoadError); - bLoadFailed = true; - _snwprintf_s(szErr, stMaxSize, _TRUNCATE, _T("Task load error. %hs"), e.what()); - } + // ensure copy-based context entries are properly updated after loading + m_tSubTaskContext.SetDestinationPath(m_tBaseData.GetDestinationPath()); + m_tSubTaskContext.SetOperationType(m_tSubTasksArray.GetOperationType()); + } + catch (const TBaseException& e) + { + SetTaskState(eTaskState_LoadError); + bLoadFailed = true; - if(bLoadFailed) - { - try + _tcscpy_s(szErr, stMaxSize, _T("Task load error: ")); + size_t stLen = _tcslen(szErr); + + e.GetDetailedErrorInfo(szErr + stLen, stMaxSize - stLen); + } + catch (const std::exception& e) { - if(bLogPathLoaded) - GetLog().loge(szErr); + SetTaskState(eTaskState_LoadError); + bLoadFailed = true; + _snwprintf_s(szErr, stMaxSize, _TRUNCATE, _T("Task load error. %hs"), e.what()); } - catch(const std::exception&) + + if (bLoadFailed) { + try + { + if (bLogPathLoaded) + GetLog().loge(szErr); + } + catch (const std::exception&) + { + } } } -} -void TTask::Store() -{ - if(GetTaskState() == eTaskState_LoadError) + void TTask::Store() { - DBTRACE0(_T("Task::Store() - not storing task as it was not loaded correctly\n")); - return; - } + if (GetTaskState() == eTaskState_LoadError) + { + DBTRACE0(_T("Task::Store() - not storing task as it was not loaded correctly\n")); + return; + } - TSimpleTimer timer(true); - DBTRACE0(_T("###### Task::Store() - starting\n")); + TSimpleTimer timer(true); + DBTRACE0(_T("###### Task::Store() - starting\n")); - using namespace chcore; + using namespace chcore; - { - boost::shared_lock lock(m_lock); + { + boost::shared_lock lock(m_lock); - ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("task")); - m_tBaseData.Store(spContainer); + ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("task")); + m_tBaseData.Store(spContainer); - // base paths - spContainer = m_spSerializer->GetContainer(_T("base_paths")); - m_spSrcPaths->Store(spContainer); + // base paths + spContainer = m_spSerializer->GetContainer(_T("base_paths")); + m_spSrcPaths->Store(spContainer); - spContainer = m_spSerializer->GetContainer(_T("scanned_files")); - m_tSubTaskContext.GetFilesCache().Store(spContainer); + spContainer = m_spSerializer->GetContainer(_T("scanned_files")); + m_tSubTaskContext.GetFilesCache().Store(spContainer); - spContainer = m_spSerializer->GetContainer(_T("task_config")); - m_tConfiguration.Store(spContainer); + spContainer = m_spSerializer->GetContainer(_T("task_config")); + m_tConfiguration.Store(spContainer); - spContainer = m_spSerializer->GetContainer(_T("filters")); - m_afFilters.Store(spContainer); + spContainer = m_spSerializer->GetContainer(_T("filters")); + m_afFilters.Store(spContainer); - spContainer = m_spSerializer->GetContainer(_T("local_stats")); - m_tLocalStats.Store(spContainer); + spContainer = m_spSerializer->GetContainer(_T("local_stats")); + m_tLocalStats.Store(spContainer); - spContainer = m_spSerializer->GetContainer(_T("feedback")); - m_spInternalFeedbackHandler->Store(spContainer); + spContainer = m_spSerializer->GetContainer(_T("feedback")); + m_spInternalFeedbackHandler->Store(spContainer); - m_tSubTasksArray.Store(m_spSerializer); - } + m_tSubTasksArray.Store(m_spSerializer); + } - unsigned long long ullGatherTime = timer.Checkpoint(); ullGatherTime; + unsigned long long ullGatherTime = timer.Checkpoint(); ullGatherTime; - m_spSerializer->Flush(); + m_spSerializer->Flush(); - unsigned long long ullFlushTime = timer.Stop(); ullFlushTime; - DBTRACE2(_T("###### Task::Store() - finished - gather: %I64u ms, flush: %I64u ms\n"), ullGatherTime, ullFlushTime); -} + unsigned long long ullFlushTime = timer.Stop(); ullFlushTime; + DBTRACE2(_T("###### Task::Store() - finished - gather: %I64u ms, flush: %I64u ms\n"), ullGatherTime, ullFlushTime); + } -void TTask::KillThread() -{ - m_workerThread.StopThread(); -} + void TTask::KillThread() + { + m_workerThread.StopThread(); + } -void TTask::BeginProcessing() -{ - GetLog().logi(_T("Requested task to begin processing")); + void TTask::BeginProcessing() + { + GetLog().logi(_T("Requested task to begin processing")); - boost::unique_lock lock(m_lock); - if(m_tBaseData.GetCurrentState() != eTaskState_LoadError) - m_workerThread.StartThread(DelegateThreadProc, this, GetTaskPropValue(m_tConfiguration)); -} + boost::unique_lock lock(m_lock); + if (m_tBaseData.GetCurrentState() != eTaskState_LoadError) + m_workerThread.StartThread(DelegateThreadProc, this, GetTaskPropValue(m_tConfiguration)); + } -void TTask::ResumeProcessing() -{ - // the same as retry but less demanding - if(GetTaskState() == eTaskState_Paused) + void TTask::ResumeProcessing() { - GetLog().logi(_T("Requested task resume")); - SetTaskState(eTaskState_Processing); - BeginProcessing(); + // the same as retry but less demanding + if (GetTaskState() == eTaskState_Paused) + { + GetLog().logi(_T("Requested task resume")); + SetTaskState(eTaskState_Processing); + BeginProcessing(); + } } -} -bool TTask::RetryProcessing() -{ - // retry used to auto-resume, after loading - switch(GetTaskState()) + bool TTask::RetryProcessing() { - case eTaskState_Paused: - case eTaskState_Finished: - case eTaskState_Cancelled: - case eTaskState_LoadError: - return false; + // retry used to auto-resume, after loading + switch (GetTaskState()) + { + case eTaskState_Paused: + case eTaskState_Finished: + case eTaskState_Cancelled: + case eTaskState_LoadError: + return false; - default: - BeginProcessing(); - return true; + default: + BeginProcessing(); + return true; + } } -} -void TTask::RestartProcessing() -{ - GetLog().logi(_T("Requested task restart")); - KillThread(); + void TTask::RestartProcessing() + { + GetLog().logi(_T("Requested task restart")); + KillThread(); - SetTaskState(eTaskState_None); + SetTaskState(eTaskState_None); - m_spInternalFeedbackHandler->RestoreDefaults(); - m_tSubTasksArray.ResetProgressAndStats(); - m_tLocalStats.Clear(); + m_spInternalFeedbackHandler->RestoreDefaults(); + m_tSubTasksArray.ResetProgressAndStats(); + m_tLocalStats.Clear(); - BeginProcessing(); -} + BeginProcessing(); + } -void TTask::PauseProcessing() -{ - if(GetTaskState() != eTaskState_Finished && GetTaskState() != eTaskState_Cancelled) + void TTask::PauseProcessing() { - GetLog().logi(_T("Requested task pause")); - KillThread(); - SetTaskState(eTaskState_Paused); + if (GetTaskState() != eTaskState_Finished && GetTaskState() != eTaskState_Cancelled) + { + GetLog().logi(_T("Requested task pause")); + KillThread(); + SetTaskState(eTaskState_Paused); + } } -} -void TTask::CancelProcessing() -{ - // change to ST_CANCELLED - if(GetTaskState() != eTaskState_Finished) + void TTask::CancelProcessing() { - GetLog().logi(_T("Requested task cancel")); - KillThread(); - SetTaskState(eTaskState_Cancelled); + // change to ST_CANCELLED + if (GetTaskState() != eTaskState_Finished) + { + GetLog().logi(_T("Requested task cancel")); + KillThread(); + SetTaskState(eTaskState_Cancelled); + } } -} -void TTask::GetStatsSnapshot(TTaskStatsSnapshotPtr& spSnapshot) -{ - if(!spSnapshot) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + void TTask::GetStatsSnapshot(TTaskStatsSnapshotPtr& spSnapshot) + { + if (!spSnapshot) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - spSnapshot->Clear(); + spSnapshot->Clear(); - boost::shared_lock lock(m_lock); - m_tSubTasksArray.GetStatsSnapshot(spSnapshot->GetSubTasksStats()); + boost::shared_lock lock(m_lock); + m_tSubTasksArray.GetStatsSnapshot(spSnapshot->GetSubTasksStats()); - m_tLocalStats.GetSnapshot(spSnapshot); + m_tLocalStats.GetSnapshot(spSnapshot); - spSnapshot->SetTaskName(m_tBaseData.GetTaskName()); - spSnapshot->SetThreadPriority(GetTaskPropValue(m_tConfiguration)); - spSnapshot->SetDestinationPath(m_tBaseData.GetDestinationPath().ToString()); - spSnapshot->SetFilters(m_afFilters); - spSnapshot->SetTaskState(m_tBaseData.GetCurrentState()); - spSnapshot->SetOperationType(m_tSubTasksArray.GetOperationType()); + spSnapshot->SetTaskName(m_tBaseData.GetTaskName()); + spSnapshot->SetThreadPriority(GetTaskPropValue(m_tConfiguration)); + spSnapshot->SetDestinationPath(m_tBaseData.GetDestinationPath().ToString()); + spSnapshot->SetFilters(m_afFilters); + spSnapshot->SetTaskState(m_tBaseData.GetCurrentState()); + spSnapshot->SetOperationType(m_tSubTasksArray.GetOperationType()); - spSnapshot->SetIgnoreDirectories(GetTaskPropValue(m_tConfiguration)); - spSnapshot->SetCreateEmptyFiles(GetTaskPropValue(m_tConfiguration)); - spSnapshot->SetBufferCount(GetTaskPropValue(m_tConfiguration)); + spSnapshot->SetIgnoreDirectories(GetTaskPropValue(m_tConfiguration)); + spSnapshot->SetCreateEmptyFiles(GetTaskPropValue(m_tConfiguration)); + spSnapshot->SetBufferCount(GetTaskPropValue(m_tConfiguration)); - TSubTaskStatsSnapshotPtr spCurrentSubTask = spSnapshot->GetSubTasksStats().GetCurrentSubTaskSnapshot(); + TSubTaskStatsSnapshotPtr spCurrentSubTask = spSnapshot->GetSubTasksStats().GetCurrentSubTaskSnapshot(); - int iCurrentBufferIndex = spCurrentSubTask ? spCurrentSubTask->GetCurrentBufferIndex() : TBufferSizes::eBuffer_Default; - switch(iCurrentBufferIndex) + int iCurrentBufferIndex = spCurrentSubTask ? spCurrentSubTask->GetCurrentBufferIndex() : TBufferSizes::eBuffer_Default; + switch (iCurrentBufferIndex) + { + case TBufferSizes::eBuffer_Default: + spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); + break; + case TBufferSizes::eBuffer_OneDisk: + spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); + break; + case TBufferSizes::eBuffer_TwoDisks: + spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); + break; + case TBufferSizes::eBuffer_CD: + spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); + break; + case TBufferSizes::eBuffer_LAN: + spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); + break; + default: + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + //BOOST_ASSERT(false); // assertions are dangerous here, because we're inside critical section + // (and there could be conflict with Get(Mini)Snapshot called OnTimer in several places. + } + } + + bool TTask::CanBegin() { - case TBufferSizes::eBuffer_Default: - spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); - break; - case TBufferSizes::eBuffer_OneDisk: - spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); - break; - case TBufferSizes::eBuffer_TwoDisks: - spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); - break; - case TBufferSizes::eBuffer_CD: - spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); - break; - case TBufferSizes::eBuffer_LAN: - spSnapshot->SetCurrentBufferSize(GetTaskPropValue(m_tConfiguration)); - break; - default: - THROW_CORE_EXCEPTION(eErr_UnhandledCase); - //BOOST_ASSERT(false); // assertions are dangerous here, because we're inside critical section - // (and there could be conflict with Get(Mini)Snapshot called OnTimer in several places. + bool bRet = true; + boost::unique_lock lock(m_lock); + + if (GetContinueFlagNL() || GetForceFlagNL()) + { + SetForceFlagNL(false); + SetContinueFlagNL(false); + } + else + bRet = false; + + return bRet; } -} -bool TTask::CanBegin() -{ - bool bRet=true; - boost::unique_lock lock(m_lock); + void TTask::SetForceFlag(bool bFlag) + { + boost::unique_lock lock(m_lock); + m_bForce = bFlag; + } - if(GetContinueFlagNL() || GetForceFlagNL()) + bool TTask::GetForceFlag() { - SetForceFlagNL(false); - SetContinueFlagNL(false); + boost::shared_lock lock(m_lock); + return m_bForce; } - else - bRet = false; - return bRet; -} + void TTask::SetContinueFlag(bool bFlag) + { + boost::unique_lock lock(m_lock); + m_bContinue = bFlag; + } -void TTask::SetForceFlag(bool bFlag) -{ - boost::unique_lock lock(m_lock); - m_bForce=bFlag; -} + bool TTask::GetContinueFlag() + { + boost::shared_lock lock(m_lock); + return m_bContinue; + } -bool TTask::GetForceFlag() -{ - boost::shared_lock lock(m_lock); - return m_bForce; -} + ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -void TTask::SetContinueFlag(bool bFlag) -{ - boost::unique_lock lock(m_lock); - m_bContinue=bFlag; -} + void TTask::SetForceFlagNL(bool bFlag) + { + m_bForce = bFlag; + } -bool TTask::GetContinueFlag() -{ - boost::shared_lock lock(m_lock); - return m_bContinue; -} + bool TTask::GetForceFlagNL() + { + return m_bForce; + } -///////////////////////////////////////////////////////////////////////////////////////////////////////////// + void TTask::SetContinueFlagNL(bool bFlag) + { + m_bContinue = bFlag; + } -void TTask::SetForceFlagNL(bool bFlag) -{ - m_bForce=bFlag; -} + bool TTask::GetContinueFlagNL() + { + return m_bContinue; + } -bool TTask::GetForceFlagNL() -{ - return m_bForce; -} + TSubTaskBase::ESubOperationResult TTask::CheckForWaitState() + { + // limiting operation count + SetTaskState(eTaskState_Waiting); + bool bContinue = false; + while (!bContinue) + { + if (CanBegin()) + { + SetTaskState(eTaskState_Processing); + bContinue = true; -void TTask::SetContinueFlagNL(bool bFlag) -{ - m_bContinue=bFlag; -} + m_log.logi(_T("Finished waiting for begin permission")); -bool TTask::GetContinueFlagNL() -{ - return m_bContinue; -} + // return; // skips sleep and kill flag checking + } + else + Sleep(50); // not to make it too hard for processor -TSubTaskBase::ESubOperationResult TTask::CheckForWaitState() -{ - // limiting operation count - SetTaskState(eTaskState_Waiting); - bool bContinue = false; - while(!bContinue) + if (m_workerThread.KillRequested()) + { + // log + m_log.logi(_T("Kill request while waiting for begin permission (wait state)")); + return TSubTaskBase::eSubResult_KillRequest; + } + } + + return TSubTaskBase::eSubResult_Continue; + } + + DWORD WINAPI TTask::DelegateThreadProc(LPVOID pParam) { - if(CanBegin()) - { - SetTaskState(eTaskState_Processing); - bContinue = true; + BOOST_ASSERT(pParam); + if (!pParam) + return 1; - m_log.logi(_T("Finished waiting for begin permission")); + TTask* pTask = (TTask*)pParam; + return pTask->ThrdProc(); + } - // return; // skips sleep and kill flag checking - } - else - Sleep(50); // not to make it too hard for processor + DWORD TTask::ThrdProc() + { + // start tracking time for this thread + TScopedRunningTimeTracker tProcessingGuard(m_tLocalStats); + TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(m_spInternalFeedbackHandler, tProcessingGuard)); - if(m_workerThread.KillRequested()) + try { - // log - m_log.logi(_T("Kill request while waiting for begin permission (wait state)")); - return TSubTaskBase::eSubResult_KillRequest; - } - } + TSubTaskBase::ESubOperationResult eResult = TSubTaskBase::eSubResult_Continue; - return TSubTaskBase::eSubResult_Continue; -} + // initialize log file + m_log.init(m_tBaseData.GetLogPath().ToString(), 262144, icpf::log_file::level_debug, false, false); -DWORD WINAPI TTask::DelegateThreadProc(LPVOID pParam) -{ - BOOST_ASSERT(pParam); - if(!pParam) - return 1; + // start operation + OnBeginOperation(); - TTask* pTask = (TTask*)pParam; - return pTask->ThrdProc(); -} + // enable configuration changes tracking + m_tConfiguration.ConnectToNotifier(TTaskConfigTracker::NotificationProc, &m_cfgTracker); + m_tConfiguration.ConnectToNotifier(TTask::OnCfgOptionChanged, this); -DWORD TTask::ThrdProc() -{ - // start tracking time for this thread - TScopedRunningTimeTracker tProcessingGuard(m_tLocalStats); - TFeedbackHandlerWrapperPtr spFeedbackHandler(boost::make_shared(m_spInternalFeedbackHandler, tProcessingGuard)); + // set thread options + HANDLE hThread = GetCurrentThread(); + ::SetThreadPriorityBoost(hThread, GetTaskPropValue(m_tConfiguration)); - try - { - TSubTaskBase::ESubOperationResult eResult = TSubTaskBase::eSubResult_Continue; + // determine when to scan directories + bool bReadTasksSize = GetTaskPropValue(m_tConfiguration); - // initialize log file - m_log.init(m_tBaseData.GetLogPath().ToString(), 262144, icpf::log_file::level_debug, false, false); + // prepare context for subtasks + if (bReadTasksSize) + eResult = m_tSubTasksArray.Execute(spFeedbackHandler, true); + if (eResult == TSubTaskBase::eSubResult_Continue) + { + TScopedRunningTimeTrackerPause scopedPause(tProcessingGuard); - // start operation - OnBeginOperation(); + eResult = CheckForWaitState(); // operation limiting + } + if (eResult == TSubTaskBase::eSubResult_Continue) + eResult = m_tSubTasksArray.Execute(spFeedbackHandler, false); - // enable configuration changes tracking - m_tConfiguration.ConnectToNotifier(TTaskConfigTracker::NotificationProc, &m_cfgTracker); - m_tConfiguration.ConnectToNotifier(TTask::OnCfgOptionChanged, this); + // change status to finished + if (eResult == TSubTaskBase::eSubResult_Continue) + SetTaskState(eTaskState_Finished); - // set thread options - HANDLE hThread = GetCurrentThread(); - ::SetThreadPriorityBoost(hThread, GetTaskPropValue(m_tConfiguration)); + // finishing processing + // change task status + switch (eResult) + { + case TSubTaskBase::eSubResult_Error: + spFeedbackHandler->OperationError(); + SetTaskState(eTaskState_Error); + break; - // determine when to scan directories - bool bReadTasksSize = GetTaskPropValue(m_tConfiguration); + case TSubTaskBase::eSubResult_CancelRequest: + SetTaskState(eTaskState_Cancelled); + break; - // prepare context for subtasks - if(bReadTasksSize) - eResult = m_tSubTasksArray.Execute(spFeedbackHandler, true); - if(eResult == TSubTaskBase::eSubResult_Continue) - { - TScopedRunningTimeTrackerPause scopedPause(tProcessingGuard); + case TSubTaskBase::eSubResult_PauseRequest: + SetTaskState(eTaskState_Paused); + break; - eResult = CheckForWaitState(); // operation limiting - } - if(eResult == TSubTaskBase::eSubResult_Continue) - eResult = m_tSubTasksArray.Execute(spFeedbackHandler, false); + case TSubTaskBase::eSubResult_KillRequest: + // the only operation + if (GetTaskState() == eTaskState_Waiting) + SetTaskState(eTaskState_Processing); + break; - // change status to finished - if(eResult == TSubTaskBase::eSubResult_Continue) - SetTaskState(eTaskState_Finished); + case TSubTaskBase::eSubResult_Continue: + spFeedbackHandler->OperationFinished(); + SetTaskState(eTaskState_Finished); + break; - // finishing processing - // change task status - switch(eResult) - { - case TSubTaskBase::eSubResult_Error: - spFeedbackHandler->OperationError(); - SetTaskState(eTaskState_Error); - break; + default: + BOOST_ASSERT(false); + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } - case TSubTaskBase::eSubResult_CancelRequest: - SetTaskState(eTaskState_Cancelled); - break; + // if the files cache is not completely read - clean it up + if (!m_tSubTaskContext.GetFilesCache().IsComplete()) + m_tSubTaskContext.GetFilesCache().Clear(); // scanning for files did not finish processing, so the content of the files cache are useless - case TSubTaskBase::eSubResult_PauseRequest: - SetTaskState(eTaskState_Paused); - break; + // save progress before killed + Store(); - case TSubTaskBase::eSubResult_KillRequest: - // the only operation - if(GetTaskState() == eTaskState_Waiting) - SetTaskState(eTaskState_Processing); - break; + // reset flags + SetContinueFlag(false); + SetForceFlag(false); - case TSubTaskBase::eSubResult_Continue: - spFeedbackHandler->OperationFinished(); - SetTaskState(eTaskState_Finished); - break; + m_tConfiguration.DisconnectFromNotifier(TTaskConfigTracker::NotificationProc); + m_tConfiguration.DisconnectFromNotifier(TTask::OnCfgOptionChanged); - default: - BOOST_ASSERT(false); - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + // and the real end + OnEndOperation(); + + return 0; } + catch (...) + { + } - // if the files cache is not completely read - clean it up - if(!m_tSubTaskContext.GetFilesCache().IsComplete()) - m_tSubTaskContext.GetFilesCache().Clear(); // scanning for files did not finish processing, so the content of the files cache are useless + m_tConfiguration.DisconnectFromNotifier(TTaskConfigTracker::NotificationProc); + m_tConfiguration.DisconnectFromNotifier(TTask::OnCfgOptionChanged); - // save progress before killed - Store(); + // log + m_log.loge(_T("Caught exception in ThrdProc")); - // reset flags + // let others know some error happened + spFeedbackHandler->OperationError(); + SetTaskState(eTaskState_Error); + SetContinueFlag(false); SetForceFlag(false); - m_tConfiguration.DisconnectFromNotifier(TTaskConfigTracker::NotificationProc); - m_tConfiguration.DisconnectFromNotifier(TTask::OnCfgOptionChanged); - - // and the real end OnEndOperation(); - return 0; + return 1; } - catch(...) + + void TTask::OnBeginOperation() { + CTime tm = CTime::GetCurrentTime(); + + TString strFormat = _T("\r\n# COPYING THREAD STARTED #\r\nBegan processing data (dd:mm:yyyy) %day.%month.%year at %hour:%minute.%second"); + strFormat.Replace(_t("%year"), boost::lexical_cast(tm.GetYear()).c_str()); + strFormat.Replace(_t("%month"), boost::lexical_cast(tm.GetMonth()).c_str()); + strFormat.Replace(_t("%day"), boost::lexical_cast(tm.GetDay()).c_str()); + strFormat.Replace(_t("%hour"), boost::lexical_cast(tm.GetHour()).c_str()); + strFormat.Replace(_t("%minute"), boost::lexical_cast(tm.GetMinute()).c_str()); + strFormat.Replace(_t("%second"), boost::lexical_cast(tm.GetSecond()).c_str()); + m_log.logi(strFormat.c_str()); } - m_tConfiguration.DisconnectFromNotifier(TTaskConfigTracker::NotificationProc); - m_tConfiguration.DisconnectFromNotifier(TTask::OnCfgOptionChanged); + void TTask::OnEndOperation() + { + CTime tm = CTime::GetCurrentTime(); - // log - m_log.loge(_T("Caught exception in ThrdProc")); + TString strFormat = _T("Finished processing data (dd:mm:yyyy) %day.%month.%year at %hour:%minute.%second"); + strFormat.Replace(_t("%year"), boost::lexical_cast(tm.GetYear()).c_str()); + strFormat.Replace(_t("%month"), boost::lexical_cast(tm.GetMonth()).c_str()); + strFormat.Replace(_t("%day"), boost::lexical_cast(tm.GetDay()).c_str()); + strFormat.Replace(_t("%hour"), boost::lexical_cast(tm.GetHour()).c_str()); + strFormat.Replace(_t("%minute"), boost::lexical_cast(tm.GetMinute()).c_str()); + strFormat.Replace(_t("%second"), boost::lexical_cast(tm.GetSecond()).c_str()); + m_log.logi(strFormat.c_str()); + } - // let others know some error happened - spFeedbackHandler->OperationError(); - SetTaskState(eTaskState_Error); + void TTask::RequestStopThread() + { + m_workerThread.SignalThreadToStop(); + } - SetContinueFlag(false); - SetForceFlag(false); + void TTask::OnCfgOptionChanged(const TStringSet& rsetChanges, void* pParam) + { + TTask* pTask = (TTask*)pParam; + if (!pTask) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - OnEndOperation(); + if (rsetChanges.HasValue(TaskPropData::GetPropertyName())) + { + pTask->m_workerThread.ChangePriority(GetTaskPropValue(pTask->m_tConfiguration)); + } + } - return 1; -} + bool TTask::IsRunning() const + { + return m_tLocalStats.IsRunning(); + } -void TTask::OnBeginOperation() -{ - CTime tm=CTime::GetCurrentTime(); + TSmartPath TTask::GetLogPath() const + { + return m_tBaseData.GetLogPath(); + } - TString strFormat = _T("\r\n# COPYING THREAD STARTED #\r\nBegan processing data (dd:mm:yyyy) %day.%month.%year at %hour:%minute.%second"); - strFormat.Replace(_t("%year"), boost::lexical_cast(tm.GetYear()).c_str()); - strFormat.Replace(_t("%month"), boost::lexical_cast(tm.GetMonth()).c_str()); - strFormat.Replace(_t("%day"), boost::lexical_cast(tm.GetDay()).c_str()); - strFormat.Replace(_t("%hour"), boost::lexical_cast(tm.GetHour()).c_str()); - strFormat.Replace(_t("%minute"), boost::lexical_cast(tm.GetMinute()).c_str()); - strFormat.Replace(_t("%second"), boost::lexical_cast(tm.GetSecond()).c_str()); - m_log.logi(strFormat.c_str()); -} + TString TTask::GetTaskName() const + { + return m_tBaseData.GetTaskName(); + } -void TTask::OnEndOperation() -{ - CTime tm=CTime::GetCurrentTime(); + void TTask::SetLogPath(const TSmartPath& pathLog) + { + m_tBaseData.SetLogPath(pathLog); + } - TString strFormat = _T("Finished processing data (dd:mm:yyyy) %day.%month.%year at %hour:%minute.%second"); - strFormat.Replace(_t("%year"), boost::lexical_cast(tm.GetYear()).c_str()); - strFormat.Replace(_t("%month"), boost::lexical_cast(tm.GetMonth()).c_str()); - strFormat.Replace(_t("%day"), boost::lexical_cast(tm.GetDay()).c_str()); - strFormat.Replace(_t("%hour"), boost::lexical_cast(tm.GetHour()).c_str()); - strFormat.Replace(_t("%minute"), boost::lexical_cast(tm.GetMinute()).c_str()); - strFormat.Replace(_t("%second"), boost::lexical_cast(tm.GetSecond()).c_str()); - m_log.logi(strFormat.c_str()); -} - -void TTask::RequestStopThread() -{ - m_workerThread.SignalThreadToStop(); -} - -void TTask::OnCfgOptionChanged(const TStringSet& rsetChanges, void* pParam) -{ - TTask* pTask = (TTask*)pParam; - if(!pTask) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); - - if(rsetChanges.HasValue(TaskPropData::GetPropertyName())) + ISerializerPtr TTask::GetSerializer() const { - pTask->m_workerThread.ChangePriority(GetTaskPropValue(pTask->m_tConfiguration)); + return m_spSerializer; } -} -bool TTask::IsRunning() const -{ - return m_tLocalStats.IsRunning(); -} + icpf::log_file& TTask::GetLog() + { + if (!m_log.is_initialized()) + m_log.init(m_tBaseData.GetLogPath().ToString(), 262144, icpf::log_file::level_debug, false, false); -TSmartPath TTask::GetLogPath() const -{ - return m_tBaseData.GetLogPath(); + return m_log; + } } - -TString TTask::GetTaskName() const -{ - return m_tBaseData.GetTaskName(); -} - -void TTask::SetLogPath(const TSmartPath& pathLog) -{ - m_tBaseData.SetLogPath(pathLog); -} - -ISerializerPtr TTask::GetSerializer() const -{ - return m_spSerializer; -} - -icpf::log_file& TTask::GetLog() -{ - if (!m_log.is_initialized()) - m_log.init(m_tBaseData.GetLogPath().ToString(), 262144, icpf::log_file::level_debug, false, false); - - return m_log; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TTask.h =================================================================== diff -u -N -r2e384de25de613cb582a966df7d1cb9468f1c825 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTask.h (.../TTask.h) (revision 2e384de25de613cb582a966df7d1cb9468f1c825) +++ src/libchcore/TTask.h (.../TTask.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -35,154 +35,153 @@ #include "ISerializer.h" #include "TTaskBaseData.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + class TBufferSizes; -class TBufferSizes; + /////////////////////////////////////////////////////////////////////////// + // TTask -/////////////////////////////////////////////////////////////////////////// -// TTask + class LIBCHCORE_API TTask + { + private: + TTask(const ISerializerPtr& spSerializer, const IFeedbackHandlerPtr& spFeedbackHandler); -class LIBCHCORE_API TTask -{ -private: - TTask(const ISerializerPtr& spSerializer, const IFeedbackHandlerPtr& spFeedbackHandler); + public: + ~TTask(); -public: - ~TTask(); + void SetTaskState(ETaskCurrentState eTaskState); + ETaskCurrentState GetTaskState() const; - void SetTaskState(ETaskCurrentState eTaskState); - ETaskCurrentState GetTaskState() const; + bool IsRunning() const; - bool IsRunning() const; + // m_nBufferSize + void SetBufferSizes(const TBufferSizes& bsSizes); + void GetBufferSizes(TBufferSizes& bsSizes); - // m_nBufferSize - void SetBufferSizes(const TBufferSizes& bsSizes); - void GetBufferSizes(TBufferSizes& bsSizes); + TSmartPath GetLogPath() const; + TString GetTaskName() const; - TSmartPath GetLogPath() const; - TString GetTaskName() const; + // thread + void SetPriority(int nPriority); - // thread - void SetPriority(int nPriority); + void Load(); + void Store(); - void Load(); - void Store(); + void BeginProcessing(); - void BeginProcessing(); + void PauseProcessing(); // pause + void ResumeProcessing(); // resume + bool RetryProcessing(); // retry + void RestartProcessing(); // from beginning + void CancelProcessing(); // cancel - void PauseProcessing(); // pause - void ResumeProcessing(); // resume - bool RetryProcessing(); // retry - void RestartProcessing(); // from beginning - void CancelProcessing(); // cancel + void GetStatsSnapshot(TTaskStatsSnapshotPtr& spSnapshot); - void GetStatsSnapshot(TTaskStatsSnapshotPtr& spSnapshot); + void SetForceFlag(bool bFlag = true); + bool GetForceFlag(); - void SetForceFlag(bool bFlag = true); - bool GetForceFlag(); + private: + void SetTaskDefinition(const TTaskDefinition& rTaskDefinition); -private: - void SetTaskDefinition(const TTaskDefinition& rTaskDefinition); + void SetLogPath(const TSmartPath& pathLog); + icpf::log_file& GetLog(); - void SetLogPath(const TSmartPath& pathLog); - icpf::log_file& GetLog(); + // methods are called when task is being added or removed from the global task array + /// Method is called when this task is being added to a TTaskManager object + void OnRegisterTask(); + /// Method is called when task is being removed from the TTaskManager object + void OnUnregisterTask(); - // methods are called when task is being added or removed from the global task array - /// Method is called when this task is being added to a TTaskManager object - void OnRegisterTask(); - /// Method is called when task is being removed from the TTaskManager object - void OnUnregisterTask(); + /// Method is called when processing is being started + void OnBeginOperation(); + /// Method is called when processing is being ended + void OnEndOperation(); - /// Method is called when processing is being started - void OnBeginOperation(); - /// Method is called when processing is being ended - void OnEndOperation(); + /// Thread function that delegates call to the TTask::ThrdProc + static DWORD WINAPI DelegateThreadProc(LPVOID pParam); - /// Thread function that delegates call to the TTask::ThrdProc - static DWORD WINAPI DelegateThreadProc(LPVOID pParam); + /// Main function for the task processing thread + DWORD WINAPI ThrdProc(); - /// Main function for the task processing thread - DWORD WINAPI ThrdProc(); + TSubTaskBase::ESubOperationResult CheckForWaitState(); - TSubTaskBase::ESubOperationResult CheckForWaitState(); + // m_nStatus + void SetStatusNL(UINT nStatus, UINT nMask); + UINT GetStatusNL(UINT nMask = 0xffffffff); - // m_nStatus - void SetStatusNL(UINT nStatus, UINT nMask); - UINT GetStatusNL(UINT nMask = 0xffffffff); + void SetForceFlagNL(bool bFlag = true); + bool GetForceFlagNL(); - void SetForceFlagNL(bool bFlag = true); - bool GetForceFlagNL(); + void SetContinueFlag(bool bFlag = true); + bool GetContinueFlag(); + void SetContinueFlagNL(bool bFlag = true); + bool GetContinueFlagNL(); - void SetContinueFlag(bool bFlag = true); - bool GetContinueFlag(); - void SetContinueFlagNL(bool bFlag = true); - bool GetContinueFlagNL(); + bool CanBegin(); - bool CanBegin(); + void KillThread(); + void RequestStopThread(); - void KillThread(); - void RequestStopThread(); + static void OnCfgOptionChanged(const TStringSet& rsetChanges, void* pParam); - static void OnCfgOptionChanged(const TStringSet& rsetChanges, void* pParam); + ISerializerPtr GetSerializer() const; - ISerializerPtr GetSerializer() const; - -private: - // serialization + private: + // serialization #pragma warning(push) #pragma warning(disable: 4251) - ISerializerPtr m_spSerializer; - IFeedbackHandlerPtr m_spInternalFeedbackHandler; + ISerializerPtr m_spSerializer; + IFeedbackHandlerPtr m_spInternalFeedbackHandler; #pragma warning(pop) - // base data - TTaskBaseData m_tBaseData; + // base data + TTaskBaseData m_tBaseData; - // basic information + // basic information #pragma warning(push) #pragma warning(disable: 4251) - TBasePathDataContainerPtr m_spSrcPaths; + TBasePathDataContainerPtr m_spSrcPaths; #pragma warning(pop) - // Global task settings - TConfig m_tConfiguration; + // Global task settings + TConfig m_tConfiguration; - TSubTasksArray m_tSubTasksArray; + TSubTasksArray m_tSubTasksArray; - TSubTaskContext m_tSubTaskContext; + TSubTaskContext m_tSubTaskContext; - TTaskConfigTracker m_cfgTracker; + TTaskConfigTracker m_cfgTracker; - // current task state (derivatives of the task initial information) + // current task state (derivatives of the task initial information) - // task settings - TFileFiltersArray m_afFilters; // filtering settings for files (will be filtered according to the rules inside when searching for files) + // task settings + TFileFiltersArray m_afFilters; // filtering settings for files (will be filtered according to the rules inside when searching for files) - bool m_bForce; // if the continuation of tasks should be independent of max concurrently running task limit - bool m_bContinue; // allows task to continue + bool m_bForce; // if the continuation of tasks should be independent of max concurrently running task limit + bool m_bContinue; // allows task to continue - // other helpers - icpf::log_file m_log; ///< Log file where task information will be stored + // other helpers + icpf::log_file m_log; ///< Log file where task information will be stored - // Local filesystem access - TLocalFilesystem m_fsLocal; + // Local filesystem access + TLocalFilesystem m_fsLocal; - /// Thread controlling object - TWorkerThreadController m_workerThread; + /// Thread controlling object + TWorkerThreadController m_workerThread; - /// Mutex for locking concurrent access to members of this class + /// Mutex for locking concurrent access to members of this class #pragma warning(push) #pragma warning(disable: 4251) - TTaskLocalStatsInfo m_tLocalStats; // local statistics + TTaskLocalStatsInfo m_tLocalStats; // local statistics - mutable boost::shared_mutex m_lock; + mutable boost::shared_mutex m_lock; #pragma warning(pop) - friend class TTaskManager; -}; + friend class TTaskManager; + }; -typedef boost::shared_ptr TTaskPtr; + typedef boost::shared_ptr TTaskPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTaskBaseData.cpp =================================================================== diff -u -N -r11b0a299be97bc3afaa633d6522c17b214ba3b79 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskBaseData.cpp (.../TTaskBaseData.cpp) (revision 11b0a299be97bc3afaa633d6522c17b214ba3b79) +++ src/libchcore/TTaskBaseData.cpp (.../TTaskBaseData.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -23,119 +23,118 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -TTaskBaseData::TTaskBaseData() : - m_strTaskName(m_setChanges), - m_eCurrentState(m_setChanges), - m_pathLog(m_setChanges), - m_pathDestinationPath(m_setChanges) +namespace chcore { - m_setChanges[eMod_Added] = true; -} + TTaskBaseData::TTaskBaseData() : + m_strTaskName(m_setChanges), + m_eCurrentState(m_setChanges), + m_pathLog(m_setChanges), + m_pathDestinationPath(m_setChanges) + { + m_setChanges[eMod_Added] = true; + } -TTaskBaseData::~TTaskBaseData() -{ -} + TTaskBaseData::~TTaskBaseData() + { + } -TString TTaskBaseData::GetTaskName() const -{ - return m_strTaskName; -} + TString TTaskBaseData::GetTaskName() const + { + return m_strTaskName; + } -void TTaskBaseData::SetTaskName(const TString& strTaskName) -{ - m_strTaskName = strTaskName; -} + void TTaskBaseData::SetTaskName(const TString& strTaskName) + { + m_strTaskName = strTaskName; + } -ETaskCurrentState TTaskBaseData::GetCurrentState() const -{ - return m_eCurrentState; -} + ETaskCurrentState TTaskBaseData::GetCurrentState() const + { + return m_eCurrentState; + } -void TTaskBaseData::SetCurrentState(ETaskCurrentState eCurrentState) -{ - m_eCurrentState = eCurrentState; -} + void TTaskBaseData::SetCurrentState(ETaskCurrentState eCurrentState) + { + m_eCurrentState = eCurrentState; + } -TSmartPath TTaskBaseData::GetLogPath() const -{ - return m_pathLog; -} + TSmartPath TTaskBaseData::GetLogPath() const + { + return m_pathLog; + } -void TTaskBaseData::SetLogPath(const TSmartPath& pathLog) -{ - m_pathLog = pathLog; -} + void TTaskBaseData::SetLogPath(const TSmartPath& pathLog) + { + m_pathLog = pathLog; + } -TSmartPath TTaskBaseData::GetDestinationPath() const -{ - return m_pathDestinationPath; -} + TSmartPath TTaskBaseData::GetDestinationPath() const + { + return m_pathDestinationPath; + } -void TTaskBaseData::SetDestinationPath(const TSmartPath& pathDst) -{ - m_pathDestinationPath = pathDst; -} + void TTaskBaseData::SetDestinationPath(const TSmartPath& pathDst) + { + m_pathDestinationPath = pathDst; + } -void TTaskBaseData::Store(const ISerializerContainerPtr& spContainer) const -{ - InitColumns(spContainer); - - // base data - if(m_setChanges.any()) + void TTaskBaseData::Store(const ISerializerContainerPtr& spContainer) const { - bool bAdded = m_setChanges[eMod_Added]; + InitColumns(spContainer); - ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); + // base data + if (m_setChanges.any()) + { + bool bAdded = m_setChanges[eMod_Added]; - if(bAdded || m_setChanges[eMod_TaskName]) - rRow.SetValue(_T("name"), m_strTaskName); + ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); - if(bAdded || m_setChanges[eMod_LogPath]) - rRow.SetValue(_T("log_path"), m_pathLog); + if (bAdded || m_setChanges[eMod_TaskName]) + rRow.SetValue(_T("name"), m_strTaskName); - if(bAdded || m_setChanges[eMod_CurrentState]) - rRow.SetValue(_T("current_state"), m_eCurrentState); + if (bAdded || m_setChanges[eMod_LogPath]) + rRow.SetValue(_T("log_path"), m_pathLog); - if(bAdded || m_setChanges[eMod_DstPath]) - rRow.SetValue(_T("destination_path"), m_pathDestinationPath); + if (bAdded || m_setChanges[eMod_CurrentState]) + rRow.SetValue(_T("current_state"), m_eCurrentState); - m_setChanges.reset(); + if (bAdded || m_setChanges[eMod_DstPath]) + rRow.SetValue(_T("destination_path"), m_pathDestinationPath); + + m_setChanges.reset(); + } } -} -void TTaskBaseData::Load(const ISerializerContainerPtr& spContainer) -{ - InitColumns(spContainer); + void TTaskBaseData::Load(const ISerializerContainerPtr& spContainer) + { + InitColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - bool bResult = spRowReader->Next(); - if(bResult) - { - spRowReader->GetValue(_T("name"), m_strTaskName.Modify()); - spRowReader->GetValue(_T("log_path"), m_pathLog.Modify()); - spRowReader->GetValue(_T("current_state"), *(int*)(ETaskCurrentState*)&m_eCurrentState.Modify()); - spRowReader->GetValue(_T("destination_path"), m_pathDestinationPath.Modify()); + bool bResult = spRowReader->Next(); + if (bResult) + { + spRowReader->GetValue(_T("name"), m_strTaskName.Modify()); + spRowReader->GetValue(_T("log_path"), m_pathLog.Modify()); + spRowReader->GetValue(_T("current_state"), *(int*)(ETaskCurrentState*)&m_eCurrentState.Modify()); + spRowReader->GetValue(_T("destination_path"), m_pathDestinationPath.Modify()); + } + else + THROW_CORE_EXCEPTION(eErr_SerializeLoadError); + + m_setChanges.reset(); } - else - THROW_CORE_EXCEPTION(eErr_SerializeLoadError); - m_setChanges.reset(); -} - -void TTaskBaseData::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) + void TTaskBaseData::InitColumns(const ISerializerContainerPtr& spContainer) const { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("name"), IColumnsDefinition::eType_string); - rColumns.AddColumn(_T("log_path"), IColumnsDefinition::eType_path); - rColumns.AddColumn(_T("current_state"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("destination_path"), IColumnsDefinition::eType_path); + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("name"), IColumnsDefinition::eType_string); + rColumns.AddColumn(_T("log_path"), IColumnsDefinition::eType_path); + rColumns.AddColumn(_T("current_state"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("destination_path"), IColumnsDefinition::eType_path); + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TTaskBaseData.h =================================================================== diff -u -N -rfc67a825635691930b3ac00dc95b16e59f3d2fae -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskBaseData.h (.../TTaskBaseData.h) (revision fc67a825635691930b3ac00dc95b16e59f3d2fae) +++ src/libchcore/TTaskBaseData.h (.../TTaskBaseData.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,59 +25,58 @@ #include "TSharedModificationTracker.h" #include "ETaskCurrentState.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TTaskBaseData +namespace chcore { -private: - TTaskBaseData(const TTaskBaseData&); - TTaskBaseData& operator=(const TTaskBaseData&); + class LIBCHCORE_API TTaskBaseData + { + private: + TTaskBaseData(const TTaskBaseData&); + TTaskBaseData& operator=(const TTaskBaseData&); -public: - TTaskBaseData(); - ~TTaskBaseData(); + public: + TTaskBaseData(); + ~TTaskBaseData(); - TString GetTaskName() const; - void SetTaskName(const TString& strTaskName); + TString GetTaskName() const; + void SetTaskName(const TString& strTaskName); - ETaskCurrentState GetCurrentState() const; - void SetCurrentState(ETaskCurrentState eCurrentState); + ETaskCurrentState GetCurrentState() const; + void SetCurrentState(ETaskCurrentState eCurrentState); - TSmartPath GetLogPath() const; - void SetLogPath(const TSmartPath& pathLog); + TSmartPath GetLogPath() const; + void SetLogPath(const TSmartPath& pathLog); - TSmartPath GetDestinationPath() const; - void SetDestinationPath(const TSmartPath& pathDst); + TSmartPath GetDestinationPath() const; + void SetDestinationPath(const TSmartPath& pathDst); - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); - void InitColumns(const ISerializerContainerPtr& spContainer) const; + void InitColumns(const ISerializerContainerPtr& spContainer) const; -private: - enum EModifications - { - eMod_Added, - eMod_TaskName, - eMod_CurrentState, - eMod_LogPath, - eMod_DstPath, + private: + enum EModifications + { + eMod_Added, + eMod_TaskName, + eMod_CurrentState, + eMod_LogPath, + eMod_DstPath, - eMod_Last - }; + eMod_Last + }; #pragma warning(push) #pragma warning(disable: 4251) - typedef std::bitset ModBitSet; - mutable ModBitSet m_setChanges; + typedef std::bitset ModBitSet; + mutable ModBitSet m_setChanges; - TSharedModificationTracker m_strTaskName; - TSharedModificationTracker m_eCurrentState; // current state of processing this task represents - TSharedModificationTracker m_pathLog; - TSharedModificationTracker m_pathDestinationPath; + TSharedModificationTracker m_strTaskName; + TSharedModificationTracker m_eCurrentState; // current state of processing this task represents + TSharedModificationTracker m_pathLog; + TSharedModificationTracker m_pathDestinationPath; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTaskConfigBufferSizes.cpp =================================================================== diff -u -N -rcdc76e1a95383dff63a5254aeb8d37035028512c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskConfigBufferSizes.cpp (.../TTaskConfigBufferSizes.cpp) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/TTaskConfigBufferSizes.cpp (.../TTaskConfigBufferSizes.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,28 +19,27 @@ #include "stdafx.h" #include "TTaskConfigBufferSizes.h" -BEGIN_CHCORE_NAMESPACE - -TBufferSizes GetTaskPropBufferSizes(const TConfig& rConfig) +namespace chcore { - return TBufferSizes(GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig)); -} + TBufferSizes GetTaskPropBufferSizes(const TConfig& rConfig) + { + return TBufferSizes(GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig)); + } -void SetTaskPropBufferSizes(TConfig& rConfig, const TBufferSizes& rBufferSizes) -{ - SetTaskPropValue(rConfig, rBufferSizes.IsOnlyDefault()); - SetTaskPropValue(rConfig, rBufferSizes.GetBufferCount()); - SetTaskPropValue(rConfig, rBufferSizes.GetDefaultSize()); - SetTaskPropValue(rConfig, rBufferSizes.GetOneDiskSize()); - SetTaskPropValue(rConfig, rBufferSizes.GetTwoDisksSize()); - SetTaskPropValue(rConfig, rBufferSizes.GetCDSize()); - SetTaskPropValue(rConfig, rBufferSizes.GetLANSize()); + void SetTaskPropBufferSizes(TConfig& rConfig, const TBufferSizes& rBufferSizes) + { + SetTaskPropValue(rConfig, rBufferSizes.IsOnlyDefault()); + SetTaskPropValue(rConfig, rBufferSizes.GetBufferCount()); + SetTaskPropValue(rConfig, rBufferSizes.GetDefaultSize()); + SetTaskPropValue(rConfig, rBufferSizes.GetOneDiskSize()); + SetTaskPropValue(rConfig, rBufferSizes.GetTwoDisksSize()); + SetTaskPropValue(rConfig, rBufferSizes.GetCDSize()); + SetTaskPropValue(rConfig, rBufferSizes.GetLANSize()); + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TTaskConfigBufferSizes.h =================================================================== diff -u -N -rcdc76e1a95383dff63a5254aeb8d37035028512c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskConfigBufferSizes.h (.../TTaskConfigBufferSizes.h) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/TTaskConfigBufferSizes.h (.../TTaskConfigBufferSizes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,11 +24,10 @@ #include "TConfig.h" #include "TTaskConfiguration.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + LIBCHCORE_API TBufferSizes GetTaskPropBufferSizes(const TConfig& rConfig); + LIBCHCORE_API void SetTaskPropBufferSizes(TConfig& rConfig, const TBufferSizes& rBufferSizes); +} -LIBCHCORE_API TBufferSizes GetTaskPropBufferSizes(const TConfig& rConfig); -LIBCHCORE_API void SetTaskPropBufferSizes(TConfig& rConfig, const TBufferSizes& rBufferSizes); - -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTaskConfigTracker.cpp =================================================================== diff -u -N -r73d92717b7ba780c7aea1489a5eaa87404afa408 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskConfigTracker.cpp (.../TTaskConfigTracker.cpp) (revision 73d92717b7ba780c7aea1489a5eaa87404afa408) +++ src/libchcore/TTaskConfigTracker.cpp (.../TTaskConfigTracker.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,229 +26,228 @@ #include "ErrorCodes.h" #include "TStringSet.h" -BEGIN_CHCORE_NAMESPACE - -TOptionsSet& TOptionsSet::operator%(ETaskOptions eOption) +namespace chcore { - m_setOptions.insert(eOption); + TOptionsSet& TOptionsSet::operator%(ETaskOptions eOption) + { + m_setOptions.insert(eOption); - return *this; -} + return *this; + } -std::set& TOptionsSet::Get() -{ - return m_setOptions; -} + std::set& TOptionsSet::Get() + { + return m_setOptions; + } -TTaskConfigTracker::TTaskConfigTracker() -{ -} + TTaskConfigTracker::TTaskConfigTracker() + { + } -TTaskConfigTracker::~TTaskConfigTracker() -{ -} + TTaskConfigTracker::~TTaskConfigTracker() + { + } -bool TTaskConfigTracker::IsModified() const -{ - boost::shared_lock lock(m_lock); - return !m_setModified.empty(); -} + bool TTaskConfigTracker::IsModified() const + { + boost::shared_lock lock(m_lock); + return !m_setModified.empty(); + } -bool TTaskConfigTracker::IsModified(ETaskOptions eOption) const -{ - boost::shared_lock lock(m_lock); - return m_setModified.find(eOption) != m_setModified.end(); -} - -bool TTaskConfigTracker::IsModified(TOptionsSet setOptions) const -{ - boost::shared_lock lock(m_lock); - - std::set setCommon; - std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); - - return !setCommon.empty(); -} - -bool TTaskConfigTracker::IsModified(ETaskOptions eOption, bool bResetModificationState) -{ - boost::upgrade_lock lock(m_lock); - - std::set::iterator iterOption = m_setModified.find(eOption); - bool bModified = (iterOption != m_setModified.end()); - if(bModified && bResetModificationState) + bool TTaskConfigTracker::IsModified(ETaskOptions eOption) const { - boost::upgrade_to_unique_lock upgraded_lock(lock); - m_setModified.erase(iterOption); + boost::shared_lock lock(m_lock); + return m_setModified.find(eOption) != m_setModified.end(); } - return bModified; -} + bool TTaskConfigTracker::IsModified(TOptionsSet setOptions) const + { + boost::shared_lock lock(m_lock); -bool TTaskConfigTracker::IsModified(TOptionsSet setOptions, bool bResetModificationState) -{ - boost::upgrade_lock lock(m_lock); + std::set setCommon; + std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); - std::set setCommon; - std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); + return !setCommon.empty(); + } - bool bModified = !setCommon.empty(); - if(bModified && bResetModificationState) + bool TTaskConfigTracker::IsModified(ETaskOptions eOption, bool bResetModificationState) { - boost::upgrade_to_unique_lock upgraded_lock(lock); - std::set::iterator iterOption; - BOOST_FOREACH(ETaskOptions eOption, setCommon) + boost::upgrade_lock lock(m_lock); + + std::set::iterator iterOption = m_setModified.find(eOption); + bool bModified = (iterOption != m_setModified.end()); + if (bModified && bResetModificationState) { - iterOption = m_setModified.find(eOption); - if(iterOption != m_setModified.end()) - m_setModified.erase(iterOption); + boost::upgrade_to_unique_lock upgraded_lock(lock); + m_setModified.erase(iterOption); } + + return bModified; } - return bModified; -} + bool TTaskConfigTracker::IsModified(TOptionsSet setOptions, bool bResetModificationState) + { + boost::upgrade_lock lock(m_lock); -void TTaskConfigTracker::AddModified(const TString& strModified) -{ - ETaskOptions eOption = TTaskConfigTracker::GetOptionFromString(strModified); + std::set setCommon; + std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); - boost::unique_lock lock(m_lock); + bool bModified = !setCommon.empty(); + if (bModified && bResetModificationState) + { + boost::upgrade_to_unique_lock upgraded_lock(lock); + std::set::iterator iterOption; + BOOST_FOREACH(ETaskOptions eOption, setCommon) + { + iterOption = m_setModified.find(eOption); + if (iterOption != m_setModified.end()) + m_setModified.erase(iterOption); + } + } - m_setModified.insert(eOption); -} + return bModified; + } -void TTaskConfigTracker::AddModified(ETaskOptions eModified) -{ - boost::unique_lock lock(m_lock); - m_setModified.insert(eModified); -} + void TTaskConfigTracker::AddModified(const TString& strModified) + { + ETaskOptions eOption = TTaskConfigTracker::GetOptionFromString(strModified); -void TTaskConfigTracker::AddModified(TOptionsSet setOptions) -{ - boost::unique_lock lock(m_lock); - m_setModified.insert(setOptions.Get().begin(), setOptions.Get().end()); -} + boost::unique_lock lock(m_lock); -void TTaskConfigTracker::AddModified(const TStringSet& setModified) -{ - TStringSet::const_iterator iterBegin = setModified.Begin(); - TStringSet::const_iterator iterEnd = setModified.End(); + m_setModified.insert(eOption); + } - for(; iterBegin != iterEnd; ++iterBegin) + void TTaskConfigTracker::AddModified(ETaskOptions eModified) { - AddModified(*iterBegin); + boost::unique_lock lock(m_lock); + m_setModified.insert(eModified); } -} -void TTaskConfigTracker::AddModified(const std::set& setModified) -{ - boost::unique_lock lock(m_lock); + void TTaskConfigTracker::AddModified(TOptionsSet setOptions) + { + boost::unique_lock lock(m_lock); + m_setModified.insert(setOptions.Get().begin(), setOptions.Get().end()); + } - m_setModified.insert(setModified.begin(), setModified.end()); -} - -void TTaskConfigTracker::RemoveModification(ETaskOptions eModified) -{ - boost::upgrade_lock lock(m_lock); - std::set::iterator iterOption = m_setModified.find(eModified); - if(iterOption != m_setModified.end()) + void TTaskConfigTracker::AddModified(const TStringSet& setModified) { - boost::upgrade_to_unique_lock upgraded_lock(lock); - m_setModified.erase(iterOption); + TStringSet::const_iterator iterBegin = setModified.Begin(); + TStringSet::const_iterator iterEnd = setModified.End(); + + for (; iterBegin != iterEnd; ++iterBegin) + { + AddModified(*iterBegin); + } } -} -void TTaskConfigTracker::RemoveModificationSet(TOptionsSet setOptions) -{ - boost::unique_lock lock(m_lock); + void TTaskConfigTracker::AddModified(const std::set& setModified) + { + boost::unique_lock lock(m_lock); - std::set setCommon; - std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); + m_setModified.insert(setModified.begin(), setModified.end()); + } - std::set::iterator iterOption; - BOOST_FOREACH(ETaskOptions eOption, setCommon) + void TTaskConfigTracker::RemoveModification(ETaskOptions eModified) { - iterOption = m_setModified.find(eOption); - if(iterOption != m_setModified.end()) + boost::upgrade_lock lock(m_lock); + std::set::iterator iterOption = m_setModified.find(eModified); + if (iterOption != m_setModified.end()) + { + boost::upgrade_to_unique_lock upgraded_lock(lock); m_setModified.erase(iterOption); + } } -} -void TTaskConfigTracker::RemoveModification(const TString& strModified) -{ - ETaskOptions eOption = TTaskConfigTracker::GetOptionFromString(strModified); - RemoveModification(eOption); -} + void TTaskConfigTracker::RemoveModificationSet(TOptionsSet setOptions) + { + boost::unique_lock lock(m_lock); -void TTaskConfigTracker::Clear() -{ - boost::unique_lock lock(m_lock); - m_setModified.clear(); -} + std::set setCommon; + std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); -void TTaskConfigTracker::NotificationProc(const TStringSet& setModifications, void* pParam) -{ - if(!pParam) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + std::set::iterator iterOption; + BOOST_FOREACH(ETaskOptions eOption, setCommon) + { + iterOption = m_setModified.find(eOption); + if (iterOption != m_setModified.end()) + m_setModified.erase(iterOption); + } + } - TTaskConfigTracker* pTracker = (TTaskConfigTracker*)pParam; - pTracker->AddModified(setModifications); -} + void TTaskConfigTracker::RemoveModification(const TString& strModified) + { + ETaskOptions eOption = TTaskConfigTracker::GetOptionFromString(strModified); + RemoveModification(eOption); + } -ETaskOptions TTaskConfigTracker::GetOptionFromString(const TString& strOption) -{ - if(strOption == TaskPropData::GetPropertyName()) - return eTO_UseOnlyDefaultBuffer; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_DefaultBufferSize; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_OneDiskBufferSize; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_TwoDisksBufferSize; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_CDBufferSize; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_LANBufferSize; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_DisableBuffering; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_DisableBufferingMinSize; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_BufferQueueDepth; + void TTaskConfigTracker::Clear() + { + boost::unique_lock lock(m_lock); + m_setModified.clear(); + } - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_SetDestinationAttributes; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_SetDestinationDateTime; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_ProtectReadOnlyFiles; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_ScanDirectoriesBeforeBlocking; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_ThreadPriority; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_DisablePriorityBoost; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_DeleteInSeparateSubTask; - - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_CreateEmptyFiles; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_CreateDirectoriesRelativeToRoot; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_IgnoreDirectories; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_AlternateFilenameFormatString_AfterFirst; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_AlternateFilenameFormatString_First; - else + void TTaskConfigTracker::NotificationProc(const TStringSet& setModifications, void* pParam) { - BOOST_ASSERT(false); // unhandled case - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + if (!pParam) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); + + TTaskConfigTracker* pTracker = (TTaskConfigTracker*)pParam; + pTracker->AddModified(setModifications); } - // add new elements before this one - BOOST_STATIC_ASSERT(eTO_Last == eTO_AlternateFilenameFormatString_AfterFirst + 1); -} + ETaskOptions TTaskConfigTracker::GetOptionFromString(const TString& strOption) + { + if (strOption == TaskPropData::GetPropertyName()) + return eTO_UseOnlyDefaultBuffer; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DefaultBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_OneDiskBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_TwoDisksBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_CDBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_LANBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DisableBuffering; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DisableBufferingMinSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_BufferQueueDepth; -END_CHCORE_NAMESPACE + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_SetDestinationAttributes; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_SetDestinationDateTime; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_ProtectReadOnlyFiles; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_ScanDirectoriesBeforeBlocking; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_ThreadPriority; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DisablePriorityBoost; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DeleteInSeparateSubTask; + + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_CreateEmptyFiles; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_CreateDirectoriesRelativeToRoot; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_IgnoreDirectories; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_AlternateFilenameFormatString_AfterFirst; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_AlternateFilenameFormatString_First; + else + { + BOOST_ASSERT(false); // unhandled case + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } + + // add new elements before this one + BOOST_STATIC_ASSERT(eTO_Last == eTO_AlternateFilenameFormatString_AfterFirst + 1); + } +} Index: src/libchcore/TTaskConfigTracker.h =================================================================== diff -u -N -rfb4c4006dee5aaf815d08bc3e89312445b994307 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskConfigTracker.h (.../TTaskConfigTracker.h) (revision fb4c4006dee5aaf815d08bc3e89312445b994307) +++ src/libchcore/TTaskConfigTracker.h (.../TTaskConfigTracker.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,58 +26,57 @@ #include "libchcore.h" #include "TTaskConfiguration.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TOptionsSet +namespace chcore { -public: - TOptionsSet& operator%(ETaskOptions eOption); + class LIBCHCORE_API TOptionsSet + { + public: + TOptionsSet& operator%(ETaskOptions eOption); - std::set& Get(); + std::set& Get(); -private: + private: #pragma warning(push) #pragma warning(disable: 4251) - std::set m_setOptions; + std::set m_setOptions; #pragma warning(pop) -}; + }; -class LIBCHCORE_API TTaskConfigTracker -{ -public: - TTaskConfigTracker(); - ~TTaskConfigTracker(); + class LIBCHCORE_API TTaskConfigTracker + { + public: + TTaskConfigTracker(); + ~TTaskConfigTracker(); - bool IsModified() const; - bool IsModified(ETaskOptions eOption) const; - bool IsModified(TOptionsSet setOptions) const; - bool IsModified(ETaskOptions eOption, bool bResetModificationState); - bool IsModified(TOptionsSet setOptions, bool bResetModificationState); + bool IsModified() const; + bool IsModified(ETaskOptions eOption) const; + bool IsModified(TOptionsSet setOptions) const; + bool IsModified(ETaskOptions eOption, bool bResetModificationState); + bool IsModified(TOptionsSet setOptions, bool bResetModificationState); - void AddModified(const TString& strModified); - void AddModified(ETaskOptions eModified); - void AddModified(TOptionsSet setOptions); - void AddModified(const TStringSet& setModified); - void AddModified(const std::set& setModified); + void AddModified(const TString& strModified); + void AddModified(ETaskOptions eModified); + void AddModified(TOptionsSet setOptions); + void AddModified(const TStringSet& setModified); + void AddModified(const std::set& setModified); - void RemoveModification(ETaskOptions eModified); - void RemoveModificationSet(TOptionsSet setOptions); - void RemoveModification(const TString& strModified); - void Clear(); + void RemoveModification(ETaskOptions eModified); + void RemoveModificationSet(TOptionsSet setOptions); + void RemoveModification(const TString& strModified); + void Clear(); - static void NotificationProc(const TStringSet& setModifications, void* pParam); + static void NotificationProc(const TStringSet& setModifications, void* pParam); -protected: - static ETaskOptions GetOptionFromString(const TString& strOption); + protected: + static ETaskOptions GetOptionFromString(const TString& strOption); -protected: + protected: #pragma warning(push) #pragma warning(disable: 4251) - std::set m_setModified; - mutable boost::shared_mutex m_lock; + std::set m_setModified; + mutable boost::shared_mutex m_lock; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif // __TCONFIGTRACKER_H__ Index: src/libchcore/TTaskConfiguration.h =================================================================== diff -u -N -rf7314a3065ebf529a998aa0f98072049d06d192f -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskConfiguration.h (.../TTaskConfiguration.h) (revision f7314a3065ebf529a998aa0f98072049d06d192f) +++ src/libchcore/TTaskConfiguration.h (.../TTaskConfiguration.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,47 +26,47 @@ #include "libchcore.h" #include "TConfig.h" -BEGIN_CHCORE_NAMESPACE - -enum ETaskOptions +namespace chcore { - eTO_UseOnlyDefaultBuffer, - eTO_DefaultBufferSize, - eTO_OneDiskBufferSize, - eTO_TwoDisksBufferSize, - eTO_CDBufferSize, - eTO_LANBufferSize, - eTO_DisableBuffering, - eTO_DisableBufferingMinSize, - eTO_BufferQueueDepth, + enum ETaskOptions + { + eTO_UseOnlyDefaultBuffer, + eTO_DefaultBufferSize, + eTO_OneDiskBufferSize, + eTO_TwoDisksBufferSize, + eTO_CDBufferSize, + eTO_LANBufferSize, + eTO_DisableBuffering, + eTO_DisableBufferingMinSize, + eTO_BufferQueueDepth, - eTO_FeedbackGeneralFileError, - eTO_FeedbackFileAlreadyExists, - eTO_FeedbackNotEnoughSpace, + eTO_FeedbackGeneralFileError, + eTO_FeedbackFileAlreadyExists, + eTO_FeedbackNotEnoughSpace, - eTO_SetDestinationAttributes, - eTO_SetDestinationDateTime, - eTO_ProtectReadOnlyFiles, - eTO_ScanDirectoriesBeforeBlocking, - eTO_ThreadPriority, - eTO_DisablePriorityBoost, - eTO_DeleteInSeparateSubTask, + eTO_SetDestinationAttributes, + eTO_SetDestinationDateTime, + eTO_ProtectReadOnlyFiles, + eTO_ScanDirectoriesBeforeBlocking, + eTO_ThreadPriority, + eTO_DisablePriorityBoost, + eTO_DeleteInSeparateSubTask, - eTO_CreateEmptyFiles, - eTO_CreateDirectoriesRelativeToRoot, - eTO_IgnoreDirectories, + eTO_CreateEmptyFiles, + eTO_CreateDirectoriesRelativeToRoot, + eTO_IgnoreDirectories, - eTO_AlternateFilenameFormatString_First, - eTO_AlternateFilenameFormatString_AfterFirst, + eTO_AlternateFilenameFormatString_First, + eTO_AlternateFilenameFormatString_AfterFirst, - // add new elements before this one - eTO_Last -}; + // add new elements before this one + eTO_Last + }; -///////////////////////////////////////////////////////////////////////////////////////////// -// Properties definitions + ///////////////////////////////////////////////////////////////////////////////////////////// + // Properties definitions -template struct TaskPropData; + template struct TaskPropData; #define TASK_PROPERTY(enum_id, val_type, val_name, def_value)\ template<> struct TaskPropData\ @@ -94,71 +94,70 @@ }\ } -// Buffer settings -TASK_PROPERTY(eTO_UseOnlyDefaultBuffer, bool, _T("Buffer.UseOnlyDefaultBuffer"), false); -TASK_PROPERTY_MINMAX(eTO_DefaultBufferSize, unsigned int, _T("Buffer.DefaultBufferSize"), 2097152, 1, 0xffffffff); -TASK_PROPERTY_MINMAX(eTO_OneDiskBufferSize, unsigned int, _T("Buffer.OnePhysicalDiskSize"), 4194304, 1, 0xffffffff); -TASK_PROPERTY_MINMAX(eTO_TwoDisksBufferSize, unsigned int, _T("Buffer.TwoPhysicalDisksSize"), 524288, 1, 0xffffffff); -TASK_PROPERTY_MINMAX(eTO_CDBufferSize, unsigned int, _T("Buffer.CDSize"), 262144, 1, 0xffffffff); -TASK_PROPERTY_MINMAX(eTO_LANBufferSize, unsigned int, _T("Buffer.LANSize"), 131072, 1, 0xffffffff); -TASK_PROPERTY_MINMAX(eTO_BufferQueueDepth, unsigned int, _T("Buffer.QueueDepth"), 5, 1, 1000); + // Buffer settings + TASK_PROPERTY(eTO_UseOnlyDefaultBuffer, bool, _T("Buffer.UseOnlyDefaultBuffer"), false); + TASK_PROPERTY_MINMAX(eTO_DefaultBufferSize, unsigned int, _T("Buffer.DefaultBufferSize"), 2097152, 1, 0xffffffff); + TASK_PROPERTY_MINMAX(eTO_OneDiskBufferSize, unsigned int, _T("Buffer.OnePhysicalDiskSize"), 4194304, 1, 0xffffffff); + TASK_PROPERTY_MINMAX(eTO_TwoDisksBufferSize, unsigned int, _T("Buffer.TwoPhysicalDisksSize"), 524288, 1, 0xffffffff); + TASK_PROPERTY_MINMAX(eTO_CDBufferSize, unsigned int, _T("Buffer.CDSize"), 262144, 1, 0xffffffff); + TASK_PROPERTY_MINMAX(eTO_LANBufferSize, unsigned int, _T("Buffer.LANSize"), 131072, 1, 0xffffffff); + TASK_PROPERTY_MINMAX(eTO_BufferQueueDepth, unsigned int, _T("Buffer.QueueDepth"), 5, 1, 1000); -TASK_PROPERTY(eTO_DisableBuffering, bool, _T("Operation.Buffering.DisableBufferingForLargeFiles"), true); -TASK_PROPERTY_MINMAX(eTO_DisableBufferingMinSize, int, _T("Operation.Buffering.MinSizeOfFileToDisableBuffering"), 2097152, 1, 0xffffffff); + TASK_PROPERTY(eTO_DisableBuffering, bool, _T("Operation.Buffering.DisableBufferingForLargeFiles"), true); + TASK_PROPERTY_MINMAX(eTO_DisableBufferingMinSize, int, _T("Operation.Buffering.MinSizeOfFileToDisableBuffering"), 2097152, 1, 0xffffffff); -TASK_PROPERTY(eTO_SetDestinationAttributes, bool, _T("Operation.SetDestinationAttributes"), true); -TASK_PROPERTY(eTO_SetDestinationDateTime, bool, _T("Operation.SetDestinationTime"), true); -TASK_PROPERTY(eTO_ProtectReadOnlyFiles, bool, _T("Operation.ProtectReadOnlyFiles"), true); -TASK_PROPERTY(eTO_ScanDirectoriesBeforeBlocking, bool, _T("Operation.ScanForFilesBeforeBlocking"), true); + TASK_PROPERTY(eTO_SetDestinationAttributes, bool, _T("Operation.SetDestinationAttributes"), true); + TASK_PROPERTY(eTO_SetDestinationDateTime, bool, _T("Operation.SetDestinationTime"), true); + TASK_PROPERTY(eTO_ProtectReadOnlyFiles, bool, _T("Operation.ProtectReadOnlyFiles"), true); + TASK_PROPERTY(eTO_ScanDirectoriesBeforeBlocking, bool, _T("Operation.ScanForFilesBeforeBlocking"), true); -// Thread settings -TASK_PROPERTY(eTO_ThreadPriority, int, _T("Operation.Thread.Priority"), THREAD_PRIORITY_NORMAL); -TASK_PROPERTY(eTO_DisablePriorityBoost, bool, _T("Operation.Thread.DisablePriorityBoost"), false); + // Thread settings + TASK_PROPERTY(eTO_ThreadPriority, int, _T("Operation.Thread.Priority"), THREAD_PRIORITY_NORMAL); + TASK_PROPERTY(eTO_DisablePriorityBoost, bool, _T("Operation.Thread.DisablePriorityBoost"), false); -// Operation settings -TASK_PROPERTY(eTO_DeleteInSeparateSubTask, bool, _T("Operation.DeleteFilesInSeparateOperation"), true); + // Operation settings + TASK_PROPERTY(eTO_DeleteInSeparateSubTask, bool, _T("Operation.DeleteFilesInSeparateOperation"), true); -TASK_PROPERTY(eTO_CreateEmptyFiles, bool, _T("Operation.CreateEmptyFiles"), false); -TASK_PROPERTY(eTO_CreateDirectoriesRelativeToRoot, bool, _T("Operation.CreateDirectoriesRelativeToRoot"), false); -TASK_PROPERTY(eTO_IgnoreDirectories, bool, _T("Operation.IgnoreDirectories"), false); + TASK_PROPERTY(eTO_CreateEmptyFiles, bool, _T("Operation.CreateEmptyFiles"), false); + TASK_PROPERTY(eTO_CreateDirectoriesRelativeToRoot, bool, _T("Operation.CreateDirectoriesRelativeToRoot"), false); + TASK_PROPERTY(eTO_IgnoreDirectories, bool, _T("Operation.IgnoreDirectories"), false); -// Naming settings -TASK_PROPERTY(eTO_AlternateFilenameFormatString_First, TString, _T("Naming.AlternateFilenameFormatFirst"), _T("Copy of %name")); -TASK_PROPERTY(eTO_AlternateFilenameFormatString_AfterFirst, TString, _T("Naming.AlternateFilenameFormatAfterFirst"), _T("Copy (%count) of %name")); + // Naming settings + TASK_PROPERTY(eTO_AlternateFilenameFormatString_First, TString, _T("Naming.AlternateFilenameFormatFirst"), _T("Copy of %name")); + TASK_PROPERTY(eTO_AlternateFilenameFormatString_AfterFirst, TString, _T("Naming.AlternateFilenameFormatAfterFirst"), _T("Copy (%count) of %name")); -///////////////////////////////////////////////////////////////////////////////////////////// -// other properties names -//#define TASK_PROP_NAME_FILTERING _T("Filtering") + ///////////////////////////////////////////////////////////////////////////////////////////// + // other properties names + //#define TASK_PROP_NAME_FILTERING _T("Filtering") -///////////////////////////////////////////////////////////////////////////////////////////// -// Properties retrieval -template -typename TaskPropData::value_type GetTaskPropValue(const TConfig& rConfig) -{ - typename TaskPropData::value_type tValue; - bool bResult = GetConfigValue(rConfig, TaskPropData::GetPropertyName(), tValue); - if(!bResult) - tValue = TaskPropData::GetDefaultValue(); + ///////////////////////////////////////////////////////////////////////////////////////////// + // Properties retrieval + template + typename TaskPropData::value_type GetTaskPropValue(const TConfig& rConfig) + { + typename TaskPropData::value_type tValue; + bool bResult = GetConfigValue(rConfig, TaskPropData::GetPropertyName(), tValue); + if (!bResult) + tValue = TaskPropData::GetDefaultValue(); - TaskPropData::ValidateRange(tValue); - return tValue; -} + TaskPropData::ValidateRange(tValue); + return tValue; + } -template -bool GetTaskPropValue(const TConfig& rConfig, typename TaskPropData::value_type& rValue) -{ - bool bResult = GetConfigValue(rConfig, TaskPropData::GetPropertyName(), rValue); - if(bResult) - TaskPropData::ValidateRange(rValue); - return bResult; -} + template + bool GetTaskPropValue(const TConfig& rConfig, typename TaskPropData::value_type& rValue) + { + bool bResult = GetConfigValue(rConfig, TaskPropData::GetPropertyName(), rValue); + if (bResult) + TaskPropData::ValidateRange(rValue); + return bResult; + } -template -void SetTaskPropValue(TConfig& rConfig, const typename TaskPropData::value_type& rValue) -{ - SetConfigValue(rConfig, TaskPropData::GetPropertyName(), rValue); + template + void SetTaskPropValue(TConfig& rConfig, const typename TaskPropData::value_type& rValue) + { + SetConfigValue(rConfig, TaskPropData::GetPropertyName(), rValue); + } } -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTaskDefinition.cpp =================================================================== diff -u -N -r31cbdfa4bdbab86ce7c143b6899395454e158293 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskDefinition.cpp (.../TTaskDefinition.cpp) (revision 31cbdfa4bdbab86ce7c143b6899395454e158293) +++ src/libchcore/TTaskDefinition.cpp (.../TTaskDefinition.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -32,270 +32,269 @@ #define CURRENT_TASK_VERSION 1 -BEGIN_CHCORE_NAMESPACE - -TTaskDefinition::TTaskDefinition() : - m_bModified(false), - m_strTaskName(), - m_ullTaskVersion(CURRENT_TASK_VERSION) +namespace chcore { - boost::uuids::random_generator gen; - boost::uuids::uuid u = gen(); - m_strTaskName = boost::lexical_cast(u).c_str(); -} + TTaskDefinition::TTaskDefinition() : + m_bModified(false), + m_strTaskName(), + m_ullTaskVersion(CURRENT_TASK_VERSION) + { + boost::uuids::random_generator gen; + boost::uuids::uuid u = gen(); + m_strTaskName = boost::lexical_cast(u).c_str(); + } -TTaskDefinition::TTaskDefinition(const TTaskDefinition& rSrc) : - m_strTaskName(rSrc.m_strTaskName), - m_vSourcePaths(rSrc.m_vSourcePaths), - m_afFilters(rSrc.m_afFilters), - m_pathDestinationPath(rSrc.m_pathDestinationPath), - m_tOperationPlan(rSrc.m_tOperationPlan), - m_ullTaskVersion(rSrc.m_ullTaskVersion), - m_tConfiguration(rSrc.m_tConfiguration), - m_bModified(rSrc.m_bModified) -{ -} + TTaskDefinition::TTaskDefinition(const TTaskDefinition& rSrc) : + m_strTaskName(rSrc.m_strTaskName), + m_vSourcePaths(rSrc.m_vSourcePaths), + m_afFilters(rSrc.m_afFilters), + m_pathDestinationPath(rSrc.m_pathDestinationPath), + m_tOperationPlan(rSrc.m_tOperationPlan), + m_ullTaskVersion(rSrc.m_ullTaskVersion), + m_tConfiguration(rSrc.m_tConfiguration), + m_bModified(rSrc.m_bModified) + { + } -TTaskDefinition::~TTaskDefinition() -{ -} + TTaskDefinition::~TTaskDefinition() + { + } -TTaskDefinition& TTaskDefinition::operator=(const TTaskDefinition& rSrc) -{ - if(this != &rSrc) + TTaskDefinition& TTaskDefinition::operator=(const TTaskDefinition& rSrc) { - m_strTaskName = rSrc.m_strTaskName; - m_vSourcePaths = rSrc.m_vSourcePaths; - m_afFilters = rSrc.m_afFilters; - m_pathDestinationPath = rSrc.m_pathDestinationPath; - m_tOperationPlan = rSrc.m_tOperationPlan; - m_ullTaskVersion = rSrc.m_ullTaskVersion; - m_tConfiguration = rSrc.m_tConfiguration; - m_bModified = rSrc.m_bModified; + if (this != &rSrc) + { + m_strTaskName = rSrc.m_strTaskName; + m_vSourcePaths = rSrc.m_vSourcePaths; + m_afFilters = rSrc.m_afFilters; + m_pathDestinationPath = rSrc.m_pathDestinationPath; + m_tOperationPlan = rSrc.m_tOperationPlan; + m_ullTaskVersion = rSrc.m_ullTaskVersion; + m_tConfiguration = rSrc.m_tConfiguration; + m_bModified = rSrc.m_bModified; + } + + return *this; } - return *this; -} + // Task unique id + TString TTaskDefinition::GetTaskName() const + { + return m_strTaskName; + } -// Task unique id -TString TTaskDefinition::GetTaskName() const -{ - return m_strTaskName; -} + // Source paths + // initialize object with data (get/set, from cfg file?, from string(cmd line options)) + void TTaskDefinition::AddSourcePath(const TSmartPath& tPath) + { + m_vSourcePaths.Add(tPath); + m_bModified = true; + } -// Source paths -// initialize object with data (get/set, from cfg file?, from string(cmd line options)) -void TTaskDefinition::AddSourcePath(const TSmartPath& tPath) -{ - m_vSourcePaths.Add(tPath); - m_bModified = true; -} + TSmartPath TTaskDefinition::GetSourcePathAt(size_t stIndex) const + { + return m_vSourcePaths.GetAt(stIndex); + } -TSmartPath TTaskDefinition::GetSourcePathAt(size_t stIndex) const -{ - return m_vSourcePaths.GetAt(stIndex); -} + size_t TTaskDefinition::GetSourcePathCount() const + { + return m_vSourcePaths.GetCount(); + } -size_t TTaskDefinition::GetSourcePathCount() const -{ - return m_vSourcePaths.GetCount(); -} + void TTaskDefinition::ClearSourcePaths() + { + m_vSourcePaths.Clear(); + m_bModified = true; + } -void TTaskDefinition::ClearSourcePaths() -{ - m_vSourcePaths.Clear(); - m_bModified = true; -} + void TTaskDefinition::SetSourcePaths(const TPathContainer& rvPaths) + { + m_vSourcePaths = rvPaths; + } -void TTaskDefinition::SetSourcePaths(const TPathContainer& rvPaths) -{ - m_vSourcePaths = rvPaths; -} + const TPathContainer& TTaskDefinition::GetSourcePaths() const + { + return m_vSourcePaths; + } -const TPathContainer& TTaskDefinition::GetSourcePaths() const -{ - return m_vSourcePaths; -} + // Destination path + void TTaskDefinition::SetDestinationPath(const TSmartPath& pathDestination) + { + m_pathDestinationPath = pathDestination; + if (!m_pathDestinationPath.IsEmpty()) + m_pathDestinationPath.AppendSeparatorIfDoesNotExist(); + m_bModified = true; + } -// Destination path -void TTaskDefinition::SetDestinationPath(const TSmartPath& pathDestination) -{ - m_pathDestinationPath = pathDestination; - if(!m_pathDestinationPath.IsEmpty()) - m_pathDestinationPath.AppendSeparatorIfDoesNotExist(); - m_bModified = true; -} + TSmartPath TTaskDefinition::GetDestinationPath() const + { + return m_pathDestinationPath; + } -TSmartPath TTaskDefinition::GetDestinationPath() const -{ - return m_pathDestinationPath; -} + // Operation type + void TTaskDefinition::SetOperationType(EOperationType eOperation) + { + m_tOperationPlan.SetOperationType(eOperation); + m_bModified = true; + } -// Operation type -void TTaskDefinition::SetOperationType(EOperationType eOperation) -{ - m_tOperationPlan.SetOperationType(eOperation); - m_bModified = true; -} + EOperationType TTaskDefinition::GetOperationType() const + { + return m_tOperationPlan.GetOperationType(); + } -EOperationType TTaskDefinition::GetOperationType() const -{ - return m_tOperationPlan.GetOperationType(); -} + const TOperationPlan& TTaskDefinition::GetOperationPlan() const + { + return m_tOperationPlan; + } -const TOperationPlan& TTaskDefinition::GetOperationPlan() const -{ - return m_tOperationPlan; -} + // Task configuration + void TTaskDefinition::SetConfiguration(const TConfig& rConfig) + { + m_tConfiguration = rConfig; + m_bModified = true; + } -// Task configuration -void TTaskDefinition::SetConfiguration(const TConfig& rConfig) -{ - m_tConfiguration = rConfig; - m_bModified = true; -} + TConfig& TTaskDefinition::GetConfiguration() + { + return m_tConfiguration; + } -TConfig& TTaskDefinition::GetConfiguration() -{ - return m_tConfiguration; -} + const TConfig& TTaskDefinition::GetConfiguration() const + { + return m_tConfiguration; + } -const TConfig& TTaskDefinition::GetConfiguration() const -{ - return m_tConfiguration; -} + // Serialization + void TTaskDefinition::Load(const TSmartPath& strPath) + { + // read everything + TConfig tTaskInfo; + tTaskInfo.Read(strPath.ToString()); -// Serialization -void TTaskDefinition::Load(const TSmartPath& strPath) -{ - // read everything - TConfig tTaskInfo; - tTaskInfo.Read(strPath.ToString()); + Load(tTaskInfo, false); + } - Load(tTaskInfo, false); -} + void TTaskDefinition::Load(const TConfig& rDataSrc, bool bAllowEmptyDstPath) + { + // clear everything + m_strTaskName.Clear(); + m_vSourcePaths.Clear(); + m_pathDestinationPath.Clear(); + m_afFilters.Clear(); -void TTaskDefinition::Load(const TConfig& rDataSrc, bool bAllowEmptyDstPath) -{ - // clear everything - m_strTaskName.Clear(); - m_vSourcePaths.Clear(); - m_pathDestinationPath.Clear(); - m_afFilters.Clear(); + m_tConfiguration.Clear(); - m_tConfiguration.Clear(); + m_bModified = false; - m_bModified = false; + // get information from config file + // NOTE: task unique id is not read from the config by design; + // by using the value, CH tried to re-use the task DB causing problems. + // So now, always a new identifier is generated. + boost::uuids::random_generator gen; + boost::uuids::uuid u = gen(); + m_strTaskName = boost::lexical_cast(u).c_str(); - // get information from config file - // NOTE: task unique id is not read from the config by design; - // by using the value, CH tried to re-use the task DB causing problems. - // So now, always a new identifier is generated. - boost::uuids::random_generator gen; - boost::uuids::uuid u = gen(); - m_strTaskName = boost::lexical_cast(u).c_str(); + // basic information + // source paths to be processed + if (!GetConfigValue(rDataSrc, _T("TaskDefinition.SourcePaths.Path"), m_vSourcePaths) || m_vSourcePaths.IsEmpty()) + THROW_CORE_EXCEPTION(eErr_MissingXmlData); - // basic information - // source paths to be processed - if (!GetConfigValue(rDataSrc, _T("TaskDefinition.SourcePaths.Path"), m_vSourcePaths) || m_vSourcePaths.IsEmpty()) - THROW_CORE_EXCEPTION(eErr_MissingXmlData); + GetConfigValue(rDataSrc, _T("TaskDefinition.Filters"), m_afFilters); - GetConfigValue(rDataSrc, _T("TaskDefinition.Filters"), m_afFilters); + // destination path + if (!GetConfigValue(rDataSrc, _T("TaskDefinition.DestinationPath"), m_pathDestinationPath) || (!bAllowEmptyDstPath && m_pathDestinationPath.IsEmpty())) + THROW_CORE_EXCEPTION(eErr_MissingXmlData); - // destination path - if (!GetConfigValue(rDataSrc, _T("TaskDefinition.DestinationPath"), m_pathDestinationPath) || (!bAllowEmptyDstPath && m_pathDestinationPath.IsEmpty())) - THROW_CORE_EXCEPTION(eErr_MissingXmlData); + // append separator only if destination path is already specified; otherwise there are problems handling chext requests with no destination path + if (!m_pathDestinationPath.IsEmpty()) + m_pathDestinationPath.AppendSeparatorIfDoesNotExist(); - // append separator only if destination path is already specified; otherwise there are problems handling chext requests with no destination path - if(!m_pathDestinationPath.IsEmpty()) - m_pathDestinationPath.AppendSeparatorIfDoesNotExist(); + // type of the operation + int iOperation = eOperation_None; + if (!rDataSrc.GetValue(_T("TaskDefinition.OperationType"), iOperation)) + THROW_CORE_EXCEPTION(eErr_MissingXmlData); - // type of the operation - int iOperation = eOperation_None; - if (!rDataSrc.GetValue(_T("TaskDefinition.OperationType"), iOperation)) - THROW_CORE_EXCEPTION(eErr_MissingXmlData); + m_tOperationPlan.SetOperationType((EOperationType)iOperation); - m_tOperationPlan.SetOperationType((EOperationType) iOperation); + // and version of the task + if (!GetConfigValue(rDataSrc, _T("TaskDefinition.Version"), m_ullTaskVersion)) + THROW_CORE_EXCEPTION(eErr_MissingXmlData); - // and version of the task - if (!GetConfigValue(rDataSrc, _T("TaskDefinition.Version"), m_ullTaskVersion)) - THROW_CORE_EXCEPTION(eErr_MissingXmlData); + if (m_ullTaskVersion < CURRENT_TASK_VERSION) + { + // migrate the task to the newer version + // (nothing to migrate at this point, since 1.40 is the first release with xml-based tasks). - if (m_ullTaskVersion < CURRENT_TASK_VERSION) - { - // migrate the task to the newer version - // (nothing to migrate at this point, since 1.40 is the first release with xml-based tasks). + // then mark it as a newest version task + m_ullTaskVersion = CURRENT_TASK_VERSION; + m_bModified = true; + } + else if (m_ullTaskVersion > CURRENT_TASK_VERSION) + THROW_CORE_EXCEPTION(eErr_UnsupportedVersion); - // then mark it as a newest version task - m_ullTaskVersion = CURRENT_TASK_VERSION; - m_bModified = true; + rDataSrc.ExtractSubConfig(_T("TaskDefinition.TaskSettings"), m_tConfiguration); } - else if (m_ullTaskVersion > CURRENT_TASK_VERSION) - THROW_CORE_EXCEPTION(eErr_UnsupportedVersion); - rDataSrc.ExtractSubConfig(_T("TaskDefinition.TaskSettings"), m_tConfiguration); -} + void TTaskDefinition::LoadFromString(const TString& strInput, bool bAllowEmptyDstPath) + { + // read everything + TConfig tTaskInfo; + tTaskInfo.ReadFromString(strInput); -void TTaskDefinition::LoadFromString(const TString& strInput, bool bAllowEmptyDstPath) -{ - // read everything - TConfig tTaskInfo; - tTaskInfo.ReadFromString(strInput); + Load(tTaskInfo, bAllowEmptyDstPath); + } - Load(tTaskInfo, bAllowEmptyDstPath); -} + void TTaskDefinition::StoreInString(TString& strOutput) + { + TConfig tTaskInfo; + Store(tTaskInfo); -void TTaskDefinition::StoreInString(TString& strOutput) -{ - TConfig tTaskInfo; - Store(tTaskInfo); + tTaskInfo.WriteToString(strOutput); + } - tTaskInfo.WriteToString(strOutput); -} + void TTaskDefinition::Store(const TSmartPath& strPath) const + { + TConfig tTaskInfo; + Store(tTaskInfo); -void TTaskDefinition::Store(const TSmartPath& strPath) const -{ - TConfig tTaskInfo; - Store(tTaskInfo); + tTaskInfo.SetFilePath(strPath.ToString()); + tTaskInfo.Write(); + } - tTaskInfo.SetFilePath(strPath.ToString()); - tTaskInfo.Write(); -} + void TTaskDefinition::Store(TConfig& rConfig) const + { + // get information from config file + // task unique id - use if provided, generate otherwise + // NOTE: not storing the task ID is by design. Loading same task twice caused problems + // when importing and was disabled. With that, storing was no longer needed. -void TTaskDefinition::Store(TConfig& rConfig) const -{ - // get information from config file - // task unique id - use if provided, generate otherwise - // NOTE: not storing the task ID is by design. Loading same task twice caused problems - // when importing and was disabled. With that, storing was no longer needed. + // basic information + SetConfigValue(rConfig, _T("TaskDefinition.SourcePaths.Path"), m_vSourcePaths); + SetConfigValue(rConfig, _T("TaskDefinition.Filters"), m_afFilters); + SetConfigValue(rConfig, _T("TaskDefinition.DestinationPath"), m_pathDestinationPath); - // basic information - SetConfigValue(rConfig, _T("TaskDefinition.SourcePaths.Path"), m_vSourcePaths); - SetConfigValue(rConfig, _T("TaskDefinition.Filters"), m_afFilters); - SetConfigValue(rConfig, _T("TaskDefinition.DestinationPath"), m_pathDestinationPath); + int iOperation = m_tOperationPlan.GetOperationType(); + SetConfigValue(rConfig, _T("TaskDefinition.OperationType"), iOperation); - int iOperation = m_tOperationPlan.GetOperationType(); - SetConfigValue(rConfig, _T("TaskDefinition.OperationType"), iOperation); + SetConfigValue(rConfig, _T("TaskDefinition.Version"), m_ullTaskVersion); - SetConfigValue(rConfig, _T("TaskDefinition.Version"), m_ullTaskVersion); + rConfig.PutSubConfig(_T("TaskDefinition.TaskSettings"), m_tConfiguration); + } - rConfig.PutSubConfig(_T("TaskDefinition.TaskSettings"), m_tConfiguration); -} + const TFileFiltersArray& TTaskDefinition::GetFilters() const + { + return m_afFilters; + } -const TFileFiltersArray& TTaskDefinition::GetFilters() const -{ - return m_afFilters; -} + TFileFiltersArray& TTaskDefinition::GetFilters() + { + return m_afFilters; + } -TFileFiltersArray& TTaskDefinition::GetFilters() -{ - return m_afFilters; + void TTaskDefinition::SetFilters(const TFileFiltersArray& rFilters) + { + m_afFilters = rFilters; + } } - -void TTaskDefinition::SetFilters(const TFileFiltersArray& rFilters) -{ - m_afFilters = rFilters; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TTaskDefinition.h =================================================================== diff -u -N -r503a68180cbb933c97e9af965744bf106994c05a -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskDefinition.h (.../TTaskDefinition.h) (revision 503a68180cbb933c97e9af965744bf106994c05a) +++ src/libchcore/TTaskDefinition.h (.../TTaskDefinition.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -29,80 +29,79 @@ #include "TPathContainer.h" #include "TFileFiltersArray.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////// -// TTaskDefinition - -class LIBCHCORE_API TTaskDefinition +namespace chcore { -public: - TTaskDefinition(); - TTaskDefinition(const TTaskDefinition& rSrc); - ~TTaskDefinition(); + /////////////////////////////////////////////////////////////////////////// + // TTaskDefinition - TTaskDefinition& operator=(const TTaskDefinition& rSrc); + class LIBCHCORE_API TTaskDefinition + { + public: + TTaskDefinition(); + TTaskDefinition(const TTaskDefinition& rSrc); + ~TTaskDefinition(); - // Task unique ID - TString GetTaskName() const; + TTaskDefinition& operator=(const TTaskDefinition& rSrc); - // Source paths - void AddSourcePath(const TSmartPath& tPath); - TSmartPath GetSourcePathAt(size_t stIndex) const; - size_t GetSourcePathCount() const; - void SetSourcePaths(const TPathContainer& rvPaths); - const TPathContainer& GetSourcePaths() const; + // Task unique ID + TString GetTaskName() const; - void ClearSourcePaths(); + // Source paths + void AddSourcePath(const TSmartPath& tPath); + TSmartPath GetSourcePathAt(size_t stIndex) const; + size_t GetSourcePathCount() const; + void SetSourcePaths(const TPathContainer& rvPaths); + const TPathContainer& GetSourcePaths() const; - // filters - const TFileFiltersArray& GetFilters() const; - TFileFiltersArray& GetFilters(); - void SetFilters(const TFileFiltersArray& rFilters); + void ClearSourcePaths(); - // Destination path - void SetDestinationPath(const TSmartPath& pathDestination); - TSmartPath GetDestinationPath() const; + // filters + const TFileFiltersArray& GetFilters() const; + TFileFiltersArray& GetFilters(); + void SetFilters(const TFileFiltersArray& rFilters); - // Operation type - void SetOperationType(EOperationType eOperation); - EOperationType GetOperationType() const; - const TOperationPlan& GetOperationPlan() const; + // Destination path + void SetDestinationPath(const TSmartPath& pathDestination); + TSmartPath GetDestinationPath() const; - // Task configuration - void SetConfiguration(const TConfig& rConfig); - TConfig& GetConfiguration(); - const TConfig& GetConfiguration() const; + // Operation type + void SetOperationType(EOperationType eOperation); + EOperationType GetOperationType() const; + const TOperationPlan& GetOperationPlan() const; - // Serialization - void Load(const TSmartPath& strPath); - void Load(const TConfig& rDataSrc, bool bAllowEmptyDstPath); - void LoadFromString(const TString& strInput, bool bAllowEmptyDstPath = false); + // Task configuration + void SetConfiguration(const TConfig& rConfig); + TConfig& GetConfiguration(); + const TConfig& GetConfiguration() const; - void Store(const TSmartPath& strPath) const; - void Store(TConfig& rConfig) const; - void StoreInString(TString& strInput); + // Serialization + void Load(const TSmartPath& strPath); + void Load(const TConfig& rDataSrc, bool bAllowEmptyDstPath); + void LoadFromString(const TString& strInput, bool bAllowEmptyDstPath = false); -private: - TString m_strTaskName; ///< Unique ID of the task that will process this request (generated automatically) + void Store(const TSmartPath& strPath) const; + void Store(TConfig& rConfig) const; + void StoreInString(TString& strInput); - // basic information - TPathContainer m_vSourcePaths; - TSmartPath m_pathDestinationPath; - TFileFiltersArray m_afFilters; + private: + TString m_strTaskName; ///< Unique ID of the task that will process this request (generated automatically) - TOperationPlan m_tOperationPlan; ///< Describes the operation along with sub-operations to be performed on the task input data + // basic information + TPathContainer m_vSourcePaths; + TSmartPath m_pathDestinationPath; + TFileFiltersArray m_afFilters; - // Task version - unsigned long long m_ullTaskVersion; + TOperationPlan m_tOperationPlan; ///< Describes the operation along with sub-operations to be performed on the task input data - // Global task settings - TConfig m_tConfiguration; + // Task version + unsigned long long m_ullTaskVersion; - // Other info (volatile, not to be saved to xml) - mutable bool m_bModified; ///< Some parameters has been modified and this object needs to be serialized again -}; + // Global task settings + TConfig m_tConfiguration; -END_CHCORE_NAMESPACE + // Other info (volatile, not to be saved to xml) + mutable bool m_bModified; ///< Some parameters has been modified and this object needs to be serialized again + }; +} #endif // __TTASKDEFINITION_H__ Index: src/libchcore/TTaskInfo.cpp =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskInfo.cpp (.../TTaskInfo.cpp) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/TTaskInfo.cpp (.../TTaskInfo.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,247 +22,246 @@ #include "ISerializerRowData.h" #include "ISerializerRowReader.h" -BEGIN_CHCORE_NAMESPACE - -TTaskInfoEntry::TTaskInfoEntry() : - m_iOrder(m_setModifications, 0), - m_pathSerializeLocation(m_setModifications), - m_oidObjectID(0) +namespace chcore { - m_setModifications[eMod_Added] = true; -} + TTaskInfoEntry::TTaskInfoEntry() : + m_iOrder(m_setModifications, 0), + m_pathSerializeLocation(m_setModifications), + m_oidObjectID(0) + { + m_setModifications[eMod_Added] = true; + } -TTaskInfoEntry::TTaskInfoEntry(object_id_t oidTaskID, const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask) : - m_oidObjectID(oidTaskID), - m_pathSerializeLocation(m_setModifications, pathTask), - m_iOrder(m_setModifications, iOrder), - m_spTask(spTask) -{ - m_setModifications[eMod_Added] = true; -} + TTaskInfoEntry::TTaskInfoEntry(object_id_t oidTaskID, const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask) : + m_oidObjectID(oidTaskID), + m_pathSerializeLocation(m_setModifications, pathTask), + m_iOrder(m_setModifications, iOrder), + m_spTask(spTask) + { + m_setModifications[eMod_Added] = true; + } -TTaskInfoEntry::TTaskInfoEntry(const TTaskInfoEntry& rSrc) : - m_oidObjectID(rSrc.m_oidObjectID), - m_pathSerializeLocation(m_setModifications, rSrc.m_pathSerializeLocation), - m_iOrder(m_setModifications, rSrc.m_iOrder), - m_spTask(rSrc.m_spTask) -{ - m_setModifications = rSrc.m_setModifications; -} - -TTaskInfoEntry& TTaskInfoEntry::operator=(const TTaskInfoEntry& rSrc) -{ - if(this != &rSrc) + TTaskInfoEntry::TTaskInfoEntry(const TTaskInfoEntry& rSrc) : + m_oidObjectID(rSrc.m_oidObjectID), + m_pathSerializeLocation(m_setModifications, rSrc.m_pathSerializeLocation), + m_iOrder(m_setModifications, rSrc.m_iOrder), + m_spTask(rSrc.m_spTask) { - m_oidObjectID = rSrc.m_oidObjectID; - m_pathSerializeLocation = rSrc.m_pathSerializeLocation; - m_iOrder = rSrc.m_iOrder; - m_spTask = rSrc.m_spTask; m_setModifications = rSrc.m_setModifications; } - return *this; -} + TTaskInfoEntry& TTaskInfoEntry::operator=(const TTaskInfoEntry& rSrc) + { + if (this != &rSrc) + { + m_oidObjectID = rSrc.m_oidObjectID; + m_pathSerializeLocation = rSrc.m_pathSerializeLocation; + m_iOrder = rSrc.m_iOrder; + m_spTask = rSrc.m_spTask; + m_setModifications = rSrc.m_setModifications; + } -TSmartPath TTaskInfoEntry::GetTaskSerializeLocation() const -{ - return m_pathSerializeLocation; -} + return *this; + } -void TTaskInfoEntry::SetTaskSerializeLocation(const TSmartPath& strTaskPath) -{ - m_pathSerializeLocation = strTaskPath; -} + TSmartPath TTaskInfoEntry::GetTaskSerializeLocation() const + { + return m_pathSerializeLocation; + } -TTaskPtr TTaskInfoEntry::GetTask() const -{ - return m_spTask; -} + void TTaskInfoEntry::SetTaskSerializeLocation(const TSmartPath& strTaskPath) + { + m_pathSerializeLocation = strTaskPath; + } -void TTaskInfoEntry::SetTask(const TTaskPtr& spTask) -{ - m_spTask = spTask; -} + TTaskPtr TTaskInfoEntry::GetTask() const + { + return m_spTask; + } -int TTaskInfoEntry::GetOrder() const -{ - return m_iOrder; -} + void TTaskInfoEntry::SetTask(const TTaskPtr& spTask) + { + m_spTask = spTask; + } -void TTaskInfoEntry::SetOrder(int iOrder) -{ - m_iOrder = iOrder; -} + int TTaskInfoEntry::GetOrder() const + { + return m_iOrder; + } -void TTaskInfoEntry::Store(const ISerializerContainerPtr& spContainer) const -{ - if(!m_setModifications.any()) - return; + void TTaskInfoEntry::SetOrder(int iOrder) + { + m_iOrder = iOrder; + } - bool bAdded = m_setModifications[eMod_Added]; - ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); + void TTaskInfoEntry::Store(const ISerializerContainerPtr& spContainer) const + { + if (!m_setModifications.any()) + return; - if(bAdded || m_setModifications[eMod_TaskPath]) - rRow.SetValue(_T("path"), m_pathSerializeLocation); - if(bAdded || m_setModifications[eMod_Order]) - rRow.SetValue(_T("task_order"), m_iOrder); + bool bAdded = m_setModifications[eMod_Added]; + ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); - m_setModifications.reset(); -} + if (bAdded || m_setModifications[eMod_TaskPath]) + rRow.SetValue(_T("path"), m_pathSerializeLocation); + if (bAdded || m_setModifications[eMod_Order]) + rRow.SetValue(_T("task_order"), m_iOrder); -void TTaskInfoEntry::Load(const ISerializerRowReaderPtr& spRowReader) -{ - spRowReader->GetValue(_T("id"), m_oidObjectID); - spRowReader->GetValue(_T("path"), m_pathSerializeLocation.Modify()); - spRowReader->GetValue(_T("task_order"), m_iOrder.Modify()); + m_setModifications.reset(); + } - m_setModifications.reset(); -} + void TTaskInfoEntry::Load(const ISerializerRowReaderPtr& spRowReader) + { + spRowReader->GetValue(_T("id"), m_oidObjectID); + spRowReader->GetValue(_T("path"), m_pathSerializeLocation.Modify()); + spRowReader->GetValue(_T("task_order"), m_iOrder.Modify()); -void TTaskInfoEntry::InitColumns(IColumnsDefinition& rColumnDefs) -{ - rColumnDefs.AddColumn(_T("id"), ColumnType::value); - rColumnDefs.AddColumn(_T("path"), IColumnsDefinition::eType_path); - rColumnDefs.AddColumn(_T("task_order"), IColumnsDefinition::eType_int); -} + m_setModifications.reset(); + } -object_id_t TTaskInfoEntry::GetObjectID() const -{ - return m_oidObjectID; -} + void TTaskInfoEntry::InitColumns(IColumnsDefinition& rColumnDefs) + { + rColumnDefs.AddColumn(_T("id"), ColumnType::value); + rColumnDefs.AddColumn(_T("path"), IColumnsDefinition::eType_path); + rColumnDefs.AddColumn(_T("task_order"), IColumnsDefinition::eType_int); + } -void TTaskInfoEntry::ResetModifications() -{ - m_setModifications.reset(); -} + object_id_t TTaskInfoEntry::GetObjectID() const + { + return m_oidObjectID; + } -/////////////////////////////////////////////////////////////////////////// -TTaskInfoContainer::TTaskInfoContainer() : - m_oidLastObjectID(0) -{ -} + void TTaskInfoEntry::ResetModifications() + { + m_setModifications.reset(); + } -void TTaskInfoContainer::Add(const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask) -{ - m_vTaskInfos.push_back(TTaskInfoEntry(++m_oidLastObjectID, pathTask, iOrder, spTask)); -} + /////////////////////////////////////////////////////////////////////////// + TTaskInfoContainer::TTaskInfoContainer() : + m_oidLastObjectID(0) + { + } -void TTaskInfoContainer::RemoveAt(size_t stIndex) -{ - if(stIndex >= m_vTaskInfos.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + void TTaskInfoContainer::Add(const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask) + { + m_vTaskInfos.push_back(TTaskInfoEntry(++m_oidLastObjectID, pathTask, iOrder, spTask)); + } - std::vector::iterator iter = m_vTaskInfos.begin() + stIndex; - object_id_t oidTaskID = (*iter).GetObjectID(); - m_vTaskInfos.erase(m_vTaskInfos.begin() + stIndex); - m_setRemovedTasks.Add(oidTaskID); -} + void TTaskInfoContainer::RemoveAt(size_t stIndex) + { + if (stIndex >= m_vTaskInfos.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); -void TTaskInfoContainer::Clear() -{ - BOOST_FOREACH(TTaskInfoEntry& rEntry, m_vTaskInfos) + std::vector::iterator iter = m_vTaskInfos.begin() + stIndex; + object_id_t oidTaskID = (*iter).GetObjectID(); + m_vTaskInfos.erase(m_vTaskInfos.begin() + stIndex); + m_setRemovedTasks.Add(oidTaskID); + } + + void TTaskInfoContainer::Clear() { - m_setRemovedTasks.Add(rEntry.GetObjectID()); + BOOST_FOREACH(TTaskInfoEntry& rEntry, m_vTaskInfos) + { + m_setRemovedTasks.Add(rEntry.GetObjectID()); + } + m_vTaskInfos.clear(); } - m_vTaskInfos.clear(); -} -TTaskInfoEntry& TTaskInfoContainer::GetAt(size_t stIndex) -{ - if(stIndex >= m_vTaskInfos.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + TTaskInfoEntry& TTaskInfoContainer::GetAt(size_t stIndex) + { + if (stIndex >= m_vTaskInfos.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - return m_vTaskInfos[stIndex]; -} + return m_vTaskInfos[stIndex]; + } -const TTaskInfoEntry& TTaskInfoContainer::GetAt(size_t stIndex) const -{ - if(stIndex >= m_vTaskInfos.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + const TTaskInfoEntry& TTaskInfoContainer::GetAt(size_t stIndex) const + { + if (stIndex >= m_vTaskInfos.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - return m_vTaskInfos[stIndex]; -} + return m_vTaskInfos[stIndex]; + } -size_t TTaskInfoContainer::GetCount() const -{ - return m_vTaskInfos.size(); -} + size_t TTaskInfoContainer::GetCount() const + { + return m_vTaskInfos.size(); + } -bool TTaskInfoContainer::GetByTaskID(taskid_t tTaskID, TTaskInfoEntry& rInfo) const -{ - for(std::vector::const_iterator iter = m_vTaskInfos.begin(); iter != m_vTaskInfos.end(); ++iter) + bool TTaskInfoContainer::GetByTaskID(taskid_t tTaskID, TTaskInfoEntry& rInfo) const { - if((*iter).GetObjectID() == tTaskID) + for (std::vector::const_iterator iter = m_vTaskInfos.begin(); iter != m_vTaskInfos.end(); ++iter) { - rInfo = *iter; - return true; + if ((*iter).GetObjectID() == tTaskID) + { + rInfo = *iter; + return true; + } } + + return false; } - return false; -} + bool TTaskInfoContainer::IsEmpty() const + { + return m_vTaskInfos.empty(); + } -bool TTaskInfoContainer::IsEmpty() const -{ - return m_vTaskInfos.empty(); -} + void TTaskInfoContainer::ClearModifications() + { + m_setRemovedTasks.Clear(); -void TTaskInfoContainer::ClearModifications() -{ - m_setRemovedTasks.Clear(); + BOOST_FOREACH(TTaskInfoEntry& rEntry, m_vTaskInfos) + { + // if marked as added, we don't consider it modified anymore + rEntry.ResetModifications(); + } + } - BOOST_FOREACH(TTaskInfoEntry& rEntry, m_vTaskInfos) + void TTaskInfoContainer::Store(const ISerializerContainerPtr& spContainer) const { - // if marked as added, we don't consider it modified anymore - rEntry.ResetModifications(); - } -} + InitColumns(spContainer); -void TTaskInfoContainer::Store(const ISerializerContainerPtr& spContainer) const -{ - InitColumns(spContainer); + spContainer->DeleteRows(m_setRemovedTasks); + m_setRemovedTasks.Clear(); - spContainer->DeleteRows(m_setRemovedTasks); - m_setRemovedTasks.Clear(); + BOOST_FOREACH(const TTaskInfoEntry& rEntry, m_vTaskInfos) + { + rEntry.Store(spContainer); + } + } - BOOST_FOREACH(const TTaskInfoEntry& rEntry, m_vTaskInfos) + void TTaskInfoContainer::Load(const ISerializerContainerPtr& spContainer) { - rEntry.Store(spContainer); - } -} + InitColumns(spContainer); -void TTaskInfoContainer::Load(const ISerializerContainerPtr& spContainer) -{ - InitColumns(spContainer); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + TTaskInfoEntry tEntry; + while (spRowReader->Next()) + { + tEntry.Load(spRowReader); - TTaskInfoEntry tEntry; - while(spRowReader->Next()) + m_vTaskInfos.push_back(tEntry); + m_oidLastObjectID = std::max(m_oidLastObjectID, tEntry.GetObjectID()); + } + } + + TTaskInfoEntry& TTaskInfoContainer::GetAtOid(object_id_t oidObjectID) { - tEntry.Load(spRowReader); + for (std::vector::iterator iter = m_vTaskInfos.begin(); iter != m_vTaskInfos.end(); ++iter) + { + if ((*iter).GetObjectID() == oidObjectID) + return *iter; + } - m_vTaskInfos.push_back(tEntry); - m_oidLastObjectID = std::max(m_oidLastObjectID, tEntry.GetObjectID()); + THROW_CORE_EXCEPTION(eErr_InvalidArgument); } -} -TTaskInfoEntry& TTaskInfoContainer::GetAtOid(object_id_t oidObjectID) -{ - for(std::vector::iterator iter = m_vTaskInfos.begin(); iter != m_vTaskInfos.end(); ++iter) + void TTaskInfoContainer::InitColumns(const ISerializerContainerPtr& spContainer) const { - if((*iter).GetObjectID() == oidObjectID) - return *iter; + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TTaskInfoEntry::InitColumns(rColumns); } - - THROW_CORE_EXCEPTION(eErr_InvalidArgument); } - -void TTaskInfoContainer::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) - TTaskInfoEntry::InitColumns(rColumns); -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TTaskInfo.h =================================================================== diff -u -N -r95a466ca0a4f95851dcacf2b80e2084e0168b7e4 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskInfo.h (.../TTaskInfo.h) (revision 95a466ca0a4f95851dcacf2b80e2084e0168b7e4) +++ src/libchcore/TTaskInfo.h (.../TTaskInfo.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -29,98 +29,97 @@ #include #include "TSharedModificationTracker.h" -BEGIN_CHCORE_NAMESPACE - -class TTask; -typedef boost::shared_ptr TTaskPtr; - -class LIBCHCORE_API TTaskInfoEntry +namespace chcore { -public: - enum EModifications + class TTask; + typedef boost::shared_ptr TTaskPtr; + + class LIBCHCORE_API TTaskInfoEntry { - eMod_None = 0, - eMod_Added, - eMod_TaskPath, - eMod_Order, + public: + enum EModifications + { + eMod_None = 0, + eMod_Added, + eMod_TaskPath, + eMod_Order, - eMod_Last - }; + eMod_Last + }; -public: - TTaskInfoEntry(); - TTaskInfoEntry(object_id_t oidTaskID, const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask); - TTaskInfoEntry(const TTaskInfoEntry& rSrc); + public: + TTaskInfoEntry(); + TTaskInfoEntry(object_id_t oidTaskID, const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask); + TTaskInfoEntry(const TTaskInfoEntry& rSrc); - TTaskInfoEntry& operator=(const TTaskInfoEntry& rSrc); + TTaskInfoEntry& operator=(const TTaskInfoEntry& rSrc); - object_id_t GetObjectID() const; + object_id_t GetObjectID() const; - TSmartPath GetTaskSerializeLocation() const; - void SetTaskSerializeLocation(const TSmartPath& pathTask); + TSmartPath GetTaskSerializeLocation() const; + void SetTaskSerializeLocation(const TSmartPath& pathTask); - TTaskPtr GetTask() const; - void SetTask(const TTaskPtr& spTask); + TTaskPtr GetTask() const; + void SetTask(const TTaskPtr& spTask); - int GetOrder() const; - void SetOrder(int iOrder); + int GetOrder() const; + void SetOrder(int iOrder); - void Store(const ISerializerContainerPtr& spContainer) const; - static void InitColumns(IColumnsDefinition& rColumnDefs); - void Load(const ISerializerRowReaderPtr& spRowReader); + void Store(const ISerializerContainerPtr& spContainer) const; + static void InitColumns(IColumnsDefinition& rColumnDefs); + void Load(const ISerializerRowReaderPtr& spRowReader); - void ResetModifications(); + void ResetModifications(); -private: + private: #pragma warning(push) #pragma warning(disable:4251) - object_id_t m_oidObjectID; - typedef std::bitset Bitset; - mutable std::bitset m_setModifications; - TSharedModificationTracker m_pathSerializeLocation; - TSharedModificationTracker m_iOrder; + object_id_t m_oidObjectID; + typedef std::bitset Bitset; + mutable std::bitset m_setModifications; + TSharedModificationTracker m_pathSerializeLocation; + TSharedModificationTracker m_iOrder; - TTaskPtr m_spTask; + TTaskPtr m_spTask; #pragma warning(pop) -}; + }; -class LIBCHCORE_API TTaskInfoContainer -{ -public: - TTaskInfoContainer(); + class LIBCHCORE_API TTaskInfoContainer + { + public: + TTaskInfoContainer(); - void Add(const TSmartPath& strPath, int iOrder, const TTaskPtr& spTask); - void RemoveAt(size_t stIndex); + void Add(const TSmartPath& strPath, int iOrder, const TTaskPtr& spTask); + void RemoveAt(size_t stIndex); - TTaskInfoEntry& GetAt(size_t stIndex); - const TTaskInfoEntry& GetAt(size_t stIndex) const; + TTaskInfoEntry& GetAt(size_t stIndex); + const TTaskInfoEntry& GetAt(size_t stIndex) const; - TTaskInfoEntry& GetAtOid(object_id_t oidObjectID); + TTaskInfoEntry& GetAtOid(object_id_t oidObjectID); - bool GetByTaskID(taskid_t tTaskID, TTaskInfoEntry& rInfo) const; + bool GetByTaskID(taskid_t tTaskID, TTaskInfoEntry& rInfo) const; - size_t GetCount() const; - bool IsEmpty() const; + size_t GetCount() const; + bool IsEmpty() const; - void Clear(); + void Clear(); - // modifications management - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); + // modifications management + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); - void InitColumns(const ISerializerContainerPtr& spContainer) const; + void InitColumns(const ISerializerContainerPtr& spContainer) const; - void ClearModifications(); + void ClearModifications(); -private: + private: #pragma warning(push) #pragma warning(disable:4251) - std::vector m_vTaskInfos; - mutable TRemovedObjects m_setRemovedTasks; + std::vector m_vTaskInfos; + mutable TRemovedObjects m_setRemovedTasks; #pragma warning(pop) - object_id_t m_oidLastObjectID; -}; + object_id_t m_oidLastObjectID; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTaskLocalStats.cpp =================================================================== diff -u -N -rcdc76e1a95383dff63a5254aeb8d37035028512c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskLocalStats.cpp (.../TTaskLocalStats.cpp) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/TTaskLocalStats.cpp (.../TTaskLocalStats.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -28,116 +28,115 @@ #include "ISerializerContainer.h" #include "ISerializerRowData.h" -BEGIN_CHCORE_NAMESPACE - -//////////////////////////////////////////////////////////////////////////////// -// TTasksGlobalStats members -TTaskLocalStatsInfo::TTaskLocalStatsInfo() : - m_tTimer(m_setModifications), - m_bTaskIsRunning(false) +namespace chcore { - m_setModifications[eMod_Added] = true; -} + //////////////////////////////////////////////////////////////////////////////// + // TTasksGlobalStats members + TTaskLocalStatsInfo::TTaskLocalStatsInfo() : + m_tTimer(m_setModifications), + m_bTaskIsRunning(false) + { + m_setModifications[eMod_Added] = true; + } -TTaskLocalStatsInfo::~TTaskLocalStatsInfo() -{ -} + TTaskLocalStatsInfo::~TTaskLocalStatsInfo() + { + } -void TTaskLocalStatsInfo::Clear() -{ - m_bTaskIsRunning = false; - m_tTimer.Modify().Reset(); -} + void TTaskLocalStatsInfo::Clear() + { + m_bTaskIsRunning = false; + m_tTimer.Modify().Reset(); + } -void TTaskLocalStatsInfo::GetSnapshot(TTaskStatsSnapshotPtr& spSnapshot) const -{ - boost::upgrade_lock lock(m_lock); - UpdateTime(lock); - spSnapshot->SetTaskRunning(m_bTaskIsRunning); - spSnapshot->SetTimeElapsed(m_tTimer.Get().GetTotalTime()); -} + void TTaskLocalStatsInfo::GetSnapshot(TTaskStatsSnapshotPtr& spSnapshot) const + { + boost::upgrade_lock lock(m_lock); + UpdateTime(lock); + spSnapshot->SetTaskRunning(m_bTaskIsRunning); + spSnapshot->SetTimeElapsed(m_tTimer.Get().GetTotalTime()); + } -void TTaskLocalStatsInfo::MarkAsRunning() -{ - boost::unique_lock lock(m_lock); - m_bTaskIsRunning = true; -} + void TTaskLocalStatsInfo::MarkAsRunning() + { + boost::unique_lock lock(m_lock); + m_bTaskIsRunning = true; + } -void TTaskLocalStatsInfo::MarkAsNotRunning() -{ - boost::unique_lock lock(m_lock); - m_bTaskIsRunning = false; -} + void TTaskLocalStatsInfo::MarkAsNotRunning() + { + boost::unique_lock lock(m_lock); + m_bTaskIsRunning = false; + } -bool TTaskLocalStatsInfo::IsRunning() const -{ - boost::shared_lock lock(m_lock); - return m_bTaskIsRunning; -} + bool TTaskLocalStatsInfo::IsRunning() const + { + boost::shared_lock lock(m_lock); + return m_bTaskIsRunning; + } -void TTaskLocalStatsInfo::EnableTimeTracking() -{ - boost::unique_lock lock(m_lock); - m_tTimer.Modify().Start(); -} + void TTaskLocalStatsInfo::EnableTimeTracking() + { + boost::unique_lock lock(m_lock); + m_tTimer.Modify().Start(); + } -void TTaskLocalStatsInfo::DisableTimeTracking() -{ - boost::unique_lock lock(m_lock); - m_tTimer.Modify().Stop(); -} - -void TTaskLocalStatsInfo::UpdateTime(boost::upgrade_lock& lock) const -{ - // if the timer is not running then there is no point modifying timer object - if(m_tTimer.Get().IsRunning()) + void TTaskLocalStatsInfo::DisableTimeTracking() { - boost::upgrade_to_unique_lock lock_upgraded(lock); - m_tTimer.Modify().Tick(); + boost::unique_lock lock(m_lock); + m_tTimer.Modify().Stop(); } -} -void TTaskLocalStatsInfo::Store(const ISerializerContainerPtr& spContainer) const -{ - boost::shared_lock lock(m_lock); - InitColumns(spContainer); - - bool bAdded = m_setModifications[eMod_Added]; - if(m_setModifications.any()) + void TTaskLocalStatsInfo::UpdateTime(boost::upgrade_lock& lock) const { - ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); - if(bAdded || m_setModifications[eMod_Timer]) + // if the timer is not running then there is no point modifying timer object + if (m_tTimer.Get().IsRunning()) { - rRow.SetValue(_T("elapsed_time"), m_tTimer.Get().GetTotalTime()); - m_setModifications.reset(); + boost::upgrade_to_unique_lock lock_upgraded(lock); + m_tTimer.Modify().Tick(); } } -} -void TTaskLocalStatsInfo::Load(const ISerializerContainerPtr& spContainer) -{ - boost::unique_lock lock(m_lock); + void TTaskLocalStatsInfo::Store(const ISerializerContainerPtr& spContainer) const + { + boost::shared_lock lock(m_lock); + InitColumns(spContainer); - InitColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if(spRowReader->Next()) + bool bAdded = m_setModifications[eMod_Added]; + if (m_setModifications.any()) + { + ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); + if (bAdded || m_setModifications[eMod_Timer]) + { + rRow.SetValue(_T("elapsed_time"), m_tTimer.Get().GetTotalTime()); + m_setModifications.reset(); + } + } + } + + void TTaskLocalStatsInfo::Load(const ISerializerContainerPtr& spContainer) { - unsigned long long ullTime = 0; - spRowReader->GetValue(_T("elapsed_time"), ullTime); - m_tTimer.Modify().Init(ullTime); + boost::unique_lock lock(m_lock); - m_setModifications.reset(); + InitColumns(spContainer); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + { + unsigned long long ullTime = 0; + spRowReader->GetValue(_T("elapsed_time"), ullTime); + m_tTimer.Modify().Init(ullTime); + + m_setModifications.reset(); + } } -} -void TTaskLocalStatsInfo::InitColumns(const ISerializerContainerPtr& spContainer) const -{ - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) + void TTaskLocalStatsInfo::InitColumns(const ISerializerContainerPtr& spContainer) const { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("elapsed_time"), IColumnsDefinition::eType_ulonglong); + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("elapsed_time"), IColumnsDefinition::eType_ulonglong); + } } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TTaskLocalStats.h =================================================================== diff -u -N -r7d59ab9183c933f2fc2682a95fb5d26cf2f952d7 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskLocalStats.h (.../TTaskLocalStats.h) (revision 7d59ab9183c933f2fc2682a95fb5d26cf2f952d7) +++ src/libchcore/TTaskLocalStats.h (.../TTaskLocalStats.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -30,74 +30,73 @@ #include "TSharedModificationTracker.h" #include "IRunningTimeControl.h" -BEGIN_CHCORE_NAMESPACE - -class TTaskLocalStatsInfo; -class TTaskStatsSnapshot; - -class TTaskLocalStatsInfo : public IRunningTimeControl +namespace chcore { -public: - TTaskLocalStatsInfo(); - ~TTaskLocalStatsInfo(); + class TTaskLocalStatsInfo; + class TTaskStatsSnapshot; - void Clear(); - void GetSnapshot(TTaskStatsSnapshotPtr& spSnapshot) const; + class TTaskLocalStatsInfo : public IRunningTimeControl + { + public: + TTaskLocalStatsInfo(); + ~TTaskLocalStatsInfo(); - void SetCurrentSubOperationType(ESubOperationType eSubOperationType); + void Clear(); + void GetSnapshot(TTaskStatsSnapshotPtr& spSnapshot) const; - bool IsRunning() const; + void SetCurrentSubOperationType(ESubOperationType eSubOperationType); - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); + bool IsRunning() const; - void InitColumns(const ISerializerContainerPtr& spContainer) const; + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); -protected: - // running/not running state - virtual void MarkAsRunning() override; - virtual void MarkAsNotRunning() override; + void InitColumns(const ISerializerContainerPtr& spContainer) const; - // time tracking - virtual void EnableTimeTracking() override; - virtual void DisableTimeTracking() override; + protected: + // running/not running state + virtual void MarkAsRunning() override; + virtual void MarkAsNotRunning() override; + // time tracking + virtual void EnableTimeTracking() override; + virtual void DisableTimeTracking() override; + #pragma warning(push) #pragma warning(disable: 4251) - void UpdateTime(boost::upgrade_lock& lock) const; + void UpdateTime(boost::upgrade_lock& lock) const; #pragma warning(pop) - void SetTimeElapsed(unsigned long long timeElapsed); - unsigned long long GetTimeElapsed(); + void SetTimeElapsed(unsigned long long timeElapsed); + unsigned long long GetTimeElapsed(); -private: - TTaskLocalStatsInfo(const TTaskLocalStatsInfo&); - TTaskLocalStatsInfo& operator=(const TTaskLocalStatsInfo&); + private: + TTaskLocalStatsInfo(const TTaskLocalStatsInfo&); + TTaskLocalStatsInfo& operator=(const TTaskLocalStatsInfo&); -private: - enum EModifications - { - eMod_Added, - eMod_Timer, + private: + enum EModifications + { + eMod_Added, + eMod_Timer, - eMod_Last - }; + eMod_Last + }; - typedef std::bitset Bitset; - mutable Bitset m_setModifications; + typedef std::bitset Bitset; + mutable Bitset m_setModifications; - volatile bool m_bTaskIsRunning; + volatile bool m_bTaskIsRunning; - mutable TSharedModificationTracker m_tTimer; + mutable TSharedModificationTracker m_tTimer; #pragma warning(push) #pragma warning(disable: 4251) - mutable boost::shared_mutex m_lock; + mutable boost::shared_mutex m_lock; #pragma warning(pop) - friend class TScopedRunningTimeTracker; -}; + friend class TScopedRunningTimeTracker; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTaskManager.cpp =================================================================== diff -u -N -r2e384de25de613cb582a966df7d1cb9468f1c825 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskManager.cpp (.../TTaskManager.cpp) (revision 2e384de25de613cb582a966df7d1cb9468f1c825) +++ src/libchcore/TTaskManager.cpp (.../TTaskManager.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -29,177 +29,143 @@ #include "SerializerTrace.h" #include "TFakeFileSerializer.h" -BEGIN_CHCORE_NAMESPACE - -//////////////////////////////////////////////////////////////////////////////// -// TTaskManager members -TTaskManager::TTaskManager(const ISerializerFactoryPtr& spSerializerFactory, - const IFeedbackHandlerFactoryPtr& spFeedbackHandlerFactory, - const TSmartPath& pathLogDir, - bool bForceRecreateSerializer) : - m_spSerializerFactory(spSerializerFactory), - m_spFeedbackFactory(spFeedbackHandlerFactory), - m_pathLogDir(pathLogDir) +namespace chcore { - if(!spFeedbackHandlerFactory || !spSerializerFactory) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); - m_spSerializer = m_spSerializerFactory->CreateTaskManagerSerializer(bForceRecreateSerializer); -} - -TTaskManager::~TTaskManager() -{ - // NOTE: do not delete the feedback factory, since we are not responsible for releasing it -} - -TTaskPtr TTaskManager::CreateTask(const TTaskDefinition& tTaskDefinition) -{ - IFeedbackHandlerPtr spHandler = m_spFeedbackFactory->Create(); - ISerializerPtr spSerializer = m_spSerializerFactory->CreateTaskSerializer(tTaskDefinition.GetTaskName()); - - TTaskPtr spTask(new TTask(spSerializer, spHandler)); - spTask->SetLogPath(CreateTaskLogPath(tTaskDefinition.GetTaskName())); - spTask->SetTaskDefinition(tTaskDefinition); - - Add(spTask); - - spTask->Store(); - - return spTask; -} - -TTaskPtr TTaskManager::ImportTask(const TSmartPath& strTaskPath) -{ - // load task definition from the new location - TTaskDefinition tTaskDefinition; - tTaskDefinition.Load(strTaskPath); - - for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + //////////////////////////////////////////////////////////////////////////////// + // TTaskManager members + TTaskManager::TTaskManager(const ISerializerFactoryPtr& spSerializerFactory, + const IFeedbackHandlerFactoryPtr& spFeedbackHandlerFactory, + const TSmartPath& pathLogDir, + bool bForceRecreateSerializer) : + m_spSerializerFactory(spSerializerFactory), + m_spFeedbackFactory(spFeedbackHandlerFactory), + m_pathLogDir(pathLogDir) { - const TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); + if (!spFeedbackHandlerFactory || !spSerializerFactory) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + m_spSerializer = m_spSerializerFactory->CreateTaskManagerSerializer(bForceRecreateSerializer); + } - if (spTask->GetTaskName() == tTaskDefinition.GetTaskName()) - THROW_CORE_EXCEPTION(eErr_TaskAlreadyExists); + TTaskManager::~TTaskManager() + { + // NOTE: do not delete the feedback factory, since we are not responsible for releasing it } - return CreateTask(tTaskDefinition); -} + TTaskPtr TTaskManager::CreateTask(const TTaskDefinition& tTaskDefinition) + { + IFeedbackHandlerPtr spHandler = m_spFeedbackFactory->Create(); + ISerializerPtr spSerializer = m_spSerializerFactory->CreateTaskSerializer(tTaskDefinition.GetTaskName()); -size_t TTaskManager::GetSize() const -{ - boost::shared_lock lock(m_lock); - return m_tTasks.GetCount(); -} + TTaskPtr spTask(new TTask(spSerializer, spHandler)); + spTask->SetLogPath(CreateTaskLogPath(tTaskDefinition.GetTaskName())); + spTask->SetTaskDefinition(tTaskDefinition); -TTaskPtr TTaskManager::GetAt(size_t nIndex) const -{ - boost::shared_lock lock(m_lock); - const TTaskInfoEntry& rInfo = m_tTasks.GetAt(nIndex); - return rInfo.GetTask(); -} + Add(spTask); -TTaskPtr TTaskManager::GetTaskByTaskID(taskid_t tTaskID) const -{ - if(tTaskID == NoTaskID) - return TTaskPtr(); + spTask->Store(); - TTaskInfoEntry tEntry; + return spTask; + } - boost::shared_lock lock(m_lock); + TTaskPtr TTaskManager::ImportTask(const TSmartPath& strTaskPath) + { + // load task definition from the new location + TTaskDefinition tTaskDefinition; + tTaskDefinition.Load(strTaskPath); - if(!m_tTasks.GetByTaskID(tTaskID, tEntry)) - return TTaskPtr(); + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + const TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); - return tEntry.GetTask(); -} + if (spTask->GetTaskName() == tTaskDefinition.GetTaskName()) + THROW_CORE_EXCEPTION(eErr_TaskAlreadyExists); + } -void TTaskManager::Add(const TTaskPtr& spNewTask) -{ - if(!spNewTask) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + return CreateTask(tTaskDefinition); + } - boost::unique_lock lock(m_lock); + size_t TTaskManager::GetSize() const + { + boost::shared_lock lock(m_lock); + return m_tTasks.GetCount(); + } - int iOrder = 1; - if(!m_tTasks.IsEmpty()) + TTaskPtr TTaskManager::GetAt(size_t nIndex) const { - const TTaskInfoEntry& rEntry = m_tTasks.GetAt(m_tTasks.GetCount() - 1); - iOrder = rEntry.GetOrder() + 1; + boost::shared_lock lock(m_lock); + const TTaskInfoEntry& rInfo = m_tTasks.GetAt(nIndex); + return rInfo.GetTask(); } - m_tTasks.Add(spNewTask->GetSerializer()->GetLocation(), iOrder, spNewTask); + TTaskPtr TTaskManager::GetTaskByTaskID(taskid_t tTaskID) const + { + if (tTaskID == NoTaskID) + return TTaskPtr(); - spNewTask->OnRegisterTask(); -} + TTaskInfoEntry tEntry; -void TTaskManager::ClearBeforeExit() -{ - StopAllTasks(); + boost::shared_lock lock(m_lock); - // ensure everything is stored so that we can resume processing in the future - Store(); + if (!m_tTasks.GetByTaskID(tTaskID, tEntry)) + return TTaskPtr(); - // now remove all tasks without serializing anymore (prevent accidental - // serialization) - { - boost::unique_lock lock(m_lock); - m_tTasks.Clear(); - m_tTasks.ClearModifications(); + return tEntry.GetTask(); } -} -void TTaskManager::RemoveAllFinished() -{ - // separate scope for locking + void TTaskManager::Add(const TTaskPtr& spNewTask) { + if (!spNewTask) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); + boost::unique_lock lock(m_lock); - size_t stIndex = m_tTasks.GetCount(); - while(stIndex--) + int iOrder = 1; + if (!m_tTasks.IsEmpty()) { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + const TTaskInfoEntry& rEntry = m_tTasks.GetAt(m_tTasks.GetCount() - 1); + iOrder = rEntry.GetOrder() + 1; + } - // delete only when the thread is finished - ETaskCurrentState eState = spTask->GetTaskState(); + m_tTasks.Add(spNewTask->GetSerializer()->GetLocation(), iOrder, spNewTask); - if((eState == eTaskState_Finished || eState == eTaskState_Cancelled || eState == eTaskState_LoadError)) - { - spTask->KillThread(); + spNewTask->OnRegisterTask(); + } - spTask->OnUnregisterTask(); + void TTaskManager::ClearBeforeExit() + { + StopAllTasks(); - m_tObsoleteFiles.DeleteObsoleteFile(spTask->GetSerializer()->GetLocation()); - m_tObsoleteFiles.DeleteObsoleteFile(spTask->GetLogPath()); + // ensure everything is stored so that we can resume processing in the future + Store(); - m_tTasks.RemoveAt(stIndex); - } + // now remove all tasks without serializing anymore (prevent accidental + // serialization) + { + boost::unique_lock lock(m_lock); + m_tTasks.Clear(); + m_tTasks.ClearModifications(); } } -} -void TTaskManager::RemoveFinished(const TTaskPtr& spSelTask) -{ - // separate scope for locking + void TTaskManager::RemoveAllFinished() { - boost::unique_lock lock(m_lock); - - size_t stIndex = m_tTasks.GetCount(); - while(stIndex--) + // separate scope for locking { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + boost::unique_lock lock(m_lock); - // delete only when the thread is finished - if(spTask == spSelTask) + size_t stIndex = m_tTasks.GetCount(); + while (stIndex--) { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + + // delete only when the thread is finished ETaskCurrentState eState = spTask->GetTaskState(); - if(eState == eTaskState_Finished || eState == eTaskState_Cancelled || eState == eTaskState_LoadError) + if ((eState == eTaskState_Finished || eState == eTaskState_Cancelled || eState == eTaskState_LoadError)) { spTask->KillThread(); @@ -210,331 +176,364 @@ m_tTasks.RemoveAt(stIndex); } - break; } } } -} -void TTaskManager::StopAllTasks() -{ - boost::unique_lock lock(m_lock); + void TTaskManager::RemoveFinished(const TTaskPtr& spSelTask) + { + // separate scope for locking + { + boost::unique_lock lock(m_lock); - StopAllTasksNL(); -} + size_t stIndex = m_tTasks.GetCount(); + while (stIndex--) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); -void TTaskManager::ResumeWaitingTasks(size_t stMaxRunningTasks) -{ - size_t stRunningCount = GetCountOfRunningTasks(); + // delete only when the thread is finished + if (spTask == spSelTask) + { + ETaskCurrentState eState = spTask->GetTaskState(); - boost::shared_lock lock(m_lock); + if (eState == eTaskState_Finished || eState == eTaskState_Cancelled || eState == eTaskState_LoadError) + { + spTask->KillThread(); - size_t stTasksToRun = stMaxRunningTasks == 0 ? std::numeric_limits::max() : stMaxRunningTasks; - stTasksToRun -= stRunningCount; + spTask->OnUnregisterTask(); - if(stTasksToRun > 0) - { - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) - { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + m_tObsoleteFiles.DeleteObsoleteFile(spTask->GetSerializer()->GetLocation()); + m_tObsoleteFiles.DeleteObsoleteFile(spTask->GetLogPath()); - // turn on some thread - find something with wait state - if(spTask->GetTaskState() == eTaskState_Waiting) - { - spTask->SetContinueFlagNL(true); - if(--stTasksToRun == 0) + m_tTasks.RemoveAt(stIndex); + } break; + } } } } -} -void TTaskManager::TasksBeginProcessing() -{ - boost::shared_lock lock(m_lock); - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + void TTaskManager::StopAllTasks() { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spTask->BeginProcessing(); + boost::unique_lock lock(m_lock); + + StopAllTasksNL(); } -} -void TTaskManager::TasksPauseProcessing() -{ - boost::shared_lock lock(m_lock); - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + void TTaskManager::ResumeWaitingTasks(size_t stMaxRunningTasks) { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spTask->PauseProcessing(); + size_t stRunningCount = GetCountOfRunningTasks(); + + boost::shared_lock lock(m_lock); + + size_t stTasksToRun = stMaxRunningTasks == 0 ? std::numeric_limits::max() : stMaxRunningTasks; + stTasksToRun -= stRunningCount; + + if (stTasksToRun > 0) + { + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + + // turn on some thread - find something with wait state + if (spTask->GetTaskState() == eTaskState_Waiting) + { + spTask->SetContinueFlagNL(true); + if (--stTasksToRun == 0) + break; + } + } + } } -} -void TTaskManager::TasksResumeProcessing() -{ - boost::shared_lock lock(m_lock); - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + void TTaskManager::TasksBeginProcessing() { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spTask->ResumeProcessing(); + boost::shared_lock lock(m_lock); + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + spTask->BeginProcessing(); + } } -} -void TTaskManager::TasksRestartProcessing() -{ - boost::shared_lock lock(m_lock); - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + void TTaskManager::TasksPauseProcessing() { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spTask->RestartProcessing(); + boost::shared_lock lock(m_lock); + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + spTask->PauseProcessing(); + } } -} -bool TTaskManager::TasksRetryProcessing() -{ - boost::shared_lock lock(m_lock); - bool bChanged=false; - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + void TTaskManager::TasksResumeProcessing() { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); - if(spTask->RetryProcessing()) - bChanged = true; + boost::shared_lock lock(m_lock); + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + spTask->ResumeProcessing(); + } } - return bChanged; -} - -void TTaskManager::TasksCancelProcessing() -{ - boost::shared_lock lock(m_lock); - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + void TTaskManager::TasksRestartProcessing() { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spTask->CancelProcessing(); + boost::shared_lock lock(m_lock); + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + spTask->RestartProcessing(); + } } -} -bool TTaskManager::AreAllFinished() -{ - bool bFlag=true; - - if(GetCountOfRunningTasks() != 0) - bFlag = false; - else + bool TTaskManager::TasksRetryProcessing() { boost::shared_lock lock(m_lock); - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + bool bChanged = false; + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) { TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) + if (!spTask) THROW_CORE_EXCEPTION(eErr_InvalidPointer); + if (spTask->RetryProcessing()) + bChanged = true; + } - ETaskCurrentState eState = spTask->GetTaskState(); - bFlag = (eState == eTaskState_Finished || eState == eTaskState_Cancelled || eState == eTaskState_Paused || eState == eTaskState_Error || eState == eTaskState_LoadError); + return bChanged; + } - if(!bFlag) - break; + void TTaskManager::TasksCancelProcessing() + { + boost::shared_lock lock(m_lock); + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + spTask->CancelProcessing(); } } - return bFlag; -} + bool TTaskManager::AreAllFinished() + { + bool bFlag = true; -void TTaskManager::GetStatsSnapshot(TTaskManagerStatsSnapshotPtr& spSnapshot) const -{ - if(!spSnapshot) - THROW_CORE_EXCEPTION(eErr_InvalidArgument); + if (GetCountOfRunningTasks() != 0) + bFlag = false; + else + { + boost::shared_lock lock(m_lock); + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spSnapshot->Clear(); + ETaskCurrentState eState = spTask->GetTaskState(); + bFlag = (eState == eTaskState_Finished || eState == eTaskState_Cancelled || eState == eTaskState_Paused || eState == eTaskState_Error || eState == eTaskState_LoadError); - boost::shared_lock lock(m_lock); + if (!bFlag) + break; + } + } - size_t stRunningTasks = 0; - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + return bFlag; + } + + void TTaskManager::GetStatsSnapshot(TTaskManagerStatsSnapshotPtr& spSnapshot) const { - const TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + if (!spSnapshot) + THROW_CORE_EXCEPTION(eErr_InvalidArgument); - TTaskStatsSnapshotPtr spStats(new TTaskStatsSnapshot); - spTask->GetStatsSnapshot(spStats); - spStats->SetTaskID(rEntry.GetObjectID()); + spSnapshot->Clear(); - if(spStats->IsTaskRunning() && spStats->GetTaskState()) - ++stRunningTasks; + boost::shared_lock lock(m_lock); - spSnapshot->AddTaskStats(spStats); - } + size_t stRunningTasks = 0; + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + const TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spSnapshot->SetRunningTasks(stRunningTasks); -} + TTaskStatsSnapshotPtr spStats(new TTaskStatsSnapshot); + spTask->GetStatsSnapshot(spStats); + spStats->SetTaskID(rEntry.GetObjectID()); -size_t TTaskManager::GetCountOfRunningTasks() const -{ - boost::shared_lock lock(m_lock); + if (spStats->IsTaskRunning() && spStats->GetTaskState()) + ++stRunningTasks; - TTaskStatsSnapshot tTaskStats; + spSnapshot->AddTaskStats(spStats); + } - size_t stRunningTasks = 0; + spSnapshot->SetRunningTasks(stRunningTasks); + } - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + size_t TTaskManager::GetCountOfRunningTasks() const { - const TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); + boost::shared_lock lock(m_lock); - if(spTask->IsRunning() && spTask->GetTaskState() == eTaskState_Processing) - ++stRunningTasks; - } + TTaskStatsSnapshot tTaskStats; - return stRunningTasks; -} + size_t stRunningTasks = 0; -void TTaskManager::StopAllTasksNL() -{ - // kill all unfinished tasks - send kill request - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) - { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spTask->RequestStopThread(); - } + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + const TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); - // wait for finishing - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) - { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - TTaskPtr spTask = rEntry.GetTask(); - if(!spTask) - THROW_CORE_EXCEPTION(eErr_InvalidPointer); - spTask->KillThread(); + if (spTask->IsRunning() && spTask->GetTaskState() == eTaskState_Processing) + ++stRunningTasks; + } + + return stRunningTasks; } -} -void TTaskManager::Store() -{ - TSimpleTimer timer(true); - - // store this container information + void TTaskManager::StopAllTasksNL() { - ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("tasks")); + // kill all unfinished tasks - send kill request + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + spTask->RequestStopThread(); + } - boost::shared_lock lock(m_lock); - m_tTasks.Store(spContainer); - - for(size_t stIndex = 0; stIndex != m_tTasks.GetCount(); ++stIndex) + // wait for finishing + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) { - TTaskPtr spTask = m_tTasks.GetAt(stIndex).GetTask(); - spTask->Store(); + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + TTaskPtr spTask = rEntry.GetTask(); + if (!spTask) + THROW_CORE_EXCEPTION(eErr_InvalidPointer); + spTask->KillThread(); } } - // store obsolete info + void TTaskManager::Store() { - ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("obsolete_tasks")); + TSimpleTimer timer(true); - boost::shared_lock lock(m_lock); - m_tObsoleteFiles.Store(spContainer); - } + // store this container information + { + ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("tasks")); - unsigned long long ullGatherTime = timer.Checkpoint(); ullGatherTime; + boost::shared_lock lock(m_lock); + m_tTasks.Store(spContainer); - m_spSerializer->Flush(); + for (size_t stIndex = 0; stIndex != m_tTasks.GetCount(); ++stIndex) + { + TTaskPtr spTask = m_tTasks.GetAt(stIndex).GetTask(); + spTask->Store(); + } + } - unsigned long long ullFlushTime = timer.Stop(); ullFlushTime; - DBTRACE2(_T("TaskManager::Store() - gather: %I64u ms, flush: %I64u ms\n"), ullGatherTime, ullFlushTime); -} + // store obsolete info + { + ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("obsolete_tasks")); -void TTaskManager::Load() -{ - // load list of tasks (without loading tasks themselves) - { - boost::unique_lock lock(m_lock); + boost::shared_lock lock(m_lock); + m_tObsoleteFiles.Store(spContainer); + } - if(!m_tTasks.IsEmpty()) - THROW_CORE_EXCEPTION(eErr_InternalProblem); + unsigned long long ullGatherTime = timer.Checkpoint(); ullGatherTime; - ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("tasks")); - m_tTasks.Load(spContainer); + m_spSerializer->Flush(); + + unsigned long long ullFlushTime = timer.Stop(); ullFlushTime; + DBTRACE2(_T("TaskManager::Store() - gather: %I64u ms, flush: %I64u ms\n"), ullGatherTime, ullFlushTime); } - // load list of task files to delete + void TTaskManager::Load() { - boost::unique_lock lock(m_lock); + // load list of tasks (without loading tasks themselves) + { + boost::unique_lock lock(m_lock); - ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("obsolete_tasks")); - m_tObsoleteFiles.Load(spContainer); // loader also tries to delete files - } + if (!m_tTasks.IsEmpty()) + THROW_CORE_EXCEPTION(eErr_InternalProblem); - // retrieve information about tasks to load - std::vector > vObjects; - { - boost::shared_lock lock(m_lock); + ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("tasks")); + m_tTasks.Load(spContainer); + } - for(size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + // load list of task files to delete { - TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); - if(!rEntry.GetTask()) - vObjects.push_back(std::make_pair(rEntry.GetObjectID(), rEntry.GetTaskSerializeLocation())); + boost::unique_lock lock(m_lock); + + ISerializerContainerPtr spContainer = m_spSerializer->GetContainer(_T("obsolete_tasks")); + m_tObsoleteFiles.Load(spContainer); // loader also tries to delete files } - } - for(const auto& rInfo : vObjects) - { - IFeedbackHandlerPtr spHandler = m_spFeedbackFactory->Create(); - ISerializerPtr spSerializer; - - try + // retrieve information about tasks to load + std::vector > vObjects; { - spSerializer = m_spSerializerFactory->CreateTaskSerializer(rInfo.second.ToWString()); + boost::shared_lock lock(m_lock); + + for (size_t stIndex = 0; stIndex < m_tTasks.GetCount(); ++stIndex) + { + TTaskInfoEntry& rEntry = m_tTasks.GetAt(stIndex); + if (!rEntry.GetTask()) + vObjects.push_back(std::make_pair(rEntry.GetObjectID(), rEntry.GetTaskSerializeLocation())); + } } - catch (const std::exception&) + + for (const auto& rInfo : vObjects) { - // ignore the exception - } + IFeedbackHandlerPtr spHandler = m_spFeedbackFactory->Create(); + ISerializerPtr spSerializer; - if (!spSerializer) - spSerializer = boost::make_shared(rInfo.second); + try + { + spSerializer = m_spSerializerFactory->CreateTaskSerializer(rInfo.second.ToWString()); + } + catch (const std::exception&) + { + // ignore the exception + } - TTaskPtr spTask(new TTask(spSerializer, spHandler)); - spTask->Load(); + if (!spSerializer) + spSerializer = boost::make_shared(rInfo.second); - boost::unique_lock lock(m_lock); + TTaskPtr spTask(new TTask(spSerializer, spHandler)); + spTask->Load(); - TTaskInfoEntry& rInfoEntry = m_tTasks.GetAtOid(rInfo.first); - rInfoEntry.SetTask(spTask); + boost::unique_lock lock(m_lock); + + TTaskInfoEntry& rInfoEntry = m_tTasks.GetAtOid(rInfo.first); + rInfoEntry.SetTask(spTask); + } } -} -TSmartPath TTaskManager::CreateTaskLogPath(const TString& strTaskUuid) const -{ - TSmartPath pathLog = m_pathLogDir + PathFromWString(TString(_T("Task-")) + strTaskUuid + _T(".log")); - return pathLog; + TSmartPath TTaskManager::CreateTaskLogPath(const TString& strTaskUuid) const + { + TSmartPath pathLog = m_pathLogDir + PathFromWString(TString(_T("Task-")) + strTaskUuid + _T(".log")); + return pathLog; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TTaskManager.h =================================================================== diff -u -N -ra99c8baeb8f6c237603df46c0f5c4cf943152c09 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskManager.h (.../TTaskManager.h) (revision a99c8baeb8f6c237603df46c0f5c4cf943152c09) +++ src/libchcore/TTaskManager.h (.../TTaskManager.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -28,84 +28,83 @@ #include "ISerializerFactory.h" #include "TObsoleteFiles.h" -BEGIN_CHCORE_NAMESPACE - -class TTaskDefinition; -class TTask; -typedef boost::shared_ptr TTaskPtr; - -/////////////////////////////////////////////////////////////////////////// -// TTaskManager -class LIBCHCORE_API TTaskManager +namespace chcore { -public: - TTaskManager(const ISerializerFactoryPtr& spSerializerFactory, - const IFeedbackHandlerFactoryPtr& spFeedbackHandlerFactory, - const TSmartPath& pathLogDir, - bool bForceRecreateSerializer = false); + class TTaskDefinition; + class TTask; + typedef boost::shared_ptr TTaskPtr; - ~TTaskManager(); + /////////////////////////////////////////////////////////////////////////// + // TTaskManager + class LIBCHCORE_API TTaskManager + { + public: + TTaskManager(const ISerializerFactoryPtr& spSerializerFactory, + const IFeedbackHandlerFactoryPtr& spFeedbackHandlerFactory, + const TSmartPath& pathLogDir, + bool bForceRecreateSerializer = false); - void Store(); - void Load(); + ~TTaskManager(); - TTaskPtr CreateTask(const TTaskDefinition& tTaskDefinition); + void Store(); + void Load(); - TTaskPtr ImportTask(const TSmartPath& strTaskPath); + TTaskPtr CreateTask(const TTaskDefinition& tTaskDefinition); - size_t GetSize() const; + TTaskPtr ImportTask(const TSmartPath& strTaskPath); - TTaskPtr GetAt(size_t stIndex) const; - TTaskPtr GetTaskByTaskID(taskid_t tTaskID) const; + size_t GetSize() const; - void Add(const TTaskPtr& spNewTask); + TTaskPtr GetAt(size_t stIndex) const; + TTaskPtr GetTaskByTaskID(taskid_t tTaskID) const; - void ClearBeforeExit(); - void RemoveAllFinished(); - void RemoveFinished(const TTaskPtr& spSelTask); + void Add(const TTaskPtr& spNewTask); - void ResumeWaitingTasks(size_t stMaxRunningTasks); - void StopAllTasks(); + void ClearBeforeExit(); + void RemoveAllFinished(); + void RemoveFinished(const TTaskPtr& spSelTask); - void TasksBeginProcessing(); - void TasksPauseProcessing(); - void TasksResumeProcessing(); - void TasksRestartProcessing(); - bool TasksRetryProcessing(); - void TasksCancelProcessing(); + void ResumeWaitingTasks(size_t stMaxRunningTasks); + void StopAllTasks(); - bool AreAllFinished(); + void TasksBeginProcessing(); + void TasksPauseProcessing(); + void TasksResumeProcessing(); + void TasksRestartProcessing(); + bool TasksRetryProcessing(); + void TasksCancelProcessing(); - void GetStatsSnapshot(TTaskManagerStatsSnapshotPtr& spSnapshot) const; - size_t GetCountOfRunningTasks() const; + bool AreAllFinished(); -protected: - void StopAllTasksNL(); + void GetStatsSnapshot(TTaskManagerStatsSnapshotPtr& spSnapshot) const; + size_t GetCountOfRunningTasks() const; - TSmartPath CreateTaskLogPath(const TString& strTaskUuid) const; + protected: + void StopAllTasksNL(); -private: + TSmartPath CreateTaskLogPath(const TString& strTaskUuid) const; + + private: #pragma warning(push) #pragma warning(disable: 4251) - mutable boost::shared_mutex m_lock; + mutable boost::shared_mutex m_lock; #pragma warning(pop) - TTaskInfoContainer m_tTasks; // serializable + TTaskInfoContainer m_tTasks; // serializable - TSmartPath m_pathLogDir; // config-based, not serializable + TSmartPath m_pathLogDir; // config-based, not serializable - TObsoleteFiles m_tObsoleteFiles; + TObsoleteFiles m_tObsoleteFiles; #pragma warning(push) #pragma warning(disable: 4251) - IFeedbackHandlerFactoryPtr m_spFeedbackFactory; - ISerializerPtr m_spSerializer; - ISerializerFactoryPtr m_spSerializerFactory; + IFeedbackHandlerFactoryPtr m_spFeedbackFactory; + ISerializerPtr m_spSerializer; + ISerializerFactoryPtr m_spSerializerFactory; #pragma warning(pop) -}; + }; -typedef boost::shared_ptr TTaskManagerPtr; + typedef boost::shared_ptr TTaskManagerPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTaskManagerStatsSnapshot.cpp =================================================================== diff -u -N -rb1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskManagerStatsSnapshot.cpp (.../TTaskManagerStatsSnapshot.cpp) (revision b1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0) +++ src/libchcore/TTaskManagerStatsSnapshot.cpp (.../TTaskManagerStatsSnapshot.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,183 +24,182 @@ #include "TTaskManagerStatsSnapshot.h" #include "MathFunctions.h" -BEGIN_CHCORE_NAMESPACE - -//////////////////////////////////////////////////////////////////////////////// -// class TTaskManagerStatsSnapshot - -TTaskManagerStatsSnapshot::TTaskManagerStatsSnapshot() : - m_stRunningTasks(0), - m_bCacheFilled(false), - m_ullProcessedCount(0), - m_ullTotalCount(0), - m_ullProcessedSize(0), - m_ullTotalSize(0), - m_dCountSpeed(0.0), - m_dSizeSpeed(0.0), - m_dCombinedProgress(0.0), - m_dAvgCountSpeed(0.0), - m_dAvgSizeSpeed(0.0) +namespace chcore { -} + //////////////////////////////////////////////////////////////////////////////// + // class TTaskManagerStatsSnapshot -void TTaskManagerStatsSnapshot::Clear() -{ - m_stRunningTasks = 0; - m_bCacheFilled = false; - m_ullProcessedCount = 0; - m_ullTotalCount = 0; - m_ullProcessedSize = 0; - m_ullTotalSize = 0; - m_dCountSpeed = 0.0; - m_dSizeSpeed = 0.0; - m_dCombinedProgress = 0.0; - m_dAvgCountSpeed = 0.0; - m_dAvgSizeSpeed = 0.0; + TTaskManagerStatsSnapshot::TTaskManagerStatsSnapshot() : + m_stRunningTasks(0), + m_bCacheFilled(false), + m_ullProcessedCount(0), + m_ullTotalCount(0), + m_ullProcessedSize(0), + m_ullTotalSize(0), + m_dCountSpeed(0.0), + m_dSizeSpeed(0.0), + m_dCombinedProgress(0.0), + m_dAvgCountSpeed(0.0), + m_dAvgSizeSpeed(0.0) + { + } - m_vTasksSnapshots.clear(); -} + void TTaskManagerStatsSnapshot::Clear() + { + m_stRunningTasks = 0; + m_bCacheFilled = false; + m_ullProcessedCount = 0; + m_ullTotalCount = 0; + m_ullProcessedSize = 0; + m_ullTotalSize = 0; + m_dCountSpeed = 0.0; + m_dSizeSpeed = 0.0; + m_dCombinedProgress = 0.0; + m_dAvgCountSpeed = 0.0; + m_dAvgSizeSpeed = 0.0; -void TTaskManagerStatsSnapshot::AddTaskStats(const TTaskStatsSnapshotPtr& spStats) -{ - m_vTasksSnapshots.push_back(spStats); -} + m_vTasksSnapshots.clear(); + } -size_t TTaskManagerStatsSnapshot::GetTaskStatsCount() const -{ - return m_vTasksSnapshots.size(); -} + void TTaskManagerStatsSnapshot::AddTaskStats(const TTaskStatsSnapshotPtr& spStats) + { + m_vTasksSnapshots.push_back(spStats); + } -TTaskStatsSnapshotPtr TTaskManagerStatsSnapshot::GetTaskStatsAt(size_t stIndex) const -{ - if(stIndex >= m_vTasksSnapshots.size()) - return TTaskStatsSnapshotPtr(); + size_t TTaskManagerStatsSnapshot::GetTaskStatsCount() const + { + return m_vTasksSnapshots.size(); + } - return m_vTasksSnapshots[stIndex]; -} - -TTaskStatsSnapshotPtr TTaskManagerStatsSnapshot::GetTaskStatsForTaskID(taskid_t tTaskID) const -{ - BOOST_FOREACH(TTaskStatsSnapshotPtr spStats, m_vTasksSnapshots) + TTaskStatsSnapshotPtr TTaskManagerStatsSnapshot::GetTaskStatsAt(size_t stIndex) const { - if(spStats->GetTaskID() == tTaskID) - return spStats; + if (stIndex >= m_vTasksSnapshots.size()) + return TTaskStatsSnapshotPtr(); + + return m_vTasksSnapshots[stIndex]; } - return TTaskStatsSnapshotPtr(); -} + TTaskStatsSnapshotPtr TTaskManagerStatsSnapshot::GetTaskStatsForTaskID(taskid_t tTaskID) const + { + BOOST_FOREACH(TTaskStatsSnapshotPtr spStats, m_vTasksSnapshots) + { + if (spStats->GetTaskID() == tTaskID) + return spStats; + } + return TTaskStatsSnapshotPtr(); + } -void TTaskManagerStatsSnapshot::CalculateProgressAndSpeeds() const -{ - m_bCacheFilled = false; - m_ullProcessedCount = 0; - m_ullTotalCount = 0; - m_ullProcessedSize = 0; - m_ullTotalSize = 0; - m_dCountSpeed = 0.0; - m_dSizeSpeed = 0.0; - m_dCombinedProgress = 0.0; - m_dAvgCountSpeed = 0.0; - m_dAvgSizeSpeed = 0.0; - BOOST_FOREACH(TTaskStatsSnapshotPtr spTaskStats, m_vTasksSnapshots) + void TTaskManagerStatsSnapshot::CalculateProgressAndSpeeds() const { - m_ullProcessedCount += spTaskStats->GetProcessedCount(); - m_ullTotalCount += spTaskStats->GetTotalCount(); + m_bCacheFilled = false; + m_ullProcessedCount = 0; + m_ullTotalCount = 0; + m_ullProcessedSize = 0; + m_ullTotalSize = 0; + m_dCountSpeed = 0.0; + m_dSizeSpeed = 0.0; + m_dCombinedProgress = 0.0; + m_dAvgCountSpeed = 0.0; + m_dAvgSizeSpeed = 0.0; - m_ullProcessedSize += spTaskStats->GetProcessedSize(); - m_ullTotalSize += spTaskStats->GetTotalSize(); + BOOST_FOREACH(TTaskStatsSnapshotPtr spTaskStats, m_vTasksSnapshots) + { + m_ullProcessedCount += spTaskStats->GetProcessedCount(); + m_ullTotalCount += spTaskStats->GetTotalCount(); - m_dCountSpeed += spTaskStats->GetCountSpeed(); - m_dSizeSpeed += spTaskStats->GetSizeSpeed(); + m_ullProcessedSize += spTaskStats->GetProcessedSize(); + m_ullTotalSize += spTaskStats->GetTotalSize(); - m_dAvgCountSpeed += spTaskStats->GetAvgCountSpeed(); - m_dAvgSizeSpeed += spTaskStats->GetAvgSizeSpeed(); - } + m_dCountSpeed += spTaskStats->GetCountSpeed(); + m_dSizeSpeed += spTaskStats->GetSizeSpeed(); - // we're treating each of the items as 512B object to process - // to have some balance between items' count and items' size in - // progress information - unsigned long long ullProcessed = 512ULL * m_ullProcessedCount + m_ullProcessedSize; - unsigned long long ullTotal = 512ULL * m_ullTotalCount + m_ullTotalSize; + m_dAvgCountSpeed += spTaskStats->GetAvgCountSpeed(); + m_dAvgSizeSpeed += spTaskStats->GetAvgSizeSpeed(); + } - if(ullTotal != 0) - m_dCombinedProgress = Math::Div64(ullProcessed, ullTotal); + // we're treating each of the items as 512B object to process + // to have some balance between items' count and items' size in + // progress information + unsigned long long ullProcessed = 512ULL * m_ullProcessedCount + m_ullProcessedSize; + unsigned long long ullTotal = 512ULL * m_ullTotalCount + m_ullTotalSize; - m_bCacheFilled = true; -} + if (ullTotal != 0) + m_dCombinedProgress = Math::Div64(ullProcessed, ullTotal); -unsigned long long TTaskManagerStatsSnapshot::GetProcessedCount() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + m_bCacheFilled = true; + } - return m_ullProcessedCount; -} + unsigned long long TTaskManagerStatsSnapshot::GetProcessedCount() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -unsigned long long TTaskManagerStatsSnapshot::GetTotalCount() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_ullProcessedCount; + } - return m_ullTotalCount; -} + unsigned long long TTaskManagerStatsSnapshot::GetTotalCount() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -unsigned long long TTaskManagerStatsSnapshot::GetProcessedSize() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_ullTotalCount; + } - return m_ullProcessedSize; -} + unsigned long long TTaskManagerStatsSnapshot::GetProcessedSize() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -unsigned long long TTaskManagerStatsSnapshot::GetTotalSize() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_ullProcessedSize; + } - return m_ullTotalSize; -} + unsigned long long TTaskManagerStatsSnapshot::GetTotalSize() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskManagerStatsSnapshot::GetCountSpeed() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_ullTotalSize; + } - return m_dCountSpeed; -} + double TTaskManagerStatsSnapshot::GetCountSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskManagerStatsSnapshot::GetSizeSpeed() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_dCountSpeed; + } - return m_dSizeSpeed; -} + double TTaskManagerStatsSnapshot::GetSizeSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskManagerStatsSnapshot::GetCombinedProgress() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_dSizeSpeed; + } - return m_dCombinedProgress; -} + double TTaskManagerStatsSnapshot::GetCombinedProgress() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskManagerStatsSnapshot::GetAvgCountSpeed() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_dCombinedProgress; + } - return m_dAvgCountSpeed; -} + double TTaskManagerStatsSnapshot::GetAvgCountSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskManagerStatsSnapshot::GetAvgSizeSpeed() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_dAvgCountSpeed; + } - return m_dAvgSizeSpeed; -} + double TTaskManagerStatsSnapshot::GetAvgSizeSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -END_CHCORE_NAMESPACE + return m_dAvgSizeSpeed; + } +} Index: src/libchcore/TTaskManagerStatsSnapshot.h =================================================================== diff -u -N -rb1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskManagerStatsSnapshot.h (.../TTaskManagerStatsSnapshot.h) (revision b1ecc12ba4c1f2a7b4acd6e82fc4193535e55ff0) +++ src/libchcore/TTaskManagerStatsSnapshot.h (.../TTaskManagerStatsSnapshot.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -26,67 +26,66 @@ #include "libchcore.h" #include "TTaskStatsSnapshot.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TTaskManagerStatsSnapshot +namespace chcore { -public: - TTaskManagerStatsSnapshot(); - TTaskManagerStatsSnapshot(const TTaskManagerStatsSnapshot& rSrc); + class LIBCHCORE_API TTaskManagerStatsSnapshot + { + public: + TTaskManagerStatsSnapshot(); + TTaskManagerStatsSnapshot(const TTaskManagerStatsSnapshot& rSrc); - TTaskManagerStatsSnapshot& operator=(const TTaskManagerStatsSnapshot& rSrc); + TTaskManagerStatsSnapshot& operator=(const TTaskManagerStatsSnapshot& rSrc); - void Clear(); + void Clear(); - void AddTaskStats(const TTaskStatsSnapshotPtr& spStats); - size_t GetTaskStatsCount() const; - TTaskStatsSnapshotPtr GetTaskStatsAt(size_t stIndex) const; - TTaskStatsSnapshotPtr GetTaskStatsForTaskID(taskid_t tTaskID) const; + void AddTaskStats(const TTaskStatsSnapshotPtr& spStats); + size_t GetTaskStatsCount() const; + TTaskStatsSnapshotPtr GetTaskStatsAt(size_t stIndex) const; + TTaskStatsSnapshotPtr GetTaskStatsForTaskID(taskid_t tTaskID) const; - size_t GetRunningTasks() const { return m_stRunningTasks; } - void SetRunningTasks(size_t stRunningTasks) { m_stRunningTasks = stRunningTasks; } + size_t GetRunningTasks() const { return m_stRunningTasks; } + void SetRunningTasks(size_t stRunningTasks) { m_stRunningTasks = stRunningTasks; } - unsigned long long GetProcessedCount() const; - unsigned long long GetTotalCount() const; - unsigned long long GetProcessedSize() const; - unsigned long long GetTotalSize() const; + unsigned long long GetProcessedCount() const; + unsigned long long GetTotalCount() const; + unsigned long long GetProcessedSize() const; + unsigned long long GetTotalSize() const; - double GetCountSpeed() const; - double GetAvgCountSpeed() const; - double GetSizeSpeed() const; - double GetAvgSizeSpeed() const; + double GetCountSpeed() const; + double GetAvgCountSpeed() const; + double GetSizeSpeed() const; + double GetAvgSizeSpeed() const; - double GetCombinedProgress() const; + double GetCombinedProgress() const; -private: - void CalculateProgressAndSpeeds() const; + private: + void CalculateProgressAndSpeeds() const; -private: - size_t m_stRunningTasks; + private: + size_t m_stRunningTasks; #pragma warning(push) #pragma warning(disable: 4251) - std::vector m_vTasksSnapshots; + std::vector m_vTasksSnapshots; #pragma warning(pop) - // cache for items calculated on-demand - mutable bool m_bCacheFilled; - mutable unsigned long long m_ullProcessedCount; - mutable unsigned long long m_ullTotalCount; - mutable unsigned long long m_ullProcessedSize; - mutable unsigned long long m_ullTotalSize; + // cache for items calculated on-demand + mutable bool m_bCacheFilled; + mutable unsigned long long m_ullProcessedCount; + mutable unsigned long long m_ullTotalCount; + mutable unsigned long long m_ullProcessedSize; + mutable unsigned long long m_ullTotalSize; - mutable double m_dCountSpeed; - mutable double m_dSizeSpeed; + mutable double m_dCountSpeed; + mutable double m_dSizeSpeed; - mutable double m_dAvgCountSpeed; - mutable double m_dAvgSizeSpeed; + mutable double m_dAvgCountSpeed; + mutable double m_dAvgSizeSpeed; - mutable double m_dCombinedProgress; -}; + mutable double m_dCombinedProgress; + }; -typedef boost::shared_ptr TTaskManagerStatsSnapshotPtr; + typedef boost::shared_ptr TTaskManagerStatsSnapshotPtr; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTaskOperationPlan.cpp =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskOperationPlan.cpp (.../TTaskOperationPlan.cpp) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TTaskOperationPlan.cpp (.../TTaskOperationPlan.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,62 +25,62 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -//////////////////////////////////////////////////////////////////////////// -// class TOperationPlan - -TOperationPlan::TOperationPlan() : - m_eOperation(eOperation_None) +namespace chcore { -} + //////////////////////////////////////////////////////////////////////////// + // class TOperationPlan -TOperationPlan::TOperationPlan(const TOperationPlan& rSrc) : -m_eOperation(eOperation_None), - m_vSubOperations() -{ - boost::shared_lock src_lock(rSrc.m_lock); + TOperationPlan::TOperationPlan() : + m_eOperation(eOperation_None) + { + } - m_eOperation = rSrc.m_eOperation; - m_vSubOperations = rSrc.m_vSubOperations; -} - -TOperationPlan::~TOperationPlan() -{ -} - -TOperationPlan& TOperationPlan::operator=(const TOperationPlan& rSrc) -{ - if(this != &rSrc) + TOperationPlan::TOperationPlan(const TOperationPlan& rSrc) : + m_eOperation(eOperation_None), + m_vSubOperations() { boost::shared_lock src_lock(rSrc.m_lock); - boost::unique_lock lock(m_lock); m_eOperation = rSrc.m_eOperation; m_vSubOperations = rSrc.m_vSubOperations; } - return *this; -} + TOperationPlan::~TOperationPlan() + { + } -void TOperationPlan::SetOperationType(EOperationType eOperation) -{ - switch(eOperation) + TOperationPlan& TOperationPlan::operator=(const TOperationPlan& rSrc) { - case eOperation_None: - THROW_CORE_EXCEPTION(eErr_InvalidArgument); - break; + if (this != &rSrc) + { + boost::shared_lock src_lock(rSrc.m_lock); + boost::unique_lock lock(m_lock); - case eOperation_Copy: + m_eOperation = rSrc.m_eOperation; + m_vSubOperations = rSrc.m_vSubOperations; + } + + return *this; + } + + void TOperationPlan::SetOperationType(EOperationType eOperation) + { + switch (eOperation) { + case eOperation_None: + THROW_CORE_EXCEPTION(eErr_InvalidArgument); + break; + + case eOperation_Copy: + { boost::unique_lock lock(m_lock); m_vSubOperations.clear(); m_vSubOperations.push_back(std::make_pair(eSubOperation_Scanning, 0.05)); m_vSubOperations.push_back(std::make_pair(eSubOperation_Copying, 0.95)); break; } - case eOperation_Move: + case eOperation_Move: { boost::unique_lock lock(m_lock); m_vSubOperations.clear(); @@ -90,43 +90,42 @@ break; } - BOOST_STATIC_ASSERT(eOperation_Move == eOperation_Max - 1); + BOOST_STATIC_ASSERT(eOperation_Move == eOperation_Max - 1); - default: - THROW_CORE_EXCEPTION(eErr_UnhandledCase); + default: + THROW_CORE_EXCEPTION(eErr_UnhandledCase); + } + + m_eOperation = eOperation; } - m_eOperation = eOperation; -} + EOperationType TOperationPlan::GetOperationType() const + { + boost::shared_lock lock(m_lock); + return m_eOperation; + } -EOperationType TOperationPlan::GetOperationType() const -{ - boost::shared_lock lock(m_lock); - return m_eOperation; -} + size_t TOperationPlan::GetSubOperationsCount() const + { + boost::shared_lock lock(m_lock); + return m_vSubOperations.size(); + } -size_t TOperationPlan::GetSubOperationsCount() const -{ - boost::shared_lock lock(m_lock); - return m_vSubOperations.size(); -} + ESubOperationType TOperationPlan::GetSubOperationAt(size_t stIndex) const + { + boost::shared_lock lock(m_lock); + if (stIndex >= m_vSubOperations.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + else + return m_vSubOperations[stIndex].first; + } -ESubOperationType TOperationPlan::GetSubOperationAt(size_t stIndex) const -{ - boost::shared_lock lock(m_lock); - if(stIndex >= m_vSubOperations.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - else - return m_vSubOperations[stIndex].first; + double TOperationPlan::GetEstimatedTimeAt(size_t stIndex) const + { + boost::shared_lock lock(m_lock); + if (stIndex >= m_vSubOperations.size()) + THROW_CORE_EXCEPTION(eErr_BoundsExceeded); + else + return m_vSubOperations[stIndex].second; + } } - -double TOperationPlan::GetEstimatedTimeAt(size_t stIndex) const -{ - boost::shared_lock lock(m_lock); - if(stIndex >= m_vSubOperations.size()) - THROW_CORE_EXCEPTION(eErr_BoundsExceeded); - else - return m_vSubOperations[stIndex].second; -} - -END_CHCORE_NAMESPACE Index: src/libchcore/TTaskOperationPlan.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskOperationPlan.h (.../TTaskOperationPlan.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TTaskOperationPlan.h (.../TTaskOperationPlan.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -27,39 +27,38 @@ #include "EOperationTypes.h" #include "ESubTaskTypes.h" -BEGIN_CHCORE_NAMESPACE - -/////////////////////////////////////////////////////////////////////////// -// TOperationPlan - -// class describes the sub-operations to be performed -class LIBCHCORE_API TOperationPlan +namespace chcore { -public: - TOperationPlan(); - TOperationPlan(const TOperationPlan& rSrc); - ~TOperationPlan(); + /////////////////////////////////////////////////////////////////////////// + // TOperationPlan - TOperationPlan& operator=(const TOperationPlan& rSrc); + // class describes the sub-operations to be performed + class LIBCHCORE_API TOperationPlan + { + public: + TOperationPlan(); + TOperationPlan(const TOperationPlan& rSrc); + ~TOperationPlan(); - void SetOperationType(EOperationType eOperation); - EOperationType GetOperationType() const; + TOperationPlan& operator=(const TOperationPlan& rSrc); -private: - size_t GetSubOperationsCount() const; - ESubOperationType GetSubOperationAt(size_t stIndex) const; - double GetEstimatedTimeAt(size_t stIndex) const; + void SetOperationType(EOperationType eOperation); + EOperationType GetOperationType() const; -private: - EOperationType m_eOperation; + private: + size_t GetSubOperationsCount() const; + ESubOperationType GetSubOperationAt(size_t stIndex) const; + double GetEstimatedTimeAt(size_t stIndex) const; + + private: + EOperationType m_eOperation; #pragma warning(push) #pragma warning(disable: 4251) - std::vector > m_vSubOperations; ///< Vector of sub-task type and estimated part in the entire task time + std::vector > m_vSubOperations; ///< Vector of sub-task type and estimated part in the entire task time - mutable boost::shared_mutex m_lock; + mutable boost::shared_mutex m_lock; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TTaskStatsSnapshot.cpp =================================================================== diff -u -N -rcdc76e1a95383dff63a5254aeb8d37035028512c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskStatsSnapshot.cpp (.../TTaskStatsSnapshot.cpp) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/TTaskStatsSnapshot.cpp (.../TTaskStatsSnapshot.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -24,190 +24,189 @@ #include "TTaskStatsSnapshot.h" #include "MathFunctions.h" -BEGIN_CHCORE_NAMESPACE - -//////////////////////////////////////////////////////////////////////////////// -// TTaskStatsSnapshot members - -TTaskStatsSnapshot::TTaskStatsSnapshot() : - m_tSubTasksStats(), - m_bTaskIsRunning(false), - m_ullTimeElapsed(0), - m_iThreadPriority(0), - m_strDestinationPath(), - m_filters(), - m_eTaskState(eTaskState_None), - m_strTaskID(), - m_eOperationType(eOperation_None), - m_bIgnoreDirectories(false), - m_bCreateEmptyFiles(false), - m_ullCurrentBufferSize(0), - m_bCacheFilled(false), - m_ullProcessedCount(0), - m_ullTotalCount(0), - m_ullProcessedSize(0), - m_ullTotalSize(0), - m_dTaskCountSpeed(0.0), - m_dTaskSizeSpeed(0.0), - m_dCombinedProgress(0.0), - m_uiBufferCount(0) +namespace chcore { -} + //////////////////////////////////////////////////////////////////////////////// + // TTaskStatsSnapshot members -void TTaskStatsSnapshot::Clear() -{ - m_tSubTasksStats.Clear(); - m_bTaskIsRunning = false; - m_ullTimeElapsed = 0; - m_iThreadPriority = 0; - m_strDestinationPath.Clear(); - m_filters.Clear(); - m_eTaskState = eTaskState_None; - m_strTaskID.Clear(); - m_eOperationType = eOperation_None; - m_bIgnoreDirectories = false; - m_bCreateEmptyFiles = false; - m_ullCurrentBufferSize = 0; - m_bCacheFilled = false; - m_ullProcessedCount = 0; - m_ullTotalCount = 0; - m_ullProcessedSize = 0; - m_ullTotalSize = 0; - m_dTaskCountSpeed = 0.0; - m_dTaskSizeSpeed = 0.0; - m_dCombinedProgress = 0.0; - m_uiBufferCount = 0; -} + TTaskStatsSnapshot::TTaskStatsSnapshot() : + m_tSubTasksStats(), + m_bTaskIsRunning(false), + m_ullTimeElapsed(0), + m_iThreadPriority(0), + m_strDestinationPath(), + m_filters(), + m_eTaskState(eTaskState_None), + m_strTaskID(), + m_eOperationType(eOperation_None), + m_bIgnoreDirectories(false), + m_bCreateEmptyFiles(false), + m_ullCurrentBufferSize(0), + m_bCacheFilled(false), + m_ullProcessedCount(0), + m_ullTotalCount(0), + m_ullProcessedSize(0), + m_ullTotalSize(0), + m_dTaskCountSpeed(0.0), + m_dTaskSizeSpeed(0.0), + m_dCombinedProgress(0.0), + m_uiBufferCount(0) + { + } -void TTaskStatsSnapshot::CalculateProgressAndSpeeds() const -{ - m_bCacheFilled = false; - m_ullProcessedCount = 0; - m_ullTotalCount = 0; - m_ullProcessedSize = 0; - m_ullTotalSize = 0; - m_dTaskCountSpeed = 0.0; - m_dTaskSizeSpeed = 0.0; - m_dCombinedProgress = 0.0; + void TTaskStatsSnapshot::Clear() + { + m_tSubTasksStats.Clear(); + m_bTaskIsRunning = false; + m_ullTimeElapsed = 0; + m_iThreadPriority = 0; + m_strDestinationPath.Clear(); + m_filters.Clear(); + m_eTaskState = eTaskState_None; + m_strTaskID.Clear(); + m_eOperationType = eOperation_None; + m_bIgnoreDirectories = false; + m_bCreateEmptyFiles = false; + m_ullCurrentBufferSize = 0; + m_bCacheFilled = false; + m_ullProcessedCount = 0; + m_ullTotalCount = 0; + m_ullProcessedSize = 0; + m_ullTotalSize = 0; + m_dTaskCountSpeed = 0.0; + m_dTaskSizeSpeed = 0.0; + m_dCombinedProgress = 0.0; + m_uiBufferCount = 0; + } - size_t stCount = m_tSubTasksStats.GetSubTaskSnapshotCount(); - for(size_t stIndex = 0; stIndex < stCount; ++stIndex) + void TTaskStatsSnapshot::CalculateProgressAndSpeeds() const { - TSubTaskStatsSnapshotPtr spSubtaskStats = m_tSubTasksStats.GetSubTaskSnapshotAt(stIndex); + m_bCacheFilled = false; + m_ullProcessedCount = 0; + m_ullTotalCount = 0; + m_ullProcessedSize = 0; + m_ullTotalSize = 0; + m_dTaskCountSpeed = 0.0; + m_dTaskSizeSpeed = 0.0; + m_dCombinedProgress = 0.0; - m_ullProcessedCount += spSubtaskStats->GetProcessedCount(); - m_ullTotalCount += spSubtaskStats->GetTotalCount(); + size_t stCount = m_tSubTasksStats.GetSubTaskSnapshotCount(); + for (size_t stIndex = 0; stIndex < stCount; ++stIndex) + { + TSubTaskStatsSnapshotPtr spSubtaskStats = m_tSubTasksStats.GetSubTaskSnapshotAt(stIndex); - m_ullProcessedSize += spSubtaskStats->GetProcessedSize(); - m_ullTotalSize += spSubtaskStats->GetTotalSize(); + m_ullProcessedCount += spSubtaskStats->GetProcessedCount(); + m_ullTotalCount += spSubtaskStats->GetTotalCount(); - m_dTaskCountSpeed += spSubtaskStats->GetCountSpeed(); - m_dTaskSizeSpeed += spSubtaskStats->GetSizeSpeed(); - } + m_ullProcessedSize += spSubtaskStats->GetProcessedSize(); + m_ullTotalSize += spSubtaskStats->GetTotalSize(); - // we're treating each of the items as 512B object to process - // to have some balance between items' count and items' size in - // progress information - unsigned long long ullProcessed = 512ULL * m_ullProcessedCount + m_ullProcessedSize; - unsigned long long ullTotal = 512ULL * m_ullTotalCount + m_ullTotalSize; + m_dTaskCountSpeed += spSubtaskStats->GetCountSpeed(); + m_dTaskSizeSpeed += spSubtaskStats->GetSizeSpeed(); + } - if(ullTotal != 0) - m_dCombinedProgress = Math::Div64(ullProcessed, ullTotal); + // we're treating each of the items as 512B object to process + // to have some balance between items' count and items' size in + // progress information + unsigned long long ullProcessed = 512ULL * m_ullProcessedCount + m_ullProcessedSize; + unsigned long long ullTotal = 512ULL * m_ullTotalCount + m_ullTotalSize; - m_bCacheFilled = true; -} + if (ullTotal != 0) + m_dCombinedProgress = Math::Div64(ullProcessed, ullTotal); -unsigned long long TTaskStatsSnapshot::GetProcessedCount() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + m_bCacheFilled = true; + } - return m_ullProcessedCount; -} + unsigned long long TTaskStatsSnapshot::GetProcessedCount() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -unsigned long long TTaskStatsSnapshot::GetTotalCount() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_ullProcessedCount; + } - return m_ullTotalCount; -} + unsigned long long TTaskStatsSnapshot::GetTotalCount() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -unsigned long long TTaskStatsSnapshot::GetProcessedSize() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_ullTotalCount; + } - return m_ullProcessedSize; -} + unsigned long long TTaskStatsSnapshot::GetProcessedSize() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -unsigned long long TTaskStatsSnapshot::GetTotalSize() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_ullProcessedSize; + } - return m_ullTotalSize; -} + unsigned long long TTaskStatsSnapshot::GetTotalSize() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskStatsSnapshot::GetCountSpeed() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_ullTotalSize; + } - return m_dTaskCountSpeed; -} + double TTaskStatsSnapshot::GetCountSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskStatsSnapshot::GetSizeSpeed() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_dTaskCountSpeed; + } - return m_dTaskSizeSpeed; -} + double TTaskStatsSnapshot::GetSizeSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskStatsSnapshot::GetCombinedProgress() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_dTaskSizeSpeed; + } - return m_dCombinedProgress; -} + double TTaskStatsSnapshot::GetCombinedProgress() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskStatsSnapshot::GetAvgCountSpeed() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + return m_dCombinedProgress; + } - if(m_ullTimeElapsed) - return Math::Div64(m_ullProcessedCount, m_ullTimeElapsed / 1000); - else - return 0.0; -} + double TTaskStatsSnapshot::GetAvgCountSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -double TTaskStatsSnapshot::GetAvgSizeSpeed() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + if (m_ullTimeElapsed) + return Math::Div64(m_ullProcessedCount, m_ullTimeElapsed / 1000); + else + return 0.0; + } - if(m_ullTimeElapsed) - return Math::Div64(m_ullProcessedSize, m_ullTimeElapsed / 1000); - else - return 0.0; -} + double TTaskStatsSnapshot::GetAvgSizeSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); -unsigned long long TTaskStatsSnapshot::GetEstimatedTotalTime() const -{ - if(!m_bCacheFilled) - CalculateProgressAndSpeeds(); + if (m_ullTimeElapsed) + return Math::Div64(m_ullProcessedSize, m_ullTimeElapsed / 1000); + else + return 0.0; + } - double dProgress = 0.0; - if(m_ullTotalSize != 0) - dProgress = Math::Div64(m_ullProcessedSize, m_ullTotalSize); + unsigned long long TTaskStatsSnapshot::GetEstimatedTotalTime() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); - if(dProgress == 0.0) - return std::numeric_limits::max(); - else - return (unsigned long long)(m_ullTimeElapsed * (1.0 / dProgress)); -} + double dProgress = 0.0; + if (m_ullTotalSize != 0) + dProgress = Math::Div64(m_ullProcessedSize, m_ullTotalSize); -END_CHCORE_NAMESPACE + if (dProgress == 0.0) + return std::numeric_limits::max(); + else + return (unsigned long long)(m_ullTimeElapsed * (1.0 / dProgress)); + } +} Index: src/libchcore/TTaskStatsSnapshot.h =================================================================== diff -u -N -rcdc76e1a95383dff63a5254aeb8d37035028512c -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTaskStatsSnapshot.h (.../TTaskStatsSnapshot.h) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/TTaskStatsSnapshot.h (.../TTaskStatsSnapshot.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -32,114 +32,113 @@ #include "ETaskCurrentState.h" #include "TaskID.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TTaskStatsSnapshot +namespace chcore { -public: - TTaskStatsSnapshot(); + class LIBCHCORE_API TTaskStatsSnapshot + { + public: + TTaskStatsSnapshot(); - void Clear(); + void Clear(); - // task ID - taskid_t GetTaskID() const { return m_tTaskID; } - void SetTaskID(taskid_t val) { m_tTaskID = val; } + // task ID + taskid_t GetTaskID() const { return m_tTaskID; } + void SetTaskID(taskid_t val) { m_tTaskID = val; } - // subtasks' stats - const TSubTaskArrayStatsSnapshot& GetSubTasksStats() const { return m_tSubTasksStats; } - TSubTaskArrayStatsSnapshot& GetSubTasksStats() { return m_tSubTasksStats; } + // subtasks' stats + const TSubTaskArrayStatsSnapshot& GetSubTasksStats() const { return m_tSubTasksStats; } + TSubTaskArrayStatsSnapshot& GetSubTasksStats() { return m_tSubTasksStats; } - // task running - bool IsTaskRunning() const { return m_bTaskIsRunning; } - void SetTaskRunning(bool bRunning) { m_bTaskIsRunning = bRunning; } + // task running + bool IsTaskRunning() const { return m_bTaskIsRunning; } + void SetTaskRunning(bool bRunning) { m_bTaskIsRunning = bRunning; } - // time elapsed - unsigned long long GetTimeElapsed() const { return m_ullTimeElapsed; } - void SetTimeElapsed(unsigned long long ullTimeElapsed) { m_ullTimeElapsed = ullTimeElapsed; } - unsigned long long GetEstimatedTotalTime() const; + // time elapsed + unsigned long long GetTimeElapsed() const { return m_ullTimeElapsed; } + void SetTimeElapsed(unsigned long long ullTimeElapsed) { m_ullTimeElapsed = ullTimeElapsed; } + unsigned long long GetEstimatedTotalTime() const; - // speed and progress - unsigned long long GetProcessedCount() const; - unsigned long long GetTotalCount() const; - unsigned long long GetProcessedSize() const; - unsigned long long GetTotalSize() const; + // speed and progress + unsigned long long GetProcessedCount() const; + unsigned long long GetTotalCount() const; + unsigned long long GetProcessedSize() const; + unsigned long long GetTotalSize() const; - double GetCountSpeed() const; - double GetSizeSpeed() const; - double GetAvgCountSpeed() const; - double GetAvgSizeSpeed() const; + double GetCountSpeed() const; + double GetSizeSpeed() const; + double GetAvgCountSpeed() const; + double GetAvgSizeSpeed() const; - double GetCombinedProgress() const; + double GetCombinedProgress() const; - // other properties - int GetThreadPriority() const { return m_iThreadPriority; } - void SetThreadPriority(int val) { m_iThreadPriority = val; } - - TString GetDestinationPath() const { return m_strDestinationPath; } - void SetDestinationPath(const TString& val) { m_strDestinationPath = val; } + // other properties + int GetThreadPriority() const { return m_iThreadPriority; } + void SetThreadPriority(int val) { m_iThreadPriority = val; } - const TFileFiltersArray& GetFilters() const { return m_filters; } - void SetFilters(const TFileFiltersArray& val) { m_filters = val; } + TString GetDestinationPath() const { return m_strDestinationPath; } + void SetDestinationPath(const TString& val) { m_strDestinationPath = val; } - ETaskCurrentState GetTaskState() const { return m_eTaskState; } - void SetTaskState(ETaskCurrentState val) { m_eTaskState = val; } + const TFileFiltersArray& GetFilters() const { return m_filters; } + void SetFilters(const TFileFiltersArray& val) { m_filters = val; } - TString GetTaskName() const { return m_strTaskID; } - void SetTaskName(const TString& val) { m_strTaskID = val; } + ETaskCurrentState GetTaskState() const { return m_eTaskState; } + void SetTaskState(ETaskCurrentState val) { m_eTaskState = val; } - EOperationType GetOperationType() const { return m_eOperationType; } - void SetOperationType(EOperationType val) { m_eOperationType = val; } + TString GetTaskName() const { return m_strTaskID; } + void SetTaskName(const TString& val) { m_strTaskID = val; } - bool GetIgnoreDirectories() const { return m_bIgnoreDirectories; } - void SetIgnoreDirectories(bool val) { m_bIgnoreDirectories = val; } + EOperationType GetOperationType() const { return m_eOperationType; } + void SetOperationType(EOperationType val) { m_eOperationType = val; } - bool GetCreateEmptyFiles() const { return m_bCreateEmptyFiles; } - void SetCreateEmptyFiles(bool val) { m_bCreateEmptyFiles = val; } + bool GetIgnoreDirectories() const { return m_bIgnoreDirectories; } + void SetIgnoreDirectories(bool val) { m_bIgnoreDirectories = val; } - void SetCurrentBufferSize(unsigned long long ullSize) { m_ullCurrentBufferSize = ullSize; } - unsigned long long GetCurrentBufferSize() const { return m_ullCurrentBufferSize; } + bool GetCreateEmptyFiles() const { return m_bCreateEmptyFiles; } + void SetCreateEmptyFiles(bool val) { m_bCreateEmptyFiles = val; } - unsigned int GetBufferCount() const { return m_uiBufferCount; } - void SetBufferCount(unsigned int uiBufferCount) { m_uiBufferCount = uiBufferCount; } + void SetCurrentBufferSize(unsigned long long ullSize) { m_ullCurrentBufferSize = ullSize; } + unsigned long long GetCurrentBufferSize() const { return m_ullCurrentBufferSize; } -private: - void CalculateProgressAndSpeeds() const; + unsigned int GetBufferCount() const { return m_uiBufferCount; } + void SetBufferCount(unsigned int uiBufferCount) { m_uiBufferCount = uiBufferCount; } -private: - TSubTaskArrayStatsSnapshot m_tSubTasksStats; + private: + void CalculateProgressAndSpeeds() const; - taskid_t m_tTaskID; + private: + TSubTaskArrayStatsSnapshot m_tSubTasksStats; - bool m_bTaskIsRunning; - unsigned long long m_ullTimeElapsed; + taskid_t m_tTaskID; - int m_iThreadPriority; - TString m_strDestinationPath; - TFileFiltersArray m_filters; - ETaskCurrentState m_eTaskState; - TString m_strTaskID; - EOperationType m_eOperationType; - bool m_bIgnoreDirectories; - bool m_bCreateEmptyFiles; + bool m_bTaskIsRunning; + unsigned long long m_ullTimeElapsed; - unsigned long long m_ullCurrentBufferSize; - unsigned int m_uiBufferCount; + int m_iThreadPriority; + TString m_strDestinationPath; + TFileFiltersArray m_filters; + ETaskCurrentState m_eTaskState; + TString m_strTaskID; + EOperationType m_eOperationType; + bool m_bIgnoreDirectories; + bool m_bCreateEmptyFiles; - // cache for items calculated on-demand - mutable bool m_bCacheFilled; - mutable unsigned long long m_ullProcessedCount; - mutable unsigned long long m_ullTotalCount; - mutable unsigned long long m_ullProcessedSize; - mutable unsigned long long m_ullTotalSize; + unsigned long long m_ullCurrentBufferSize; + unsigned int m_uiBufferCount; - mutable double m_dTaskCountSpeed; - mutable double m_dTaskSizeSpeed; + // cache for items calculated on-demand + mutable bool m_bCacheFilled; + mutable unsigned long long m_ullProcessedCount; + mutable unsigned long long m_ullTotalCount; + mutable unsigned long long m_ullProcessedSize; + mutable unsigned long long m_ullTotalSize; - mutable double m_dCombinedProgress; -}; + mutable double m_dTaskCountSpeed; + mutable double m_dTaskSizeSpeed; -typedef boost::shared_ptr TTaskStatsSnapshotPtr; + mutable double m_dCombinedProgress; + }; -END_CHCORE_NAMESPACE + typedef boost::shared_ptr TTaskStatsSnapshotPtr; +} #endif Index: src/libchcore/TTimestampProviderTickCount.cpp =================================================================== diff -u -N -r9b8cccbee0fcfeca28a112cc0253a7641f73f74f -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTimestampProviderTickCount.cpp (.../TTimestampProviderTickCount.cpp) (revision 9b8cccbee0fcfeca28a112cc0253a7641f73f74f) +++ src/libchcore/TTimestampProviderTickCount.cpp (.../TTimestampProviderTickCount.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,25 +19,23 @@ #include "stdafx.h" #include "TTimestampProviderTickCount.h" -BEGIN_CHCORE_NAMESPACE - -TTimestampProviderTickCount::TTimestampProviderTickCount() : - m_dwLastTimestamp(0), - m_ullTimestampAdjustment(0) +namespace chcore { -} - -unsigned long long TTimestampProviderTickCount::GetCurrentTimestamp() const -{ - DWORD dwTimestamp = GetTickCount(); - if(dwTimestamp < m_dwLastTimestamp) + TTimestampProviderTickCount::TTimestampProviderTickCount() : + m_dwLastTimestamp(0), + m_ullTimestampAdjustment(0) { - m_ullTimestampAdjustment += (1ULL << 32); } - m_dwLastTimestamp = dwTimestamp; - return m_ullTimestampAdjustment + dwTimestamp; -} + unsigned long long TTimestampProviderTickCount::GetCurrentTimestamp() const + { + DWORD dwTimestamp = GetTickCount(); + if (dwTimestamp < m_dwLastTimestamp) + { + m_ullTimestampAdjustment += (1ULL << 32); + } + m_dwLastTimestamp = dwTimestamp; - -END_CHCORE_NAMESPACE + return m_ullTimestampAdjustment + dwTimestamp; + } +} Index: src/libchcore/TTimestampProviderTickCount.h =================================================================== diff -u -N -r9b8cccbee0fcfeca28a112cc0253a7641f73f74f -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TTimestampProviderTickCount.h (.../TTimestampProviderTickCount.h) (revision 9b8cccbee0fcfeca28a112cc0253a7641f73f74f) +++ src/libchcore/TTimestampProviderTickCount.h (.../TTimestampProviderTickCount.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,20 +22,19 @@ #include "libchcore.h" #include "ITimestampProvider.h" -BEGIN_CHCORE_NAMESPACE - -class TTimestampProviderTickCount : public ITimestampProvider +namespace chcore { -public: - TTimestampProviderTickCount(); + class TTimestampProviderTickCount : public ITimestampProvider + { + public: + TTimestampProviderTickCount(); - virtual unsigned long long GetCurrentTimestamp() const; + virtual unsigned long long GetCurrentTimestamp() const; -private: - mutable unsigned long long m_ullTimestampAdjustment; - mutable DWORD m_dwLastTimestamp; -}; + private: + mutable unsigned long long m_ullTimestampAdjustment; + mutable DWORD m_dwLastTimestamp; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TWin32ErrorFormatter.cpp =================================================================== diff -u -N -r387751793d274e49253e796ca7cec4f3d0cf07a9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TWin32ErrorFormatter.cpp (.../TWin32ErrorFormatter.cpp) (revision 387751793d274e49253e796ca7cec4f3d0cf07a9) +++ src/libchcore/TWin32ErrorFormatter.cpp (.../TWin32ErrorFormatter.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -20,43 +20,42 @@ #include "TWin32ErrorFormatter.h" #include -BEGIN_CHCORE_NAMESPACE - -TString TWin32ErrorFormatter::FormatWin32ErrorCode(DWORD dwErrorCode, bool bUseNumberFallback) +namespace chcore { - return FormatWin32ErrorCodeWithModule(dwErrorCode, nullptr, bUseNumberFallback); -} + TString TWin32ErrorFormatter::FormatWin32ErrorCode(DWORD dwErrorCode, bool bUseNumberFallback) + { + return FormatWin32ErrorCodeWithModule(dwErrorCode, nullptr, bUseNumberFallback); + } -TString TWin32ErrorFormatter::FormatWin32ErrorCodeWithFallback(DWORD dwErrorCode, const wchar_t* pszModuleName, bool bUseNumberFallback) -{ - TString strError = FormatWin32ErrorCode(dwErrorCode, false); - if (strError.IsEmpty()) - return FormatWin32ErrorCodeWithModule(dwErrorCode, GetModuleHandle(pszModuleName), bUseNumberFallback); + TString TWin32ErrorFormatter::FormatWin32ErrorCodeWithFallback(DWORD dwErrorCode, const wchar_t* pszModuleName, bool bUseNumberFallback) + { + TString strError = FormatWin32ErrorCode(dwErrorCode, false); + if (strError.IsEmpty()) + return FormatWin32ErrorCodeWithModule(dwErrorCode, GetModuleHandle(pszModuleName), bUseNumberFallback); - return strError; -} + return strError; + } -TString TWin32ErrorFormatter::FormatWin32ErrorCodeWithModule(DWORD dwErrorCode, HMODULE hModule, bool bUseNumberFallback) -{ - const DWORD dwMaxError = 1024; + TString TWin32ErrorFormatter::FormatWin32ErrorCodeWithModule(DWORD dwErrorCode, HMODULE hModule, bool bUseNumberFallback) + { + const DWORD dwMaxError = 1024; - TString strData; - wchar_t* pszBuffer = strData.GetBuffer(dwMaxError); + TString strData; + wchar_t* pszBuffer = strData.GetBuffer(dwMaxError); - DWORD dwPos = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, hModule, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), pszBuffer, dwMaxError - 1, NULL); - if (dwPos == 0xffffffff) - { - int iPos = 0; - if (bUseNumberFallback) - iPos = _sntprintf_s(pszBuffer, dwMaxError, _TRUNCATE, _T("ErrorCode: 0x%lx"), dwErrorCode); - strData.ReleaseBufferSetLength(iPos); - } - else - strData.ReleaseBufferSetLength(std::min(dwPos, dwMaxError - 1)); + DWORD dwPos = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, hModule, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), pszBuffer, dwMaxError - 1, NULL); + if (dwPos == 0xffffffff) + { + int iPos = 0; + if (bUseNumberFallback) + iPos = _sntprintf_s(pszBuffer, dwMaxError, _TRUNCATE, _T("ErrorCode: 0x%lx"), dwErrorCode); + strData.ReleaseBufferSetLength(iPos); + } + else + strData.ReleaseBufferSetLength(std::min(dwPos, dwMaxError - 1)); - strData.TrimRightSelf(_T("\r\n")); + strData.TrimRightSelf(_T("\r\n")); - return strData; + return strData; + } } - -END_CHCORE_NAMESPACE Index: src/libchcore/TWin32ErrorFormatter.h =================================================================== diff -u -N -r387751793d274e49253e796ca7cec4f3d0cf07a9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TWin32ErrorFormatter.h (.../TWin32ErrorFormatter.h) (revision 387751793d274e49253e796ca7cec4f3d0cf07a9) +++ src/libchcore/TWin32ErrorFormatter.h (.../TWin32ErrorFormatter.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,18 +22,17 @@ #include "libchcore.h" #include "TString.h" -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TWin32ErrorFormatter +namespace chcore { -public: - static TString FormatWin32ErrorCode(DWORD dwErrorCode, bool bUseNumberFallback); - static TString FormatWin32ErrorCodeWithFallback(DWORD dwErrorCode, const wchar_t* pszModuleName, bool bUseNumberFallback); + class LIBCHCORE_API TWin32ErrorFormatter + { + public: + static TString FormatWin32ErrorCode(DWORD dwErrorCode, bool bUseNumberFallback); + static TString FormatWin32ErrorCodeWithFallback(DWORD dwErrorCode, const wchar_t* pszModuleName, bool bUseNumberFallback); -private: - static TString FormatWin32ErrorCodeWithModule(DWORD dwErrorCode, HMODULE hModule, bool bUseNumberFallback); -}; + private: + static TString FormatWin32ErrorCodeWithModule(DWORD dwErrorCode, HMODULE hModule, bool bUseNumberFallback); + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TWorkerThreadController.cpp =================================================================== diff -u -N -r6103ac74583f2136b821dc67515ed8469abd8155 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TWorkerThreadController.cpp (.../TWorkerThreadController.cpp) (revision 6103ac74583f2136b821dc67515ed8469abd8155) +++ src/libchcore/TWorkerThreadController.cpp (.../TWorkerThreadController.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -25,197 +25,196 @@ #include "TCoreException.h" #include "ErrorCodes.h" -BEGIN_CHCORE_NAMESPACE - -TWorkerThreadController::TWorkerThreadController() : - m_hThread(NULL), - m_hKillThread(NULL) +namespace chcore { - m_hKillThread = CreateEvent(NULL, TRUE, FALSE, NULL); - if(!m_hKillThread) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotCreateEvent, GetLastError()); -} - -TWorkerThreadController::~TWorkerThreadController() -{ - try + TWorkerThreadController::TWorkerThreadController() : + m_hThread(NULL), + m_hKillThread(NULL) { - StopThread(); - CloseHandle(m_hKillThread); + m_hKillThread = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!m_hKillThread) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotCreateEvent, GetLastError()); } - catch(...) + + TWorkerThreadController::~TWorkerThreadController() { + try + { + StopThread(); + CloseHandle(m_hKillThread); + } + catch (...) + { + } } -} -void TWorkerThreadController::StartThread(PTHREAD_START_ROUTINE pThreadFunction, PVOID pThreadParam, int iPriority) -{ - boost::upgrade_lock lock(m_lock); + void TWorkerThreadController::StartThread(PTHREAD_START_ROUTINE pThreadFunction, PVOID pThreadParam, int iPriority) + { + boost::upgrade_lock lock(m_lock); - RemoveZombieData(lock); + RemoveZombieData(lock); - if(m_hThread) - THROW_CORE_EXCEPTION(eErr_ThreadAlreadyStarted); + if (m_hThread) + THROW_CORE_EXCEPTION(eErr_ThreadAlreadyStarted); - // just in case reset the kill event to avoid early death of the thread to be created - if(!::ResetEvent(m_hKillThread)) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotResetEvent, GetLastError()); + // just in case reset the kill event to avoid early death of the thread to be created + if (!::ResetEvent(m_hKillThread)) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotResetEvent, GetLastError()); - boost::upgrade_to_unique_lock lock_upgraded(lock); + boost::upgrade_to_unique_lock lock_upgraded(lock); - m_hThread = ::CreateThread(NULL, 0, pThreadFunction, pThreadParam, CREATE_SUSPENDED, NULL); - if(!m_hThread) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotCreateThread, GetLastError()); + m_hThread = ::CreateThread(NULL, 0, pThreadFunction, pThreadParam, CREATE_SUSPENDED, NULL); + if (!m_hThread) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotCreateThread, GetLastError()); - if(!::SetThreadPriority(m_hThread, iPriority)) - { - DWORD dwLastError = GetLastError(); + if (!::SetThreadPriority(m_hThread, iPriority)) + { + DWORD dwLastError = GetLastError(); - CloseHandle(m_hThread); - m_hThread = NULL; + CloseHandle(m_hThread); + m_hThread = NULL; - THROW_CORE_EXCEPTION_WIN32(eErr_CannotChangeThreadPriority, dwLastError); - } + THROW_CORE_EXCEPTION_WIN32(eErr_CannotChangeThreadPriority, dwLastError); + } - if(::ResumeThread(m_hThread) == (DWORD)-1) - { - DWORD dwLastError = GetLastError(); + if (::ResumeThread(m_hThread) == (DWORD)-1) + { + DWORD dwLastError = GetLastError(); - CloseHandle(m_hThread); - m_hThread = NULL; + CloseHandle(m_hThread); + m_hThread = NULL; - THROW_CORE_EXCEPTION_WIN32(eErr_CannotResumeThread, dwLastError); + THROW_CORE_EXCEPTION_WIN32(eErr_CannotResumeThread, dwLastError); + } } -} -void TWorkerThreadController::SignalThreadToStop() -{ - boost::upgrade_lock lock(m_lock); - - SignalThreadToStop(lock); -} - -void TWorkerThreadController::WaitForThreadToExit() -{ - boost::upgrade_lock lock(m_lock); - - DWORD dwRes = WaitForSingleObject(m_hThread, INFINITE); - if(dwRes == WAIT_OBJECT_0) + void TWorkerThreadController::SignalThreadToStop() { - if(!::ResetEvent(m_hKillThread)) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotResetEvent, GetLastError()); + boost::upgrade_lock lock(m_lock); - boost::upgrade_to_unique_lock lock_upgraded(lock); - - CloseHandle(m_hThread); - m_hThread = NULL; + SignalThreadToStop(lock); } - else - THROW_CORE_EXCEPTION_WIN32(eErr_WaitingFailed, GetLastError()); -} -void TWorkerThreadController::StopThread() -{ - boost::upgrade_lock lock(m_lock); + void TWorkerThreadController::WaitForThreadToExit() + { + boost::upgrade_lock lock(m_lock); - SignalThreadToStop(lock); + DWORD dwRes = WaitForSingleObject(m_hThread, INFINITE); + if (dwRes == WAIT_OBJECT_0) + { + if (!::ResetEvent(m_hKillThread)) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotResetEvent, GetLastError()); - WaitForThreadToExit(lock); -} + boost::upgrade_to_unique_lock lock_upgraded(lock); -void TWorkerThreadController::ChangePriority(int iPriority) -{ - boost::upgrade_lock lock(m_lock); + CloseHandle(m_hThread); + m_hThread = NULL; + } + else + THROW_CORE_EXCEPTION_WIN32(eErr_WaitingFailed, GetLastError()); + } - RemoveZombieData(lock); + void TWorkerThreadController::StopThread() + { + boost::upgrade_lock lock(m_lock); - if(!m_hThread) - return; + SignalThreadToStop(lock); - if(m_hThread != NULL) + WaitForThreadToExit(lock); + } + + void TWorkerThreadController::ChangePriority(int iPriority) { - if(::SuspendThread(m_hThread) == (DWORD)-1) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotSuspendThread, GetLastError()); + boost::upgrade_lock lock(m_lock); - if(!::SetThreadPriority(m_hThread, iPriority)) + RemoveZombieData(lock); + + if (!m_hThread) + return; + + if (m_hThread != NULL) { - DWORD dwLastError = GetLastError(); + if (::SuspendThread(m_hThread) == (DWORD)-1) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotSuspendThread, GetLastError()); - // try to resume thread priority cannot be changed - DWORD dwResult = ::ResumeThread(m_hThread); - dwResult; // to avoid warnings in release builds - BOOST_ASSERT(dwResult != (DWORD)-1); + if (!::SetThreadPriority(m_hThread, iPriority)) + { + DWORD dwLastError = GetLastError(); - THROW_CORE_EXCEPTION_WIN32(eErr_CannotChangeThreadPriority, dwLastError); + // try to resume thread priority cannot be changed + DWORD dwResult = ::ResumeThread(m_hThread); + dwResult; // to avoid warnings in release builds + BOOST_ASSERT(dwResult != (DWORD)-1); + + THROW_CORE_EXCEPTION_WIN32(eErr_CannotChangeThreadPriority, dwLastError); + } + + if (::ResumeThread(m_hThread) == (DWORD)-1) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotResumeThread, GetLastError()); } + } - if(::ResumeThread(m_hThread) == (DWORD)-1) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotResumeThread, GetLastError()); + bool TWorkerThreadController::KillRequested(DWORD dwWaitForSignal) + { + // this method does not have any mutexes, because it should be only called from within the thread + // being controlled by this object. This implies that the thread is alive and running, + // this class must exist because it should not be possible for the thread to exist and be active + // when this object is out of scope, and so the m_hKillThread should be non-NULL, since it is being destroyed + // in destructor. + return (m_hKillThread && WaitForSingleObject(m_hKillThread, dwWaitForSignal) == WAIT_OBJECT_0); } -} -bool TWorkerThreadController::KillRequested(DWORD dwWaitForSignal) -{ - // this method does not have any mutexes, because it should be only called from within the thread - // being controlled by this object. This implies that the thread is alive and running, - // this class must exist because it should not be possible for the thread to exist and be active - // when this object is out of scope, and so the m_hKillThread should be non-NULL, since it is being destroyed - // in destructor. - return (m_hKillThread && WaitForSingleObject(m_hKillThread, dwWaitForSignal) == WAIT_OBJECT_0); -} + HANDLE TWorkerThreadController::GetKillThreadHandle() const + { + return m_hKillThread; + } -HANDLE TWorkerThreadController::GetKillThreadHandle() const -{ - return m_hKillThread; -} - -void TWorkerThreadController::RemoveZombieData(boost::upgrade_lock& rUpgradeLock) -{ - // if thread is already stopped, then there is nothing to do - if(!m_hThread) - return; - - // thread already stopped? - if(WaitForSingleObject(m_hThread, 0) == WAIT_OBJECT_0) + void TWorkerThreadController::RemoveZombieData(boost::upgrade_lock& rUpgradeLock) { - if(!::ResetEvent(m_hKillThread)) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotResetEvent, GetLastError()); + // if thread is already stopped, then there is nothing to do + if (!m_hThread) + return; - boost::upgrade_to_unique_lock lock_upgraded(rUpgradeLock); + // thread already stopped? + if (WaitForSingleObject(m_hThread, 0) == WAIT_OBJECT_0) + { + if (!::ResetEvent(m_hKillThread)) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotResetEvent, GetLastError()); - CloseHandle(m_hThread); - m_hThread = NULL; + boost::upgrade_to_unique_lock lock_upgraded(rUpgradeLock); + + CloseHandle(m_hThread); + m_hThread = NULL; + } } -} -void TWorkerThreadController::SignalThreadToStop(boost::upgrade_lock& rUpgradeLock) -{ - RemoveZombieData(rUpgradeLock); - if(!m_hThread) - return; + void TWorkerThreadController::SignalThreadToStop(boost::upgrade_lock& rUpgradeLock) + { + RemoveZombieData(rUpgradeLock); + if (!m_hThread) + return; - if(!::SetEvent(m_hKillThread)) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotSetEvent, GetLastError()); -} + if (!::SetEvent(m_hKillThread)) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotSetEvent, GetLastError()); + } -void TWorkerThreadController::WaitForThreadToExit(boost::upgrade_lock& rUpgradeLock) -{ - if(!m_hThread) - return; - - DWORD dwRes = WaitForSingleObject(m_hThread, INFINITE); - if(dwRes == WAIT_OBJECT_0) + void TWorkerThreadController::WaitForThreadToExit(boost::upgrade_lock& rUpgradeLock) { - if(!::ResetEvent(m_hKillThread)) - THROW_CORE_EXCEPTION_WIN32(eErr_CannotResetEvent, GetLastError()); + if (!m_hThread) + return; - boost::upgrade_to_unique_lock lock_upgraded(rUpgradeLock); + DWORD dwRes = WaitForSingleObject(m_hThread, INFINITE); + if (dwRes == WAIT_OBJECT_0) + { + if (!::ResetEvent(m_hKillThread)) + THROW_CORE_EXCEPTION_WIN32(eErr_CannotResetEvent, GetLastError()); - CloseHandle(m_hThread); - m_hThread = NULL; + boost::upgrade_to_unique_lock lock_upgraded(rUpgradeLock); + + CloseHandle(m_hThread); + m_hThread = NULL; + } + else + THROW_CORE_EXCEPTION_WIN32(eErr_WaitingFailed, GetLastError()); } - else - THROW_CORE_EXCEPTION_WIN32(eErr_WaitingFailed, GetLastError()); } - -END_CHCORE_NAMESPACE Index: src/libchcore/TWorkerThreadController.h =================================================================== diff -u -N -r6103ac74583f2136b821dc67515ed8469abd8155 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TWorkerThreadController.h (.../TWorkerThreadController.h) (revision 6103ac74583f2136b821dc67515ed8469abd8155) +++ src/libchcore/TWorkerThreadController.h (.../TWorkerThreadController.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -28,45 +28,44 @@ /////////////////////////////////////////////////////////////////////////// // TWorkerThreadController -BEGIN_CHCORE_NAMESPACE - -class LIBCHCORE_API TWorkerThreadController +namespace chcore { -public: - TWorkerThreadController(); - ~TWorkerThreadController(); + class LIBCHCORE_API TWorkerThreadController + { + public: + TWorkerThreadController(); + ~TWorkerThreadController(); - // methods to be used outside of the thread being controlled - void StartThread(PTHREAD_START_ROUTINE pThreadFunction, PVOID pThreadParam, int iPriority = THREAD_PRIORITY_NORMAL); - void SignalThreadToStop(); - void WaitForThreadToExit(); + // methods to be used outside of the thread being controlled + void StartThread(PTHREAD_START_ROUTINE pThreadFunction, PVOID pThreadParam, int iPriority = THREAD_PRIORITY_NORMAL); + void SignalThreadToStop(); + void WaitForThreadToExit(); - void StopThread(); - void ChangePriority(int iPriority); + void StopThread(); + void ChangePriority(int iPriority); - // methods to be used only inside the thread being controlled - bool KillRequested(DWORD dwWaitForSignal = 0); + // methods to be used only inside the thread being controlled + bool KillRequested(DWORD dwWaitForSignal = 0); - HANDLE GetKillThreadHandle() const; -protected: - void RemoveZombieData(boost::upgrade_lock& rUpgradeLock); + HANDLE GetKillThreadHandle() const; + protected: + void RemoveZombieData(boost::upgrade_lock& rUpgradeLock); - void SignalThreadToStop(boost::upgrade_lock& rUpgradeLock); - void WaitForThreadToExit(boost::upgrade_lock& rUpgradeLock); + void SignalThreadToStop(boost::upgrade_lock& rUpgradeLock); + void WaitForThreadToExit(boost::upgrade_lock& rUpgradeLock); -private: - TWorkerThreadController(const TWorkerThreadController&); - TWorkerThreadController& operator=(const TWorkerThreadController&); + private: + TWorkerThreadController(const TWorkerThreadController&); + TWorkerThreadController& operator=(const TWorkerThreadController&); -private: - HANDLE m_hThread; - HANDLE m_hKillThread; + private: + HANDLE m_hThread; + HANDLE m_hKillThread; #pragma warning(push) #pragma warning(disable: 4251) - boost::shared_mutex m_lock; + boost::shared_mutex m_lock; #pragma warning(pop) -}; + }; +} -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/TaskID.h =================================================================== diff -u -N -ra44714d5c7ec0f50a376f4d0ea919ee5a224f834 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/TaskID.h (.../TaskID.h) (revision a44714d5c7ec0f50a376f4d0ea919ee5a224f834) +++ src/libchcore/TaskID.h (.../TaskID.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -22,11 +22,10 @@ #include "libchcore.h" #include "SerializerDataTypes.h" -BEGIN_CHCORE_NAMESPACE +namespace chcore +{ + typedef object_id_t taskid_t; + enum ENoTaskID { NoTaskID = 0 }; +} -typedef object_id_t taskid_t; -enum ENoTaskID { NoTaskID = 0 }; - -END_CHCORE_NAMESPACE - #endif Index: src/libchcore/libchcore.h =================================================================== diff -u -N -rd5c3edd0d167db9b5d47d04248820fda49499a5e -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/libchcore.h (.../libchcore.h) (revision d5c3edd0d167db9b5d47d04248820fda49499a5e) +++ src/libchcore/libchcore.h (.../libchcore.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -19,8 +19,3 @@ */ #define LIBCHCORE_API #endif - -/// Begins ch namespace -#define BEGIN_CHCORE_NAMESPACE namespace chcore { -/// Ends ch namespace -#define END_CHCORE_NAMESPACE } Index: src/libchcore/libchcore.vc140.vcxproj =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/libchcore.vc140.vcxproj (.../libchcore.vc140.vcxproj) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/libchcore.vc140.vcxproj (.../libchcore.vc140.vcxproj) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -489,11 +489,14 @@ + + + @@ -511,6 +514,7 @@ + Index: src/libchcore/libchcore.vc140.vcxproj.filters =================================================================== diff -u -N -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 --- src/libchcore/libchcore.vc140.vcxproj.filters (.../libchcore.vc140.vcxproj.filters) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/libchcore.vc140.vcxproj.filters (.../libchcore.vc140.vcxproj.filters) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) @@ -440,6 +440,18 @@ Source Files\Filesystems\Fake + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools +