src: Updating code style to conform (more or less) to ndn-cxx style
Also, adding .clang-format that describes the applied style. Note that
this style requires a slightly customized version of clang-format.
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..e5011d2
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,33 @@
+# This style requires customized clang-format from https://github.com/cawka/clang
+#
+BasedOnStyle: GNU
+---
+Language: Cpp
+AlwaysBreakAfterDefinitionReturnType: true
+AlwaysBreakAfterDeclarationReturnType: true
+ColumnLimit: 100
+SpaceBeforeParens: ControlStatements
+Cpp11BracedListStyle: true
+BreakBeforeBraces: Stroustrup
+PointerAlignment: Left
+PenaltyReturnTypeOnItsOwnLine: 0
+AllowShortBlocksOnASingleLine: false
+# AllowShortCaseLabelsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: false
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+
+BreakConstructorInitializersBeforeComma: true
+NamespaceIndentation: None
+Standard: Cpp11
+
+AlwaysBreakTemplateDeclarations: true
+IndentWidth: 2
+PenaltyBreakBeforeFirstCallParameter: 500
+SpacesBeforeTrailingComments: 1
+UseTab: Never
+ConstructorInitializerIndentWidth: 2
+
+SpaceBetweenTemplateAndOpeningAngle: false
+BreakBeforeBinaryOperators: NonAssignment
+ContinuationIndentWidth: 2
\ No newline at end of file
diff --git a/apps/ndn-app.cpp b/apps/ndn-app.cpp
index 1c62745..f353e62 100644
--- a/apps/ndn-app.cpp
+++ b/apps/ndn-app.cpp
@@ -30,137 +30,135 @@
#include "ns3/ndn-app-face.hpp"
#include "ns3/ndn-forwarding-strategy.hpp"
-NS_LOG_COMPONENT_DEFINE ("ndn.App");
+NS_LOG_COMPONENT_DEFINE("ndn.App");
namespace ns3 {
namespace ndn {
-
-NS_OBJECT_ENSURE_REGISTERED (App);
-
+
+NS_OBJECT_ENSURE_REGISTERED(App);
+
TypeId
-App::GetTypeId (void)
+App::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::App")
- .SetGroupName ("Ndn")
- .SetParent<Application> ()
- .AddConstructor<App> ()
+ static TypeId tid = TypeId("ns3::ndn::App")
+ .SetGroupName("Ndn")
+ .SetParent<Application>()
+ .AddConstructor<App>()
- .AddTraceSource ("ReceivedInterests", "ReceivedInterests",
- MakeTraceSourceAccessor (&App::m_receivedInterests))
-
- .AddTraceSource ("ReceivedNacks", "ReceivedNacks",
- MakeTraceSourceAccessor (&App::m_receivedNacks))
-
- .AddTraceSource ("ReceivedDatas", "ReceivedDatas",
- MakeTraceSourceAccessor (&App::m_receivedDatas))
+ .AddTraceSource("ReceivedInterests", "ReceivedInterests",
+ MakeTraceSourceAccessor(&App::m_receivedInterests))
- .AddTraceSource ("TransmittedInterests", "TransmittedInterests",
- MakeTraceSourceAccessor (&App::m_transmittedInterests))
+ .AddTraceSource("ReceivedNacks", "ReceivedNacks",
+ MakeTraceSourceAccessor(&App::m_receivedNacks))
- .AddTraceSource ("TransmittedDatas", "TransmittedDatas",
- MakeTraceSourceAccessor (&App::m_transmittedDatas))
- ;
+ .AddTraceSource("ReceivedDatas", "ReceivedDatas",
+ MakeTraceSourceAccessor(&App::m_receivedDatas))
+
+ .AddTraceSource("TransmittedInterests", "TransmittedInterests",
+ MakeTraceSourceAccessor(&App::m_transmittedInterests))
+
+ .AddTraceSource("TransmittedDatas", "TransmittedDatas",
+ MakeTraceSourceAccessor(&App::m_transmittedDatas));
return tid;
}
-
-App::App ()
- : m_active (false)
- , m_face (0)
+
+App::App()
+ : m_active(false)
+ , m_face(0)
{
}
-
-App::~App ()
+
+App::~App()
{
}
void
-App::DoDispose (void)
+App::DoDispose(void)
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
// Unfortunately, this causes SEGFAULT
// The best reason I see is that apps are freed after ndn stack is removed
- // StopApplication ();
- Application::DoDispose ();
+ // StopApplication ();
+ Application::DoDispose();
}
uint32_t
-App::GetId () const
+App::GetId() const
{
if (m_face == 0)
return (uint32_t)-1;
else
- return m_face->GetId ();
+ return m_face->GetId();
}
void
-App::OnInterest (Ptr<const Interest> interest)
+App::OnInterest(Ptr<const Interest> interest)
{
- NS_LOG_FUNCTION (this << interest);
- m_receivedInterests (interest, this, m_face);
+ NS_LOG_FUNCTION(this << interest);
+ m_receivedInterests(interest, this, m_face);
}
void
-App::OnNack (Ptr<const Interest> interest)
+App::OnNack(Ptr<const Interest> interest)
{
- NS_LOG_FUNCTION (this << interest);
- m_receivedNacks (interest, this, m_face);
+ NS_LOG_FUNCTION(this << interest);
+ m_receivedNacks(interest, this, m_face);
}
void
-App::OnData (Ptr<const Data> contentObject)
+App::OnData(Ptr<const Data> contentObject)
{
- NS_LOG_FUNCTION (this << contentObject);
- m_receivedDatas (contentObject, this, m_face);
+ NS_LOG_FUNCTION(this << contentObject);
+ m_receivedDatas(contentObject, this, m_face);
}
// Application Methods
-void
-App::StartApplication () // Called at time specified by Start
+void
+App::StartApplication() // Called at time specified by Start
{
- NS_LOG_FUNCTION_NOARGS ();
-
- NS_ASSERT (m_active != true);
+ NS_LOG_FUNCTION_NOARGS();
+
+ NS_ASSERT(m_active != true);
m_active = true;
- NS_ASSERT_MSG (GetNode ()->GetObject<L3Protocol> () != 0,
- "Ndn stack should be installed on the node " << GetNode ());
+ NS_ASSERT_MSG(GetNode()->GetObject<L3Protocol>() != 0,
+ "Ndn stack should be installed on the node " << GetNode());
// step 1. Create a face
- m_face = CreateObject<AppFace> (/*Ptr<App> (this)*/this);
-
+ m_face = CreateObject<AppFace>(/*Ptr<App> (this)*/ this);
+
// step 2. Add face to the Ndn stack
- GetNode ()->GetObject<L3Protocol> ()->AddFace (m_face);
+ GetNode()->GetObject<L3Protocol>()->AddFace(m_face);
// step 3. Enable face
- m_face->SetUp (true);
+ m_face->SetUp(true);
}
-
-void
-App::StopApplication () // Called at time specified by Stop
-{
- NS_LOG_FUNCTION_NOARGS ();
- if (!m_active) return; //don't assert here, just return
-
- NS_ASSERT (GetNode ()->GetObject<L3Protocol> () != 0);
+void
+App::StopApplication() // Called at time specified by Stop
+{
+ NS_LOG_FUNCTION_NOARGS();
+
+ if (!m_active)
+ return; // don't assert here, just return
+
+ NS_ASSERT(GetNode()->GetObject<L3Protocol>() != 0);
m_active = false;
// step 1. Disable face
- m_face->SetUp (false);
+ m_face->SetUp(false);
// step 2. Remove face from Ndn stack
- GetNode ()->GetObject<L3Protocol> ()->RemoveFace (m_face);
+ GetNode()->GetObject<L3Protocol>()->RemoveFace(m_face);
// step 3. Destroy face
- if (m_face->GetReferenceCount () != 1)
- {
- NS_LOG_ERROR ("Please a bug report on https://github.com/NDN-Routing/ndnSIM/issues");
- NS_LOG_ERROR ("At this point, nobody else should have referenced this face, but we have "
- << m_face->GetReferenceCount () << " references");
-
- }
+ if (m_face->GetReferenceCount() != 1) {
+ NS_LOG_ERROR("Please a bug report on https://github.com/NDN-Routing/ndnSIM/issues");
+ NS_LOG_ERROR("At this point, nobody else should have referenced this face, but we have "
+ << m_face->GetReferenceCount() << " references");
+ }
// NS_ASSERT_MSG (m_face->GetReferenceCount ()==2,
// "At this point, nobody else should have referenced this face, but we have "
// << m_face->GetReferenceCount () << " references");
diff --git a/apps/ndn-app.hpp b/apps/ndn-app.hpp
index 2157a7f..edede34 100644
--- a/apps/ndn-app.hpp
+++ b/apps/ndn-app.hpp
@@ -44,83 +44,86 @@
/**
* @ingroup ndn-apps
* @brief Base class that all NDN applications should be derived from.
- *
+ *
* The class implements virtual calls onInterest, onNack, and onData
*/
-class App: public Application
-{
+class App : public Application {
public:
- static TypeId GetTypeId ();
+ static TypeId
+ GetTypeId();
/**
* @brief Default constructor
*/
- App ();
- virtual ~App ();
+ App();
+ virtual ~App();
/**
* @brief Get application ID (ID of applications face)
*/
uint32_t
- GetId () const;
-
+ GetId() const;
+
/**
* @brief Method that will be called every time new Interest arrives
* @param interest Interest header
- * @param packet "Payload" of the interests packet. The actual payload should be zero, but packet itself
+ * @param packet "Payload" of the interests packet. The actual payload should be zero, but
+ * packet itself
* may be useful to get packet tags
*/
virtual void
- OnInterest (Ptr<const Interest> interest);
+ OnInterest(Ptr<const Interest> interest);
/**
* @brief Method that will be called every time new NACK arrives
* @param interest Interest header
*/
virtual void
- OnNack (Ptr<const Interest> interest);
-
+ OnNack(Ptr<const Interest> interest);
+
/**
* @brief Method that will be called every time new Data arrives
* @param contentObject Data header
- * @param payload payload (potentially virtual) of the Data packet (may include packet tags of original packet)
+ * @param payload payload (potentially virtual) of the Data packet (may include packet tags of
+ * original packet)
*/
virtual void
- OnData (Ptr<const Data> contentObject);
-
+ OnData(Ptr<const Data> contentObject);
+
protected:
/**
* @brief Do cleanup when application is destroyed
*/
virtual void
- DoDispose ();
+ DoDispose();
// inherited from Application base class. Originally they were private
virtual void
- StartApplication (); ///< @brief Called at time specified by Start
+ StartApplication(); ///< @brief Called at time specified by Start
virtual void
- StopApplication (); ///< @brief Called at time specified by Stop
+ StopApplication(); ///< @brief Called at time specified by Stop
protected:
- bool m_active; ///< @brief Flag to indicate that application is active (set by StartApplication and StopApplication)
- Ptr<Face> m_face; ///< @brief automatically created application face through which application communicates
+ bool m_active; ///< @brief Flag to indicate that application is active (set by StartApplication
+ /// and StopApplication)
+ Ptr<Face> m_face; ///< @brief automatically created application face through which application
+ /// communicates
- TracedCallback<Ptr<const Interest>,
- Ptr<App>, Ptr<Face> > m_receivedInterests; ///< @brief App-level trace of received Interests
+ TracedCallback<Ptr<const Interest>, Ptr<App>, Ptr<Face>>
+ m_receivedInterests; ///< @brief App-level trace of received Interests
- TracedCallback<Ptr<const Interest>,
- Ptr<App>, Ptr<Face> > m_receivedNacks; ///< @brief App-level trace of received NACKs
+ TracedCallback<Ptr<const Interest>, Ptr<App>, Ptr<Face>>
+ m_receivedNacks; ///< @brief App-level trace of received NACKs
- TracedCallback<Ptr<const Data>,
- Ptr<App>, Ptr<Face> > m_receivedDatas; ///< @brief App-level trace of received Data
+ TracedCallback<Ptr<const Data>, Ptr<App>, Ptr<Face>>
+ m_receivedDatas; ///< @brief App-level trace of received Data
+ TracedCallback<Ptr<const Interest>, Ptr<App>, Ptr<Face>>
+ m_transmittedInterests; ///< @brief App-level trace of transmitted Interests
- TracedCallback<Ptr<const Interest>,
- Ptr<App>, Ptr<Face> > m_transmittedInterests; ///< @brief App-level trace of transmitted Interests
-
- TracedCallback<Ptr<const Data>,
- Ptr<App>, Ptr<Face> > m_transmittedDatas; ///< @brief App-level trace of transmitted Data
+ TracedCallback<Ptr<const Data>, Ptr<App>, Ptr<Face>>
+ m_transmittedDatas; ///< @brief App-level trace of transmitted Data
};
} // namespace ndn
diff --git a/apps/ndn-consumer-batches.cpp b/apps/ndn-consumer-batches.cpp
index db158c5..b7406ae 100644
--- a/apps/ndn-consumer-batches.cpp
+++ b/apps/ndn-consumer-batches.cpp
@@ -30,69 +30,70 @@
#include "../utils/batches.hpp"
-NS_LOG_COMPONENT_DEFINE ("ndn.ConsumerBatches");
+NS_LOG_COMPONENT_DEFINE("ndn.ConsumerBatches");
namespace ns3 {
namespace ndn {
-
-NS_OBJECT_ENSURE_REGISTERED (ConsumerBatches);
-
-TypeId
-ConsumerBatches::GetTypeId (void)
-{
- static TypeId tid = TypeId ("ns3::ndn::ConsumerBatches")
- .SetGroupName ("Ndn")
- .SetParent<Consumer> ()
- .AddConstructor<ConsumerBatches> ()
- .AddAttribute ("Batches", "Batches to schedule. Should be vector, containing pairs of time and amount",
- // TypeId::ATTR_SET,
- StringValue (""),
- MakeBatchesAccessor (&ConsumerBatches::m_batches),
- MakeBatchesChecker ())
- ;
+NS_OBJECT_ENSURE_REGISTERED(ConsumerBatches);
+
+TypeId
+ConsumerBatches::GetTypeId(void)
+{
+ static TypeId tid =
+ TypeId("ns3::ndn::ConsumerBatches")
+ .SetGroupName("Ndn")
+ .SetParent<Consumer>()
+ .AddConstructor<ConsumerBatches>()
+
+ .AddAttribute("Batches",
+ "Batches to schedule. Should be vector, containing pairs of time and amount",
+ // TypeId::ATTR_SET,
+ StringValue(""), MakeBatchesAccessor(&ConsumerBatches::m_batches),
+ MakeBatchesChecker());
return tid;
}
-ConsumerBatches::ConsumerBatches ()
- : m_initial (true)
+ConsumerBatches::ConsumerBatches()
+ : m_initial(true)
{
}
void
-ConsumerBatches::StartApplication ()
+ConsumerBatches::StartApplication()
{
- Consumer::StartApplication ();
-
+ Consumer::StartApplication();
+
// std::cout << "Batches: " << batches << "\n";
- for (Batches::const_iterator i = m_batches.begin (); i != m_batches.end (); i++)
- {
- Simulator::ScheduleWithContext (GetNode ()->GetId (), i->get<0> (), &ConsumerBatches::AddBatch, this, i->get<1> ());
- }
+ for (Batches::const_iterator i = m_batches.begin(); i != m_batches.end(); i++) {
+ Simulator::ScheduleWithContext(GetNode()->GetId(), i->get<0>(), &ConsumerBatches::AddBatch,
+ this, i->get<1>());
+ }
}
void
-ConsumerBatches::AddBatch (uint32_t amount)
+ConsumerBatches::AddBatch(uint32_t amount)
{
// std::cout << Simulator::Now () << " adding batch of " << amount << "\n";
m_seqMax += amount;
- m_rtt->ClearSent (); // this is important, otherwise RTT estimation for the new batch will be affected by previous batch history
+ m_rtt->ClearSent(); // this is important, otherwise RTT estimation for the new batch will be
+ // affected by previous batch history
m_initial = true;
- ScheduleNextPacket ();
+ ScheduleNextPacket();
}
void
-ConsumerBatches::ScheduleNextPacket ()
+ConsumerBatches::ScheduleNextPacket()
{
- if (!m_sendEvent.IsRunning ())
- {
- Time delay = Seconds (0);
- if (!m_initial) delay = m_rtt->RetransmitTimeout ();
-
- m_initial = false;
- m_sendEvent = Simulator::Schedule (delay, &Consumer::SendPacket, this);
- }
+ if (!m_sendEvent.IsRunning()) {
+ Time delay = Seconds(0);
+ if (!m_initial)
+ delay = m_rtt->RetransmitTimeout();
+
+ m_initial = false;
+ m_sendEvent = Simulator::Schedule(delay, &Consumer::SendPacket, this);
+ }
}
///////////////////////////////////////////////////
diff --git a/apps/ndn-consumer-batches.hpp b/apps/ndn-consumer-batches.hpp
index 979108e..0c7c25d 100644
--- a/apps/ndn-consumer-batches.hpp
+++ b/apps/ndn-consumer-batches.hpp
@@ -32,15 +32,15 @@
* @ingroup ndn-apps
* \brief Ndn application for sending out Interest packets in batches
*/
-class ConsumerBatches: public Consumer
-{
-public:
- static TypeId GetTypeId ();
-
+class ConsumerBatches : public Consumer {
+public:
+ static TypeId
+ GetTypeId();
+
/**
- * \brief Default constructor
+ * \brief Default constructor
*/
- ConsumerBatches ();
+ ConsumerBatches();
// From App
// virtual void
@@ -58,16 +58,18 @@
private:
virtual void
- StartApplication (); ///< @brief Called at time specified by Start
-
+ StartApplication(); ///< @brief Called at time specified by Start
+
void
- AddBatch (uint32_t amount);
+ AddBatch(uint32_t amount);
+
protected:
/**
- * \brief Constructs the Interest packet and sends it using a callback to the underlying NDN protocol
+ * \brief Constructs the Interest packet and sends it using a callback to the underlying NDN
+ * protocol
*/
virtual void
- ScheduleNextPacket ();
+ ScheduleNextPacket();
private:
bool m_initial;
diff --git a/apps/ndn-consumer-cbr.cpp b/apps/ndn-consumer-cbr.cpp
index 90e46d5..c9c81b9 100644
--- a/apps/ndn-consumer-cbr.cpp
+++ b/apps/ndn-consumer-cbr.cpp
@@ -34,105 +34,95 @@
#include "ns3/ndn-interest.hpp"
#include "ns3/ndn-data.hpp"
-NS_LOG_COMPONENT_DEFINE ("ndn.ConsumerCbr");
+NS_LOG_COMPONENT_DEFINE("ndn.ConsumerCbr");
namespace ns3 {
namespace ndn {
-
-NS_OBJECT_ENSURE_REGISTERED (ConsumerCbr);
-
+
+NS_OBJECT_ENSURE_REGISTERED(ConsumerCbr);
+
TypeId
-ConsumerCbr::GetTypeId (void)
+ConsumerCbr::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::ConsumerCbr")
- .SetGroupName ("Ndn")
- .SetParent<Consumer> ()
- .AddConstructor<ConsumerCbr> ()
+ static TypeId tid =
+ TypeId("ns3::ndn::ConsumerCbr")
+ .SetGroupName("Ndn")
+ .SetParent<Consumer>()
+ .AddConstructor<ConsumerCbr>()
- .AddAttribute ("Frequency", "Frequency of interest packets",
- StringValue ("1.0"),
- MakeDoubleAccessor (&ConsumerCbr::m_frequency),
- MakeDoubleChecker<double> ())
-
- .AddAttribute ("Randomize", "Type of send time randomization: none (default), uniform, exponential",
- StringValue ("none"),
- MakeStringAccessor (&ConsumerCbr::SetRandomize, &ConsumerCbr::GetRandomize),
- MakeStringChecker ())
+ .AddAttribute("Frequency", "Frequency of interest packets", StringValue("1.0"),
+ MakeDoubleAccessor(&ConsumerCbr::m_frequency), MakeDoubleChecker<double>())
- .AddAttribute ("MaxSeq",
- "Maximum sequence number to request",
- IntegerValue (std::numeric_limits<uint32_t>::max ()),
- MakeIntegerAccessor (&ConsumerCbr::m_seqMax),
- MakeIntegerChecker<uint32_t> ())
+ .AddAttribute("Randomize",
+ "Type of send time randomization: none (default), uniform, exponential",
+ StringValue("none"),
+ MakeStringAccessor(&ConsumerCbr::SetRandomize, &ConsumerCbr::GetRandomize),
+ MakeStringChecker())
+
+ .AddAttribute("MaxSeq", "Maximum sequence number to request",
+ IntegerValue(std::numeric_limits<uint32_t>::max()),
+ MakeIntegerAccessor(&ConsumerCbr::m_seqMax), MakeIntegerChecker<uint32_t>())
;
return tid;
}
-
-ConsumerCbr::ConsumerCbr ()
- : m_frequency (1.0)
- , m_firstTime (true)
- , m_random (0)
+
+ConsumerCbr::ConsumerCbr()
+ : m_frequency(1.0)
+ , m_firstTime(true)
+ , m_random(0)
{
- NS_LOG_FUNCTION_NOARGS ();
- m_seqMax = std::numeric_limits<uint32_t>::max ();
+ NS_LOG_FUNCTION_NOARGS();
+ m_seqMax = std::numeric_limits<uint32_t>::max();
}
-ConsumerCbr::~ConsumerCbr ()
+ConsumerCbr::~ConsumerCbr()
{
if (m_random)
delete m_random;
}
void
-ConsumerCbr::ScheduleNextPacket ()
+ConsumerCbr::ScheduleNextPacket()
{
// double mean = 8.0 * m_payloadSize / m_desiredRate.GetBitRate ();
// std::cout << "next: " << Simulator::Now().ToDouble(Time::S) + mean << "s\n";
- if (m_firstTime)
- {
- m_sendEvent = Simulator::Schedule (Seconds (0.0),
- &Consumer::SendPacket, this);
- m_firstTime = false;
- }
- else if (!m_sendEvent.IsRunning ())
- m_sendEvent = Simulator::Schedule (
- (m_random == 0) ?
- Seconds(1.0 / m_frequency)
- :
- Seconds(m_random->GetValue ()),
- &Consumer::SendPacket, this);
+ if (m_firstTime) {
+ m_sendEvent = Simulator::Schedule(Seconds(0.0), &Consumer::SendPacket, this);
+ m_firstTime = false;
+ }
+ else if (!m_sendEvent.IsRunning())
+ m_sendEvent = Simulator::Schedule((m_random == 0) ? Seconds(1.0 / m_frequency)
+ : Seconds(m_random->GetValue()),
+ &Consumer::SendPacket, this);
}
void
-ConsumerCbr::SetRandomize (const std::string &value)
+ConsumerCbr::SetRandomize(const std::string& value)
{
if (m_random)
delete m_random;
- if (value == "uniform")
- {
- m_random = new UniformVariable (0.0, 2 * 1.0 / m_frequency);
- }
- else if (value == "exponential")
- {
- m_random = new ExponentialVariable (1.0 / m_frequency, 50 * 1.0 / m_frequency);
- }
+ if (value == "uniform") {
+ m_random = new UniformVariable(0.0, 2 * 1.0 / m_frequency);
+ }
+ else if (value == "exponential") {
+ m_random = new ExponentialVariable(1.0 / m_frequency, 50 * 1.0 / m_frequency);
+ }
else
m_random = 0;
- m_randomType = value;
+ m_randomType = value;
}
std::string
-ConsumerCbr::GetRandomize () const
+ConsumerCbr::GetRandomize() const
{
return m_randomType;
}
-
///////////////////////////////////////////////////
// Process incoming packets //
///////////////////////////////////////////////////
diff --git a/apps/ndn-consumer-cbr.hpp b/apps/ndn-consumer-cbr.hpp
index ebe015f..47134b6 100644
--- a/apps/ndn-consumer-cbr.hpp
+++ b/apps/ndn-consumer-cbr.hpp
@@ -31,17 +31,17 @@
* @ingroup ndn-apps
* @brief Ndn application for sending out Interest packets at a "constant" rate (Poisson process)
*/
-class ConsumerCbr: public Consumer
-{
-public:
- static TypeId GetTypeId ();
-
+class ConsumerCbr : public Consumer {
+public:
+ static TypeId
+ GetTypeId();
+
/**
- * \brief Default constructor
+ * \brief Default constructor
* Sets up randomizer function and packet sequence number
*/
- ConsumerCbr ();
- virtual ~ConsumerCbr ();
+ ConsumerCbr();
+ virtual ~ConsumerCbr();
// From NdnApp
// virtual void
@@ -56,25 +56,26 @@
protected:
/**
- * \brief Constructs the Interest packet and sends it using a callback to the underlying NDN protocol
+ * \brief Constructs the Interest packet and sends it using a callback to the underlying NDN
+ * protocol
*/
virtual void
- ScheduleNextPacket ();
+ ScheduleNextPacket();
/**
* @brief Set type of frequency randomization
* @param value Either 'none', 'uniform', or 'exponential'
*/
void
- SetRandomize (const std::string &value);
+ SetRandomize(const std::string& value);
/**
* @brief Get type of frequency randomization
* @returns either 'none', 'uniform', or 'exponential'
*/
std::string
- GetRandomize () const;
-
+ GetRandomize() const;
+
private:
// void
// UpdateMean ();
@@ -87,12 +88,12 @@
// DataRate
// GetDesiredRate () const;
-
+
protected:
- double m_frequency; // Frequency of interest packets (in hertz)
- bool m_firstTime;
- RandomVariable *m_random;
- std::string m_randomType;
+ double m_frequency; // Frequency of interest packets (in hertz)
+ bool m_firstTime;
+ RandomVariable* m_random;
+ std::string m_randomType;
};
} // namespace ndn
diff --git a/apps/ndn-consumer-window.cpp b/apps/ndn-consumer-window.cpp
index a4a6ad5..595842c 100644
--- a/apps/ndn-consumer-window.cpp
+++ b/apps/ndn-consumer-window.cpp
@@ -30,93 +30,92 @@
#include "ns3/ndn-data.hpp"
#include "ns3/ndn-interest.hpp"
-NS_LOG_COMPONENT_DEFINE ("ndn.ConsumerWindow");
+NS_LOG_COMPONENT_DEFINE("ndn.ConsumerWindow");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (ConsumerWindow);
+NS_OBJECT_ENSURE_REGISTERED(ConsumerWindow);
TypeId
-ConsumerWindow::GetTypeId (void)
+ConsumerWindow::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::ConsumerWindow")
- .SetGroupName ("Ndn")
- .SetParent<Consumer> ()
- .AddConstructor<ConsumerWindow> ()
+ static TypeId tid =
+ TypeId("ns3::ndn::ConsumerWindow")
+ .SetGroupName("Ndn")
+ .SetParent<Consumer>()
+ .AddConstructor<ConsumerWindow>()
- .AddAttribute ("Window", "Initial size of the window",
- StringValue ("1"),
- MakeUintegerAccessor (&ConsumerWindow::GetWindow, &ConsumerWindow::SetWindow),
- MakeUintegerChecker<uint32_t> ())
+ .AddAttribute("Window", "Initial size of the window", StringValue("1"),
+ MakeUintegerAccessor(&ConsumerWindow::GetWindow, &ConsumerWindow::SetWindow),
+ MakeUintegerChecker<uint32_t>())
- .AddAttribute ("PayloadSize", "Average size of content object size (to calculate interest generation rate)",
- UintegerValue (1040),
- MakeUintegerAccessor (&ConsumerWindow::GetPayloadSize, &ConsumerWindow::SetPayloadSize),
- MakeUintegerChecker<uint32_t>())
+ .AddAttribute("PayloadSize",
+ "Average size of content object size (to calculate interest generation rate)",
+ UintegerValue(1040), MakeUintegerAccessor(&ConsumerWindow::GetPayloadSize,
+ &ConsumerWindow::SetPayloadSize),
+ MakeUintegerChecker<uint32_t>())
- .AddAttribute ("Size",
- "Amount of data in megabytes to request, relying on PayloadSize parameter (alternative to MaxSeq attribute)",
- DoubleValue (-1), // don't impose limit by default
- MakeDoubleAccessor (&ConsumerWindow::GetMaxSize, &ConsumerWindow::SetMaxSize),
- MakeDoubleChecker<double> ())
+ .AddAttribute("Size", "Amount of data in megabytes to request, relying on PayloadSize "
+ "parameter (alternative to MaxSeq attribute)",
+ DoubleValue(-1), // don't impose limit by default
+ MakeDoubleAccessor(&ConsumerWindow::GetMaxSize, &ConsumerWindow::SetMaxSize),
+ MakeDoubleChecker<double>())
- .AddAttribute ("MaxSeq",
- "Maximum sequence number to request (alternative to Size attribute, would activate only if Size is -1). "
- "The parameter is activated only if Size negative (not set)",
- IntegerValue (std::numeric_limits<uint32_t>::max ()),
- MakeUintegerAccessor (&ConsumerWindow::GetSeqMax, &ConsumerWindow::SetSeqMax),
- MakeUintegerChecker<uint32_t> ())
+ .AddAttribute("MaxSeq", "Maximum sequence number to request (alternative to Size attribute, "
+ "would activate only if Size is -1). "
+ "The parameter is activated only if Size negative (not set)",
+ IntegerValue(std::numeric_limits<uint32_t>::max()),
+ MakeUintegerAccessor(&ConsumerWindow::GetSeqMax, &ConsumerWindow::SetSeqMax),
+ MakeUintegerChecker<uint32_t>())
- .AddAttribute ("InitialWindowOnTimeout", "Set window to initial value when timeout occurs",
- BooleanValue (true),
- MakeBooleanAccessor (&ConsumerWindow::m_setInitialWindowOnTimeout),
- MakeBooleanChecker ())
+ .AddAttribute("InitialWindowOnTimeout", "Set window to initial value when timeout occurs",
+ BooleanValue(true),
+ MakeBooleanAccessor(&ConsumerWindow::m_setInitialWindowOnTimeout),
+ MakeBooleanChecker())
- .AddTraceSource ("WindowTrace",
- "Window that controls how many outstanding interests are allowed",
- MakeTraceSourceAccessor (&ConsumerWindow::m_window))
- .AddTraceSource ("InFlight",
- "Current number of outstanding interests",
- MakeTraceSourceAccessor (&ConsumerWindow::m_inFlight))
- ;
+ .AddTraceSource("WindowTrace",
+ "Window that controls how many outstanding interests are allowed",
+ MakeTraceSourceAccessor(&ConsumerWindow::m_window))
+ .AddTraceSource("InFlight", "Current number of outstanding interests",
+ MakeTraceSourceAccessor(&ConsumerWindow::m_inFlight));
return tid;
}
-ConsumerWindow::ConsumerWindow ()
- : m_payloadSize (1040)
- , m_inFlight (0)
+ConsumerWindow::ConsumerWindow()
+ : m_payloadSize(1040)
+ , m_inFlight(0)
{
}
void
-ConsumerWindow::SetWindow (uint32_t window)
+ConsumerWindow::SetWindow(uint32_t window)
{
m_initialWindow = window;
m_window = m_initialWindow;
}
uint32_t
-ConsumerWindow::GetWindow () const
+ConsumerWindow::GetWindow() const
{
return m_initialWindow;
}
uint32_t
-ConsumerWindow::GetPayloadSize () const
+ConsumerWindow::GetPayloadSize() const
{
return m_payloadSize;
}
void
-ConsumerWindow::SetPayloadSize (uint32_t payload)
+ConsumerWindow::SetPayloadSize(uint32_t payload)
{
m_payloadSize = payload;
}
double
-ConsumerWindow::GetMaxSize () const
+ConsumerWindow::GetMaxSize() const
{
if (m_seqMax == 0)
return -1.0;
@@ -125,28 +124,27 @@
}
void
-ConsumerWindow::SetMaxSize (double size)
+ConsumerWindow::SetMaxSize(double size)
{
m_maxSize = size;
- if (m_maxSize < 0)
- {
- m_seqMax = 0;
- return;
- }
+ if (m_maxSize < 0) {
+ m_seqMax = 0;
+ return;
+ }
m_seqMax = floor(1.0 + m_maxSize * 1024.0 * 1024.0 / m_payloadSize);
- NS_LOG_DEBUG ("MaxSeqNo: " << m_seqMax);
+ NS_LOG_DEBUG("MaxSeqNo: " << m_seqMax);
// std::cout << "MaxSeqNo: " << m_seqMax << "\n";
}
uint32_t
-ConsumerWindow::GetSeqMax () const
+ConsumerWindow::GetSeqMax() const
{
return m_seqMax;
}
void
-ConsumerWindow::SetSeqMax (uint32_t seqMax)
+ConsumerWindow::SetSeqMax(uint32_t seqMax)
{
if (m_maxSize < 0)
m_seqMax = seqMax;
@@ -154,31 +152,30 @@
// ignore otherwise
}
-
void
-ConsumerWindow::ScheduleNextPacket ()
+ConsumerWindow::ScheduleNextPacket()
{
- if (m_window == static_cast<uint32_t> (0))
- {
- Simulator::Remove (m_sendEvent);
+ if (m_window == static_cast<uint32_t>(0)) {
+ Simulator::Remove(m_sendEvent);
- NS_LOG_DEBUG ("Next event in " << (std::min<double> (0.5, m_rtt->RetransmitTimeout ().ToDouble (Time::S))) << " sec");
- m_sendEvent = Simulator::Schedule (Seconds (std::min<double> (0.5, m_rtt->RetransmitTimeout ().ToDouble (Time::S))),
- &Consumer::SendPacket, this);
+ NS_LOG_DEBUG(
+ "Next event in " << (std::min<double>(0.5, m_rtt->RetransmitTimeout().ToDouble(Time::S)))
+ << " sec");
+ m_sendEvent =
+ Simulator::Schedule(Seconds(
+ std::min<double>(0.5, m_rtt->RetransmitTimeout().ToDouble(Time::S))),
+ &Consumer::SendPacket, this);
+ }
+ else if (m_inFlight >= m_window) {
+ // simply do nothing
+ }
+ else {
+ if (m_sendEvent.IsRunning()) {
+ Simulator::Remove(m_sendEvent);
}
- else if (m_inFlight >= m_window)
- {
- // simply do nothing
- }
- else
- {
- if (m_sendEvent.IsRunning ())
- {
- Simulator::Remove (m_sendEvent);
- }
- m_sendEvent = Simulator::ScheduleNow (&Consumer::SendPacket, this);
- }
+ m_sendEvent = Simulator::ScheduleNow(&Consumer::SendPacket, this);
+ }
}
///////////////////////////////////////////////////
@@ -186,58 +183,58 @@
///////////////////////////////////////////////////
void
-ConsumerWindow::OnData (Ptr<const Data> contentObject)
+ConsumerWindow::OnData(Ptr<const Data> contentObject)
{
- Consumer::OnData (contentObject);
+ Consumer::OnData(contentObject);
m_window = m_window + 1;
- if (m_inFlight > static_cast<uint32_t> (0)) m_inFlight--;
- NS_LOG_DEBUG ("Window: " << m_window << ", InFlight: " << m_inFlight);
+ if (m_inFlight > static_cast<uint32_t>(0))
+ m_inFlight--;
+ NS_LOG_DEBUG("Window: " << m_window << ", InFlight: " << m_inFlight);
- ScheduleNextPacket ();
+ ScheduleNextPacket();
}
void
-ConsumerWindow::OnNack (Ptr<const Interest> interest)
+ConsumerWindow::OnNack(Ptr<const Interest> interest)
{
- Consumer::OnNack (interest);
+ Consumer::OnNack(interest);
- if (m_inFlight > static_cast<uint32_t> (0)) m_inFlight--;
+ if (m_inFlight > static_cast<uint32_t>(0))
+ m_inFlight--;
- if (m_window > static_cast<uint32_t> (0))
- {
- // m_window = 0.5 * m_window;//m_window - 1;
- m_window = std::max<uint32_t> (0, m_window - 1);
- }
+ if (m_window > static_cast<uint32_t>(0)) {
+ // m_window = 0.5 * m_window;//m_window - 1;
+ m_window = std::max<uint32_t>(0, m_window - 1);
+ }
- NS_LOG_DEBUG ("Window: " << m_window << ", InFlight: " << m_inFlight);
+ NS_LOG_DEBUG("Window: " << m_window << ", InFlight: " << m_inFlight);
- ScheduleNextPacket ();
+ ScheduleNextPacket();
}
void
-ConsumerWindow::OnTimeout (uint32_t sequenceNumber)
+ConsumerWindow::OnTimeout(uint32_t sequenceNumber)
{
- if (m_inFlight > static_cast<uint32_t> (0)) m_inFlight--;
+ if (m_inFlight > static_cast<uint32_t>(0))
+ m_inFlight--;
- if (m_setInitialWindowOnTimeout)
- {
- // m_window = std::max<uint32_t> (0, m_window - 1);
- m_window = m_initialWindow;
- }
+ if (m_setInitialWindowOnTimeout) {
+ // m_window = std::max<uint32_t> (0, m_window - 1);
+ m_window = m_initialWindow;
+ }
- NS_LOG_DEBUG ("Window: " << m_window << ", InFlight: " << m_inFlight);
- Consumer::OnTimeout (sequenceNumber);
+ NS_LOG_DEBUG("Window: " << m_window << ", InFlight: " << m_inFlight);
+ Consumer::OnTimeout(sequenceNumber);
}
void
-ConsumerWindow::WillSendOutInterest (uint32_t sequenceNumber)
+ConsumerWindow::WillSendOutInterest(uint32_t sequenceNumber)
{
- m_inFlight ++;
- Consumer::WillSendOutInterest (sequenceNumber);
+ m_inFlight++;
+ Consumer::WillSendOutInterest(sequenceNumber);
}
-
} // namespace ndn
} // namespace ns3
diff --git a/apps/ndn-consumer-window.hpp b/apps/ndn-consumer-window.hpp
index 886621e..923cae0 100644
--- a/apps/ndn-consumer-window.hpp
+++ b/apps/ndn-consumer-window.hpp
@@ -32,70 +32,72 @@
* @ingroup ndn-apps
* \brief Ndn application for sending out Interest packets (window-based)
*
- * !!! ATTENTION !!! This is highly experimental and relies on experimental features of the simulator.
+ * !!! ATTENTION !!! This is highly experimental and relies on experimental features of the
+ *simulator.
* Behavior may be unpredictable if used incorrectly.
*/
-class ConsumerWindow: public Consumer
-{
+class ConsumerWindow : public Consumer {
public:
- static TypeId GetTypeId ();
+ static TypeId
+ GetTypeId();
/**
* \brief Default constructor
*/
- ConsumerWindow ();
+ ConsumerWindow();
// From App
// virtual void
// OnInterest (const Ptr<const Interest> &interest);
virtual void
- OnNack (Ptr<const Interest> interest);
+ OnNack(Ptr<const Interest> interest);
virtual void
- OnData (Ptr<const Data> contentObject);
+ OnData(Ptr<const Data> contentObject);
virtual void
- OnTimeout (uint32_t sequenceNumber);
+ OnTimeout(uint32_t sequenceNumber);
virtual void
- WillSendOutInterest (uint32_t sequenceNumber);
+ WillSendOutInterest(uint32_t sequenceNumber);
protected:
/**
- * \brief Constructs the Interest packet and sends it using a callback to the underlying NDN protocol
+ * \brief Constructs the Interest packet and sends it using a callback to the underlying NDN
+ * protocol
*/
virtual void
- ScheduleNextPacket ();
+ ScheduleNextPacket();
private:
virtual void
- SetWindow (uint32_t window);
+ SetWindow(uint32_t window);
uint32_t
- GetWindow () const;
+ GetWindow() const;
virtual void
- SetPayloadSize (uint32_t payload);
+ SetPayloadSize(uint32_t payload);
uint32_t
- GetPayloadSize () const;
+ GetPayloadSize() const;
double
- GetMaxSize () const;
+ GetMaxSize() const;
void
- SetMaxSize (double size);
+ SetMaxSize(double size);
uint32_t
- GetSeqMax () const;
+ GetSeqMax() const;
void
- SetSeqMax (uint32_t seqMax);
+ SetSeqMax(uint32_t seqMax);
private:
uint32_t m_payloadSize; // expected payload size
- double m_maxSize; // max size to request
+ double m_maxSize; // max size to request
uint32_t m_initialWindow;
bool m_setInitialWindowOnTimeout;
diff --git a/apps/ndn-consumer-zipf-mandelbrot.cpp b/apps/ndn-consumer-zipf-mandelbrot.cpp
index a88befb..806b8e3 100644
--- a/apps/ndn-consumer-zipf-mandelbrot.cpp
+++ b/apps/ndn-consumer-zipf-mandelbrot.cpp
@@ -28,47 +28,45 @@
#include <math.h>
-
-NS_LOG_COMPONENT_DEFINE ("ndn.ConsumerZipfMandelbrot");
+NS_LOG_COMPONENT_DEFINE("ndn.ConsumerZipfMandelbrot");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (ConsumerZipfMandelbrot);
+NS_OBJECT_ENSURE_REGISTERED(ConsumerZipfMandelbrot);
TypeId
-ConsumerZipfMandelbrot::GetTypeId (void)
+ConsumerZipfMandelbrot::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::ConsumerZipfMandelbrot")
- .SetGroupName ("Ndn")
- .SetParent<ConsumerCbr> ()
- .AddConstructor<ConsumerZipfMandelbrot> ()
+ static TypeId tid =
+ TypeId("ns3::ndn::ConsumerZipfMandelbrot")
+ .SetGroupName("Ndn")
+ .SetParent<ConsumerCbr>()
+ .AddConstructor<ConsumerZipfMandelbrot>()
- .AddAttribute ("NumberOfContents", "Number of the Contents in total",
- StringValue ("100"),
- MakeUintegerAccessor (&ConsumerZipfMandelbrot::SetNumberOfContents, &ConsumerZipfMandelbrot::GetNumberOfContents),
- MakeUintegerChecker<uint32_t> ())
+ .AddAttribute("NumberOfContents", "Number of the Contents in total", StringValue("100"),
+ MakeUintegerAccessor(&ConsumerZipfMandelbrot::SetNumberOfContents,
+ &ConsumerZipfMandelbrot::GetNumberOfContents),
+ MakeUintegerChecker<uint32_t>())
- .AddAttribute ("q", "parameter of improve rank",
- StringValue ("0.7"),
- MakeDoubleAccessor (&ConsumerZipfMandelbrot::SetQ, &ConsumerZipfMandelbrot::GetQ),
- MakeDoubleChecker<double> ())
-
- .AddAttribute ("s", "parameter of power",
- StringValue ("0.7"),
- MakeDoubleAccessor (&ConsumerZipfMandelbrot::SetS, &ConsumerZipfMandelbrot::GetS),
- MakeDoubleChecker<double> ())
- ;
+ .AddAttribute("q", "parameter of improve rank", StringValue("0.7"),
+ MakeDoubleAccessor(&ConsumerZipfMandelbrot::SetQ,
+ &ConsumerZipfMandelbrot::GetQ),
+ MakeDoubleChecker<double>())
+
+ .AddAttribute("s", "parameter of power", StringValue("0.7"),
+ MakeDoubleAccessor(&ConsumerZipfMandelbrot::SetS,
+ &ConsumerZipfMandelbrot::GetS),
+ MakeDoubleChecker<double>());
return tid;
}
-
ConsumerZipfMandelbrot::ConsumerZipfMandelbrot()
- : m_N (100) // needed here to make sure when SetQ/SetS are called, there is a valid value of N
- , m_q (0.7)
- , m_s (0.7)
- , m_SeqRng (0.0, 1.0)
+ : m_N(100) // needed here to make sure when SetQ/SetS are called, there is a valid value of N
+ , m_q(0.7)
+ , m_s(0.7)
+ , m_SeqRng(0.0, 1.0)
{
// SetNumberOfContents is called by NS-3 object system during the initialization
}
@@ -78,135 +76,133 @@
}
void
-ConsumerZipfMandelbrot::SetNumberOfContents (uint32_t numOfContents)
+ConsumerZipfMandelbrot::SetNumberOfContents(uint32_t numOfContents)
{
m_N = numOfContents;
- NS_LOG_DEBUG (m_q << " and " << m_s << " and " << m_N);
+ NS_LOG_DEBUG(m_q << " and " << m_s << " and " << m_N);
- m_Pcum = std::vector<double> (m_N + 1);
+ m_Pcum = std::vector<double>(m_N + 1);
m_Pcum[0] = 0.0;
- for (uint32_t i=1; i<=m_N; i++)
- {
- m_Pcum[i] = m_Pcum[i-1] + 1.0 / std::pow(i+m_q, m_s);
- }
+ for (uint32_t i = 1; i <= m_N; i++) {
+ m_Pcum[i] = m_Pcum[i - 1] + 1.0 / std::pow(i + m_q, m_s);
+ }
- for (uint32_t i=1; i<=m_N; i++)
- {
- m_Pcum[i] = m_Pcum[i] / m_Pcum[m_N];
- NS_LOG_LOGIC ("Cumulative probability [" << i << "]=" << m_Pcum[i]);
+ for (uint32_t i = 1; i <= m_N; i++) {
+ m_Pcum[i] = m_Pcum[i] / m_Pcum[m_N];
+ NS_LOG_LOGIC("Cumulative probability [" << i << "]=" << m_Pcum[i]);
}
}
uint32_t
-ConsumerZipfMandelbrot::GetNumberOfContents () const
+ConsumerZipfMandelbrot::GetNumberOfContents() const
{
return m_N;
}
void
-ConsumerZipfMandelbrot::SetQ (double q)
+ConsumerZipfMandelbrot::SetQ(double q)
{
m_q = q;
- SetNumberOfContents (m_N);
+ SetNumberOfContents(m_N);
}
double
-ConsumerZipfMandelbrot::GetQ () const
+ConsumerZipfMandelbrot::GetQ() const
{
return m_q;
}
void
-ConsumerZipfMandelbrot::SetS (double s)
+ConsumerZipfMandelbrot::SetS(double s)
{
m_s = s;
- SetNumberOfContents (m_N);
+ SetNumberOfContents(m_N);
}
double
-ConsumerZipfMandelbrot::GetS () const
+ConsumerZipfMandelbrot::GetS() const
{
return m_s;
}
void
-ConsumerZipfMandelbrot::SendPacket() {
- if (!m_active) return;
+ConsumerZipfMandelbrot::SendPacket()
+{
+ if (!m_active)
+ return;
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
- uint32_t seq=std::numeric_limits<uint32_t>::max (); //invalid
+ uint32_t seq = std::numeric_limits<uint32_t>::max(); // invalid
// std::cout << Simulator::Now ().ToDouble (Time::S) << "s max -> " << m_seqMax << "\n";
- while (m_retxSeqs.size ())
- {
- seq = *m_retxSeqs.begin ();
- m_retxSeqs.erase (m_retxSeqs.begin ());
+ while (m_retxSeqs.size()) {
+ seq = *m_retxSeqs.begin();
+ m_retxSeqs.erase(m_retxSeqs.begin());
- // NS_ASSERT (m_seqLifetimes.find (seq) != m_seqLifetimes.end ());
- // if (m_seqLifetimes.find (seq)->time <= Simulator::Now ())
- // {
+ // NS_ASSERT (m_seqLifetimes.find (seq) != m_seqLifetimes.end ());
+ // if (m_seqLifetimes.find (seq)->time <= Simulator::Now ())
+ // {
- // NS_LOG_DEBUG ("Expire " << seq);
- // m_seqLifetimes.erase (seq); // lifetime expired. Trying to find another unexpired sequence number
- // continue;
- // }
- NS_LOG_DEBUG("=interest seq "<<seq<<" from m_retxSeqs");
- break;
+ // NS_LOG_DEBUG ("Expire " << seq);
+ // m_seqLifetimes.erase (seq); // lifetime expired. Trying to find another unexpired
+ // sequence number
+ // continue;
+ // }
+ NS_LOG_DEBUG("=interest seq " << seq << " from m_retxSeqs");
+ break;
+ }
+
+ if (seq == std::numeric_limits<uint32_t>::max()) // no retransmission
+ {
+ if (m_seqMax != std::numeric_limits<uint32_t>::max()) {
+ if (m_seq >= m_seqMax) {
+ return; // we are totally done
+ }
}
- if (seq == std::numeric_limits<uint32_t>::max ()) //no retransmission
- {
- if (m_seqMax != std::numeric_limits<uint32_t>::max ())
- {
- if (m_seq >= m_seqMax)
- {
- return; // we are totally done
- }
- }
-
- seq = ConsumerZipfMandelbrot::GetNextSeq();
- m_seq ++;
- }
+ seq = ConsumerZipfMandelbrot::GetNextSeq();
+ m_seq++;
+ }
// std::cout << Simulator::Now ().ToDouble (Time::S) << "s -> " << seq << "\n";
//
- Ptr<Name> nameWithSequence = Create<Name> (m_interestName);
- nameWithSequence->appendSeqNum (seq);
+ Ptr<Name> nameWithSequence = Create<Name>(m_interestName);
+ nameWithSequence->appendSeqNum(seq);
//
- Ptr<Interest> interest = Create<Interest> ();
- interest->SetNonce (m_rand.GetValue ());
- interest->SetName (nameWithSequence);
+ Ptr<Interest> interest = Create<Interest>();
+ interest->SetNonce(m_rand.GetValue());
+ interest->SetName(nameWithSequence);
// NS_LOG_INFO ("Requesting Interest: \n" << *interest);
- NS_LOG_INFO ("> Interest for " << seq<<", Total: "<<m_seq<<", face: "<<m_face->GetId());
- NS_LOG_DEBUG ("Trying to add " << seq << " with " << Simulator::Now () << ". already " << m_seqTimeouts.size () << " items");
+ NS_LOG_INFO("> Interest for " << seq << ", Total: " << m_seq << ", face: " << m_face->GetId());
+ NS_LOG_DEBUG("Trying to add " << seq << " with " << Simulator::Now() << ". already "
+ << m_seqTimeouts.size() << " items");
- m_seqTimeouts.insert (SeqTimeout (seq, Simulator::Now ()));
- m_seqFullDelay.insert (SeqTimeout (seq, Simulator::Now ()));
+ m_seqTimeouts.insert(SeqTimeout(seq, Simulator::Now()));
+ m_seqFullDelay.insert(SeqTimeout(seq, Simulator::Now()));
- m_seqLastDelay.erase (seq);
- m_seqLastDelay.insert (SeqTimeout (seq, Simulator::Now ()));
+ m_seqLastDelay.erase(seq);
+ m_seqLastDelay.insert(SeqTimeout(seq, Simulator::Now()));
- m_seqRetxCounts[seq] ++;
+ m_seqRetxCounts[seq]++;
- m_rtt->SentSeq (SequenceNumber32 (seq), 1);
+ m_rtt->SentSeq(SequenceNumber32(seq), 1);
FwHopCountTag hopCountTag;
- interest->GetPayload ()->AddPacketTag (hopCountTag);
+ interest->GetPayload()->AddPacketTag(hopCountTag);
- m_transmittedInterests (interest, this, m_face);
- m_face->ReceiveInterest (interest);
+ m_transmittedInterests(interest, this, m_face);
+ m_face->ReceiveInterest(interest);
- ConsumerZipfMandelbrot::ScheduleNextPacket ();
+ ConsumerZipfMandelbrot::ScheduleNextPacket();
}
-
uint32_t
ConsumerZipfMandelbrot::GetNextSeq()
{
@@ -214,42 +210,36 @@
double p_sum = 0;
double p_random = m_SeqRng.GetValue();
- while (p_random == 0)
- {
- p_random = m_SeqRng.GetValue();
- }
- //if (p_random == 0)
- NS_LOG_LOGIC("p_random="<<p_random);
- for (uint32_t i=1; i<=m_N; i++)
- {
- p_sum = m_Pcum[i]; //m_Pcum[i] = m_Pcum[i-1] + p[i], p[0] = 0; e.g.: p_cum[1] = p[1], p_cum[2] = p[1] + p[2]
- if (p_random <= p_sum)
- {
- content_index = i;
- break;
- } //if
- } //for
- //content_index = 1;
- NS_LOG_DEBUG("RandomNumber="<<content_index);
+ while (p_random == 0) {
+ p_random = m_SeqRng.GetValue();
+ }
+ // if (p_random == 0)
+ NS_LOG_LOGIC("p_random=" << p_random);
+ for (uint32_t i = 1; i <= m_N; i++) {
+ p_sum = m_Pcum[i]; // m_Pcum[i] = m_Pcum[i-1] + p[i], p[0] = 0; e.g.: p_cum[1] = p[1],
+ // p_cum[2] = p[1] + p[2]
+ if (p_random <= p_sum) {
+ content_index = i;
+ break;
+ } // if
+ } // for
+ // content_index = 1;
+ NS_LOG_DEBUG("RandomNumber=" << content_index);
return content_index;
}
void
-ConsumerZipfMandelbrot::ScheduleNextPacket() {
+ConsumerZipfMandelbrot::ScheduleNextPacket()
+{
- if (m_firstTime)
- {
- m_sendEvent = Simulator::Schedule (Seconds (0.0),
- &ConsumerZipfMandelbrot::SendPacket, this);
- m_firstTime = false;
- }
- else if (!m_sendEvent.IsRunning ())
- m_sendEvent = Simulator::Schedule (
- (m_random == 0) ?
- Seconds(1.0 / m_frequency)
- :
- Seconds(m_random->GetValue ()),
- &ConsumerZipfMandelbrot::SendPacket, this);
+ if (m_firstTime) {
+ m_sendEvent = Simulator::Schedule(Seconds(0.0), &ConsumerZipfMandelbrot::SendPacket, this);
+ m_firstTime = false;
+ }
+ else if (!m_sendEvent.IsRunning())
+ m_sendEvent = Simulator::Schedule((m_random == 0) ? Seconds(1.0 / m_frequency)
+ : Seconds(m_random->GetValue()),
+ &ConsumerZipfMandelbrot::SendPacket, this);
}
} /* namespace ndn */
diff --git a/apps/ndn-consumer-zipf-mandelbrot.hpp b/apps/ndn-consumer-zipf-mandelbrot.hpp
index 302427b..ee192db 100644
--- a/apps/ndn-consumer-zipf-mandelbrot.hpp
+++ b/apps/ndn-consumer-zipf-mandelbrot.hpp
@@ -18,7 +18,6 @@
* Author: Xiaoke Jiang <shock.jiang@gmail.com>
*/
-
#ifndef NDN_CONSUMER_ZIPF_MANDELBROT_H_
#define NDN_CONSUMER_ZIPF_MANDELBROT_H_
@@ -42,54 +41,57 @@
* @brief NDN app requesting contents following Zipf-Mandelbrot Distbituion
*
* The class implements an app which requests contents following Zipf-Mandelbrot Distribution
- * Here is the explaination of Zipf-Mandelbrot Distribution: http://en.wikipedia.org/wiki/Zipf%E2%80%93Mandelbrot_law
+ * Here is the explaination of Zipf-Mandelbrot Distribution:
+ *http://en.wikipedia.org/wiki/Zipf%E2%80%93Mandelbrot_law
*/
-class ConsumerZipfMandelbrot: public ConsumerCbr
-{
+class ConsumerZipfMandelbrot : public ConsumerCbr {
public:
- static TypeId GetTypeId ();
+ static TypeId
+ GetTypeId();
/**
* \brief Default constructor
* Sets up randomized Number Generator (RNG)
* Note: m_seq of its parent class ConsumerCbr here is used to record the interest number
*/
- ConsumerZipfMandelbrot ();
- virtual ~ConsumerZipfMandelbrot ();
+ ConsumerZipfMandelbrot();
+ virtual ~ConsumerZipfMandelbrot();
- virtual void SendPacket();
- uint32_t GetNextSeq();
+ virtual void
+ SendPacket();
+ uint32_t
+ GetNextSeq();
protected:
virtual void
- ScheduleNextPacket ();
+ ScheduleNextPacket();
private:
void
- SetNumberOfContents (uint32_t numOfContents);
+ SetNumberOfContents(uint32_t numOfContents);
uint32_t
- GetNumberOfContents () const;
+ GetNumberOfContents() const;
void
- SetQ (double q);
+ SetQ(double q);
double
- GetQ () const;
+ GetQ() const;
void
- SetS (double s);
+ SetS(double s);
double
- GetS () const;
+ GetS() const;
private:
- uint32_t m_N; //number of the contents
- double m_q; //q in (k+q)^s
- double m_s; //s in (k+q)^s
- std::vector<double> m_Pcum; //cumulative probability
+ uint32_t m_N; // number of the contents
+ double m_q; // q in (k+q)^s
+ double m_s; // s in (k+q)^s
+ std::vector<double> m_Pcum; // cumulative probability
- UniformVariable m_SeqRng; //RNG
+ UniformVariable m_SeqRng; // RNG
};
} /* namespace ndn */
diff --git a/apps/ndn-consumer.cpp b/apps/ndn-consumer.cpp
index e94f751..fabbe95 100644
--- a/apps/ndn-consumer.cpp
+++ b/apps/ndn-consumer.cpp
@@ -40,286 +40,276 @@
#include "ns3/names.h"
-NS_LOG_COMPONENT_DEFINE ("ndn.Consumer");
+NS_LOG_COMPONENT_DEFINE("ndn.Consumer");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (Consumer);
+NS_OBJECT_ENSURE_REGISTERED(Consumer);
TypeId
-Consumer::GetTypeId (void)
+Consumer::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::Consumer")
- .SetGroupName ("Ndn")
- .SetParent<App> ()
- .AddAttribute ("StartSeq", "Initial sequence number",
- IntegerValue (0),
- MakeIntegerAccessor(&Consumer::m_seq),
- MakeIntegerChecker<int32_t>())
+ static TypeId tid =
+ TypeId("ns3::ndn::Consumer")
+ .SetGroupName("Ndn")
+ .SetParent<App>()
+ .AddAttribute("StartSeq", "Initial sequence number", IntegerValue(0),
+ MakeIntegerAccessor(&Consumer::m_seq), MakeIntegerChecker<int32_t>())
- .AddAttribute ("Prefix","Name of the Interest",
- StringValue ("/"),
- MakeNameAccessor (&Consumer::m_interestName),
- MakeNameChecker ())
- .AddAttribute ("LifeTime", "LifeTime for interest packet",
- StringValue ("2s"),
- MakeTimeAccessor (&Consumer::m_interestLifeTime),
- MakeTimeChecker ())
+ .AddAttribute("Prefix", "Name of the Interest", StringValue("/"),
+ MakeNameAccessor(&Consumer::m_interestName), MakeNameChecker())
+ .AddAttribute("LifeTime", "LifeTime for interest packet", StringValue("2s"),
+ MakeTimeAccessor(&Consumer::m_interestLifeTime), MakeTimeChecker())
- .AddAttribute ("RetxTimer",
- "Timeout defining how frequent retransmission timeouts should be checked",
- StringValue ("50ms"),
- MakeTimeAccessor (&Consumer::GetRetxTimer, &Consumer::SetRetxTimer),
- MakeTimeChecker ())
+ .AddAttribute("RetxTimer",
+ "Timeout defining how frequent retransmission timeouts should be checked",
+ StringValue("50ms"),
+ MakeTimeAccessor(&Consumer::GetRetxTimer, &Consumer::SetRetxTimer),
+ MakeTimeChecker())
- .AddTraceSource ("LastRetransmittedInterestDataDelay", "Delay between last retransmitted Interest and received Data",
- MakeTraceSourceAccessor (&Consumer::m_lastRetransmittedInterestDataDelay))
+ .AddTraceSource("LastRetransmittedInterestDataDelay",
+ "Delay between last retransmitted Interest and received Data",
+ MakeTraceSourceAccessor(&Consumer::m_lastRetransmittedInterestDataDelay))
- .AddTraceSource ("FirstInterestDataDelay", "Delay between first transmitted Interest and received Data",
- MakeTraceSourceAccessor (&Consumer::m_firstInterestDataDelay))
- ;
+ .AddTraceSource("FirstInterestDataDelay",
+ "Delay between first transmitted Interest and received Data",
+ MakeTraceSourceAccessor(&Consumer::m_firstInterestDataDelay));
return tid;
}
-Consumer::Consumer ()
- : m_rand (0, std::numeric_limits<uint32_t>::max ())
- , m_seq (0)
- , m_seqMax (0) // don't request anything
+Consumer::Consumer()
+ : m_rand(0, std::numeric_limits<uint32_t>::max())
+ , m_seq(0)
+ , m_seqMax(0) // don't request anything
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
- m_rtt = CreateObject<RttMeanDeviation> ();
+ m_rtt = CreateObject<RttMeanDeviation>();
}
void
-Consumer::SetRetxTimer (Time retxTimer)
+Consumer::SetRetxTimer(Time retxTimer)
{
m_retxTimer = retxTimer;
- if (m_retxEvent.IsRunning ())
- {
- // m_retxEvent.Cancel (); // cancel any scheduled cleanup events
- Simulator::Remove (m_retxEvent); // slower, but better for memory
- }
+ if (m_retxEvent.IsRunning()) {
+ // m_retxEvent.Cancel (); // cancel any scheduled cleanup events
+ Simulator::Remove(m_retxEvent); // slower, but better for memory
+ }
// schedule even with new timeout
- m_retxEvent = Simulator::Schedule (m_retxTimer,
- &Consumer::CheckRetxTimeout, this);
+ m_retxEvent = Simulator::Schedule(m_retxTimer, &Consumer::CheckRetxTimeout, this);
}
Time
-Consumer::GetRetxTimer () const
+Consumer::GetRetxTimer() const
{
return m_retxTimer;
}
void
-Consumer::CheckRetxTimeout ()
+Consumer::CheckRetxTimeout()
{
- Time now = Simulator::Now ();
+ Time now = Simulator::Now();
- Time rto = m_rtt->RetransmitTimeout ();
+ Time rto = m_rtt->RetransmitTimeout();
// NS_LOG_DEBUG ("Current RTO: " << rto.ToDouble (Time::S) << "s");
- while (!m_seqTimeouts.empty ())
+ while (!m_seqTimeouts.empty()) {
+ SeqTimeoutsContainer::index<i_timestamp>::type::iterator entry =
+ m_seqTimeouts.get<i_timestamp>().begin();
+ if (entry->time + rto <= now) // timeout expired?
{
- SeqTimeoutsContainer::index<i_timestamp>::type::iterator entry =
- m_seqTimeouts.get<i_timestamp> ().begin ();
- if (entry->time + rto <= now) // timeout expired?
- {
- uint32_t seqNo = entry->seq;
- m_seqTimeouts.get<i_timestamp> ().erase (entry);
- OnTimeout (seqNo);
- }
- else
- break; // nothing else to do. All later packets need not be retransmitted
+ uint32_t seqNo = entry->seq;
+ m_seqTimeouts.get<i_timestamp>().erase(entry);
+ OnTimeout(seqNo);
}
+ else
+ break; // nothing else to do. All later packets need not be retransmitted
+ }
- m_retxEvent = Simulator::Schedule (m_retxTimer,
- &Consumer::CheckRetxTimeout, this);
+ m_retxEvent = Simulator::Schedule(m_retxTimer, &Consumer::CheckRetxTimeout, this);
}
// Application Methods
void
-Consumer::StartApplication () // Called at time specified by Start
+Consumer::StartApplication() // Called at time specified by Start
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
// do base stuff
- App::StartApplication ();
+ App::StartApplication();
- ScheduleNextPacket ();
+ ScheduleNextPacket();
}
void
-Consumer::StopApplication () // Called at time specified by Stop
+Consumer::StopApplication() // Called at time specified by Stop
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
// cancel periodic packet generation
- Simulator::Cancel (m_sendEvent);
+ Simulator::Cancel(m_sendEvent);
// cleanup base stuff
- App::StopApplication ();
+ App::StopApplication();
}
void
-Consumer::SendPacket ()
+Consumer::SendPacket()
{
- if (!m_active) return;
+ if (!m_active)
+ return;
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
- uint32_t seq=std::numeric_limits<uint32_t>::max (); //invalid
+ uint32_t seq = std::numeric_limits<uint32_t>::max(); // invalid
- while (m_retxSeqs.size ())
- {
- seq = *m_retxSeqs.begin ();
- m_retxSeqs.erase (m_retxSeqs.begin ());
- break;
+ while (m_retxSeqs.size()) {
+ seq = *m_retxSeqs.begin();
+ m_retxSeqs.erase(m_retxSeqs.begin());
+ break;
+ }
+
+ if (seq == std::numeric_limits<uint32_t>::max()) {
+ if (m_seqMax != std::numeric_limits<uint32_t>::max()) {
+ if (m_seq >= m_seqMax) {
+ return; // we are totally done
+ }
}
- if (seq == std::numeric_limits<uint32_t>::max ())
- {
- if (m_seqMax != std::numeric_limits<uint32_t>::max ())
- {
- if (m_seq >= m_seqMax)
- {
- return; // we are totally done
- }
- }
-
- seq = m_seq++;
- }
+ seq = m_seq++;
+ }
//
- Ptr<Name> nameWithSequence = Create<Name> (m_interestName);
- nameWithSequence->appendSeqNum (seq);
+ Ptr<Name> nameWithSequence = Create<Name>(m_interestName);
+ nameWithSequence->appendSeqNum(seq);
//
- Ptr<Interest> interest = Create<Interest> ();
- interest->SetNonce (m_rand.GetValue ());
- interest->SetName (nameWithSequence);
- interest->SetInterestLifetime (m_interestLifeTime);
+ Ptr<Interest> interest = Create<Interest>();
+ interest->SetNonce(m_rand.GetValue());
+ interest->SetName(nameWithSequence);
+ interest->SetInterestLifetime(m_interestLifeTime);
// NS_LOG_INFO ("Requesting Interest: \n" << *interest);
- NS_LOG_INFO ("> Interest for " << seq);
+ NS_LOG_INFO("> Interest for " << seq);
- WillSendOutInterest (seq);
+ WillSendOutInterest(seq);
FwHopCountTag hopCountTag;
- interest->GetPayload ()->AddPacketTag (hopCountTag);
+ interest->GetPayload()->AddPacketTag(hopCountTag);
- m_transmittedInterests (interest, this, m_face);
- m_face->ReceiveInterest (interest);
+ m_transmittedInterests(interest, this, m_face);
+ m_face->ReceiveInterest(interest);
- ScheduleNextPacket ();
+ ScheduleNextPacket();
}
///////////////////////////////////////////////////
// Process incoming packets //
///////////////////////////////////////////////////
-
void
-Consumer::OnData (Ptr<const Data> data)
+Consumer::OnData(Ptr<const Data> data)
{
- if (!m_active) return;
+ if (!m_active)
+ return;
- App::OnData (data); // tracing inside
+ App::OnData(data); // tracing inside
- NS_LOG_FUNCTION (this << data);
+ NS_LOG_FUNCTION(this << data);
// NS_LOG_INFO ("Received content object: " << boost::cref(*data));
- uint32_t seq = data->GetName ().get (-1).toSeqNum ();
- NS_LOG_INFO ("< DATA for " << seq);
+ uint32_t seq = data->GetName().get(-1).toSeqNum();
+ NS_LOG_INFO("< DATA for " << seq);
int hopCount = -1;
FwHopCountTag hopCountTag;
- if (data->GetPayload ()->PeekPacketTag (hopCountTag))
- {
- hopCount = hopCountTag.Get ();
- }
+ if (data->GetPayload()->PeekPacketTag(hopCountTag)) {
+ hopCount = hopCountTag.Get();
+ }
- SeqTimeoutsContainer::iterator entry = m_seqLastDelay.find (seq);
- if (entry != m_seqLastDelay.end ())
- {
- m_lastRetransmittedInterestDataDelay (this, seq, Simulator::Now () - entry->time, hopCount);
- }
+ SeqTimeoutsContainer::iterator entry = m_seqLastDelay.find(seq);
+ if (entry != m_seqLastDelay.end()) {
+ m_lastRetransmittedInterestDataDelay(this, seq, Simulator::Now() - entry->time, hopCount);
+ }
- entry = m_seqFullDelay.find (seq);
- if (entry != m_seqFullDelay.end ())
- {
- m_firstInterestDataDelay (this, seq, Simulator::Now () - entry->time, m_seqRetxCounts[seq], hopCount);
- }
+ entry = m_seqFullDelay.find(seq);
+ if (entry != m_seqFullDelay.end()) {
+ m_firstInterestDataDelay(this, seq, Simulator::Now() - entry->time, m_seqRetxCounts[seq],
+ hopCount);
+ }
- m_seqRetxCounts.erase (seq);
- m_seqFullDelay.erase (seq);
- m_seqLastDelay.erase (seq);
+ m_seqRetxCounts.erase(seq);
+ m_seqFullDelay.erase(seq);
+ m_seqLastDelay.erase(seq);
- m_seqTimeouts.erase (seq);
- m_retxSeqs.erase (seq);
+ m_seqTimeouts.erase(seq);
+ m_retxSeqs.erase(seq);
- m_rtt->AckSeq (SequenceNumber32 (seq));
+ m_rtt->AckSeq(SequenceNumber32(seq));
}
void
-Consumer::OnNack (Ptr<const Interest> interest)
+Consumer::OnNack(Ptr<const Interest> interest)
{
- if (!m_active) return;
+ if (!m_active)
+ return;
- App::OnNack (interest); // tracing inside
+ App::OnNack(interest); // tracing inside
// NS_LOG_DEBUG ("Nack type: " << interest->GetNack ());
// NS_LOG_FUNCTION (interest->GetName ());
// NS_LOG_INFO ("Received NACK: " << boost::cref(*interest));
- uint32_t seq = interest->GetName ().get (-1).toSeqNum ();
- NS_LOG_INFO ("< NACK for " << seq);
+ uint32_t seq = interest->GetName().get(-1).toSeqNum();
+ NS_LOG_INFO("< NACK for " << seq);
// std::cout << Simulator::Now ().ToDouble (Time::S) << "s -> " << "NACK for " << seq << "\n";
// put in the queue of interests to be retransmitted
// NS_LOG_INFO ("Before: " << m_retxSeqs.size ());
- m_retxSeqs.insert (seq);
+ m_retxSeqs.insert(seq);
// NS_LOG_INFO ("After: " << m_retxSeqs.size ());
- m_seqTimeouts.erase (seq);
+ m_seqTimeouts.erase(seq);
- m_rtt->IncreaseMultiplier (); // Double the next RTO ??
- ScheduleNextPacket ();
+ m_rtt->IncreaseMultiplier(); // Double the next RTO ??
+ ScheduleNextPacket();
}
void
-Consumer::OnTimeout (uint32_t sequenceNumber)
+Consumer::OnTimeout(uint32_t sequenceNumber)
{
- NS_LOG_FUNCTION (sequenceNumber);
- // std::cout << Simulator::Now () << ", TO: " << sequenceNumber << ", current RTO: " << m_rtt->RetransmitTimeout ().ToDouble (Time::S) << "s\n";
+ NS_LOG_FUNCTION(sequenceNumber);
+ // std::cout << Simulator::Now () << ", TO: " << sequenceNumber << ", current RTO: " <<
+ // m_rtt->RetransmitTimeout ().ToDouble (Time::S) << "s\n";
- m_rtt->IncreaseMultiplier (); // Double the next RTO
- m_rtt->SentSeq (SequenceNumber32 (sequenceNumber), 1); // make sure to disable RTT calculation for this sample
- m_retxSeqs.insert (sequenceNumber);
- ScheduleNextPacket ();
+ m_rtt->IncreaseMultiplier(); // Double the next RTO
+ m_rtt->SentSeq(SequenceNumber32(sequenceNumber),
+ 1); // make sure to disable RTT calculation for this sample
+ m_retxSeqs.insert(sequenceNumber);
+ ScheduleNextPacket();
}
void
-Consumer::WillSendOutInterest (uint32_t sequenceNumber)
+Consumer::WillSendOutInterest(uint32_t sequenceNumber)
{
- NS_LOG_DEBUG ("Trying to add " << sequenceNumber << " with " << Simulator::Now () << ". already " << m_seqTimeouts.size () << " items");
+ NS_LOG_DEBUG("Trying to add " << sequenceNumber << " with " << Simulator::Now() << ". already "
+ << m_seqTimeouts.size() << " items");
- m_seqTimeouts.insert (SeqTimeout (sequenceNumber, Simulator::Now ()));
- m_seqFullDelay.insert (SeqTimeout (sequenceNumber, Simulator::Now ()));
+ m_seqTimeouts.insert(SeqTimeout(sequenceNumber, Simulator::Now()));
+ m_seqFullDelay.insert(SeqTimeout(sequenceNumber, Simulator::Now()));
- m_seqLastDelay.erase (sequenceNumber);
- m_seqLastDelay.insert (SeqTimeout (sequenceNumber, Simulator::Now ()));
+ m_seqLastDelay.erase(sequenceNumber);
+ m_seqLastDelay.insert(SeqTimeout(sequenceNumber, Simulator::Now()));
- m_seqRetxCounts[sequenceNumber] ++;
+ m_seqRetxCounts[sequenceNumber]++;
- m_rtt->SentSeq (SequenceNumber32 (sequenceNumber), 1);
+ m_rtt->SentSeq(SequenceNumber32(sequenceNumber), 1);
}
-
} // namespace ndn
} // namespace ns3
diff --git a/apps/ndn-consumer.hpp b/apps/ndn-consumer.hpp
index d0f82cc..83ece12 100644
--- a/apps/ndn-consumer.hpp
+++ b/apps/ndn-consumer.hpp
@@ -44,158 +44,168 @@
* @ingroup ndn-apps
* \brief NDN application for sending out Interest packets
*/
-class Consumer: public App
-{
+class Consumer : public App {
public:
- static TypeId GetTypeId ();
+ static TypeId
+ GetTypeId();
/**
* \brief Default constructor
* Sets up randomizer function and packet sequence number
*/
- Consumer ();
- virtual ~Consumer () {};
+ Consumer();
+ virtual ~Consumer(){};
// From App
// virtual void
// OnInterest (const Ptr<const Interest> &interest);
virtual void
- OnNack (Ptr<const Interest> interest);
+ OnNack(Ptr<const Interest> interest);
virtual void
- OnData (Ptr<const Data> contentObject);
+ OnData(Ptr<const Data> contentObject);
/**
* @brief Timeout event
* @param sequenceNumber time outed sequence number
*/
virtual void
- OnTimeout (uint32_t sequenceNumber);
+ OnTimeout(uint32_t sequenceNumber);
/**
* @brief Actually send packet
*/
void
- SendPacket ();
+ SendPacket();
/**
- * @brief An event that is fired just before an Interest packet is actually send out (send is inevitable)
+ * @brief An event that is fired just before an Interest packet is actually send out (send is
+ *inevitable)
*
- * The reason for "before" even is that in certain cases (when it is possible to satisfy from the local cache),
- * the send call will immediately return data, and if "after" even was used, this after would be called after
+ * The reason for "before" even is that in certain cases (when it is possible to satisfy from the
+ *local cache),
+ * the send call will immediately return data, and if "after" even was used, this after would be
+ *called after
* all processing of incoming data, potentially producing unexpected results.
*/
virtual void
- WillSendOutInterest (uint32_t sequenceNumber);
-
+ WillSendOutInterest(uint32_t sequenceNumber);
+
protected:
// from App
virtual void
- StartApplication ();
+ StartApplication();
virtual void
- StopApplication ();
+ StopApplication();
/**
- * \brief Constructs the Interest packet and sends it using a callback to the underlying NDN protocol
+ * \brief Constructs the Interest packet and sends it using a callback to the underlying NDN
+ * protocol
*/
virtual void
- ScheduleNextPacket () = 0;
+ ScheduleNextPacket() = 0;
/**
* \brief Checks if the packet need to be retransmitted becuase of retransmission timer expiration
*/
void
- CheckRetxTimeout ();
+ CheckRetxTimeout();
/**
* \brief Modifies the frequency of checking the retransmission timeouts
* \param retxTimer Timeout defining how frequent retransmission timeouts should be checked
*/
void
- SetRetxTimer (Time retxTimer);
+ SetRetxTimer(Time retxTimer);
/**
* \brief Returns the frequency of checking the retransmission timeouts
* \return Timeout defining how frequent retransmission timeouts should be checked
*/
Time
- GetRetxTimer () const;
+ GetRetxTimer() const;
protected:
UniformVariable m_rand; ///< @brief nonce generator
- uint32_t m_seq; ///< @brief currently requested sequence number
- uint32_t m_seqMax; ///< @brief maximum number of sequence number
- EventId m_sendEvent; ///< @brief EventId of pending "send packet" event
- Time m_retxTimer; ///< @brief Currently estimated retransmission timer
- EventId m_retxEvent; ///< @brief Event to check whether or not retransmission should be performed
+ uint32_t m_seq; ///< @brief currently requested sequence number
+ uint32_t m_seqMax; ///< @brief maximum number of sequence number
+ EventId m_sendEvent; ///< @brief EventId of pending "send packet" event
+ Time m_retxTimer; ///< @brief Currently estimated retransmission timer
+ EventId m_retxEvent; ///< @brief Event to check whether or not retransmission should be performed
Ptr<RttEstimator> m_rtt; ///< @brief RTT estimator
- Time m_offTime; ///< \brief Time interval between packets
- Name m_interestName; ///< \brief NDN Name of the Interest (use Name)
- Time m_interestLifeTime; ///< \brief LifeTime for interest packet
+ Time m_offTime; ///< \brief Time interval between packets
+ Name m_interestName; ///< \brief NDN Name of the Interest (use Name)
+ Time m_interestLifeTime; ///< \brief LifeTime for interest packet
-/// @cond include_hidden
+ /// @cond include_hidden
/**
* \struct This struct contains sequence numbers of packets to be retransmitted
*/
- struct RetxSeqsContainer :
- public std::set<uint32_t> { };
+ struct RetxSeqsContainer : public std::set<uint32_t> {
+ };
- RetxSeqsContainer m_retxSeqs; ///< \brief ordered set of sequence numbers to be retransmitted
+ RetxSeqsContainer m_retxSeqs; ///< \brief ordered set of sequence numbers to be retransmitted
/**
* \struct This struct contains a pair of packet sequence number and its timeout
*/
- struct SeqTimeout
- {
- SeqTimeout (uint32_t _seq, Time _time) : seq (_seq), time (_time) { }
+ struct SeqTimeout {
+ SeqTimeout(uint32_t _seq, Time _time)
+ : seq(_seq)
+ , time(_time)
+ {
+ }
uint32_t seq;
Time time;
};
-/// @endcond
+ /// @endcond
-/// @cond include_hidden
- class i_seq { };
- class i_timestamp { };
-/// @endcond
+ /// @cond include_hidden
+ class i_seq {
+ };
+ class i_timestamp {
+ };
+ /// @endcond
-/// @cond include_hidden
+ /// @cond include_hidden
/**
* \struct This struct contains a multi-index for the set of SeqTimeout structs
*/
- struct SeqTimeoutsContainer :
- public boost::multi_index::multi_index_container<
- SeqTimeout,
- boost::multi_index::indexed_by<
- boost::multi_index::ordered_unique<
- boost::multi_index::tag<i_seq>,
- boost::multi_index::member<SeqTimeout, uint32_t, &SeqTimeout::seq>
- >,
- boost::multi_index::ordered_non_unique<
- boost::multi_index::tag<i_timestamp>,
- boost::multi_index::member<SeqTimeout, Time, &SeqTimeout::time>
- >
- >
- > { } ;
+ struct SeqTimeoutsContainer
+ : public boost::multi_index::
+ multi_index_container<SeqTimeout,
+ boost::multi_index::
+ indexed_by<boost::multi_index::
+ ordered_unique<boost::multi_index::tag<i_seq>,
+ boost::multi_index::
+ member<SeqTimeout, uint32_t,
+ &SeqTimeout::seq>>,
+ boost::multi_index::
+ ordered_non_unique<boost::multi_index::
+ tag<i_timestamp>,
+ boost::multi_index::
+ member<SeqTimeout, Time,
+ &SeqTimeout::time>>>> {
+ };
- SeqTimeoutsContainer m_seqTimeouts; ///< \brief multi-index for the set of SeqTimeout structs
+ SeqTimeoutsContainer m_seqTimeouts; ///< \brief multi-index for the set of SeqTimeout structs
SeqTimeoutsContainer m_seqLastDelay;
SeqTimeoutsContainer m_seqFullDelay;
std::map<uint32_t, uint32_t> m_seqRetxCounts;
- TracedCallback<Ptr<App> /* app */, uint32_t /* seqno */,
- Time /* delay */, int32_t /*hop count*/> m_lastRetransmittedInterestDataDelay;
- TracedCallback<Ptr<App> /* app */, uint32_t /* seqno */,
- Time /* delay */, uint32_t /*retx count*/,
- int32_t /*hop count*/> m_firstInterestDataDelay;
+ TracedCallback<Ptr<App> /* app */, uint32_t /* seqno */, Time /* delay */, int32_t /*hop count*/>
+ m_lastRetransmittedInterestDataDelay;
+ TracedCallback<Ptr<App> /* app */, uint32_t /* seqno */, Time /* delay */,
+ uint32_t /*retx count*/, int32_t /*hop count*/> m_firstInterestDataDelay;
-/// @endcond
+ /// @endcond
};
} // namespace ndn
diff --git a/apps/ndn-producer.cpp b/apps/ndn-producer.cpp
index 605b082..67a5043 100644
--- a/apps/ndn-producer.cpp
+++ b/apps/ndn-producer.cpp
@@ -38,119 +38,114 @@
#include <boost/lambda/bind.hpp>
namespace ll = boost::lambda;
-NS_LOG_COMPONENT_DEFINE ("ndn.Producer");
+NS_LOG_COMPONENT_DEFINE("ndn.Producer");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (Producer);
+NS_OBJECT_ENSURE_REGISTERED(Producer);
TypeId
-Producer::GetTypeId (void)
+Producer::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::Producer")
- .SetGroupName ("Ndn")
- .SetParent<App> ()
- .AddConstructor<Producer> ()
- .AddAttribute ("Prefix","Prefix, for which producer has the data",
- StringValue ("/"),
- MakeNameAccessor (&Producer::m_prefix),
- MakeNameChecker ())
- .AddAttribute ("Postfix", "Postfix that is added to the output data (e.g., for adding producer-uniqueness)",
- StringValue ("/"),
- MakeNameAccessor (&Producer::m_postfix),
- MakeNameChecker ())
- .AddAttribute ("PayloadSize", "Virtual payload size for Content packets",
- UintegerValue (1024),
- MakeUintegerAccessor (&Producer::m_virtualPayloadSize),
- MakeUintegerChecker<uint32_t> ())
- .AddAttribute ("Freshness", "Freshness of data packets, if 0, then unlimited freshness",
- TimeValue (Seconds (0)),
- MakeTimeAccessor (&Producer::m_freshness),
- MakeTimeChecker ())
- .AddAttribute ("Signature", "Fake signature, 0 valid signature (default), other values application-specific",
- UintegerValue (0),
- MakeUintegerAccessor (&Producer::m_signature),
- MakeUintegerChecker<uint32_t> ())
- .AddAttribute ("KeyLocator", "Name to be used for key locator. If root, then key locator is not used",
- NameValue (),
- MakeNameAccessor (&Producer::m_keyLocator),
- MakeNameChecker ())
- ;
+ static TypeId tid =
+ TypeId("ns3::ndn::Producer")
+ .SetGroupName("Ndn")
+ .SetParent<App>()
+ .AddConstructor<Producer>()
+ .AddAttribute("Prefix", "Prefix, for which producer has the data", StringValue("/"),
+ MakeNameAccessor(&Producer::m_prefix), MakeNameChecker())
+ .AddAttribute(
+ "Postfix",
+ "Postfix that is added to the output data (e.g., for adding producer-uniqueness)",
+ StringValue("/"), MakeNameAccessor(&Producer::m_postfix), MakeNameChecker())
+ .AddAttribute("PayloadSize", "Virtual payload size for Content packets", UintegerValue(1024),
+ MakeUintegerAccessor(&Producer::m_virtualPayloadSize),
+ MakeUintegerChecker<uint32_t>())
+ .AddAttribute("Freshness", "Freshness of data packets, if 0, then unlimited freshness",
+ TimeValue(Seconds(0)), MakeTimeAccessor(&Producer::m_freshness),
+ MakeTimeChecker())
+ .AddAttribute(
+ "Signature",
+ "Fake signature, 0 valid signature (default), other values application-specific",
+ UintegerValue(0), MakeUintegerAccessor(&Producer::m_signature),
+ MakeUintegerChecker<uint32_t>())
+ .AddAttribute("KeyLocator",
+ "Name to be used for key locator. If root, then key locator is not used",
+ NameValue(), MakeNameAccessor(&Producer::m_keyLocator), MakeNameChecker());
return tid;
}
-Producer::Producer ()
+Producer::Producer()
{
// NS_LOG_FUNCTION_NOARGS ();
}
// inherited from Application base class.
void
-Producer::StartApplication ()
+Producer::StartApplication()
{
- NS_LOG_FUNCTION_NOARGS ();
- NS_ASSERT (GetNode ()->GetObject<Fib> () != 0);
+ NS_LOG_FUNCTION_NOARGS();
+ NS_ASSERT(GetNode()->GetObject<Fib>() != 0);
- App::StartApplication ();
+ App::StartApplication();
- NS_LOG_DEBUG ("NodeID: " << GetNode ()->GetId ());
+ NS_LOG_DEBUG("NodeID: " << GetNode()->GetId());
- Ptr<Fib> fib = GetNode ()->GetObject<Fib> ();
+ Ptr<Fib> fib = GetNode()->GetObject<Fib>();
- Ptr<fib::Entry> fibEntry = fib->Add (m_prefix, m_face, 0);
+ Ptr<fib::Entry> fibEntry = fib->Add(m_prefix, m_face, 0);
- fibEntry->UpdateStatus (m_face, fib::FaceMetric::NDN_FIB_GREEN);
+ fibEntry->UpdateStatus(m_face, fib::FaceMetric::NDN_FIB_GREEN);
// // make face green, so it will be used primarily
// StaticCast<fib::FibImpl> (fib)->modify (fibEntry,
// ll::bind (&fib::Entry::UpdateStatus,
- // ll::_1, m_face, fib::FaceMetric::NDN_FIB_GREEN));
+ // ll::_1, m_face,
+ // fib::FaceMetric::NDN_FIB_GREEN));
}
void
-Producer::StopApplication ()
+Producer::StopApplication()
{
- NS_LOG_FUNCTION_NOARGS ();
- NS_ASSERT (GetNode ()->GetObject<Fib> () != 0);
+ NS_LOG_FUNCTION_NOARGS();
+ NS_ASSERT(GetNode()->GetObject<Fib>() != 0);
- App::StopApplication ();
+ App::StopApplication();
}
-
void
-Producer::OnInterest (Ptr<const Interest> interest)
+Producer::OnInterest(Ptr<const Interest> interest)
{
- App::OnInterest (interest); // tracing inside
+ App::OnInterest(interest); // tracing inside
- NS_LOG_FUNCTION (this << interest);
+ NS_LOG_FUNCTION(this << interest);
- if (!m_active) return;
+ if (!m_active)
+ return;
- Ptr<Data> data = Create<Data> (Create<Packet> (m_virtualPayloadSize));
- Ptr<Name> dataName = Create<Name> (interest->GetName ());
- dataName->append (m_postfix);
- data->SetName (dataName);
- data->SetFreshness (m_freshness);
- data->SetTimestamp (Simulator::Now());
+ Ptr<Data> data = Create<Data>(Create<Packet>(m_virtualPayloadSize));
+ Ptr<Name> dataName = Create<Name>(interest->GetName());
+ dataName->append(m_postfix);
+ data->SetName(dataName);
+ data->SetFreshness(m_freshness);
+ data->SetTimestamp(Simulator::Now());
- data->SetSignature (m_signature);
- if (m_keyLocator.size () > 0)
- {
- data->SetKeyLocator (Create<Name> (m_keyLocator));
- }
+ data->SetSignature(m_signature);
+ if (m_keyLocator.size() > 0) {
+ data->SetKeyLocator(Create<Name>(m_keyLocator));
+ }
- NS_LOG_INFO ("node("<< GetNode()->GetId() <<") respodning with Data: " << data->GetName ());
+ NS_LOG_INFO("node(" << GetNode()->GetId() << ") respodning with Data: " << data->GetName());
// Echo back FwHopCountTag if exists
FwHopCountTag hopCountTag;
- if (interest->GetPayload ()->PeekPacketTag (hopCountTag))
- {
- data->GetPayload ()->AddPacketTag (hopCountTag);
- }
+ if (interest->GetPayload()->PeekPacketTag(hopCountTag)) {
+ data->GetPayload()->AddPacketTag(hopCountTag);
+ }
- m_face->ReceiveData (data);
- m_transmittedDatas (data, this, m_face);
+ m_face->ReceiveData(data);
+ m_transmittedDatas(data, this, m_face);
}
} // namespace ndn
diff --git a/apps/ndn-producer.hpp b/apps/ndn-producer.hpp
index 7905b9b..11ebc56 100644
--- a/apps/ndn-producer.hpp
+++ b/apps/ndn-producer.hpp
@@ -40,24 +40,24 @@
* size and name same as in Interest.cation, which replying every incoming Interest
* with Data packet with a specified size and name same as in Interest.
*/
-class Producer : public App
-{
+class Producer : public App {
public:
static TypeId
- GetTypeId (void);
+ GetTypeId(void);
- Producer ();
+ Producer();
// inherited from NdnApp
- void OnInterest (Ptr<const Interest> interest);
+ void
+ OnInterest(Ptr<const Interest> interest);
protected:
// inherited from Application base class.
virtual void
- StartApplication (); // Called at time specified by Start
+ StartApplication(); // Called at time specified by Start
virtual void
- StopApplication (); // Called at time specified by Stop
+ StopApplication(); // Called at time specified by Stop
private:
Name m_prefix;
diff --git a/docs/doxygen.hpp b/docs/doxygen.hpp
index 02d45c1..008ebdb 100644
--- a/docs/doxygen.hpp
+++ b/docs/doxygen.hpp
@@ -20,4 +20,3 @@
* @brief ContentStore with FIFO cache replacement policy
*/
template class ContentStoreImpl<fifo_policy_traits>;
-
diff --git a/examples/custom-apps/custom-app.cpp b/examples/custom-apps/custom-app.cpp
index 71ca87e..001c440 100644
--- a/examples/custom-apps/custom-app.cpp
+++ b/examples/custom-apps/custom-app.cpp
@@ -33,112 +33,110 @@
#include "ns3/ndn-fib.hpp"
#include "ns3/random-variable.h"
-NS_LOG_COMPONENT_DEFINE ("CustomApp");
+NS_LOG_COMPONENT_DEFINE("CustomApp");
namespace ns3 {
-NS_OBJECT_ENSURE_REGISTERED (CustomApp);
+NS_OBJECT_ENSURE_REGISTERED(CustomApp);
// register NS-3 type
TypeId
-CustomApp::GetTypeId ()
+CustomApp::GetTypeId()
{
- static TypeId tid = TypeId ("CustomApp")
- .SetParent<ndn::App> ()
- .AddConstructor<CustomApp> ()
- ;
+ static TypeId tid = TypeId("CustomApp").SetParent<ndn::App>().AddConstructor<CustomApp>();
return tid;
}
// Processing upon start of the application
void
-CustomApp::StartApplication ()
+CustomApp::StartApplication()
{
// initialize ndn::App
- ndn::App::StartApplication ();
+ ndn::App::StartApplication();
// Create a name components object for name ``/prefix/sub``
- Ptr<ndn::Name> prefix = Create<ndn::Name> (); // now prefix contains ``/``
- prefix->append ("prefix"); // now prefix contains ``/prefix``
- prefix->append ("sub"); // now prefix contains ``/prefix/sub``
+ Ptr<ndn::Name> prefix = Create<ndn::Name>(); // now prefix contains ``/``
+ prefix->append("prefix"); // now prefix contains ``/prefix``
+ prefix->append("sub"); // now prefix contains ``/prefix/sub``
/////////////////////////////////////////////////////////////////////////////
// Creating FIB entry that ensures that we will receive incoming Interests //
/////////////////////////////////////////////////////////////////////////////
// Get FIB object
- Ptr<ndn::Fib> fib = GetNode ()->GetObject<ndn::Fib> ();
+ Ptr<ndn::Fib> fib = GetNode()->GetObject<ndn::Fib>();
// Add entry to FIB
// Note that ``m_face`` is cretaed by ndn::App
- Ptr<ndn::fib::Entry> fibEntry = fib->Add (*prefix, m_face, 0);
+ Ptr<ndn::fib::Entry> fibEntry = fib->Add(*prefix, m_face, 0);
- Simulator::Schedule (Seconds (1.0), &CustomApp::SendInterest, this);
+ Simulator::Schedule(Seconds(1.0), &CustomApp::SendInterest, this);
}
// Processing when application is stopped
void
-CustomApp::StopApplication ()
+CustomApp::StopApplication()
{
// cleanup ndn::App
- ndn::App::StopApplication ();
+ ndn::App::StopApplication();
}
void
-CustomApp::SendInterest ()
+CustomApp::SendInterest()
{
/////////////////////////////////////
// Sending one Interest packet out //
/////////////////////////////////////
-
- Ptr<ndn::Name> prefix = Create<ndn::Name> ("/prefix/sub"); // another way to create name
+
+ Ptr<ndn::Name> prefix = Create<ndn::Name>("/prefix/sub"); // another way to create name
// Create and configure ndn::Interest
- Ptr<ndn::Interest> interest = Create<ndn::Interest> ();
- UniformVariable rand (0,std::numeric_limits<uint32_t>::max ());
- interest->SetNonce (rand.GetValue ());
- interest->SetName (prefix);
- interest->SetInterestLifetime (Seconds (1.0));
+ Ptr<ndn::Interest> interest = Create<ndn::Interest>();
+ UniformVariable rand(0, std::numeric_limits<uint32_t>::max());
+ interest->SetNonce(rand.GetValue());
+ interest->SetName(prefix);
+ interest->SetInterestLifetime(Seconds(1.0));
- NS_LOG_DEBUG ("Sending Interest packet for " << *prefix);
-
+ NS_LOG_DEBUG("Sending Interest packet for " << *prefix);
+
// Call trace (for logging purposes)
- m_transmittedInterests (interest, this, m_face);
+ m_transmittedInterests(interest, this, m_face);
- m_face->ReceiveInterest (interest);
+ m_face->ReceiveInterest(interest);
}
// Callback that will be called when Interest arrives
void
-CustomApp::OnInterest (Ptr<const ndn::Interest> interest)
+CustomApp::OnInterest(Ptr<const ndn::Interest> interest)
{
- ndn::App::OnInterest (interest);
-
- NS_LOG_DEBUG ("Received Interest packet for " << interest->GetName ());
+ ndn::App::OnInterest(interest);
+
+ NS_LOG_DEBUG("Received Interest packet for " << interest->GetName());
// Create and configure ndn::Data and ndn::DataTail
// (header is added in front of the packet, tail is added at the end of the packet)
// Note that Interests send out by the app will not be sent back to the app !
-
- Ptr<ndn::Data> data = Create<ndn::Data> (Create<Packet> (1024));
- data->SetName (Create<ndn::Name> (interest->GetName ())); // data will have the same name as Interests
- NS_LOG_DEBUG ("Sending Data packet for " << data->GetName ());
+ Ptr<ndn::Data> data = Create<ndn::Data>(Create<Packet>(1024));
+ data->SetName(
+ Create<ndn::Name>(interest->GetName())); // data will have the same name as Interests
+
+ NS_LOG_DEBUG("Sending Data packet for " << data->GetName());
// Call trace (for logging purposes)
- m_transmittedDatas (data, this, m_face);
+ m_transmittedDatas(data, this, m_face);
- m_face->ReceiveData (data);
+ m_face->ReceiveData(data);
}
// Callback that will be called when Data arrives
void
-CustomApp::OnData (Ptr<const ndn::Data> contentObject)
+CustomApp::OnData(Ptr<const ndn::Data> contentObject)
{
- NS_LOG_DEBUG ("Receiving Data packet for " << contentObject->GetName ());
+ NS_LOG_DEBUG("Receiving Data packet for " << contentObject->GetName());
- std::cout << "DATA received for name " << contentObject->GetName () << std::endl;
+ std::cout << "DATA received for name " << contentObject->GetName() << std::endl;
}
} // namespace ns3
diff --git a/examples/custom-apps/custom-app.hpp b/examples/custom-apps/custom-app.hpp
index 86f7bb4..5d05e99 100644
--- a/examples/custom-apps/custom-app.hpp
+++ b/examples/custom-apps/custom-app.hpp
@@ -37,32 +37,31 @@
*
* When an Interest is received, it is replied with a Data with 1024-byte fake payload
*/
-class CustomApp : public ndn::App
-{
+class CustomApp : public ndn::App {
public:
// register NS-3 type "CustomApp"
static TypeId
- GetTypeId ();
-
+ GetTypeId();
+
// (overridden from ndn::App) Processing upon start of the application
virtual void
- StartApplication ();
+ StartApplication();
// (overridden from ndn::App) Processing when application is stopped
virtual void
- StopApplication ();
+ StopApplication();
// (overridden from ndn::App) Callback that will be called when Interest arrives
virtual void
- OnInterest (Ptr<const ndn::Interest> interest);
+ OnInterest(Ptr<const ndn::Interest> interest);
// (overridden from ndn::App) Callback that will be called when Data arrives
virtual void
- OnData (Ptr<const ndn::Data> contentObject);
+ OnData(Ptr<const ndn::Data> contentObject);
private:
void
- SendInterest ();
+ SendInterest();
};
} // namespace ns3
diff --git a/examples/custom-apps/dumb-requester.cpp b/examples/custom-apps/dumb-requester.cpp
index eca1cf2..f81548f 100644
--- a/examples/custom-apps/dumb-requester.cpp
+++ b/examples/custom-apps/dumb-requester.cpp
@@ -32,88 +32,85 @@
#include "ns3/ndn-interest.hpp"
#include "ns3/ndn-data.hpp"
-NS_LOG_COMPONENT_DEFINE ("DumbRequester");
+NS_LOG_COMPONENT_DEFINE("DumbRequester");
namespace ns3 {
-NS_OBJECT_ENSURE_REGISTERED (DumbRequester);
+NS_OBJECT_ENSURE_REGISTERED(DumbRequester);
// register NS-3 type
TypeId
-DumbRequester::GetTypeId ()
+DumbRequester::GetTypeId()
{
- static TypeId tid = TypeId ("DumbRequester")
- .SetParent<ndn::App> ()
- .AddConstructor<DumbRequester> ()
+ static TypeId tid =
+ TypeId("DumbRequester")
+ .SetParent<ndn::App>()
+ .AddConstructor<DumbRequester>()
- .AddAttribute ("Prefix", "Requested name",
- StringValue ("/dumb-interest"),
- ndn::MakeNameAccessor (&DumbRequester::m_name),
- ndn::MakeNameChecker ())
- ;
+ .AddAttribute("Prefix", "Requested name", StringValue("/dumb-interest"),
+ ndn::MakeNameAccessor(&DumbRequester::m_name), ndn::MakeNameChecker());
return tid;
}
-DumbRequester::DumbRequester ()
- : m_isRunning (false)
+DumbRequester::DumbRequester()
+ : m_isRunning(false)
{
}
// Processing upon start of the application
void
-DumbRequester::StartApplication ()
+DumbRequester::StartApplication()
{
// initialize ndn::App
- ndn::App::StartApplication ();
+ ndn::App::StartApplication();
m_isRunning = true;
- Simulator::ScheduleNow (&DumbRequester::SendInterest, this);
+ Simulator::ScheduleNow(&DumbRequester::SendInterest, this);
}
// Processing when application is stopped
void
-DumbRequester::StopApplication ()
+DumbRequester::StopApplication()
{
m_isRunning = false;
// cleanup ndn::App
- ndn::App::StopApplication ();
+ ndn::App::StopApplication();
}
void
-DumbRequester::SendInterest ()
+DumbRequester::SendInterest()
{
- if (!m_isRunning) return;
-
+ if (!m_isRunning)
+ return;
+
/////////////////////////////////////
// Sending one Interest packet out //
/////////////////////////////////////
-
- Ptr<ndn::Name> prefix = Create<ndn::Name> (m_name); // another way to create name
+
+ Ptr<ndn::Name> prefix = Create<ndn::Name>(m_name); // another way to create name
// Create and configure ndn::Interest
- Ptr<ndn::Interest> interest = Create<ndn::Interest> ();
- UniformVariable rand (0,std::numeric_limits<uint32_t>::max ());
- interest->SetNonce (rand.GetValue ());
- interest->SetName (prefix);
- interest->SetInterestLifetime (Seconds (1.0));
+ Ptr<ndn::Interest> interest = Create<ndn::Interest>();
+ UniformVariable rand(0, std::numeric_limits<uint32_t>::max());
+ interest->SetNonce(rand.GetValue());
+ interest->SetName(prefix);
+ interest->SetInterestLifetime(Seconds(1.0));
- NS_LOG_DEBUG ("Sending Interest packet for " << *prefix);
-
+ NS_LOG_DEBUG("Sending Interest packet for " << *prefix);
// Call trace (for logging purposes)
- m_transmittedInterests (interest, this, m_face);
+ m_transmittedInterests(interest, this, m_face);
// Forward packet to lower (network) layer
- m_face->ReceiveInterest (interest);
+ m_face->ReceiveInterest(interest);
- Simulator::Schedule (Seconds (1.0), &DumbRequester::SendInterest, this);
+ Simulator::Schedule(Seconds(1.0), &DumbRequester::SendInterest, this);
}
void
-DumbRequester::OnData (Ptr<const ndn::Data> contentObject)
+DumbRequester::OnData(Ptr<const ndn::Data> contentObject)
{
- NS_LOG_DEBUG ("Receiving Data packet for " << contentObject->GetName ());
+ NS_LOG_DEBUG("Receiving Data packet for " << contentObject->GetName());
}
-
} // namespace ns3
diff --git a/examples/custom-apps/dumb-requester.hpp b/examples/custom-apps/dumb-requester.hpp
index 7a1272d..55bdace 100644
--- a/examples/custom-apps/dumb-requester.hpp
+++ b/examples/custom-apps/dumb-requester.hpp
@@ -31,32 +31,31 @@
/**
* @brief A dumb requester application
*
- * This app keeps requesting every second the same content object
+ * This app keeps requesting every second the same content object
*/
-class DumbRequester : public ndn::App
-{
+class DumbRequester : public ndn::App {
public:
// register NS-3 type "DumbRequester"
static TypeId
- GetTypeId ();
+ GetTypeId();
- DumbRequester ();
-
+ DumbRequester();
+
// (overridden from ndn::App) Processing upon start of the application
virtual void
- StartApplication ();
+ StartApplication();
// (overridden from ndn::App) Processing when application is stopped
virtual void
- StopApplication ();
+ StopApplication();
// (overridden from ndn::App) Callback that will be called when Data arrives
virtual void
- OnData (Ptr<const ndn::Data> contentObject);
-
+ OnData(Ptr<const ndn::Data> contentObject);
+
private:
void
- SendInterest ();
+ SendInterest();
private:
bool m_isRunning;
diff --git a/examples/custom-apps/hijacker.cpp b/examples/custom-apps/hijacker.cpp
index f1852d4..bcff26a 100644
--- a/examples/custom-apps/hijacker.cpp
+++ b/examples/custom-apps/hijacker.cpp
@@ -23,53 +23,49 @@
#include "hijacker.hpp"
#include "ns3/ndn-name.hpp"
-NS_LOG_COMPONENT_DEFINE ("Hijacker");
+NS_LOG_COMPONENT_DEFINE("Hijacker");
namespace ns3 {
// Necessary if you are planning to use ndn::AppHelper
-NS_OBJECT_ENSURE_REGISTERED (Hijacker);
+NS_OBJECT_ENSURE_REGISTERED(Hijacker);
TypeId
-Hijacker::GetTypeId ()
+Hijacker::GetTypeId()
{
- static TypeId tid = TypeId ("Hijacker")
- .SetParent<ndn::App> ()
- .AddConstructor<Hijacker> ()
- ;
+ static TypeId tid = TypeId("Hijacker").SetParent<ndn::App>().AddConstructor<Hijacker>();
return tid;
}
-Hijacker::Hijacker ()
+Hijacker::Hijacker()
{
}
void
-Hijacker::OnInterest (Ptr<const ndn::Interest> interest)
+Hijacker::OnInterest(Ptr<const ndn::Interest> interest)
{
- ndn::App::OnInterest (interest); // forward call to perform app-level tracing
+ ndn::App::OnInterest(interest); // forward call to perform app-level tracing
// do nothing else (hijack interest)
- NS_LOG_DEBUG ("Do nothing for incoming interest for" << interest->GetName ());
+ NS_LOG_DEBUG("Do nothing for incoming interest for" << interest->GetName());
}
void
-Hijacker::StartApplication ()
+Hijacker::StartApplication()
{
- App::StartApplication ();
+ App::StartApplication();
// equivalent to setting interest filter for "/" prefix
- Ptr<ndn::Fib> fib = GetNode ()->GetObject<ndn::Fib> ();
- Ptr<ndn::fib::Entry> fibEntry = fib->Add (ndn::Name ("/"), m_face, 0);
- fibEntry->UpdateStatus (m_face, ndn::fib::FaceMetric::NDN_FIB_GREEN);
+ Ptr<ndn::Fib> fib = GetNode()->GetObject<ndn::Fib>();
+ Ptr<ndn::fib::Entry> fibEntry = fib->Add(ndn::Name("/"), m_face, 0);
+ fibEntry->UpdateStatus(m_face, ndn::fib::FaceMetric::NDN_FIB_GREEN);
}
void
-Hijacker::StopApplication ()
+Hijacker::StopApplication()
{
- App::StopApplication ();
+ App::StopApplication();
}
} // namespace ns3
-
diff --git a/examples/custom-apps/hijacker.hpp b/examples/custom-apps/hijacker.hpp
index a90166d..a794f12 100644
--- a/examples/custom-apps/hijacker.hpp
+++ b/examples/custom-apps/hijacker.hpp
@@ -29,25 +29,24 @@
namespace ns3 {
-class Hijacker : public ndn::App
-{
+class Hijacker : public ndn::App {
public:
static TypeId
- GetTypeId ();
+ GetTypeId();
- Hijacker ();
+ Hijacker();
// Receive all Interests but do nothing in response
void
- OnInterest (Ptr<const ndn::Interest> interest);
+ OnInterest(Ptr<const ndn::Interest> interest);
protected:
// inherited from Application base class.
virtual void
- StartApplication ();
+ StartApplication();
virtual void
- StopApplication ();
+ StopApplication();
};
} // namespace ns3
diff --git a/examples/ndn-congestion-alt-topo-plugin.cpp b/examples/ndn-congestion-alt-topo-plugin.cpp
index b591250..9491be4 100644
--- a/examples/ndn-congestion-alt-topo-plugin.cpp
+++ b/examples/ndn-congestion-alt-topo-plugin.cpp
@@ -31,25 +31,25 @@
* /------\ 0 0 /------\
* | c1 |<-----+ +----->| p1 |
* \------/ \ / \------/
- * \ /-----\ /
+ * \ /-----\ /
* /------\ 0 \ +==>| r12 |<==+ / 0 /------\
* | c2 |<--+ \ / \-----/ \ / +-->| p2 |
* \------/ \ \ | | / / \------/
- * \ | | 1Mbps links | | /
- * \ 1 v0 v5 1v 2v 3 /
- * +->/------\ /------\<-+
- * 2| r1 |<===============>| r2 |4
- * +->\------/4 0\------/<-+
- * / 3^ ^5 \
- * / | | \
+ * \ | | 1Mbps links | | /
+ * \ 1 v0 v5 1v 2v 3 /
+ * +->/------\ /------\<-+
+ * 2| r1 |<===============>| r2 |4
+ * +->\------/4 0\------/<-+
+ * / 3^ ^5 \
+ * / | | \
* /------\ 0 / / \ \ 0 /------\
* | c3 |<--+ / \ +-->| p3 |
* \------/ / \ \------/
- * / "All consumer-router and" \
+ * / "All consumer-router and" \
* /------\ 0 / "router-producer links are" \ 0 /------\
* | c4 |<-----+ "10Mbps" +---->| p4 |
* \------/ \------/
- *
+ *
* "Numbers near nodes denote face IDs. Face ID is assigned based on the order of link"
* "definitions in the topology file"
*
@@ -59,81 +59,81 @@
*/
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
- AnnotatedTopologyReader topologyReader ("", 1);
- topologyReader.SetFileName ("src/ndnSIM/examples/topologies/topo-11-node-two-bottlenecks.txt");
- topologyReader.Read ();
+ AnnotatedTopologyReader topologyReader("", 1);
+ topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-11-node-two-bottlenecks.txt");
+ topologyReader.Read();
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetForwardingStrategy ("ns3::ndn::fw::CustomStrategy");
- ndnHelper.SetContentStore ("ns3::ndn::cs::Lru",
- "MaxSize", "1"); // ! Attention ! If set to 0, then MaxSize is infinite
- ndnHelper.InstallAll ();
+ ndnHelper.SetForwardingStrategy("ns3::ndn::fw::CustomStrategy");
+ ndnHelper.SetContentStore("ns3::ndn::cs::Lru", "MaxSize",
+ "1"); // ! Attention ! If set to 0, then MaxSize is infinite
+ ndnHelper.InstallAll();
// Getting containers for the consumer/producer
- Ptr<Node> consumers[4] = { Names::Find<Node> ("c1"), Names::Find<Node> ("c2"), Names::Find<Node> ("c3"), Names::Find<Node> ("c4") };
- Ptr<Node> producers[4] = { Names::Find<Node> ("p1"), Names::Find<Node> ("p2"), Names::Find<Node> ("p3"), Names::Find<Node> ("p4") };
+ Ptr<Node> consumers[4] = {Names::Find<Node>("c1"), Names::Find<Node>("c2"),
+ Names::Find<Node>("c3"), Names::Find<Node>("c4")};
+ Ptr<Node> producers[4] = {Names::Find<Node>("p1"), Names::Find<Node>("p2"),
+ Names::Find<Node>("p3"), Names::Find<Node>("p4")};
- if (consumers[0] == 0 || consumers[1] == 0 || consumers[2] == 0 || consumers[3] == 0 ||
- producers[0] == 0 || producers[1] == 0 || producers[2] == 0 || producers[3] == 0)
- {
- NS_FATAL_ERROR ("Error in topology: one nodes c1, c2, c3, c4, p1, p2, p3, or p4 is missing");
- }
+ if (consumers[0] == 0 || consumers[1] == 0 || consumers[2] == 0 || consumers[3] == 0
+ || producers[0] == 0 || producers[1] == 0 || producers[2] == 0 || producers[3] == 0) {
+ NS_FATAL_ERROR("Error in topology: one nodes c1, c2, c3, c4, p1, p2, p3, or p4 is missing");
+ }
- for (int i = 0; i < 4; i++)
- {
- std::string prefix = "/data/"+Names::FindName (producers[i]);
-
- /////////////////////////////////////////////////////////////////////////////////
- // install consumer app on consumer node c_i to request data from producer p_i //
- /////////////////////////////////////////////////////////////////////////////////
+ for (int i = 0; i < 4; i++) {
+ std::string prefix = "/data/" + Names::FindName(producers[i]);
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
- consumerHelper.SetAttribute ("Frequency", StringValue ("10")); // 100 interests a second
-
- consumerHelper.SetPrefix (prefix);
- ApplicationContainer consumer = consumerHelper.Install (consumers[i]);
- consumer.Start (Seconds (i)); // start consumers at 0s, 1s, 2s, 3s
- consumer.Stop (Seconds (19-i)); // stop consumers at 19s, 18s, 17s, 16s
-
- ///////////////////////////////////////////////
- // install producer app on producer node p_i //
- ///////////////////////////////////////////////
-
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
+ /////////////////////////////////////////////////////////////////////////////////
+ // install consumer app on consumer node c_i to request data from producer p_i //
+ /////////////////////////////////////////////////////////////////////////////////
- // install producer that will satisfy Interests in /dst1 namespace
- producerHelper.SetPrefix (prefix);
- ApplicationContainer producer = producerHelper.Install (producers[i]);
- // when Start/Stop time is not specified, the application is running throughout the simulation
- }
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
+ consumerHelper.SetAttribute("Frequency", StringValue("10")); // 100 interests a second
+
+ consumerHelper.SetPrefix(prefix);
+ ApplicationContainer consumer = consumerHelper.Install(consumers[i]);
+ consumer.Start(Seconds(i)); // start consumers at 0s, 1s, 2s, 3s
+ consumer.Stop(Seconds(19 - i)); // stop consumers at 19s, 18s, 17s, 16s
+
+ ///////////////////////////////////////////////
+ // install producer app on producer node p_i //
+ ///////////////////////////////////////////////
+
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
+
+ // install producer that will satisfy Interests in /dst1 namespace
+ producerHelper.SetPrefix(prefix);
+ ApplicationContainer producer = producerHelper.Install(producers[i]);
+ // when Start/Stop time is not specified, the application is running throughout the simulation
+ }
// Manually configure FIB routes
- ndn::StackHelper::AddRoute ("c1", "/data", "n1", 1); // link to n1
- ndn::StackHelper::AddRoute ("c2", "/data", "n1", 1); // link to n1
- ndn::StackHelper::AddRoute ("c3", "/data", "n1", 1); // link to n1
- ndn::StackHelper::AddRoute ("c4", "/data", "n1", 1); // link to n1
+ ndn::StackHelper::AddRoute("c1", "/data", "n1", 1); // link to n1
+ ndn::StackHelper::AddRoute("c2", "/data", "n1", 1); // link to n1
+ ndn::StackHelper::AddRoute("c3", "/data", "n1", 1); // link to n1
+ ndn::StackHelper::AddRoute("c4", "/data", "n1", 1); // link to n1
- ndn::StackHelper::AddRoute ("n1", "/data", "n2", 1); // link to n2
- ndn::StackHelper::AddRoute ("n1", "/data", "n12", 2); // link to n12
+ ndn::StackHelper::AddRoute("n1", "/data", "n2", 1); // link to n2
+ ndn::StackHelper::AddRoute("n1", "/data", "n12", 2); // link to n12
- ndn::StackHelper::AddRoute ("n12", "/data", "n2", 1); // link to n2
+ ndn::StackHelper::AddRoute("n12", "/data", "n2", 1); // link to n2
- ndn::StackHelper::AddRoute ("n2", "/data/p1", "p1", 1); // link to p1
- ndn::StackHelper::AddRoute ("n2", "/data/p2", "p2", 1); // link to p2
- ndn::StackHelper::AddRoute ("n2", "/data/p3", "p3", 1); // link to p3
- ndn::StackHelper::AddRoute ("n2", "/data/p4", "p4", 1); // link to p4
+ ndn::StackHelper::AddRoute("n2", "/data/p1", "p1", 1); // link to p1
+ ndn::StackHelper::AddRoute("n2", "/data/p2", "p2", 1); // link to p2
+ ndn::StackHelper::AddRoute("n2", "/data/p3", "p3", 1); // link to p3
+ ndn::StackHelper::AddRoute("n2", "/data/p4", "p4", 1); // link to p4
// Schedule simulation time and run the simulation
- Simulator::Stop (Seconds (20.0));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Stop(Seconds(20.0));
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-congestion-topo-plugin.cpp b/examples/ndn-congestion-topo-plugin.cpp
index 77069ee..0a6a58b 100644
--- a/examples/ndn-congestion-topo-plugin.cpp
+++ b/examples/ndn-congestion-topo-plugin.cpp
@@ -30,10 +30,10 @@
* /------\ /------\
* | Src1 |<--+ +-->| Dst1 |
* \------/ \ / \------/
- * \ /
- * +-->/------\ "bottleneck" /------\<-+
- * | Rtr1 |<===============>| Rtr2 |
- * +-->\------/ \------/<-+
+ * \ /
+ * +-->/------\ "bottleneck" /------\<-+
+ * | Rtr1 |<===============>| Rtr2 |
+ * +-->\------/ \------/<-+
* / \
* /------\ / \ /------\
* | Src2 |<--+ +-->| Dst2 |
@@ -45,68 +45,67 @@
*/
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
- AnnotatedTopologyReader topologyReader ("", 25);
- topologyReader.SetFileName ("src/ndnSIM/examples/topologies/topo-6-node.txt");
- topologyReader.Read ();
+ AnnotatedTopologyReader topologyReader("", 25);
+ topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-6-node.txt");
+ topologyReader.Read();
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetForwardingStrategy ("ns3::ndn::fw::BestRoute");
- ndnHelper.SetContentStore ("ns3::ndn::cs::Lru",
- "MaxSize", "10000");
- ndnHelper.InstallAll ();
+ ndnHelper.SetForwardingStrategy("ns3::ndn::fw::BestRoute");
+ ndnHelper.SetContentStore("ns3::ndn::cs::Lru", "MaxSize", "10000");
+ ndnHelper.InstallAll();
// Installing global routing interface on all nodes
ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
- ndnGlobalRoutingHelper.InstallAll ();
+ ndnGlobalRoutingHelper.InstallAll();
// Getting containers for the consumer/producer
- Ptr<Node> consumer1 = Names::Find<Node> ("Src1");
- Ptr<Node> consumer2 = Names::Find<Node> ("Src2");
+ Ptr<Node> consumer1 = Names::Find<Node>("Src1");
+ Ptr<Node> consumer2 = Names::Find<Node>("Src2");
- Ptr<Node> producer1 = Names::Find<Node> ("Dst1");
- Ptr<Node> producer2 = Names::Find<Node> ("Dst2");
+ Ptr<Node> producer1 = Names::Find<Node>("Dst1");
+ Ptr<Node> producer2 = Names::Find<Node>("Dst2");
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
- consumerHelper.SetAttribute ("Frequency", StringValue ("100")); // 100 interests a second
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
+ consumerHelper.SetAttribute("Frequency", StringValue("100")); // 100 interests a second
// on the first consumer node install a Consumer application
// that will express interests in /dst1 namespace
- consumerHelper.SetPrefix ("/dst1");
- consumerHelper.Install (consumer1);
+ consumerHelper.SetPrefix("/dst1");
+ consumerHelper.Install(consumer1);
// on the second consumer node install a Consumer application
// that will express interests in /dst2 namespace
- consumerHelper.SetPrefix ("/dst2");
- consumerHelper.Install (consumer2);
-
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
+ consumerHelper.SetPrefix("/dst2");
+ consumerHelper.Install(consumer2);
+
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
// Register /dst1 prefix with global routing controller and
// install producer that will satisfy Interests in /dst1 namespace
- ndnGlobalRoutingHelper.AddOrigins ("/dst1", producer1);
- producerHelper.SetPrefix ("/dst1");
- producerHelper.Install (producer1);
+ ndnGlobalRoutingHelper.AddOrigins("/dst1", producer1);
+ producerHelper.SetPrefix("/dst1");
+ producerHelper.Install(producer1);
// Register /dst2 prefix with global routing controller and
// install producer that will satisfy Interests in /dst2 namespace
- ndnGlobalRoutingHelper.AddOrigins ("/dst2", producer2);
- producerHelper.SetPrefix ("/dst2");
- producerHelper.Install (producer2);
+ ndnGlobalRoutingHelper.AddOrigins("/dst2", producer2);
+ producerHelper.SetPrefix("/dst2");
+ producerHelper.Install(producer2);
// Calculate and install FIBs
- ndn::GlobalRoutingHelper::CalculateRoutes ();
+ ndn::GlobalRoutingHelper::CalculateRoutes();
- Simulator::Stop (Seconds (20.0));
+ Simulator::Stop(Seconds(20.0));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-csma.cpp b/examples/ndn-csma.cpp
index cafddd5..71d1cfb 100644
--- a/examples/ndn-csma.cpp
+++ b/examples/ndn-csma.cpp
@@ -48,51 +48,51 @@
* NS_LOG=ndn.Consumer:ndn.Producer ./waf --run=ndn-csma
*/
-int
-main (int argc, char *argv[])
+int
+main(int argc, char* argv[])
{
// setting default parameters for PointToPoint links and channels
- Config::SetDefault ("ns3::CsmaChannel::DataRate", StringValue ("1Mbps"));
- Config::SetDefault ("ns3::CsmaChannel::Delay", StringValue ("10ms"));
- Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("20"));
+ Config::SetDefault("ns3::CsmaChannel::DataRate", StringValue("1Mbps"));
+ Config::SetDefault("ns3::CsmaChannel::Delay", StringValue("10ms"));
+ Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
// Creating nodes
NodeContainer nodes;
- nodes.Create (3);
+ nodes.Create(3);
// Connecting nodes using two links
CsmaHelper csma;
- csma.Install (nodes);
+ csma.Install(nodes);
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetDefaultRoutes (true);
- ndnHelper.InstallAll ();
+ ndnHelper.SetDefaultRoutes(true);
+ ndnHelper.InstallAll();
// Installing applications
// Consumer
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
// Consumer will request /prefix/0, /prefix/1, ...
- consumerHelper.SetPrefix ("/prefix");
- consumerHelper.SetAttribute ("Frequency", StringValue ("10")); // 10 interests a second
- consumerHelper.Install (nodes.Get (0)); // first node
+ consumerHelper.SetPrefix("/prefix");
+ consumerHelper.SetAttribute("Frequency", StringValue("10")); // 10 interests a second
+ consumerHelper.Install(nodes.Get(0)); // first node
// Producer
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
// Producer will reply to all requests starting with /prefix
- producerHelper.SetPrefix ("/prefix");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
- producerHelper.Install (nodes.Get (2)); // last node
+ producerHelper.SetPrefix("/prefix");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
+ producerHelper.Install(nodes.Get(2)); // last node
- Simulator::Stop (Seconds (20.0));
+ Simulator::Stop(Seconds(20.0));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-grid-topo-plugin.cpp b/examples/ndn-grid-topo-plugin.cpp
index bbb8e86..84f5f17 100644
--- a/examples/ndn-grid-topo-plugin.cpp
+++ b/examples/ndn-grid-topo-plugin.cpp
@@ -33,7 +33,7 @@
* | | |
* ( ) ------ ( ) -- (producer)
*
- * All links are 1Mbps with propagation 10ms delay.
+ * All links are 1Mbps with propagation 10ms delay.
*
* FIB is populated using NdnGlobalRoutingHelper.
*
@@ -49,52 +49,52 @@
*/
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
- AnnotatedTopologyReader topologyReader ("", 25);
- topologyReader.SetFileName ("src/ndnSIM/examples/topologies/topo-grid-3x3.txt");
- topologyReader.Read ();
+ AnnotatedTopologyReader topologyReader("", 25);
+ topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-grid-3x3.txt");
+ topologyReader.Read();
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetForwardingStrategy ("ns3::ndn::fw::BestRoute");
- ndnHelper.InstallAll ();
+ ndnHelper.SetForwardingStrategy("ns3::ndn::fw::BestRoute");
+ ndnHelper.InstallAll();
// Installing global routing interface on all nodes
ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
- ndnGlobalRoutingHelper.InstallAll ();
+ ndnGlobalRoutingHelper.InstallAll();
// Getting containers for the consumer/producer
- Ptr<Node> producer = Names::Find<Node> ("Node8");
+ Ptr<Node> producer = Names::Find<Node>("Node8");
NodeContainer consumerNodes;
- consumerNodes.Add (Names::Find<Node> ("Node0"));
+ consumerNodes.Add(Names::Find<Node>("Node0"));
// Install NDN applications
std::string prefix = "/prefix";
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
- consumerHelper.SetPrefix (prefix);
- consumerHelper.SetAttribute ("Frequency", StringValue ("100")); // 100 interests a second
- consumerHelper.Install (consumerNodes);
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
+ consumerHelper.SetPrefix(prefix);
+ consumerHelper.SetAttribute("Frequency", StringValue("100")); // 100 interests a second
+ consumerHelper.Install(consumerNodes);
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetPrefix (prefix);
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
- producerHelper.Install (producer);
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetPrefix(prefix);
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
+ producerHelper.Install(producer);
// Add /prefix origins to ndn::GlobalRouter
- ndnGlobalRoutingHelper.AddOrigins (prefix, producer);
+ ndnGlobalRoutingHelper.AddOrigins(prefix, producer);
// Calculate and install FIBs
- ndn::GlobalRoutingHelper::CalculateRoutes ();
+ ndn::GlobalRoutingHelper::CalculateRoutes();
- Simulator::Stop (Seconds (20.0));
+ Simulator::Stop(Seconds(20.0));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-grid.cpp b/examples/ndn-grid.cpp
index 8b75165..d475dfd 100644
--- a/examples/ndn-grid.cpp
+++ b/examples/ndn-grid.cpp
@@ -35,7 +35,7 @@
* | | |
* ( ) ------ ( ) -- (producer)
*
- * All links are 1Mbps with propagation 10ms delay.
+ * All links are 1Mbps with propagation 10ms delay.
*
* FIB is populated using NdnGlobalRoutingHelper.
*
@@ -51,59 +51,59 @@
*/
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
// Setting default parameters for PointToPoint links and channels
- Config::SetDefault ("ns3::PointToPointNetDevice::DataRate", StringValue ("1Mbps"));
- Config::SetDefault ("ns3::PointToPointChannel::Delay", StringValue ("10ms"));
- Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("10"));
+ Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
+ Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
+ Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("10"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
// Creating 3x3 topology
PointToPointHelper p2p;
- PointToPointGridHelper grid (3, 3, p2p);
- grid.BoundingBox(100,100,200,200);
+ PointToPointGridHelper grid(3, 3, p2p);
+ grid.BoundingBox(100, 100, 200, 200);
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetForwardingStrategy ("ns3::ndn::fw::BestRoute");
- ndnHelper.InstallAll ();
+ ndnHelper.SetForwardingStrategy("ns3::ndn::fw::BestRoute");
+ ndnHelper.InstallAll();
// Installing global routing interface on all nodes
ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
- ndnGlobalRoutingHelper.InstallAll ();
+ ndnGlobalRoutingHelper.InstallAll();
// Getting containers for the consumer/producer
- Ptr<Node> producer = grid.GetNode (2, 2);
+ Ptr<Node> producer = grid.GetNode(2, 2);
NodeContainer consumerNodes;
- consumerNodes.Add (grid.GetNode (0,0));
+ consumerNodes.Add(grid.GetNode(0, 0));
// Install NDN applications
std::string prefix = "/prefix";
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
- consumerHelper.SetPrefix (prefix);
- consumerHelper.SetAttribute ("Frequency", StringValue ("100")); // 100 interests a second
- consumerHelper.Install (consumerNodes);
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
+ consumerHelper.SetPrefix(prefix);
+ consumerHelper.SetAttribute("Frequency", StringValue("100")); // 100 interests a second
+ consumerHelper.Install(consumerNodes);
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetPrefix (prefix);
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
- producerHelper.Install (producer);
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetPrefix(prefix);
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
+ producerHelper.Install(producer);
// Add /prefix origins to ndn::GlobalRouter
- ndnGlobalRoutingHelper.AddOrigins (prefix, producer);
+ ndnGlobalRoutingHelper.AddOrigins(prefix, producer);
// Calculate and install FIBs
- ndn::GlobalRoutingHelper::CalculateRoutes ();
+ ndn::GlobalRoutingHelper::CalculateRoutes();
- Simulator::Stop (Seconds (20.0));
+ Simulator::Stop(Seconds(20.0));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-simple-wifi.cpp b/examples/ndn-simple-wifi.cpp
index db54c93..a2b083f 100644
--- a/examples/ndn-simple-wifi.cpp
+++ b/examples/ndn-simple-wifi.cpp
@@ -30,10 +30,11 @@
using namespace std;
using namespace ns3;
-NS_LOG_COMPONENT_DEFINE ("ndn.WifiExample");
+NS_LOG_COMPONENT_DEFINE("ndn.WifiExample");
//
-// DISCLAIMER: Note that this is an extremely simple example, containing just 2 wifi nodes communicating
+// DISCLAIMER: Note that this is an extremely simple example, containing just 2 wifi nodes
+// communicating
// directly over AdHoc channel.
//
@@ -47,90 +48,89 @@
// }
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
// disable fragmentation
- Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
- Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2200"));
- Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue ("OfdmRate24Mbps"));
+ Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue("2200"));
+ Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("2200"));
+ Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode",
+ StringValue("OfdmRate24Mbps"));
CommandLine cmd;
- cmd.Parse (argc,argv);
+ cmd.Parse(argc, argv);
//////////////////////
//////////////////////
//////////////////////
- WifiHelper wifi = WifiHelper::Default ();
+ WifiHelper wifi = WifiHelper::Default();
// wifi.SetRemoteStationManager ("ns3::AarfWifiManager");
- wifi.SetStandard (WIFI_PHY_STANDARD_80211a);
- wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
- "DataMode", StringValue ("OfdmRate24Mbps"));
+ wifi.SetStandard(WIFI_PHY_STANDARD_80211a);
+ wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
+ StringValue("OfdmRate24Mbps"));
- YansWifiChannelHelper wifiChannel;// = YansWifiChannelHelper::Default ();
- wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
- wifiChannel.AddPropagationLoss ("ns3::ThreeLogDistancePropagationLossModel");
- wifiChannel.AddPropagationLoss ("ns3::NakagamiPropagationLossModel");
+ YansWifiChannelHelper wifiChannel; // = YansWifiChannelHelper::Default ();
+ wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
+ wifiChannel.AddPropagationLoss("ns3::ThreeLogDistancePropagationLossModel");
+ wifiChannel.AddPropagationLoss("ns3::NakagamiPropagationLossModel");
- //YansWifiPhy wifiPhy = YansWifiPhy::Default();
- YansWifiPhyHelper wifiPhyHelper = YansWifiPhyHelper::Default ();
- wifiPhyHelper.SetChannel (wifiChannel.Create ());
+ // YansWifiPhy wifiPhy = YansWifiPhy::Default();
+ YansWifiPhyHelper wifiPhyHelper = YansWifiPhyHelper::Default();
+ wifiPhyHelper.SetChannel(wifiChannel.Create());
wifiPhyHelper.Set("TxPowerStart", DoubleValue(5));
wifiPhyHelper.Set("TxPowerEnd", DoubleValue(5));
-
- NqosWifiMacHelper wifiMacHelper = NqosWifiMacHelper::Default ();
+ NqosWifiMacHelper wifiMacHelper = NqosWifiMacHelper::Default();
wifiMacHelper.SetType("ns3::AdhocWifiMac");
- Ptr<UniformRandomVariable> randomizer = CreateObject<UniformRandomVariable> ();
- randomizer->SetAttribute ("Min", DoubleValue (10));
- randomizer->SetAttribute ("Max", DoubleValue (100));
+ Ptr<UniformRandomVariable> randomizer = CreateObject<UniformRandomVariable>();
+ randomizer->SetAttribute("Min", DoubleValue(10));
+ randomizer->SetAttribute("Max", DoubleValue(100));
MobilityHelper mobility;
- mobility.SetPositionAllocator ("ns3::RandomBoxPositionAllocator",
- "X", PointerValue (randomizer),
- "Y", PointerValue (randomizer),
- "Z", PointerValue (randomizer));
+ mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizer),
+ "Y", PointerValue(randomizer), "Z", PointerValue(randomizer));
- mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
+ mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
NodeContainer nodes;
- nodes.Create (2);
+ nodes.Create(2);
////////////////
// 1. Install Wifi
- NetDeviceContainer wifiNetDevices = wifi.Install (wifiPhyHelper, wifiMacHelper, nodes);
+ NetDeviceContainer wifiNetDevices = wifi.Install(wifiPhyHelper, wifiMacHelper, nodes);
// 2. Install Mobility model
- mobility.Install (nodes);
+ mobility.Install(nodes);
// 3. Install NDN stack
- NS_LOG_INFO ("Installing NDN stack");
+ NS_LOG_INFO("Installing NDN stack");
ndn::StackHelper ndnHelper;
- // ndnHelper.AddNetDeviceFaceCreateCallback (WifiNetDevice::GetTypeId (), MakeCallback (MyNetDeviceFaceCallback));
- ndnHelper.SetForwardingStrategy ("ns3::ndn::fw::BestRoute");
- ndnHelper.SetContentStore ("ns3::ndn::cs::Lru", "MaxSize", "1000");
- ndnHelper.SetDefaultRoutes (true);
- ndnHelper.Install (nodes);
+ // ndnHelper.AddNetDeviceFaceCreateCallback (WifiNetDevice::GetTypeId (), MakeCallback
+ // (MyNetDeviceFaceCallback));
+ ndnHelper.SetForwardingStrategy("ns3::ndn::fw::BestRoute");
+ ndnHelper.SetContentStore("ns3::ndn::cs::Lru", "MaxSize", "1000");
+ ndnHelper.SetDefaultRoutes(true);
+ ndnHelper.Install(nodes);
// 4. Set up applications
- NS_LOG_INFO ("Installing Applications");
+ NS_LOG_INFO("Installing Applications");
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
- consumerHelper.SetPrefix ("/test/prefix");
- consumerHelper.SetAttribute ("Frequency", DoubleValue (10.0));
- consumerHelper.Install (nodes.Get (0));
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
+ consumerHelper.SetPrefix("/test/prefix");
+ consumerHelper.SetAttribute("Frequency", DoubleValue(10.0));
+ consumerHelper.Install(nodes.Get(0));
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetPrefix ("/");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1200"));
- producerHelper.Install (nodes.Get (1));
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetPrefix("/");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1200"));
+ producerHelper.Install(nodes.Get(1));
////////////////
- Simulator::Stop (Seconds (30.0));
+ Simulator::Stop(Seconds(30.0));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-simple-with-cs-lfu.cpp b/examples/ndn-simple-with-cs-lfu.cpp
index 4025763..d22a549 100644
--- a/examples/ndn-simple-with-cs-lfu.cpp
+++ b/examples/ndn-simple-with-cs-lfu.cpp
@@ -36,32 +36,40 @@
* | consumer | <------------> | router | <------------> | producer |
* +----------+ 10ms +--------+ 10ms +----------+
*
- * This scenario demonstrates how to use content store that responds to Freshness parameter set in Datas.
- * That is, if producer set Freshness field to 2 seconds, the corresponding content object will not be cached
+ * This scenario demonstrates how to use content store that responds to Freshness parameter set in
+ *Datas.
+ * That is, if producer set Freshness field to 2 seconds, the corresponding content object will not
+ *be cached
* more than 2 seconds (can be cached for a shorter time, if entry is evicted earlier)
*
* NS_LOG=ndn.Consumer ./waf --run ndn-simple-with-cs-lfu
*/
-void PrintCsMemStatsHeader (std::ostream &os)
+void
+PrintCsMemStatsHeader(std::ostream& os)
{
- os << "SimulationTime" << "\t"
- << "RealTime" << "\t"
+ os << "SimulationTime"
+ << "\t"
+ << "RealTime"
+ << "\t"
// << "NumberOfProcessedData" << "\t"
// << "NumberOfProcessedInterests" << "\t"
- << "NumberPitEntries" << "\t"
- << "NumberCsEntries" << "\t"
- << "MemUsage" << "\n";
+ << "NumberPitEntries"
+ << "\t"
+ << "NumberCsEntries"
+ << "\t"
+ << "MemUsage"
+ << "\n";
}
void
-PrintCsMemStats (std::ostream &os, Time nextPrintTime, double beginRealTime)
+PrintCsMemStats(std::ostream& os, Time nextPrintTime, double beginRealTime)
{
::timeval t;
gettimeofday(&t, NULL);
double realTime = t.tv_sec + (0.000001 * (unsigned)t.tv_usec) - beginRealTime;
- os << Simulator::Now ().ToDouble (Time::S) << "\t";
+ os << Simulator::Now().ToDouble(Time::S) << "\t";
os << realTime << "\t";
// os << ndn::L3Protocol::GetDataCounter () << "\t";
@@ -69,91 +77,90 @@
uint64_t pitCount = 0;
uint64_t csCount = 0;
- for (NodeList::Iterator node = NodeList::Begin ();
- node != NodeList::End ();
- node ++)
- {
- Ptr<ndn::Pit> pit = (*node)->GetObject<ndn::Pit> ();
- Ptr<ndn::ContentStore> cs = (*node)->GetObject<ndn::ContentStore> ();
+ for (NodeList::Iterator node = NodeList::Begin(); node != NodeList::End(); node++) {
+ Ptr<ndn::Pit> pit = (*node)->GetObject<ndn::Pit>();
+ Ptr<ndn::ContentStore> cs = (*node)->GetObject<ndn::ContentStore>();
- if (pit != 0)
- pitCount += pit->GetSize ();
+ if (pit != 0)
+ pitCount += pit->GetSize();
- if (cs != 0)
- csCount += cs->GetSize ();
- }
+ if (cs != 0)
+ csCount += cs->GetSize();
+ }
os << pitCount << "\t";
os << csCount << "\t";
- os << MemUsage::Get () / 1024.0 / 1024.0 << "\n";
+ os << MemUsage::Get() / 1024.0 / 1024.0 << "\n";
- Simulator::Schedule (nextPrintTime, PrintCsMemStats, boost::ref (os), nextPrintTime, beginRealTime);
+ Simulator::Schedule(nextPrintTime, PrintCsMemStats, boost::ref(os), nextPrintTime, beginRealTime);
}
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
// setting default parameters for PointToPoint links and channels
- Config::SetDefault ("ns3::PointToPointNetDevice::DataRate", StringValue ("1Mbps"));
- Config::SetDefault ("ns3::PointToPointChannel::Delay", StringValue ("10ms"));
- Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("20"));
+ Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
+ Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
+ Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
// Creating nodes
NodeContainer nodes;
- nodes.Create (3);
+ nodes.Create(3);
// Connecting nodes using two links
PointToPointHelper p2p;
- p2p.Install (nodes.Get (0), nodes.Get (1));
- p2p.Install (nodes.Get (1), nodes.Get (2));
+ p2p.Install(nodes.Get(0), nodes.Get(1));
+ p2p.Install(nodes.Get(1), nodes.Get(2));
// Install CCNx stack on all nodes
ndn::StackHelper ccnxHelper;
- ccnxHelper.SetDefaultRoutes (true);
+ ccnxHelper.SetDefaultRoutes(true);
// node 0: disable cache completely
- ccnxHelper.SetContentStore ("ns3::ndn::cs::Nocache"); // disable cache
- ccnxHelper.Install (nodes.Get (0));
+ ccnxHelper.SetContentStore("ns3::ndn::cs::Nocache"); // disable cache
+ ccnxHelper.Install(nodes.Get(0));
// node 1 and 2: set cache with Lfu policy
- ccnxHelper.SetContentStore ("ns3::ndn::cs::Freshness::Lfu", "MaxSize", "2"); // can set cache size this way
- ccnxHelper.Install (nodes.Get (1));
- ccnxHelper.Install (nodes.Get (2));
+ ccnxHelper.SetContentStore("ns3::ndn::cs::Freshness::Lfu", "MaxSize",
+ "2"); // can set cache size this way
+ ccnxHelper.Install(nodes.Get(1));
+ ccnxHelper.Install(nodes.Get(2));
// alternative way to configure cache size
// [number after nodeList is global ID of the node (= node->GetId ())]
- Config::Set ("/NodeList/2/$ns3::ndn::ContentStore/MaxSize", UintegerValue (100000));
+ Config::Set("/NodeList/2/$ns3::ndn::ContentStore/MaxSize", UintegerValue(100000));
// Installing applications
// Consumer
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
// Consumer will request /prefix/0, /prefix/1, ...
- consumerHelper.SetPrefix ("/prefix");
- consumerHelper.SetAttribute ("Frequency", StringValue ("10")); // 10 interests a second
- consumerHelper.Install (nodes.Get (0)); // first node
+ consumerHelper.SetPrefix("/prefix");
+ consumerHelper.SetAttribute("Frequency", StringValue("10")); // 10 interests a second
+ consumerHelper.Install(nodes.Get(0)); // first node
// Producer
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
// Producer will reply to all requests starting with /prefix
- producerHelper.SetPrefix ("/prefix");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
- producerHelper.Install (nodes.Get (2)); // last node
+ producerHelper.SetPrefix("/prefix");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
+ producerHelper.Install(nodes.Get(2)); // last node
- Simulator::Stop (Seconds (200000.0));
+ Simulator::Stop(Seconds(200000.0));
struct ::timeval t;
gettimeofday(&t, NULL);
double beginRealTime = t.tv_sec + (0.000001 * (unsigned)t.tv_usec);
- Simulator::Schedule (Seconds (0), PrintCsMemStatsHeader, boost::ref (std::cout));
- Simulator::Schedule (Seconds (100), PrintCsMemStats, boost::ref (std::cout), Seconds (100), beginRealTime);
+ Simulator::Schedule(Seconds(0), PrintCsMemStatsHeader, boost::ref(std::cout));
+ Simulator::Schedule(Seconds(100), PrintCsMemStats, boost::ref(std::cout), Seconds(100),
+ beginRealTime);
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-simple-with-custom-app.cpp b/examples/ndn-simple-with-custom-app.cpp
index 2c9d1b9..c10ceaa 100644
--- a/examples/ndn-simple-with-custom-app.cpp
+++ b/examples/ndn-simple-with-custom-app.cpp
@@ -29,41 +29,43 @@
/**
* This scenario simulates a one-node two-app scenario:
*
- * +------+ <-----> (CustomApp1)
- * | Node |
+ * +------+ <-----> (CustomApp1)
+ * | Node |
* +------+ <-----> (CustomApp2)
*
* NS_LOG=CustomApp ./waf --run=ndn-simple-with-custom-app
*/
-int
-main (int argc, char *argv[])
+int
+main(int argc, char* argv[])
{
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
// Creating nodes
- Ptr<Node> node = CreateObject<Node> ();
+ Ptr<Node> node = CreateObject<Node>();
// Install CCNx stack on all nodes
ndn::StackHelper ccnxHelper;
- ccnxHelper.InstallAll ();
+ ccnxHelper.InstallAll();
// Installing applications
// Consumer
- ndn::AppHelper consumerHelper ("CustomApp");
- ApplicationContainer app1 = consumerHelper.Install (node);
- ApplicationContainer app2 = consumerHelper.Install (node);
+ ndn::AppHelper consumerHelper("CustomApp");
+ ApplicationContainer app1 = consumerHelper.Install(node);
+ ApplicationContainer app2 = consumerHelper.Install(node);
- app1.Start (Seconds (1.0)); // will send out Interest, which nobody will receive (Interests generated by an app will not got back to the app)
- app2.Start (Seconds (2.0)); // will send out an Interests, which will be received and satisfied by app1
-
- Simulator::Stop (Seconds (3.0));
+ app1.Start(Seconds(1.0)); // will send out Interest, which nobody will receive (Interests
+ // generated by an app will not got back to the app)
+ app2.Start(
+ Seconds(2.0)); // will send out an Interests, which will be received and satisfied by app1
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Stop(Seconds(3.0));
+
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-simple-with-link-failure.cpp b/examples/ndn-simple-with-link-failure.cpp
index c96103d..c020a36 100644
--- a/examples/ndn-simple-with-link-failure.cpp
+++ b/examples/ndn-simple-with-link-failure.cpp
@@ -49,56 +49,56 @@
* NS_LOG=ndn.Consumer:ndn.Producer ./waf --run=ndn-simple
*/
-int
-main (int argc, char *argv[])
+int
+main(int argc, char* argv[])
{
// setting default parameters for PointToPoint links and channels
- Config::SetDefault ("ns3::PointToPointNetDevice::DataRate", StringValue ("1Mbps"));
- Config::SetDefault ("ns3::PointToPointChannel::Delay", StringValue ("10ms"));
- Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("20"));
+ Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
+ Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
+ Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
// Creating nodes
NodeContainer nodes;
- nodes.Create (3);
+ nodes.Create(3);
// Connecting nodes using two links
PointToPointHelper p2p;
- p2p.Install (nodes.Get (0), nodes.Get (1));
- p2p.Install (nodes.Get (1), nodes.Get (2));
+ p2p.Install(nodes.Get(0), nodes.Get(1));
+ p2p.Install(nodes.Get(1), nodes.Get(2));
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetDefaultRoutes (true);
- ndnHelper.InstallAll ();
+ ndnHelper.SetDefaultRoutes(true);
+ ndnHelper.InstallAll();
// Installing applications
// Consumer
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
// Consumer will request /prefix/0, /prefix/1, ...
- consumerHelper.SetPrefix ("/prefix");
- consumerHelper.SetAttribute ("Frequency", StringValue ("10")); // 10 interests a second
- consumerHelper.Install (nodes.Get (0)); // first node
+ consumerHelper.SetPrefix("/prefix");
+ consumerHelper.SetAttribute("Frequency", StringValue("10")); // 10 interests a second
+ consumerHelper.Install(nodes.Get(0)); // first node
// Producer
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
// Producer will reply to all requests starting with /prefix
- producerHelper.SetPrefix ("/prefix");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
- producerHelper.Install (nodes.Get (2)); // last node
+ producerHelper.SetPrefix("/prefix");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
+ producerHelper.Install(nodes.Get(2)); // last node
// The failure of the link connecting consumer and router will start from seconds 10.0 to 15.0
- Simulator::Schedule (Seconds (10.0), ndn::LinkControlHelper::FailLink, nodes.Get (0), nodes.Get (1));
- Simulator::Schedule (Seconds (15.0), ndn::LinkControlHelper::UpLink, nodes.Get (0), nodes.Get (1));
-
- Simulator::Stop (Seconds (20.0));
+ Simulator::Schedule(Seconds(10.0), ndn::LinkControlHelper::FailLink, nodes.Get(0), nodes.Get(1));
+ Simulator::Schedule(Seconds(15.0), ndn::LinkControlHelper::UpLink, nodes.Get(0), nodes.Get(1));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Stop(Seconds(20.0));
+
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-simple-with-pcap.cpp b/examples/ndn-simple-with-pcap.cpp
index 1e35fb0..ecbc8eb 100644
--- a/examples/ndn-simple-with-pcap.cpp
+++ b/examples/ndn-simple-with-pcap.cpp
@@ -25,84 +25,81 @@
using namespace ns3;
-class PcapWriter
-{
+class PcapWriter {
public:
- PcapWriter (const std::string &file)
+ PcapWriter(const std::string& file)
{
PcapHelper helper;
- m_pcap = helper.CreateFile (file, std::ios::out, PcapHelper::DLT_PPP);
+ m_pcap = helper.CreateFile(file, std::ios::out, PcapHelper::DLT_PPP);
}
void
- TracePacket (Ptr<const Packet> packet)
+ TracePacket(Ptr<const Packet> packet)
{
static PppHeader pppHeader;
- pppHeader.SetProtocol (0x0077);
+ pppHeader.SetProtocol(0x0077);
- m_pcap->Write (Simulator::Now (), pppHeader, packet);
+ m_pcap->Write(Simulator::Now(), pppHeader, packet);
}
private:
Ptr<PcapFileWrapper> m_pcap;
};
-
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
// setting default parameters for PointToPoint links and channels
- Config::SetDefault ("ns3::PointToPointNetDevice::DataRate", StringValue ("1Mbps"));
- Config::SetDefault ("ns3::PointToPointChannel::Delay", StringValue ("10ms"));
- Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("20"));
+ Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
+ Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
+ Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));
- Config::SetGlobal ("ndn::WireFormat", StringValue ("1"));
+ Config::SetGlobal("ndn::WireFormat", StringValue("1"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
- cmd.Parse (argc, argv);
-
+ cmd.Parse(argc, argv);
+
// Creating nodes
NodeContainer nodes;
- nodes.Create (3);
+ nodes.Create(3);
// Connecting nodes using two links
PointToPointHelper p2p;
- p2p.Install (nodes.Get (0), nodes.Get (1));
- p2p.Install (nodes.Get (1), nodes.Get (2));
+ p2p.Install(nodes.Get(0), nodes.Get(1));
+ p2p.Install(nodes.Get(1), nodes.Get(2));
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetDefaultRoutes (true);
- ndnHelper.InstallAll ();
+ ndnHelper.SetDefaultRoutes(true);
+ ndnHelper.InstallAll();
// Installing applications
// Consumer
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
// Consumer will request /prefix/0, /prefix/1, ...
- consumerHelper.SetPrefix ("/prefix");
- consumerHelper.SetAttribute ("Frequency", StringValue ("10")); // 10 interests a second
- consumerHelper.Install (nodes.Get (0)); // first node
+ consumerHelper.SetPrefix("/prefix");
+ consumerHelper.SetAttribute("Frequency", StringValue("10")); // 10 interests a second
+ consumerHelper.Install(nodes.Get(0)); // first node
// Producer
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
// Producer will reply to all requests starting with /prefix
- producerHelper.SetPrefix ("/prefix");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
- producerHelper.SetAttribute ("Signature", UintegerValue (100));
- producerHelper.SetAttribute ("KeyLocator", StringValue ("/unique/key/locator"));
- producerHelper.Install (nodes.Get (2)); // last node
+ producerHelper.SetPrefix("/prefix");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
+ producerHelper.SetAttribute("Signature", UintegerValue(100));
+ producerHelper.SetAttribute("KeyLocator", StringValue("/unique/key/locator"));
+ producerHelper.Install(nodes.Get(2)); // last node
- PcapWriter trace ("ndn-simple-trace.pcap");
- Config::ConnectWithoutContext ("/NodeList/*/DeviceList/*/$ns3::PointToPointNetDevice/MacTx",
- MakeCallback (&PcapWriter::TracePacket, &trace));
+ PcapWriter trace("ndn-simple-trace.pcap");
+ Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::PointToPointNetDevice/MacTx",
+ MakeCallback(&PcapWriter::TracePacket, &trace));
- Simulator::Stop (Seconds (20.0));
+ Simulator::Stop(Seconds(20.0));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
-
diff --git a/examples/ndn-simple.cpp b/examples/ndn-simple.cpp
index dea70a0..b7755e8 100644
--- a/examples/ndn-simple.cpp
+++ b/examples/ndn-simple.cpp
@@ -45,52 +45,52 @@
* NS_LOG=ndn.Consumer:ndn.Producer ./waf --run=ndn-simple
*/
-int
-main (int argc, char *argv[])
+int
+main(int argc, char* argv[])
{
// setting default parameters for PointToPoint links and channels
- Config::SetDefault ("ns3::PointToPointNetDevice::DataRate", StringValue ("1Mbps"));
- Config::SetDefault ("ns3::PointToPointChannel::Delay", StringValue ("10ms"));
- Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("20"));
+ Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
+ Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
+ Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
// Creating nodes
NodeContainer nodes;
- nodes.Create (3);
+ nodes.Create(3);
// Connecting nodes using two links
PointToPointHelper p2p;
- p2p.Install (nodes.Get (0), nodes.Get (1));
- p2p.Install (nodes.Get (1), nodes.Get (2));
+ p2p.Install(nodes.Get(0), nodes.Get(1));
+ p2p.Install(nodes.Get(1), nodes.Get(2));
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetDefaultRoutes (true);
- ndnHelper.InstallAll ();
+ ndnHelper.SetDefaultRoutes(true);
+ ndnHelper.InstallAll();
// Installing applications
// Consumer
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
// Consumer will request /prefix/0, /prefix/1, ...
- consumerHelper.SetPrefix ("/prefix");
- consumerHelper.SetAttribute ("Frequency", StringValue ("10")); // 10 interests a second
- consumerHelper.Install (nodes.Get (0)); // first node
+ consumerHelper.SetPrefix("/prefix");
+ consumerHelper.SetAttribute("Frequency", StringValue("10")); // 10 interests a second
+ consumerHelper.Install(nodes.Get(0)); // first node
// Producer
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
// Producer will reply to all requests starting with /prefix
- producerHelper.SetPrefix ("/prefix");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
- producerHelper.Install (nodes.Get (2)); // last node
+ producerHelper.SetPrefix("/prefix");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
+ producerHelper.Install(nodes.Get(2)); // last node
- Simulator::Stop (Seconds (20.0));
+ Simulator::Stop(Seconds(20.0));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-tree-app-delay-tracer.cpp b/examples/ndn-tree-app-delay-tracer.cpp
index b4563a9..b503843 100644
--- a/examples/ndn-tree-app-delay-tracer.cpp
+++ b/examples/ndn-tree-app-delay-tracer.cpp
@@ -32,21 +32,21 @@
* /------\ /------\ /------\ /------\
* |leaf-1| |leaf-2| |leaf-3| |leaf-4|
* \------/ \------/ \------/ \------/
- * ^ ^ ^ ^
+ * ^ ^ ^ ^
* | | | |
- * \ / \ /
+ * \ / \ /
* \ / \ / 10Mbps / 1ms
* \ / \ /
- * | | | |
- * v v v v
+ * | | | |
+ * v v v v
* /-------\ /-------\
* | rtr-1 | | rtr-2 |
* \-------/ \-------/
- * ^ ^
+ * ^ ^
* | |
- * \ / 10 Mpbs / 1ms
- * +--------+ +--------+
- * | |
+ * \ / 10 Mpbs / 1ms
+ * +--------+ +--------+
+ * | |
* v v
* /--------\
* | root |
@@ -59,59 +59,58 @@
*/
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
- AnnotatedTopologyReader topologyReader ("", 1);
- topologyReader.SetFileName ("src/ndnSIM/examples/topologies/topo-tree.txt");
- topologyReader.Read ();
+ AnnotatedTopologyReader topologyReader("", 1);
+ topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-tree.txt");
+ topologyReader.Read();
// Install CCNx stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetForwardingStrategy ("ns3::ndn::fw::BestRoute");
- ndnHelper.InstallAll ();
+ ndnHelper.SetForwardingStrategy("ns3::ndn::fw::BestRoute");
+ ndnHelper.InstallAll();
// Installing global routing interface on all nodes
ndn::GlobalRoutingHelper ccnxGlobalRoutingHelper;
- ccnxGlobalRoutingHelper.InstallAll ();
+ ccnxGlobalRoutingHelper.InstallAll();
// Getting containers for the consumer/producer
- Ptr<Node> consumers[4] = { Names::Find<Node> ("leaf-1"), Names::Find<Node> ("leaf-2"),
- Names::Find<Node> ("leaf-3"), Names::Find<Node> ("leaf-4") };
- Ptr<Node> producer = Names::Find<Node> ("root");
-
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerBatches");
- consumerHelper.SetPrefix ("/root");
- consumerHelper.SetAttribute ("Batches", StringValue ("1s 1 10s 1"));
- consumerHelper.Install (consumers[0]);
+ Ptr<Node> consumers[4] = {Names::Find<Node>("leaf-1"), Names::Find<Node>("leaf-2"),
+ Names::Find<Node>("leaf-3"), Names::Find<Node>("leaf-4")};
+ Ptr<Node> producer = Names::Find<Node>("root");
- consumerHelper.SetAttribute ("Batches", StringValue ("11s 1"));
- consumerHelper.Install (consumers[1]);
-
- consumerHelper.SetAttribute ("Batches", StringValue ("11s 1"));
- consumerHelper.Install (consumers[2]);
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerBatches");
+ consumerHelper.SetPrefix("/root");
+ consumerHelper.SetAttribute("Batches", StringValue("1s 1 10s 1"));
+ consumerHelper.Install(consumers[0]);
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
+ consumerHelper.SetAttribute("Batches", StringValue("11s 1"));
+ consumerHelper.Install(consumers[1]);
+
+ consumerHelper.SetAttribute("Batches", StringValue("11s 1"));
+ consumerHelper.Install(consumers[2]);
+
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
// Register /root prefix with global routing controller and
// install producer that will satisfy Interests in /root namespace
- ccnxGlobalRoutingHelper.AddOrigins ("/root", producer);
- producerHelper.SetPrefix ("/root");
- producerHelper.Install (producer)
- .Start (Seconds (9));
+ ccnxGlobalRoutingHelper.AddOrigins("/root", producer);
+ producerHelper.SetPrefix("/root");
+ producerHelper.Install(producer).Start(Seconds(9));
// Calculate and install FIBs
- ccnxGlobalRoutingHelper.CalculateRoutes ();
+ ccnxGlobalRoutingHelper.CalculateRoutes();
- Simulator::Stop (Seconds (20.0));
+ Simulator::Stop(Seconds(20.0));
- ndn::AppDelayTracer::InstallAll ("app-delays-trace.txt");
-
- Simulator::Run ();
- Simulator::Destroy ();
+ ndn::AppDelayTracer::InstallAll("app-delays-trace.txt");
+
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-tree-cs-tracers.cpp b/examples/ndn-tree-cs-tracers.cpp
index eaa5bf9..ce27888 100644
--- a/examples/ndn-tree-cs-tracers.cpp
+++ b/examples/ndn-tree-cs-tracers.cpp
@@ -32,21 +32,21 @@
* /------\ /------\ /------\ /------\
* |leaf-1| |leaf-2| |leaf-3| |leaf-4|
* \------/ \------/ \------/ \------/
- * ^ ^ ^ ^
+ * ^ ^ ^ ^
* | | | |
- * \ / \ /
+ * \ / \ /
* \ / \ / 10Mbps / 1ms
* \ / \ /
- * | | | |
- * v v v v
+ * | | | |
+ * v v v v
* /-------\ /-------\
* | rtr-1 | | rtr-2 |
* \-------/ \-------/
- * ^ ^
+ * ^ ^
* | |
- * \ / 10 Mpbs / 1ms
- * +--------+ +--------+
- * | |
+ * \ / 10 Mpbs / 1ms
+ * +--------+ +--------+
+ * | |
* v v
* /--------\
* | root |
@@ -59,59 +59,59 @@
*/
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
- AnnotatedTopologyReader topologyReader ("", 1);
- topologyReader.SetFileName ("src/ndnSIM/examples/topologies/topo-tree.txt");
- topologyReader.Read ();
+ AnnotatedTopologyReader topologyReader("", 1);
+ topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-tree.txt");
+ topologyReader.Read();
// Install CCNx stack on all nodes
ndn::StackHelper ndnHelper;
- ndnHelper.SetForwardingStrategy ("ns3::ndn::fw::BestRoute");
- ndnHelper.SetContentStore ("ns3::ndn::cs::Lru", "MaxSize", "100"); // default ContentStore parameters
- ndnHelper.InstallAll ();
+ ndnHelper.SetForwardingStrategy("ns3::ndn::fw::BestRoute");
+ ndnHelper.SetContentStore("ns3::ndn::cs::Lru", "MaxSize",
+ "100"); // default ContentStore parameters
+ ndnHelper.InstallAll();
// Installing global routing interface on all nodes
ndn::GlobalRoutingHelper ccnxGlobalRoutingHelper;
- ccnxGlobalRoutingHelper.InstallAll ();
+ ccnxGlobalRoutingHelper.InstallAll();
// Getting containers for the consumer/producer
- Ptr<Node> consumers[4] = { Names::Find<Node> ("leaf-1"), Names::Find<Node> ("leaf-2"),
- Names::Find<Node> ("leaf-3"), Names::Find<Node> ("leaf-4") };
- Ptr<Node> producer = Names::Find<Node> ("root");
+ Ptr<Node> consumers[4] = {Names::Find<Node>("leaf-1"), Names::Find<Node>("leaf-2"),
+ Names::Find<Node>("leaf-3"), Names::Find<Node>("leaf-4")};
+ Ptr<Node> producer = Names::Find<Node>("root");
- for (int i = 0; i < 4; i++)
- {
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
- consumerHelper.SetAttribute ("Frequency", StringValue ("10")); // 100 interests a second
+ for (int i = 0; i < 4; i++) {
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
+ consumerHelper.SetAttribute("Frequency", StringValue("10")); // 100 interests a second
- // Each consumer will express the same data /root/<seq-no>
- consumerHelper.SetPrefix ("/root");
- ApplicationContainer app = consumerHelper.Install (consumers[i]);
- app.Start (Seconds (0.01 * i));
- }
-
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
+ // Each consumer will express the same data /root/<seq-no>
+ consumerHelper.SetPrefix("/root");
+ ApplicationContainer app = consumerHelper.Install(consumers[i]);
+ app.Start(Seconds(0.01 * i));
+ }
+
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
// Register /root prefix with global routing controller and
// install producer that will satisfy Interests in /root namespace
- ccnxGlobalRoutingHelper.AddOrigins ("/root", producer);
- producerHelper.SetPrefix ("/root");
- producerHelper.Install (producer);
+ ccnxGlobalRoutingHelper.AddOrigins("/root", producer);
+ producerHelper.SetPrefix("/root");
+ producerHelper.Install(producer);
// Calculate and install FIBs
- ccnxGlobalRoutingHelper.CalculateRoutes ();
+ ccnxGlobalRoutingHelper.CalculateRoutes();
- Simulator::Stop (Seconds (20.0));
+ Simulator::Stop(Seconds(20.0));
- ndn::CsTracer::InstallAll ("cs-trace.txt", Seconds (1));
-
- Simulator::Run ();
- Simulator::Destroy ();
+ ndn::CsTracer::InstallAll("cs-trace.txt", Seconds(1));
+
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-tree-tracers.cpp b/examples/ndn-tree-tracers.cpp
index aeb65f9..29772f7 100644
--- a/examples/ndn-tree-tracers.cpp
+++ b/examples/ndn-tree-tracers.cpp
@@ -32,21 +32,21 @@
* /------\ /------\ /------\ /------\
* |leaf-1| |leaf-2| |leaf-3| |leaf-4|
* \------/ \------/ \------/ \------/
- * ^ ^ ^ ^
+ * ^ ^ ^ ^
* | | | |
- * \ / \ /
+ * \ / \ /
* \ / \ / 10Mbps / 1ms
* \ / \ /
- * | | | |
- * v v v v
+ * | | | |
+ * v v v v
* /-------\ /-------\
* | rtr-1 | | rtr-2 |
* \-------/ \-------/
- * ^ ^
+ * ^ ^
* | |
- * \ / 10 Mpbs / 1ms
- * +--------+ +--------+
- * | |
+ * \ / 10 Mpbs / 1ms
+ * +--------+ +--------+
+ * | |
* v v
* /--------\
* | root |
@@ -59,58 +59,57 @@
*/
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
- AnnotatedTopologyReader topologyReader ("", 1);
- topologyReader.SetFileName ("src/ndnSIM/examples/topologies/topo-tree.txt");
- topologyReader.Read ();
+ AnnotatedTopologyReader topologyReader("", 1);
+ topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-tree.txt");
+ topologyReader.Read();
// Install CCNx stack on all nodes
ndn::StackHelper ccnxHelper;
- ccnxHelper.SetForwardingStrategy ("ns3::ndn::fw::BestRoute");
- ccnxHelper.InstallAll ();
+ ccnxHelper.SetForwardingStrategy("ns3::ndn::fw::BestRoute");
+ ccnxHelper.InstallAll();
// Installing global routing interface on all nodes
ndn::GlobalRoutingHelper ccnxGlobalRoutingHelper;
- ccnxGlobalRoutingHelper.InstallAll ();
+ ccnxGlobalRoutingHelper.InstallAll();
// Getting containers for the consumer/producer
- Ptr<Node> consumers[4] = { Names::Find<Node> ("leaf-1"), Names::Find<Node> ("leaf-2"),
- Names::Find<Node> ("leaf-3"), Names::Find<Node> ("leaf-4") };
- Ptr<Node> producer = Names::Find<Node> ("root");
+ Ptr<Node> consumers[4] = {Names::Find<Node>("leaf-1"), Names::Find<Node>("leaf-2"),
+ Names::Find<Node>("leaf-3"), Names::Find<Node>("leaf-4")};
+ Ptr<Node> producer = Names::Find<Node>("root");
- for (int i = 0; i < 4; i++)
- {
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
- consumerHelper.SetAttribute ("Frequency", StringValue ("100")); // 100 interests a second
+ for (int i = 0; i < 4; i++) {
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
+ consumerHelper.SetAttribute("Frequency", StringValue("100")); // 100 interests a second
- // Each consumer will express unique interests /root/<leaf-name>/<seq-no>
- consumerHelper.SetPrefix ("/root/" + Names::FindName (consumers[i]));
- consumerHelper.Install (consumers[i]);
- }
-
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
+ // Each consumer will express unique interests /root/<leaf-name>/<seq-no>
+ consumerHelper.SetPrefix("/root/" + Names::FindName(consumers[i]));
+ consumerHelper.Install(consumers[i]);
+ }
+
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
// Register /root prefix with global routing controller and
// install producer that will satisfy Interests in /root namespace
- ccnxGlobalRoutingHelper.AddOrigins ("/root", producer);
- producerHelper.SetPrefix ("/root");
- producerHelper.Install (producer);
+ ccnxGlobalRoutingHelper.AddOrigins("/root", producer);
+ producerHelper.SetPrefix("/root");
+ producerHelper.Install(producer);
// Calculate and install FIBs
- ccnxGlobalRoutingHelper.CalculateRoutes ();
+ ccnxGlobalRoutingHelper.CalculateRoutes();
- Simulator::Stop (Seconds (20.0));
+ Simulator::Stop(Seconds(20.0));
- ndn::L3AggregateTracer::InstallAll ("aggregate-trace.txt", Seconds (0.5));
- ndn::L3RateTracer::InstallAll ("rate-trace.txt", Seconds (0.5));
-
- Simulator::Run ();
- Simulator::Destroy ();
+ ndn::L3AggregateTracer::InstallAll("aggregate-trace.txt", Seconds(0.5));
+ ndn::L3RateTracer::InstallAll("rate-trace.txt", Seconds(0.5));
+
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-tree-with-l2tracer.cpp b/examples/ndn-tree-with-l2tracer.cpp
index 19ba3a2..8d5e3e0 100644
--- a/examples/ndn-tree-with-l2tracer.cpp
+++ b/examples/ndn-tree-with-l2tracer.cpp
@@ -7,135 +7,135 @@
using namespace ns3;
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
- AnnotatedTopologyReader topologyReader ("", 10);
- topologyReader.SetFileName ("src/ndnSIM/examples/topologies/topo-tree-25-node.txt");
- topologyReader.Read ();
-
+ AnnotatedTopologyReader topologyReader("", 10);
+ topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-tree-25-node.txt");
+ topologyReader.Read();
+
/****************************************************************************/
// Install CCNx stack on all nodes
ndn::StackHelper ccnxHelper;
- ccnxHelper.SetContentStore ("ns3::ndn::cs::Lru", "MaxSize", "1000");
- ccnxHelper.SetForwardingStrategy ("ns3::ndn::fw::BestRoute");
- ccnxHelper.InstallAll ();
+ ccnxHelper.SetContentStore("ns3::ndn::cs::Lru", "MaxSize", "1000");
+ ccnxHelper.SetForwardingStrategy("ns3::ndn::fw::BestRoute");
+ ccnxHelper.InstallAll();
/****************************************************************************/
// Installing global routing interface on all nodes
ndn::GlobalRoutingHelper ccnxGlobalRoutingHelper;
- ccnxGlobalRoutingHelper.InstallAll ();
+ ccnxGlobalRoutingHelper.InstallAll();
/****************************************************************************/
// Getting containers for the consumer/producer
- Ptr<Node> consumer1 = Names::Find<Node> ("Src1");
- Ptr<Node> consumer2 = Names::Find<Node> ("Src2");
- Ptr<Node> consumer3 = Names::Find<Node> ("Src3");
- Ptr<Node> consumer4 = Names::Find<Node> ("Src4");
- Ptr<Node> consumer5 = Names::Find<Node> ("Src5");
- Ptr<Node> consumer6 = Names::Find<Node> ("Src6");
- Ptr<Node> consumer7 = Names::Find<Node> ("Src7");
- Ptr<Node> consumer8 = Names::Find<Node> ("Src8");
- Ptr<Node> consumer9 = Names::Find<Node> ("Src9");
+ Ptr<Node> consumer1 = Names::Find<Node>("Src1");
+ Ptr<Node> consumer2 = Names::Find<Node>("Src2");
+ Ptr<Node> consumer3 = Names::Find<Node>("Src3");
+ Ptr<Node> consumer4 = Names::Find<Node>("Src4");
+ Ptr<Node> consumer5 = Names::Find<Node>("Src5");
+ Ptr<Node> consumer6 = Names::Find<Node>("Src6");
+ Ptr<Node> consumer7 = Names::Find<Node>("Src7");
+ Ptr<Node> consumer8 = Names::Find<Node>("Src8");
+ Ptr<Node> consumer9 = Names::Find<Node>("Src9");
- Ptr<Node> producer1 = Names::Find<Node> ("Dst1");
- Ptr<Node> producer2 = Names::Find<Node> ("Dst2");
- Ptr<Node> producer3 = Names::Find<Node> ("Dst3");
- Ptr<Node> producer4 = Names::Find<Node> ("Dst4");
- Ptr<Node> producer5 = Names::Find<Node> ("Dst5");
- Ptr<Node> producer6 = Names::Find<Node> ("Dst6");
- Ptr<Node> producer7 = Names::Find<Node> ("Dst7");
- Ptr<Node> producer8 = Names::Find<Node> ("Dst8");
- Ptr<Node> producer9 = Names::Find<Node> ("Dst9");
+ Ptr<Node> producer1 = Names::Find<Node>("Dst1");
+ Ptr<Node> producer2 = Names::Find<Node>("Dst2");
+ Ptr<Node> producer3 = Names::Find<Node>("Dst3");
+ Ptr<Node> producer4 = Names::Find<Node>("Dst4");
+ Ptr<Node> producer5 = Names::Find<Node>("Dst5");
+ Ptr<Node> producer6 = Names::Find<Node>("Dst6");
+ Ptr<Node> producer7 = Names::Find<Node>("Dst7");
+ Ptr<Node> producer8 = Names::Find<Node>("Dst8");
+ Ptr<Node> producer9 = Names::Find<Node>("Dst9");
/****************************************************************************/
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
- consumerHelper.SetAttribute ("Frequency", StringValue ("1000"));//interests per Second
- consumerHelper.SetAttribute ("Randomize", StringValue ("uniform"));
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
+ consumerHelper.SetAttribute("Frequency", StringValue("1000")); // interests per Second
+ consumerHelper.SetAttribute("Randomize", StringValue("uniform"));
/****************************************************************************/
// on the first to ninth consumer node install a Consumer application
// that will express interests in /dst1 to /dst9 namespace
- consumerHelper.SetPrefix ("/dst9");
- consumerHelper.Install (consumer1);
+ consumerHelper.SetPrefix("/dst9");
+ consumerHelper.Install(consumer1);
- consumerHelper.SetPrefix ("/dst8");
- consumerHelper.Install (consumer2);
+ consumerHelper.SetPrefix("/dst8");
+ consumerHelper.Install(consumer2);
- consumerHelper.SetPrefix ("/dst7");
- consumerHelper.Install (consumer3);
+ consumerHelper.SetPrefix("/dst7");
+ consumerHelper.Install(consumer3);
- consumerHelper.SetPrefix ("/dst6");
- consumerHelper.Install (consumer4);
+ consumerHelper.SetPrefix("/dst6");
+ consumerHelper.Install(consumer4);
- consumerHelper.SetPrefix ("/dst5");
- consumerHelper.Install (consumer5);
+ consumerHelper.SetPrefix("/dst5");
+ consumerHelper.Install(consumer5);
- consumerHelper.SetPrefix ("/dst4");
- consumerHelper.Install (consumer6);
+ consumerHelper.SetPrefix("/dst4");
+ consumerHelper.Install(consumer6);
- consumerHelper.SetPrefix ("/dst3");
- consumerHelper.Install (consumer7);
+ consumerHelper.SetPrefix("/dst3");
+ consumerHelper.Install(consumer7);
- consumerHelper.SetPrefix ("/dst2");
- consumerHelper.Install (consumer8);
+ consumerHelper.SetPrefix("/dst2");
+ consumerHelper.Install(consumer8);
- consumerHelper.SetPrefix ("/dst1");
- consumerHelper.Install (consumer9);
-
+ consumerHelper.SetPrefix("/dst1");
+ consumerHelper.Install(consumer9);
+
/****************************************************************************/
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetAttribute ("PayloadSize", StringValue("1024"));
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
/****************************************************************************/
// Register /dst1 to /dst9 prefix with global routing controller and
// install producer that will satisfy Interests in /dst1 to /dst9 namespace
- ccnxGlobalRoutingHelper.AddOrigins ("/dst1", producer1);
- producerHelper.SetPrefix ("/dst1");
- producerHelper.Install (producer1);
+ ccnxGlobalRoutingHelper.AddOrigins("/dst1", producer1);
+ producerHelper.SetPrefix("/dst1");
+ producerHelper.Install(producer1);
- ccnxGlobalRoutingHelper.AddOrigins ("/dst2", producer2);
- producerHelper.SetPrefix ("/dst2");
- producerHelper.Install (producer2);
+ ccnxGlobalRoutingHelper.AddOrigins("/dst2", producer2);
+ producerHelper.SetPrefix("/dst2");
+ producerHelper.Install(producer2);
- ccnxGlobalRoutingHelper.AddOrigins ("/dst3", producer3);
- producerHelper.SetPrefix ("/dst3");
- producerHelper.Install (producer3);
+ ccnxGlobalRoutingHelper.AddOrigins("/dst3", producer3);
+ producerHelper.SetPrefix("/dst3");
+ producerHelper.Install(producer3);
- ccnxGlobalRoutingHelper.AddOrigins ("/dst4", producer4);
- producerHelper.SetPrefix ("/dst4");
- producerHelper.Install (producer4);
+ ccnxGlobalRoutingHelper.AddOrigins("/dst4", producer4);
+ producerHelper.SetPrefix("/dst4");
+ producerHelper.Install(producer4);
- ccnxGlobalRoutingHelper.AddOrigins ("/dst5", producer5);
- producerHelper.SetPrefix ("/dst5");
- producerHelper.Install (producer5);
+ ccnxGlobalRoutingHelper.AddOrigins("/dst5", producer5);
+ producerHelper.SetPrefix("/dst5");
+ producerHelper.Install(producer5);
- ccnxGlobalRoutingHelper.AddOrigins ("/dst6", producer6);
- producerHelper.SetPrefix ("/dst6");
- producerHelper.Install (producer6);
+ ccnxGlobalRoutingHelper.AddOrigins("/dst6", producer6);
+ producerHelper.SetPrefix("/dst6");
+ producerHelper.Install(producer6);
- ccnxGlobalRoutingHelper.AddOrigins ("/dst7", producer7);
- producerHelper.SetPrefix ("/dst7");
- producerHelper.Install (producer7);
+ ccnxGlobalRoutingHelper.AddOrigins("/dst7", producer7);
+ producerHelper.SetPrefix("/dst7");
+ producerHelper.Install(producer7);
- ccnxGlobalRoutingHelper.AddOrigins ("/dst8", producer8);
- producerHelper.SetPrefix ("/dst8");
- producerHelper.Install (producer8);
+ ccnxGlobalRoutingHelper.AddOrigins("/dst8", producer8);
+ producerHelper.SetPrefix("/dst8");
+ producerHelper.Install(producer8);
- ccnxGlobalRoutingHelper.AddOrigins ("/dst9", producer9);
- producerHelper.SetPrefix ("/dst9");
- producerHelper.Install (producer9);
+ ccnxGlobalRoutingHelper.AddOrigins("/dst9", producer9);
+ producerHelper.SetPrefix("/dst9");
+ producerHelper.Install(producer9);
/*****************************************************************************/
// Calculate and install FIBs
- ccnxGlobalRoutingHelper.CalculateRoutes ();
+ ccnxGlobalRoutingHelper.CalculateRoutes();
- Simulator::Stop (Seconds (10.0));
+ Simulator::Stop(Seconds(10.0));
/****************************************************************************/
- //Tracer:
+ // Tracer:
- L2RateTracer::InstallAll ("drop-trace.txt", Seconds (0.5));
+ L2RateTracer::InstallAll("drop-trace.txt", Seconds(0.5));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/examples/ndn-zipf-mandelbrot.cpp b/examples/ndn-zipf-mandelbrot.cpp
index 64e385c..4bec18e 100644
--- a/examples/ndn-zipf-mandelbrot.cpp
+++ b/examples/ndn-zipf-mandelbrot.cpp
@@ -51,63 +51,63 @@
*/
int
-main (int argc, char *argv[])
+main(int argc, char* argv[])
{
- //LogComponentEnable("ndn.CbisGlobalRoutingHelper", LOG_LEVEL_INFO);
+ // LogComponentEnable("ndn.CbisGlobalRoutingHelper", LOG_LEVEL_INFO);
// Setting default parameters for PointToPoint links and channels
- Config::SetDefault ("ns3::PointToPointNetDevice::DataRate", StringValue ("1Mbps"));
- Config::SetDefault ("ns3::PointToPointChannel::Delay", StringValue ("1ms"));
- Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("10"));
+ Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
+ Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("1ms"));
+ Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("10"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
- cmd.Parse (argc, argv);
+ cmd.Parse(argc, argv);
// Creating 3x3 topology
PointToPointHelper p2p;
- PointToPointGridHelper grid (3, 3, p2p);
- grid.BoundingBox(100,100,200,200);
+ PointToPointGridHelper grid(3, 3, p2p);
+ grid.BoundingBox(100, 100, 200, 200);
// Install CCNx stack on all nodes
ndn::StackHelper ccnxHelper;
- ccnxHelper.SetForwardingStrategy ("ns3::ndn::fw::SmartFlooding");
- ccnxHelper.SetContentStore ("ns3::ndn::cs::Lru", "MaxSize", "10");
- ccnxHelper.InstallAll ();
+ ccnxHelper.SetForwardingStrategy("ns3::ndn::fw::SmartFlooding");
+ ccnxHelper.SetContentStore("ns3::ndn::cs::Lru", "MaxSize", "10");
+ ccnxHelper.InstallAll();
// Installing global routing interface on all nodes
- //ndn::CbisGlobalRoutingHelper ccnxGlobalRoutingHelper;
+ // ndn::CbisGlobalRoutingHelper ccnxGlobalRoutingHelper;
ndn::GlobalRoutingHelper ccnxGlobalRoutingHelper;
- ccnxGlobalRoutingHelper.InstallAll ();
+ ccnxGlobalRoutingHelper.InstallAll();
// Getting containers for the consumer/producer
- Ptr<Node> producer = grid.GetNode (2, 2);
+ Ptr<Node> producer = grid.GetNode(2, 2);
NodeContainer consumerNodes;
- consumerNodes.Add (grid.GetNode (0,0));
+ consumerNodes.Add(grid.GetNode(0, 0));
// Install CCNx applications
std::string prefix = "/prefix";
- ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerZipfMandelbrot");
- //ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
- consumerHelper.SetPrefix (prefix);
- consumerHelper.SetAttribute ("Frequency", StringValue ("100")); // 100 interests a second
- consumerHelper.SetAttribute ("NumberOfContents", StringValue ("100")); // 10 different contents
- //consumerHelper.SetAttribute ("Randomize", StringValue ("uniform")); // 100 interests a second
- consumerHelper.Install (consumerNodes);
+ ndn::AppHelper consumerHelper("ns3::ndn::ConsumerZipfMandelbrot");
+ // ndn::AppHelper consumerHelper ("ns3::ndn::ConsumerCbr");
+ consumerHelper.SetPrefix(prefix);
+ consumerHelper.SetAttribute("Frequency", StringValue("100")); // 100 interests a second
+ consumerHelper.SetAttribute("NumberOfContents", StringValue("100")); // 10 different contents
+ // consumerHelper.SetAttribute ("Randomize", StringValue ("uniform")); // 100 interests a second
+ consumerHelper.Install(consumerNodes);
- ndn::AppHelper producerHelper ("ns3::ndn::Producer");
- producerHelper.SetPrefix (prefix);
- producerHelper.SetAttribute ("PayloadSize", StringValue("100"));
- producerHelper.Install (producer);
- ccnxGlobalRoutingHelper.AddOrigins (prefix, producer);
+ ndn::AppHelper producerHelper("ns3::ndn::Producer");
+ producerHelper.SetPrefix(prefix);
+ producerHelper.SetAttribute("PayloadSize", StringValue("100"));
+ producerHelper.Install(producer);
+ ccnxGlobalRoutingHelper.AddOrigins(prefix, producer);
// Calculate and install FIBs
- ccnxGlobalRoutingHelper.CalculateRoutes ();
+ ccnxGlobalRoutingHelper.CalculateRoutes();
- Simulator::Stop (Seconds (10.0));
+ Simulator::Stop(Seconds(10.0));
- Simulator::Run ();
- Simulator::Destroy ();
+ Simulator::Run();
+ Simulator::Destroy();
return 0;
}
diff --git a/helper/boost-graph-ndn-global-routing-helper.hpp b/helper/boost-graph-ndn-global-routing-helper.hpp
index e615494..85bac72 100644
--- a/helper/boost-graph-ndn-global-routing-helper.hpp
+++ b/helper/boost-graph-ndn-global-routing-helper.hpp
@@ -18,7 +18,6 @@
* Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
-
#ifndef BOOST_GRAPH_NDN_GLOBAL_ROUTING_HELPER_H
#define BOOST_GRAPH_NDN_GLOBAL_ROUTING_HELPER_H
@@ -38,51 +37,45 @@
namespace boost {
-class NdnGlobalRouterGraph
-{
+class NdnGlobalRouterGraph {
public:
- typedef ns3::Ptr< ns3::ndn::GlobalRouter > Vertice;
+ typedef ns3::Ptr<ns3::ndn::GlobalRouter> Vertice;
typedef uint16_t edge_property_type;
typedef uint32_t vertex_property_type;
-
- NdnGlobalRouterGraph ()
- {
- for (ns3::NodeList::Iterator node = ns3::NodeList::Begin (); node != ns3::NodeList::End (); node++)
- {
- ns3::Ptr<ns3::ndn::GlobalRouter> gr = (*node)->GetObject<ns3::ndn::GlobalRouter> ();
- if (gr != 0)
- m_vertices.push_back (gr);
- }
- for (ns3::ChannelList::Iterator channel = ns3::ChannelList::Begin (); channel != ns3::ChannelList::End (); channel++)
- {
- ns3::Ptr<ns3::ndn::GlobalRouter> gr = (*channel)->GetObject<ns3::ndn::GlobalRouter> ();
- if (gr != 0)
- m_vertices.push_back (gr);
- }
+ NdnGlobalRouterGraph()
+ {
+ for (ns3::NodeList::Iterator node = ns3::NodeList::Begin(); node != ns3::NodeList::End();
+ node++) {
+ ns3::Ptr<ns3::ndn::GlobalRouter> gr = (*node)->GetObject<ns3::ndn::GlobalRouter>();
+ if (gr != 0)
+ m_vertices.push_back(gr);
+ }
+
+ for (ns3::ChannelList::Iterator channel = ns3::ChannelList::Begin();
+ channel != ns3::ChannelList::End(); channel++) {
+ ns3::Ptr<ns3::ndn::GlobalRouter> gr = (*channel)->GetObject<ns3::ndn::GlobalRouter>();
+ if (gr != 0)
+ m_vertices.push_back(gr);
+ }
}
- const std::list< Vertice > &
- GetVertices () const
+ const std::list<Vertice>&
+ GetVertices() const
{
return m_vertices;
}
-
+
public:
- std::list< Vertice > m_vertices;
+ std::list<Vertice> m_vertices;
};
-
-class ndn_global_router_graph_category :
- public virtual vertex_list_graph_tag,
- public virtual incidence_graph_tag
-{
+class ndn_global_router_graph_category : public virtual vertex_list_graph_tag,
+ public virtual incidence_graph_tag {
};
-
template<>
-struct graph_traits< NdnGlobalRouterGraph >
-{
+struct graph_traits<NdnGlobalRouterGraph> {
// Graph concept
typedef NdnGlobalRouterGraph::Vertice vertex_descriptor;
typedef ns3::ndn::GlobalRouter::Incidency edge_descriptor;
@@ -91,7 +84,7 @@
typedef ndn_global_router_graph_category traversal_category;
// VertexList concept
- typedef std::list< vertex_descriptor >::const_iterator vertex_iterator;
+ typedef std::list<vertex_descriptor>::const_iterator vertex_iterator;
typedef size_t vertices_size_type;
// AdjacencyGraph concept
@@ -103,265 +96,223 @@
} // namespace boost
-namespace boost
-{
+namespace boost {
-inline
-graph_traits< NdnGlobalRouterGraph >::vertex_descriptor
-source(
- graph_traits< NdnGlobalRouterGraph >::edge_descriptor e,
- const NdnGlobalRouterGraph& g)
+inline graph_traits<NdnGlobalRouterGraph>::vertex_descriptor
+source(graph_traits<NdnGlobalRouterGraph>::edge_descriptor e, const NdnGlobalRouterGraph& g)
{
- return e.get<0> ();
+ return e.get<0>();
}
-inline
-graph_traits< NdnGlobalRouterGraph >::vertex_descriptor
-target(
- graph_traits< NdnGlobalRouterGraph >::edge_descriptor e,
- const NdnGlobalRouterGraph& g)
+inline graph_traits<NdnGlobalRouterGraph>::vertex_descriptor
+target(graph_traits<NdnGlobalRouterGraph>::edge_descriptor e, const NdnGlobalRouterGraph& g)
{
- return e.get<2> ();
+ return e.get<2>();
}
-inline
-std::pair< graph_traits< NdnGlobalRouterGraph >::vertex_iterator,
- graph_traits< NdnGlobalRouterGraph >::vertex_iterator >
-vertices (const NdnGlobalRouterGraph&g)
+inline std::pair<graph_traits<NdnGlobalRouterGraph>::vertex_iterator,
+ graph_traits<NdnGlobalRouterGraph>::vertex_iterator>
+vertices(const NdnGlobalRouterGraph& g)
{
- return make_pair (g.GetVertices ().begin (), g.GetVertices ().end ());
+ return make_pair(g.GetVertices().begin(), g.GetVertices().end());
}
-inline
-graph_traits< NdnGlobalRouterGraph >::vertices_size_type
-num_vertices(const NdnGlobalRouterGraph &g)
+inline graph_traits<NdnGlobalRouterGraph>::vertices_size_type
+num_vertices(const NdnGlobalRouterGraph& g)
{
- return g.GetVertices ().size ();
-}
-
-
-inline
-std::pair< graph_traits< NdnGlobalRouterGraph >::out_edge_iterator,
- graph_traits< NdnGlobalRouterGraph >::out_edge_iterator >
-out_edges(
- graph_traits< NdnGlobalRouterGraph >::vertex_descriptor u,
- const NdnGlobalRouterGraph& g)
-{
- return std::make_pair(u->GetIncidencies ().begin (),
- u->GetIncidencies ().end ());
+ return g.GetVertices().size();
}
-inline
-graph_traits< NdnGlobalRouterGraph >::degree_size_type
-out_degree(
- graph_traits< NdnGlobalRouterGraph >::vertex_descriptor u,
- const NdnGlobalRouterGraph& g)
+inline std::pair<graph_traits<NdnGlobalRouterGraph>::out_edge_iterator,
+ graph_traits<NdnGlobalRouterGraph>::out_edge_iterator>
+out_edges(graph_traits<NdnGlobalRouterGraph>::vertex_descriptor u, const NdnGlobalRouterGraph& g)
{
- return u->GetIncidencies ().size ();
+ return std::make_pair(u->GetIncidencies().begin(), u->GetIncidencies().end());
}
+inline graph_traits<NdnGlobalRouterGraph>::degree_size_type
+out_degree(graph_traits<NdnGlobalRouterGraph>::vertex_descriptor u, const NdnGlobalRouterGraph& g)
+{
+ return u->GetIncidencies().size();
+}
//////////////////////////////////////////////////////////////
// Property maps
-struct EdgeWeights
-{
- EdgeWeights (const NdnGlobalRouterGraph &graph)
- : m_graph (graph)
- {
+struct EdgeWeights {
+ EdgeWeights(const NdnGlobalRouterGraph& graph)
+ : m_graph(graph)
+ {
}
private:
- const NdnGlobalRouterGraph &m_graph;
+ const NdnGlobalRouterGraph& m_graph;
};
-
-struct VertexIds
-{
- VertexIds (const NdnGlobalRouterGraph &graph)
- : m_graph (graph)
- {
+struct VertexIds {
+ VertexIds(const NdnGlobalRouterGraph& graph)
+ : m_graph(graph)
+ {
}
private:
- const NdnGlobalRouterGraph &m_graph;
+ const NdnGlobalRouterGraph& m_graph;
};
template<>
-struct property_map< NdnGlobalRouterGraph, edge_weight_t >
-{
+struct property_map<NdnGlobalRouterGraph, edge_weight_t> {
typedef const EdgeWeights const_type;
typedef EdgeWeights type;
};
template<>
-struct property_map< NdnGlobalRouterGraph, vertex_index_t >
-{
+struct property_map<NdnGlobalRouterGraph, vertex_index_t> {
typedef const VertexIds const_type;
typedef VertexIds type;
};
-
template<>
-struct property_traits< EdgeWeights >
-{
+struct property_traits<EdgeWeights> {
// Metric property map
- typedef tuple< ns3::Ptr<ns3::ndn::Face>, uint16_t, double > value_type;
- typedef tuple< ns3::Ptr<ns3::ndn::Face>, uint16_t, double > reference;
+ typedef tuple<ns3::Ptr<ns3::ndn::Face>, uint16_t, double> value_type;
+ typedef tuple<ns3::Ptr<ns3::ndn::Face>, uint16_t, double> reference;
typedef ns3::ndn::GlobalRouter::Incidency key_type;
typedef readable_property_map_tag category;
};
-const property_traits< EdgeWeights >::value_type WeightZero (0, 0, 0.0);
-const property_traits< EdgeWeights >::value_type WeightInf (0, std::numeric_limits<uint16_t>::max (), 0.0);
+const property_traits<EdgeWeights>::value_type WeightZero(0, 0, 0.0);
+const property_traits<EdgeWeights>::value_type
+ WeightInf(0, std::numeric_limits<uint16_t>::max(), 0.0);
-struct WeightCompare :
- public std::binary_function<property_traits< EdgeWeights >::reference,
- property_traits< EdgeWeights >::reference,
- bool>
-{
+struct WeightCompare : public std::binary_function<property_traits<EdgeWeights>::reference,
+ property_traits<EdgeWeights>::reference, bool> {
bool
- operator () (tuple< ns3::Ptr<ns3::ndn::Face>, uint32_t, double > a,
- tuple< ns3::Ptr<ns3::ndn::Face>, uint32_t, double > b) const
+ operator()(tuple<ns3::Ptr<ns3::ndn::Face>, uint32_t, double> a,
+ tuple<ns3::Ptr<ns3::ndn::Face>, uint32_t, double> b) const
{
- return a.get<1> () < b.get<1> ();
+ return a.get<1>() < b.get<1>();
}
bool
- operator () (property_traits< EdgeWeights >::reference a,
- uint32_t b) const
+ operator()(property_traits<EdgeWeights>::reference a, uint32_t b) const
{
- return a.get<1> () < b;
+ return a.get<1>() < b;
}
-
+
bool
- operator () (uint32_t a,
- uint32_t b) const
+ operator()(uint32_t a, uint32_t b) const
{
return a < b;
}
-
};
-struct WeightCombine :
- public std::binary_function<uint32_t,
- property_traits< EdgeWeights >::reference,
- uint32_t>
-{
+struct WeightCombine
+ : public std::binary_function<uint32_t, property_traits<EdgeWeights>::reference, uint32_t> {
uint32_t
- operator () (uint32_t a, property_traits< EdgeWeights >::reference b) const
+ operator()(uint32_t a, property_traits<EdgeWeights>::reference b) const
{
- return a + b.get<1> ();
+ return a + b.get<1>();
}
- tuple< ns3::Ptr<ns3::ndn::Face>, uint32_t, double >
- operator () (tuple< ns3::Ptr<ns3::ndn::Face>, uint32_t, double > a,
- property_traits< EdgeWeights >::reference b) const
+ tuple<ns3::Ptr<ns3::ndn::Face>, uint32_t, double>
+ operator()(tuple<ns3::Ptr<ns3::ndn::Face>, uint32_t, double> a,
+ property_traits<EdgeWeights>::reference b) const
{
- if (a.get<0> () == 0)
- return make_tuple (b.get<0> (), a.get<1> () + b.get<1> (), a.get<2> () + b.get<2> ());
+ if (a.get<0>() == 0)
+ return make_tuple(b.get<0>(), a.get<1>() + b.get<1>(), a.get<2>() + b.get<2>());
else
- return make_tuple (a.get<0> (), a.get<1> () + b.get<1> (), a.get<2> () + b.get<2> ());
+ return make_tuple(a.get<0>(), a.get<1>() + b.get<1>(), a.get<2>() + b.get<2>());
}
};
-
+
template<>
-struct property_traits< VertexIds >
-{
+struct property_traits<VertexIds> {
// Metric property map
typedef uint32_t value_type;
typedef uint32_t reference;
- typedef ns3::Ptr< ns3::ndn::GlobalRouter > key_type;
+ typedef ns3::Ptr<ns3::ndn::GlobalRouter> key_type;
typedef readable_property_map_tag category;
};
-
inline EdgeWeights
-get(edge_weight_t,
- const NdnGlobalRouterGraph &g)
+get(edge_weight_t, const NdnGlobalRouterGraph& g)
{
- return EdgeWeights (g);
+ return EdgeWeights(g);
}
-
inline VertexIds
-get(vertex_index_t,
- const NdnGlobalRouterGraph &g)
+get(vertex_index_t, const NdnGlobalRouterGraph& g)
{
- return VertexIds (g);
+ return VertexIds(g);
}
template<class M, class K, class V>
inline void
-put (reference_wrapper< M > mapp,
- K a, V p)
+put(reference_wrapper<M> mapp, K a, V p)
{
- mapp.get ()[a] = p;
+ mapp.get()[a] = p;
}
// void
// put (cref< std::map< ns3::Ptr<ns3::ndn::GlobalRouter>, ns3::Ptr<ns3::ndn::GlobalRouter> > > map,
inline uint32_t
-get (const boost::VertexIds&, ns3::Ptr<ns3::ndn::GlobalRouter> &gr)
+get(const boost::VertexIds&, ns3::Ptr<ns3::ndn::GlobalRouter>& gr)
{
- return gr->GetId ();
+ return gr->GetId();
}
-inline property_traits< EdgeWeights >::reference
-get(const boost::EdgeWeights&, ns3::ndn::GlobalRouter::Incidency &edge)
+inline property_traits<EdgeWeights>::reference
+get(const boost::EdgeWeights&, ns3::ndn::GlobalRouter::Incidency& edge)
{
- if (edge.get<1> () == 0)
- return property_traits< EdgeWeights >::reference (0, 0, 0.0);
- else
+ if (edge.get<1>() == 0)
+ return property_traits<EdgeWeights>::reference(0, 0, 0.0);
+ else {
+ ns3::Ptr<ns3::ndn::Limits> limits = edge.get<1>()->GetObject<ns3::ndn::Limits>();
+ double delay = 0.0;
+ if (limits != 0) // valid limits object
{
- ns3::Ptr<ns3::ndn::Limits> limits = edge.get<1> ()->GetObject<ns3::ndn::Limits> ();
- double delay = 0.0;
- if (limits != 0) // valid limits object
- {
- delay = limits->GetLinkDelay ();
- }
- return property_traits< EdgeWeights >::reference (edge.get<1> (), edge.get<1> ()->GetMetric (), delay);
+ delay = limits->GetLinkDelay();
}
+ return property_traits<EdgeWeights>::reference(edge.get<1>(), edge.get<1>()->GetMetric(),
+ delay);
+ }
}
-struct PredecessorsMap :
- public std::map< ns3::Ptr< ns3::ndn::GlobalRouter >, ns3::Ptr< ns3::ndn::GlobalRouter > >
-{
+struct PredecessorsMap
+ : public std::map<ns3::Ptr<ns3::ndn::GlobalRouter>, ns3::Ptr<ns3::ndn::GlobalRouter>> {
};
template<>
-struct property_traits< reference_wrapper<PredecessorsMap> >
-{
+struct property_traits<reference_wrapper<PredecessorsMap>> {
// Metric property map
- typedef ns3::Ptr< ns3::ndn::GlobalRouter > value_type;
- typedef ns3::Ptr< ns3::ndn::GlobalRouter > reference;
- typedef ns3::Ptr< ns3::ndn::GlobalRouter > key_type;
+ typedef ns3::Ptr<ns3::ndn::GlobalRouter> value_type;
+ typedef ns3::Ptr<ns3::ndn::GlobalRouter> reference;
+ typedef ns3::Ptr<ns3::ndn::GlobalRouter> key_type;
typedef read_write_property_map_tag category;
};
-
-struct DistancesMap :
- public std::map< ns3::Ptr< ns3::ndn::GlobalRouter >, tuple< ns3::Ptr<ns3::ndn::Face>, uint32_t, double > >
-{
+struct DistancesMap : public std::map<ns3::Ptr<ns3::ndn::GlobalRouter>,
+ tuple<ns3::Ptr<ns3::ndn::Face>, uint32_t, double>> {
};
template<>
-struct property_traits< reference_wrapper<DistancesMap> >
-{
+struct property_traits<reference_wrapper<DistancesMap>> {
// Metric property map
- typedef tuple< ns3::Ptr<ns3::ndn::Face>, uint32_t, double > value_type;
- typedef tuple< ns3::Ptr<ns3::ndn::Face>, uint32_t, double > reference;
- typedef ns3::Ptr< ns3::ndn::GlobalRouter > key_type;
+ typedef tuple<ns3::Ptr<ns3::ndn::Face>, uint32_t, double> value_type;
+ typedef tuple<ns3::Ptr<ns3::ndn::Face>, uint32_t, double> reference;
+ typedef ns3::Ptr<ns3::ndn::GlobalRouter> key_type;
typedef read_write_property_map_tag category;
};
-inline tuple< ns3::Ptr<ns3::ndn::Face>, uint32_t, double >
-get (DistancesMap &map, ns3::Ptr<ns3::ndn::GlobalRouter> key)
+inline tuple<ns3::Ptr<ns3::ndn::Face>, uint32_t, double>
+get(DistancesMap& map, ns3::Ptr<ns3::ndn::GlobalRouter> key)
{
- boost::DistancesMap::iterator i = map.find (key);
- if (i == map.end ())
- return tuple< ns3::Ptr<ns3::ndn::Face>, uint32_t, double > (0, std::numeric_limits<uint32_t>::max (), 0.0);
+ boost::DistancesMap::iterator i = map.find(key);
+ if (i == map.end())
+ return tuple<ns3::Ptr<ns3::ndn::Face>, uint32_t, double>(0,
+ std::numeric_limits<uint32_t>::max(),
+ 0.0);
else
return i->second;
}
diff --git a/helper/ndn-app-helper.cpp b/helper/ndn-app-helper.cpp
index b181f3b..f1f4381 100644
--- a/helper/ndn-app-helper.cpp
+++ b/helper/ndn-app-helper.cpp
@@ -28,75 +28,72 @@
#include "ns3/mpi-interface.h"
#endif
-NS_LOG_COMPONENT_DEFINE ("ndn.AppHelper");
+NS_LOG_COMPONENT_DEFINE("ndn.AppHelper");
namespace ns3 {
namespace ndn {
-AppHelper::AppHelper (const std::string &app)
+AppHelper::AppHelper(const std::string& app)
{
- m_factory.SetTypeId (app);
+ m_factory.SetTypeId(app);
}
void
-AppHelper::SetPrefix (const std::string &prefix)
+AppHelper::SetPrefix(const std::string& prefix)
{
- m_factory.Set ("Prefix", StringValue(prefix));
+ m_factory.Set("Prefix", StringValue(prefix));
}
-void
-AppHelper::SetAttribute (std::string name, const AttributeValue &value)
+void
+AppHelper::SetAttribute(std::string name, const AttributeValue& value)
{
- m_factory.Set (name, value);
+ m_factory.Set(name, value);
}
-
+
ApplicationContainer
-AppHelper::Install (Ptr<Node> node)
+AppHelper::Install(Ptr<Node> node)
{
ApplicationContainer apps;
- Ptr<Application> app = InstallPriv (node);
+ Ptr<Application> app = InstallPriv(node);
if (app != 0)
- apps.Add (app);
-
+ apps.Add(app);
+
return apps;
}
-
+
ApplicationContainer
-AppHelper::Install (std::string nodeName)
+AppHelper::Install(std::string nodeName)
{
- Ptr<Node> node = Names::Find<Node> (nodeName);
- return Install (node);
+ Ptr<Node> node = Names::Find<Node>(nodeName);
+ return Install(node);
}
-
+
ApplicationContainer
-AppHelper::Install (NodeContainer c)
+AppHelper::Install(NodeContainer c)
{
ApplicationContainer apps;
- for (NodeContainer::Iterator i = c.Begin (); i != c.End (); ++i)
- {
- Ptr<Application> app = InstallPriv (*i);
- if (app != 0)
- apps.Add (app);
- }
-
+ for (NodeContainer::Iterator i = c.Begin(); i != c.End(); ++i) {
+ Ptr<Application> app = InstallPriv(*i);
+ if (app != 0)
+ apps.Add(app);
+ }
+
return apps;
}
-
+
Ptr<Application>
-AppHelper::InstallPriv (Ptr<Node> node)
+AppHelper::InstallPriv(Ptr<Node> node)
{
#ifdef NS3_MPI
- if (MpiInterface::IsEnabled () &&
- node->GetSystemId () != MpiInterface::GetSystemId ())
- {
- // don't create an app if MPI is enabled and node is not in the correct partition
- return 0;
- }
+ if (MpiInterface::IsEnabled() && node->GetSystemId() != MpiInterface::GetSystemId()) {
+ // don't create an app if MPI is enabled and node is not in the correct partition
+ return 0;
+ }
#endif
-
- Ptr<Application> app = m_factory.Create<Application> ();
- node->AddApplication (app);
-
+
+ Ptr<Application> app = m_factory.Create<Application>();
+ node->AddApplication(app);
+
return app;
}
diff --git a/helper/ndn-app-helper.hpp b/helper/ndn-app-helper.hpp
index e559260..63fa705 100644
--- a/helper/ndn-app-helper.hpp
+++ b/helper/ndn-app-helper.hpp
@@ -35,69 +35,72 @@
* \brief A helper to make it easier to instantiate an ns3::NdnConsumer Application
* on a set of nodes.
*/
-class AppHelper
-{
+class AppHelper {
public:
-
/**
* \brief Create an NdnAppHelper to make it easier to work with Ndn apps
*
* \param app Class of the application
*/
- AppHelper (const std::string &prefix);
+ AppHelper(const std::string& prefix);
/**
* @brief Set the prefix consumer will be requesting
*/
void
- SetPrefix (const std::string &prefix);
-
+ SetPrefix(const std::string& prefix);
+
/**
* \brief Helper function used to set the underlying application attributes.
*
* \param name the name of the application attribute to set
* \param value the value of the application attribute to set
*/
- void SetAttribute (std::string name, const AttributeValue &value);
-
+ void
+ SetAttribute(std::string name, const AttributeValue& value);
+
/**
* Install an ns3::NdnConsumer on each node of the input container
* configured with all the attributes set with SetAttribute.
*
- * \param c NodeContainer of the set of nodes on which an NdnConsumer
+ * \param c NodeContainer of the set of nodes on which an NdnConsumer
* will be installed.
* \returns Container of Ptr to the applications installed.
*/
- ApplicationContainer Install (NodeContainer c);
-
+ ApplicationContainer
+ Install(NodeContainer c);
+
/**
- * Install an ns3::NdnConsumer on the node configured with all the
+ * Install an ns3::NdnConsumer on the node configured with all the
* attributes set with SetAttribute.
*
* \param node The node on which an NdnConsumer will be installed.
* \returns Container of Ptr to the applications installed.
*/
- ApplicationContainer Install (Ptr<Node> node);
-
+ ApplicationContainer
+ Install(Ptr<Node> node);
+
/**
- * Install an ns3::NdnConsumer on the node configured with all the
+ * Install an ns3::NdnConsumer on the node configured with all the
* attributes set with SetAttribute.
*
* \param nodeName The node on which an NdnConsumer will be installed.
* \returns Container of Ptr to the applications installed.
*/
- ApplicationContainer Install (std::string nodeName);
-
+ ApplicationContainer
+ Install(std::string nodeName);
+
private:
/**
* \internal
- * Install an ns3::NdnConsumer on the node configured with all the
+ * Install an ns3::NdnConsumer on the node configured with all the
* attributes set with SetAttribute.
*
* \param node The node on which an NdnConsumer will be installed.
* \returns Ptr to the application installed.
*/
- Ptr<Application> InstallPriv (Ptr<Node> node);
+ Ptr<Application>
+ InstallPriv(Ptr<Node> node);
ObjectFactory m_factory;
};
@@ -105,4 +108,3 @@
} // namespace ns3
#endif // NDN_APP_HELPER_H
-
diff --git a/helper/ndn-face-container.cpp b/helper/ndn-face-container.cpp
index 69e90c9..150eea3 100644
--- a/helper/ndn-face-container.cpp
+++ b/helper/ndn-face-container.cpp
@@ -27,57 +27,55 @@
namespace ns3 {
namespace ndn {
-FaceContainer::FaceContainer ()
+FaceContainer::FaceContainer()
{
}
-FaceContainer::FaceContainer (const FaceContainer &other)
+FaceContainer::FaceContainer(const FaceContainer& other)
{
- AddAll (other);
+ AddAll(other);
}
FaceContainer&
FaceContainer::operator= (const FaceContainer &other)
{
- m_faces.clear ();
- AddAll (other);
+ m_faces.clear();
+ AddAll(other);
return *this;
}
-
void
-FaceContainer::AddAll (Ptr<FaceContainer> other)
+FaceContainer::AddAll(Ptr<FaceContainer> other)
{
- AddAll (*other);
+ AddAll(*other);
}
void
-FaceContainer::AddAll (const FaceContainer &other)
+FaceContainer::AddAll(const FaceContainer& other)
{
- m_faces.insert (m_faces.end (),
- other.m_faces.begin (), other.m_faces.end ());
+ m_faces.insert(m_faces.end(), other.m_faces.begin(), other.m_faces.end());
}
FaceContainer::Iterator
-FaceContainer::Begin (void) const
+FaceContainer::Begin(void) const
{
- return m_faces.begin ();
+ return m_faces.begin();
}
FaceContainer::Iterator
-FaceContainer::End (void) const
+FaceContainer::End(void) const
{
- return m_faces.end ();
+ return m_faces.end();
}
uint32_t
-FaceContainer::GetN (void) const
+FaceContainer::GetN(void) const
{
- return m_faces.size ();
+ return m_faces.size();
}
-// void
+// void
// FaceContainer::SetMetricToAll (uint16_t metric)
// {
// for (FaceContainer::iterator it=m_faces.begin ();
@@ -88,14 +86,14 @@
// }
// }
-void
-FaceContainer::Add (const Ptr<Face> &face)
+void
+FaceContainer::Add(const Ptr<Face>& face)
{
- m_faces.push_back (face);
+ m_faces.push_back(face);
}
Ptr<Face>
-FaceContainer::Get (FaceContainer::Iterator i) const
+FaceContainer::Get(FaceContainer::Iterator i) const
{
return *i;
}
diff --git a/helper/ndn-face-container.hpp b/helper/ndn-face-container.hpp
index f430c96..776a5ec 100644
--- a/helper/ndn-face-container.hpp
+++ b/helper/ndn-face-container.hpp
@@ -34,30 +34,30 @@
/**
* @ingroup ndn-helpers
* \brief A pool for Ndn faces
- *
+ *
* Provides tools to perform basic manipulation on faces, such as
* setting metrics and states on faces
*
* \see NdnStackHelper
*/
-class FaceContainer : public SimpleRefCount<FaceContainer>
-{
+class FaceContainer : public SimpleRefCount<FaceContainer> {
private:
- typedef std::vector< Ptr<Face> > Container;
+ typedef std::vector<Ptr<Face>> Container;
+
public:
typedef Container::const_iterator Iterator; ///< \brief Iterator over FaceContainer
/**
* \brief Create an empty FaceContainer.
*/
- FaceContainer ();
+ FaceContainer();
/**
* \brief Copy constructor for FaceContainer. Calls AddAll method
*
* \see FaceContainer::AddAll
*/
- FaceContainer (const FaceContainer &other);
+ FaceContainer(const FaceContainer& other);
/**
* \brief Copy operator for FaceContainer. Empties vector and calls AddAll method
@@ -66,21 +66,24 @@
*
* \see FaceContainer::AddAll
*/
- FaceContainer& operator= (const FaceContainer &other);
-
+ FaceContainer&
+ operator=(const FaceContainer& other);
+
/**
* \brief Add all entries from other container
*
* \param other smart pointer to a container
*/
- void AddAll (Ptr<FaceContainer> other);
+ void
+ AddAll(Ptr<FaceContainer> other);
/**
* \brief Add all entries from other container
*
* \param other container
*/
- void AddAll (const FaceContainer &other);
+ void
+ AddAll(const FaceContainer& other);
/**
* \brief Get an iterator which refers to the first pair in the
@@ -88,22 +91,25 @@
*
* \returns an iterator which refers to the first pair in the container.
*/
- Iterator Begin () const;
+ Iterator
+ Begin() const;
/**
- * \brief Get an iterator which indicates past-the-last Node in the
+ * \brief Get an iterator which indicates past-the-last Node in the
* container.
*
* \returns an iterator which indicates an ending condition for a loop.
*/
- Iterator End () const;
+ Iterator
+ End() const;
/**
* \brief Get the number of faces stored in this container
*
* \returns the number of faces stored in this container
*/
- uint32_t GetN () const;
+ uint32_t
+ GetN() const;
// /**
// * \brief Set a metric for all faces in the container
@@ -119,7 +125,8 @@
*
* @see Face
*/
- void Add (const Ptr<Face> &face);
+ void
+ Add(const Ptr<Face>& face);
/**
* Get a smart pointer to Face-derived object stored in the container
@@ -130,7 +137,8 @@
*
* @see Face
*/
- Ptr<Face> Get (Iterator i) const;
+ Ptr<Face>
+ Get(Iterator i) const;
private:
Container m_faces;
diff --git a/helper/ndn-global-routing-helper.cpp b/helper/ndn-global-routing-helper.cpp
index ac462c0..0528be3 100644
--- a/helper/ndn-global-routing-helper.cpp
+++ b/helper/ndn-global-routing-helper.cpp
@@ -54,7 +54,7 @@
#include <math.h>
-NS_LOG_COMPONENT_DEFINE ("ndn.GlobalRoutingHelper");
+NS_LOG_COMPONENT_DEFINE("ndn.GlobalRoutingHelper");
using namespace std;
using namespace boost;
@@ -63,398 +63,352 @@
namespace ndn {
void
-GlobalRoutingHelper::Install (Ptr<Node> node)
+GlobalRoutingHelper::Install(Ptr<Node> node)
{
- NS_LOG_LOGIC ("Node: " << node->GetId ());
+ NS_LOG_LOGIC("Node: " << node->GetId());
- Ptr<L3Protocol> ndn = node->GetObject<L3Protocol> ();
- NS_ASSERT_MSG (ndn != 0, "Cannot install GlobalRoutingHelper before Ndn is installed on a node");
+ Ptr<L3Protocol> ndn = node->GetObject<L3Protocol>();
+ NS_ASSERT_MSG(ndn != 0, "Cannot install GlobalRoutingHelper before Ndn is installed on a node");
- Ptr<GlobalRouter> gr = node->GetObject<GlobalRouter> ();
- if (gr != 0)
- {
- NS_LOG_DEBUG ("GlobalRouter is already installed: " << gr);
- return; // already installed
+ Ptr<GlobalRouter> gr = node->GetObject<GlobalRouter>();
+ if (gr != 0) {
+ NS_LOG_DEBUG("GlobalRouter is already installed: " << gr);
+ return; // already installed
+ }
+
+ gr = CreateObject<GlobalRouter>();
+ node->AggregateObject(gr);
+
+ for (uint32_t faceId = 0; faceId < ndn->GetNFaces(); faceId++) {
+ Ptr<NetDeviceFace> face = DynamicCast<NetDeviceFace>(ndn->GetFace(faceId));
+ if (face == 0) {
+ NS_LOG_DEBUG("Skipping non-netdevice face");
+ continue;
}
- gr = CreateObject<GlobalRouter> ();
- node->AggregateObject (gr);
-
- for (uint32_t faceId = 0; faceId < ndn->GetNFaces (); faceId++)
- {
- Ptr<NetDeviceFace> face = DynamicCast<NetDeviceFace> (ndn->GetFace (faceId));
- if (face == 0)
- {
- NS_LOG_DEBUG ("Skipping non-netdevice face");
- continue;
- }
-
- Ptr<NetDevice> nd = face->GetNetDevice ();
- if (nd == 0)
- {
- NS_LOG_DEBUG ("Not a NetDevice associated with NetDeviceFace");
- continue;
- }
-
- Ptr<Channel> ch = nd->GetChannel ();
-
- if (ch == 0)
- {
- NS_LOG_DEBUG ("Channel is not associated with NetDevice");
- continue;
- }
-
- if (ch->GetNDevices () == 2) // e.g., point-to-point channel
- {
- for (uint32_t deviceId = 0; deviceId < ch->GetNDevices (); deviceId ++)
- {
- Ptr<NetDevice> otherSide = ch->GetDevice (deviceId);
- if (nd == otherSide) continue;
-
- Ptr<Node> otherNode = otherSide->GetNode ();
- NS_ASSERT (otherNode != 0);
-
- Ptr<GlobalRouter> otherGr = otherNode->GetObject<GlobalRouter> ();
- if (otherGr == 0)
- {
- Install (otherNode);
- }
- otherGr = otherNode->GetObject<GlobalRouter> ();
- NS_ASSERT (otherGr != 0);
- gr->AddIncidency (face, otherGr);
- }
- }
- else
- {
- Ptr<GlobalRouter> grChannel = ch->GetObject<GlobalRouter> ();
- if (grChannel == 0)
- {
- Install (ch);
- }
- grChannel = ch->GetObject<GlobalRouter> ();
-
- gr->AddIncidency (face, grChannel);
- }
+ Ptr<NetDevice> nd = face->GetNetDevice();
+ if (nd == 0) {
+ NS_LOG_DEBUG("Not a NetDevice associated with NetDeviceFace");
+ continue;
}
+
+ Ptr<Channel> ch = nd->GetChannel();
+
+ if (ch == 0) {
+ NS_LOG_DEBUG("Channel is not associated with NetDevice");
+ continue;
+ }
+
+ if (ch->GetNDevices() == 2) // e.g., point-to-point channel
+ {
+ for (uint32_t deviceId = 0; deviceId < ch->GetNDevices(); deviceId++) {
+ Ptr<NetDevice> otherSide = ch->GetDevice(deviceId);
+ if (nd == otherSide)
+ continue;
+
+ Ptr<Node> otherNode = otherSide->GetNode();
+ NS_ASSERT(otherNode != 0);
+
+ Ptr<GlobalRouter> otherGr = otherNode->GetObject<GlobalRouter>();
+ if (otherGr == 0) {
+ Install(otherNode);
+ }
+ otherGr = otherNode->GetObject<GlobalRouter>();
+ NS_ASSERT(otherGr != 0);
+ gr->AddIncidency(face, otherGr);
+ }
+ }
+ else {
+ Ptr<GlobalRouter> grChannel = ch->GetObject<GlobalRouter>();
+ if (grChannel == 0) {
+ Install(ch);
+ }
+ grChannel = ch->GetObject<GlobalRouter>();
+
+ gr->AddIncidency(face, grChannel);
+ }
+ }
}
void
-GlobalRoutingHelper::Install (Ptr<Channel> channel)
+GlobalRoutingHelper::Install(Ptr<Channel> channel)
{
- NS_LOG_LOGIC ("Channel: " << channel->GetId ());
+ NS_LOG_LOGIC("Channel: " << channel->GetId());
- Ptr<GlobalRouter> gr = channel->GetObject<GlobalRouter> ();
+ Ptr<GlobalRouter> gr = channel->GetObject<GlobalRouter>();
if (gr != 0)
return;
- gr = CreateObject<GlobalRouter> ();
- channel->AggregateObject (gr);
+ gr = CreateObject<GlobalRouter>();
+ channel->AggregateObject(gr);
- for (uint32_t deviceId = 0; deviceId < channel->GetNDevices (); deviceId ++)
- {
- Ptr<NetDevice> dev = channel->GetDevice (deviceId);
+ for (uint32_t deviceId = 0; deviceId < channel->GetNDevices(); deviceId++) {
+ Ptr<NetDevice> dev = channel->GetDevice(deviceId);
- Ptr<Node> node = dev->GetNode ();
- NS_ASSERT (node != 0);
+ Ptr<Node> node = dev->GetNode();
+ NS_ASSERT(node != 0);
- Ptr<GlobalRouter> grOther = node->GetObject<GlobalRouter> ();
- if (grOther == 0)
- {
- Install (node);
- }
- grOther = node->GetObject<GlobalRouter> ();
- NS_ASSERT (grOther != 0);
-
- gr->AddIncidency (0, grOther);
+ Ptr<GlobalRouter> grOther = node->GetObject<GlobalRouter>();
+ if (grOther == 0) {
+ Install(node);
}
+ grOther = node->GetObject<GlobalRouter>();
+ NS_ASSERT(grOther != 0);
+
+ gr->AddIncidency(0, grOther);
+ }
}
void
-GlobalRoutingHelper::Install (const NodeContainer &nodes)
+GlobalRoutingHelper::Install(const NodeContainer& nodes)
{
- for (NodeContainer::Iterator node = nodes.Begin ();
- node != nodes.End ();
- node ++)
- {
- Install (*node);
+ for (NodeContainer::Iterator node = nodes.Begin(); node != nodes.End(); node++) {
+ Install(*node);
+ }
+}
+
+void
+GlobalRoutingHelper::InstallAll()
+{
+ Install(NodeContainer::GetGlobal());
+}
+
+void
+GlobalRoutingHelper::AddOrigin(const std::string& prefix, Ptr<Node> node)
+{
+ Ptr<GlobalRouter> gr = node->GetObject<GlobalRouter>();
+ NS_ASSERT_MSG(gr != 0, "GlobalRouter is not installed on the node");
+
+ Ptr<Name> name = Create<Name>(boost::lexical_cast<Name>(prefix));
+ gr->AddLocalPrefix(name);
+}
+
+void
+GlobalRoutingHelper::AddOrigins(const std::string& prefix, const NodeContainer& nodes)
+{
+ for (NodeContainer::Iterator node = nodes.Begin(); node != nodes.End(); node++) {
+ AddOrigin(prefix, *node);
+ }
+}
+
+void
+GlobalRoutingHelper::AddOrigin(const std::string& prefix, const std::string& nodeName)
+{
+ Ptr<Node> node = Names::Find<Node>(nodeName);
+ NS_ASSERT_MSG(node != 0, nodeName << "is not a Node");
+
+ AddOrigin(prefix, node);
+}
+
+void
+GlobalRoutingHelper::AddOriginsForAll()
+{
+ for (NodeList::Iterator node = NodeList::Begin(); node != NodeList::End(); node++) {
+ Ptr<GlobalRouter> gr = (*node)->GetObject<GlobalRouter>();
+ string name = Names::FindName(*node);
+
+ if (gr != 0 && !name.empty()) {
+ AddOrigin("/" + name, *node);
}
+ }
}
void
-GlobalRoutingHelper::InstallAll ()
-{
- Install (NodeContainer::GetGlobal ());
-}
-
-
-void
-GlobalRoutingHelper::AddOrigin (const std::string &prefix, Ptr<Node> node)
-{
- Ptr<GlobalRouter> gr = node->GetObject<GlobalRouter> ();
- NS_ASSERT_MSG (gr != 0,
- "GlobalRouter is not installed on the node");
-
- Ptr<Name> name = Create<Name> (boost::lexical_cast<Name> (prefix));
- gr->AddLocalPrefix (name);
-}
-
-void
-GlobalRoutingHelper::AddOrigins (const std::string &prefix, const NodeContainer &nodes)
-{
- for (NodeContainer::Iterator node = nodes.Begin ();
- node != nodes.End ();
- node++)
- {
- AddOrigin (prefix, *node);
- }
-}
-
-void
-GlobalRoutingHelper::AddOrigin (const std::string &prefix, const std::string &nodeName)
-{
- Ptr<Node> node = Names::Find<Node> (nodeName);
- NS_ASSERT_MSG (node != 0, nodeName << "is not a Node");
-
- AddOrigin (prefix, node);
-}
-
-void
-GlobalRoutingHelper::AddOriginsForAll ()
-{
- for (NodeList::Iterator node = NodeList::Begin (); node != NodeList::End (); node ++)
- {
- Ptr<GlobalRouter> gr = (*node)->GetObject<GlobalRouter> ();
- string name = Names::FindName (*node);
-
- if (gr != 0 && !name.empty ())
- {
- AddOrigin ("/"+name, *node);
- }
- }
-}
-
-void
-GlobalRoutingHelper::CalculateRoutes (bool invalidatedRoutes/* = true*/)
+GlobalRoutingHelper::CalculateRoutes(bool invalidatedRoutes /* = true*/)
{
/**
* Implementation of route calculation is heavily based on Boost Graph Library
* See http://www.boost.org/doc/libs/1_49_0/libs/graph/doc/table_of_contents.html for more details
*/
- BOOST_CONCEPT_ASSERT(( VertexListGraphConcept< NdnGlobalRouterGraph > ));
- BOOST_CONCEPT_ASSERT(( IncidenceGraphConcept< NdnGlobalRouterGraph > ));
+ BOOST_CONCEPT_ASSERT((VertexListGraphConcept<NdnGlobalRouterGraph>));
+ BOOST_CONCEPT_ASSERT((IncidenceGraphConcept<NdnGlobalRouterGraph>));
NdnGlobalRouterGraph graph;
// typedef graph_traits < NdnGlobalRouterGraph >::vertex_descriptor vertex_descriptor;
// For now we doing Dijkstra for every node. Can be replaced with Bellman-Ford or Floyd-Warshall.
- // Other algorithms should be faster, but they need additional EdgeListGraph concept provided by the graph, which
+ // Other algorithms should be faster, but they need additional EdgeListGraph concept provided by
+ // the graph, which
// is not obviously how implement in an efficient manner
- for (NodeList::Iterator node = NodeList::Begin (); node != NodeList::End (); node++)
- {
- Ptr<GlobalRouter> source = (*node)->GetObject<GlobalRouter> ();
- if (source == 0)
- {
- NS_LOG_DEBUG ("Node " << (*node)->GetId () << " does not export GlobalRouter interface");
- continue;
- }
+ for (NodeList::Iterator node = NodeList::Begin(); node != NodeList::End(); node++) {
+ Ptr<GlobalRouter> source = (*node)->GetObject<GlobalRouter>();
+ if (source == 0) {
+ NS_LOG_DEBUG("Node " << (*node)->GetId() << " does not export GlobalRouter interface");
+ continue;
+ }
- DistancesMap distances;
+ DistancesMap distances;
- dijkstra_shortest_paths (graph, source,
- // predecessor_map (boost::ref(predecessors))
- // .
- distance_map (boost::ref(distances))
- .
- distance_inf (WeightInf)
- .
- distance_zero (WeightZero)
- .
- distance_compare (boost::WeightCompare ())
- .
- distance_combine (boost::WeightCombine ())
- );
+ dijkstra_shortest_paths(graph, source,
+ // predecessor_map (boost::ref(predecessors))
+ // .
+ distance_map(boost::ref(distances))
+ .distance_inf(WeightInf)
+ .distance_zero(WeightZero)
+ .distance_compare(boost::WeightCompare())
+ .distance_combine(boost::WeightCombine()));
+
+ // NS_LOG_DEBUG (predecessors.size () << ", " << distances.size ());
+
+ Ptr<Fib> fib = source->GetObject<Fib>();
+ if (invalidatedRoutes) {
+ fib->InvalidateAll();
+ }
+ NS_ASSERT(fib != 0);
+
+ NS_LOG_DEBUG("Reachability from Node: " << source->GetObject<Node>()->GetId());
+ for (DistancesMap::iterator i = distances.begin(); i != distances.end(); i++) {
+ if (i->first == source)
+ continue;
+ else {
+ // cout << " Node " << i->first->GetObject<Node> ()->GetId ();
+ if (i->second.get<0>() == 0) {
+ // cout << " is unreachable" << endl;
+ }
+ else {
+ BOOST_FOREACH (const Ptr<const Name>& prefix, i->first->GetLocalPrefixes()) {
+ NS_LOG_DEBUG(" prefix " << prefix << " reachable via face " << *i->second.get<0>()
+ << " with distance " << i->second.get<1>() << " with delay "
+ << i->second.get<2>());
+
+ Ptr<fib::Entry> entry = fib->Add(prefix, i->second.get<0>(), i->second.get<1>());
+ entry->SetRealDelayToProducer(i->second.get<0>(), Seconds(i->second.get<2>()));
+
+ Ptr<Limits> faceLimits = i->second.get<0>()->GetObject<Limits>();
+
+ Ptr<Limits> fibLimits = entry->GetObject<Limits>();
+ if (fibLimits != 0) {
+ // if it was created by the forwarding strategy via DidAddFibEntry event
+ fibLimits->SetLimits(faceLimits->GetMaxRate(), 2 * i->second.get<2>() /*exact RTT*/);
+ NS_LOG_DEBUG("Set limit for prefix "
+ << *prefix << " " << faceLimits->GetMaxRate() << " / "
+ << 2 * i->second.get<2>() << "s ("
+ << faceLimits->GetMaxRate() * 2 * i->second.get<2>() << ")");
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+void
+GlobalRoutingHelper::CalculateAllPossibleRoutes(bool invalidatedRoutes /* = true*/)
+{
+ /**
+ * Implementation of route calculation is heavily based on Boost Graph Library
+ * See http://www.boost.org/doc/libs/1_49_0/libs/graph/doc/table_of_contents.html for more details
+ */
+
+ BOOST_CONCEPT_ASSERT((VertexListGraphConcept<NdnGlobalRouterGraph>));
+ BOOST_CONCEPT_ASSERT((IncidenceGraphConcept<NdnGlobalRouterGraph>));
+
+ NdnGlobalRouterGraph graph;
+ // typedef graph_traits < NdnGlobalRouterGraph >::vertex_descriptor vertex_descriptor;
+
+ // For now we doing Dijkstra for every node. Can be replaced with Bellman-Ford or Floyd-Warshall.
+ // Other algorithms should be faster, but they need additional EdgeListGraph concept provided by
+ // the graph, which
+ // is not obviously how implement in an efficient manner
+ for (NodeList::Iterator node = NodeList::Begin(); node != NodeList::End(); node++) {
+ Ptr<GlobalRouter> source = (*node)->GetObject<GlobalRouter>();
+ if (source == 0) {
+ NS_LOG_DEBUG("Node " << (*node)->GetId() << " does not export GlobalRouter interface");
+ continue;
+ }
+
+ Ptr<Fib> fib = source->GetObject<Fib>();
+ if (invalidatedRoutes) {
+ fib->InvalidateAll();
+ }
+ NS_ASSERT(fib != 0);
+
+ NS_LOG_DEBUG("===========");
+ NS_LOG_DEBUG("Reachability from Node: " << source->GetObject<Node>()->GetId() << " ("
+ << Names::FindName(source->GetObject<Node>()) << ")");
+
+ Ptr<L3Protocol> l3 = source->GetObject<L3Protocol>();
+ NS_ASSERT(l3 != 0);
+
+ // remember interface statuses
+ std::vector<uint16_t> originalMetric(l3->GetNFaces());
+ for (uint32_t faceId = 0; faceId < l3->GetNFaces(); faceId++) {
+ originalMetric[faceId] = l3->GetFace(faceId)->GetMetric();
+ l3->GetFace(faceId)
+ ->SetMetric(std::numeric_limits<uint16_t>::max()
+ - 1); // value std::numeric_limits<uint16_t>::max () MUST NOT be used (reserved)
+ }
+
+ for (uint32_t enabledFaceId = 0; enabledFaceId < l3->GetNFaces(); enabledFaceId++) {
+ if (DynamicCast<ndn::NetDeviceFace>(l3->GetFace(enabledFaceId)) == 0)
+ continue;
+
+ // enabling only faceId
+ l3->GetFace(enabledFaceId)->SetMetric(originalMetric[enabledFaceId]);
+
+ DistancesMap distances;
+
+ NS_LOG_DEBUG("-----------");
+
+ dijkstra_shortest_paths(graph, source,
+ // predecessor_map (boost::ref(predecessors))
+ // .
+ distance_map(boost::ref(distances))
+ .distance_inf(WeightInf)
+ .distance_zero(WeightZero)
+ .distance_compare(boost::WeightCompare())
+ .distance_combine(boost::WeightCombine()));
// NS_LOG_DEBUG (predecessors.size () << ", " << distances.size ());
- Ptr<Fib> fib = source->GetObject<Fib> ();
- if (invalidatedRoutes)
- {
- fib->InvalidateAll ();
- }
- NS_ASSERT (fib != 0);
+ for (DistancesMap::iterator i = distances.begin(); i != distances.end(); i++) {
+ if (i->first == source)
+ continue;
+ else {
+ // cout << " Node " << i->first->GetObject<Node> ()->GetId ();
+ if (i->second.get<0>() == 0) {
+ // cout << " is unreachable" << endl;
+ }
+ else {
+ BOOST_FOREACH (const Ptr<const Name>& prefix, i->first->GetLocalPrefixes()) {
+ NS_LOG_DEBUG(" prefix " << *prefix << " reachable via face " << *i->second.get<0>()
+ << " with distance " << i->second.get<1>() << " with delay "
+ << i->second.get<2>());
- NS_LOG_DEBUG ("Reachability from Node: " << source->GetObject<Node> ()->GetId ());
- for (DistancesMap::iterator i = distances.begin ();
- i != distances.end ();
- i++)
- {
- if (i->first == source)
- continue;
- else
- {
- // cout << " Node " << i->first->GetObject<Node> ()->GetId ();
- if (i->second.get<0> () == 0)
- {
- // cout << " is unreachable" << endl;
- }
- else
- {
- BOOST_FOREACH (const Ptr<const Name> &prefix, i->first->GetLocalPrefixes ())
- {
- NS_LOG_DEBUG (" prefix " << prefix << " reachable via face " << *i->second.get<0> ()
- << " with distance " << i->second.get<1> ()
- << " with delay " << i->second.get<2> ());
-
- Ptr<fib::Entry> entry = fib->Add (prefix, i->second.get<0> (), i->second.get<1> ());
- entry->SetRealDelayToProducer (i->second.get<0> (), Seconds (i->second.get<2> ()));
-
- Ptr<Limits> faceLimits = i->second.get<0> ()->GetObject<Limits> ();
-
- Ptr<Limits> fibLimits = entry->GetObject<Limits> ();
- if (fibLimits != 0)
- {
- // if it was created by the forwarding strategy via DidAddFibEntry event
- fibLimits->SetLimits (faceLimits->GetMaxRate (), 2 * i->second.get<2> () /*exact RTT*/);
- NS_LOG_DEBUG ("Set limit for prefix " << *prefix << " " << faceLimits->GetMaxRate () << " / " <<
- 2*i->second.get<2> () << "s (" << faceLimits->GetMaxRate () * 2 * i->second.get<2> () << ")");
- }
- }
- }
- }
- }
- }
-}
-
-void
-GlobalRoutingHelper::CalculateAllPossibleRoutes (bool invalidatedRoutes/* = true*/)
-{
- /**
- * Implementation of route calculation is heavily based on Boost Graph Library
- * See http://www.boost.org/doc/libs/1_49_0/libs/graph/doc/table_of_contents.html for more details
- */
-
- BOOST_CONCEPT_ASSERT(( VertexListGraphConcept< NdnGlobalRouterGraph > ));
- BOOST_CONCEPT_ASSERT(( IncidenceGraphConcept< NdnGlobalRouterGraph > ));
-
- NdnGlobalRouterGraph graph;
- // typedef graph_traits < NdnGlobalRouterGraph >::vertex_descriptor vertex_descriptor;
-
- // For now we doing Dijkstra for every node. Can be replaced with Bellman-Ford or Floyd-Warshall.
- // Other algorithms should be faster, but they need additional EdgeListGraph concept provided by the graph, which
- // is not obviously how implement in an efficient manner
- for (NodeList::Iterator node = NodeList::Begin (); node != NodeList::End (); node++)
- {
- Ptr<GlobalRouter> source = (*node)->GetObject<GlobalRouter> ();
- if (source == 0)
- {
- NS_LOG_DEBUG ("Node " << (*node)->GetId () << " does not export GlobalRouter interface");
- continue;
- }
-
- Ptr<Fib> fib = source->GetObject<Fib> ();
- if (invalidatedRoutes)
- {
- fib->InvalidateAll ();
- }
- NS_ASSERT (fib != 0);
-
- NS_LOG_DEBUG ("===========");
- NS_LOG_DEBUG ("Reachability from Node: " << source->GetObject<Node> ()->GetId () << " (" << Names::FindName (source->GetObject<Node> ()) << ")");
-
- Ptr<L3Protocol> l3 = source->GetObject<L3Protocol> ();
- NS_ASSERT (l3 != 0);
-
- // remember interface statuses
- std::vector<uint16_t> originalMetric (l3->GetNFaces ());
- for (uint32_t faceId = 0; faceId < l3->GetNFaces (); faceId++)
- {
- originalMetric[faceId] = l3->GetFace (faceId)->GetMetric ();
- l3->GetFace (faceId)->SetMetric (std::numeric_limits<uint16_t>::max ()-1); // value std::numeric_limits<uint16_t>::max () MUST NOT be used (reserved)
- }
-
- for (uint32_t enabledFaceId = 0; enabledFaceId < l3->GetNFaces (); enabledFaceId++)
- {
- if (DynamicCast<ndn::NetDeviceFace> (l3->GetFace (enabledFaceId)) == 0)
- continue;
-
- // enabling only faceId
- l3->GetFace (enabledFaceId)->SetMetric (originalMetric[enabledFaceId]);
-
- DistancesMap distances;
-
- NS_LOG_DEBUG ("-----------");
-
- dijkstra_shortest_paths (graph, source,
- // predecessor_map (boost::ref(predecessors))
- // .
- distance_map (boost::ref(distances))
- .
- distance_inf (WeightInf)
- .
- distance_zero (WeightZero)
- .
- distance_compare (boost::WeightCompare ())
- .
- distance_combine (boost::WeightCombine ())
- );
-
- // NS_LOG_DEBUG (predecessors.size () << ", " << distances.size ());
-
- for (DistancesMap::iterator i = distances.begin ();
- i != distances.end ();
- i++)
- {
- if (i->first == source)
+ if (i->second.get<0>()->GetMetric() == std::numeric_limits<uint16_t>::max() - 1)
continue;
- else
- {
- // cout << " Node " << i->first->GetObject<Node> ()->GetId ();
- if (i->second.get<0> () == 0)
- {
- // cout << " is unreachable" << endl;
- }
- else
- {
- BOOST_FOREACH (const Ptr<const Name> &prefix, i->first->GetLocalPrefixes ())
- {
- NS_LOG_DEBUG (" prefix " << *prefix << " reachable via face " << *i->second.get<0> ()
- << " with distance " << i->second.get<1> ()
- << " with delay " << i->second.get<2> ());
- if (i->second.get<0> ()->GetMetric () == std::numeric_limits<uint16_t>::max ()-1)
- continue;
+ Ptr<fib::Entry> entry = fib->Add(prefix, i->second.get<0>(), i->second.get<1>());
+ entry->SetRealDelayToProducer(i->second.get<0>(), Seconds(i->second.get<2>()));
- Ptr<fib::Entry> entry = fib->Add (prefix, i->second.get<0> (), i->second.get<1> ());
- entry->SetRealDelayToProducer (i->second.get<0> (), Seconds (i->second.get<2> ()));
+ Ptr<Limits> faceLimits = i->second.get<0>()->GetObject<Limits>();
- Ptr<Limits> faceLimits = i->second.get<0> ()->GetObject<Limits> ();
-
- Ptr<Limits> fibLimits = entry->GetObject<Limits> ();
- if (fibLimits != 0)
- {
- // if it was created by the forwarding strategy via DidAddFibEntry event
- fibLimits->SetLimits (faceLimits->GetMaxRate (), 2 * i->second.get<2> () /*exact RTT*/);
- NS_LOG_DEBUG ("Set limit for prefix " << *prefix << " " << faceLimits->GetMaxRate () << " / " <<
- 2*i->second.get<2> () << "s (" << faceLimits->GetMaxRate () * 2 * i->second.get<2> () << ")");
- }
- }
- }
- }
+ Ptr<Limits> fibLimits = entry->GetObject<Limits>();
+ if (fibLimits != 0) {
+ // if it was created by the forwarding strategy via DidAddFibEntry event
+ fibLimits->SetLimits(faceLimits->GetMaxRate(),
+ 2 * i->second.get<2>() /*exact RTT*/);
+ NS_LOG_DEBUG("Set limit for prefix "
+ << *prefix << " " << faceLimits->GetMaxRate() << " / "
+ << 2 * i->second.get<2>() << "s ("
+ << faceLimits->GetMaxRate() * 2 * i->second.get<2>() << ")");
+ }
}
-
- // disabling the face again
- l3->GetFace (enabledFaceId)->SetMetric (std::numeric_limits<uint16_t>::max ()-1);
+ }
}
+ }
- // recover original interface statuses
- for (uint32_t faceId = 0; faceId < l3->GetNFaces (); faceId++)
- {
- l3->GetFace (faceId)->SetMetric (originalMetric[faceId]);
- }
+ // disabling the face again
+ l3->GetFace(enabledFaceId)->SetMetric(std::numeric_limits<uint16_t>::max() - 1);
}
-}
+ // recover original interface statuses
+ for (uint32_t faceId = 0; faceId < l3->GetNFaces(); faceId++) {
+ l3->GetFace(faceId)->SetMetric(originalMetric[faceId]);
+ }
+ }
+}
} // namespace ndn
} // namespace ns3
diff --git a/helper/ndn-global-routing-helper.hpp b/helper/ndn-global-routing-helper.hpp
index fa7dabd..a765ebf 100644
--- a/helper/ndn-global-routing-helper.hpp
+++ b/helper/ndn-global-routing-helper.hpp
@@ -35,8 +35,7 @@
* @ingroup ndn-helpers
* @brief Helper for GlobalRouter interface
*/
-class GlobalRoutingHelper
-{
+class GlobalRoutingHelper {
public:
/**
* @brief Install GlobalRouter interface on a node
@@ -46,8 +45,7 @@
* @param node Node to install GlobalRouter interface
*/
void
- Install (Ptr<Node> node);
-
+ Install(Ptr<Node> node);
/**
* @brief Install GlobalRouter interface on nodes
@@ -57,13 +55,13 @@
* @param nodes NodeContainer to install GlobalRouter interface
*/
void
- Install (const NodeContainer &nodes);
+ Install(const NodeContainer& nodes);
/**
* @brief Install GlobalRouter interface on all nodes
*/
void
- InstallAll ();
+ InstallAll();
/**
* @brief Add `prefix' as origin on `node'
@@ -71,7 +69,7 @@
* @param node Pointer to a node
*/
void
- AddOrigin (const std::string &prefix, Ptr<Node> node);
+ AddOrigin(const std::string& prefix, Ptr<Node> node);
/**
* @brief Add `prefix' as origin on all `nodes'
@@ -79,7 +77,7 @@
* @param nodes NodeContainer
*/
void
- AddOrigins (const std::string &prefix, const NodeContainer &nodes);
+ AddOrigins(const std::string& prefix, const NodeContainer& nodes);
/**
* @brief Add `prefix' as origin on node `nodeName'
@@ -87,37 +85,40 @@
* @param nodeName Name of the node that is associated with Ptr<Node> using ns3::Names
*/
void
- AddOrigin (const std::string &prefix, const std::string &nodeName);
+ AddOrigin(const std::string& prefix, const std::string& nodeName);
/**
* @brief Add origin to each node based on the node's name (using Names class)
*/
void
- AddOriginsForAll ();
+ AddOriginsForAll();
/**
* @brief Calculate for every node shortest path trees and install routes to all prefix origins
*
- * @param invalidatedRoutes flag indicating whether existing routes should be invalidated or keps as is
+ * @param invalidatedRoutes flag indicating whether existing routes should be invalidated or keps
+ *as is
*/
static void
- CalculateRoutes (bool invalidatedRoutes = true);
+ CalculateRoutes(bool invalidatedRoutes = true);
/**
* @brief Calculate all possible next-hop independent alternative routes
*
- * @param invalidatedRoutes flag indicating whether existing routes should be invalidated or keps as is
+ * @param invalidatedRoutes flag indicating whether existing routes should be invalidated or keps
+ *as is
*
* Refer to the implementation for more details.
*
- * Note that this method is highly experimental and should be used with caution (very time consuming).
+ * Note that this method is highly experimental and should be used with caution (very time
+ *consuming).
*/
static void
- CalculateAllPossibleRoutes (bool invalidatedRoutes = true);
+ CalculateAllPossibleRoutes(bool invalidatedRoutes = true);
private:
void
- Install (Ptr<Channel> channel);
+ Install(Ptr<Channel> channel);
};
} // namespace ndn
diff --git a/helper/ndn-link-control-helper.cpp b/helper/ndn-link-control-helper.cpp
index 1c43666..524ba46 100644
--- a/helper/ndn-link-control-helper.cpp
+++ b/helper/ndn-link-control-helper.cpp
@@ -31,109 +31,110 @@
#include "ns3/ndn-l3-protocol.hpp"
#include "ns3/ndn-net-device-face.hpp"
-NS_LOG_COMPONENT_DEFINE ("ndn.LinkControlHelper");
+NS_LOG_COMPONENT_DEFINE("ndn.LinkControlHelper");
namespace ns3 {
namespace ndn {
void
-LinkControlHelper::FailLink (Ptr<Node> node1, Ptr<Node> node2)
+LinkControlHelper::FailLink(Ptr<Node> node1, Ptr<Node> node2)
{
- NS_LOG_FUNCTION (node1 << node2);
-
- NS_ASSERT (node1 != 0);
- NS_ASSERT (node2 != 0);
-
- Ptr<ndn::L3Protocol> ndn1 = node1->GetObject<ndn::L3Protocol> ();
- Ptr<ndn::L3Protocol> ndn2 = node2->GetObject<ndn::L3Protocol> ();
+ NS_LOG_FUNCTION(node1 << node2);
- NS_ASSERT (ndn1 != 0);
- NS_ASSERT (ndn2 != 0);
+ NS_ASSERT(node1 != 0);
+ NS_ASSERT(node2 != 0);
+
+ Ptr<ndn::L3Protocol> ndn1 = node1->GetObject<ndn::L3Protocol>();
+ Ptr<ndn::L3Protocol> ndn2 = node2->GetObject<ndn::L3Protocol>();
+
+ NS_ASSERT(ndn1 != 0);
+ NS_ASSERT(ndn2 != 0);
// iterate over all faces to find the right one
- for (uint32_t faceId = 0; faceId < ndn1->GetNFaces (); faceId++)
- {
- Ptr<ndn::NetDeviceFace> ndFace = ndn1->GetFace (faceId)->GetObject<ndn::NetDeviceFace> ();
- if (ndFace == 0) continue;
+ for (uint32_t faceId = 0; faceId < ndn1->GetNFaces(); faceId++) {
+ Ptr<ndn::NetDeviceFace> ndFace = ndn1->GetFace(faceId)->GetObject<ndn::NetDeviceFace>();
+ if (ndFace == 0)
+ continue;
- Ptr<PointToPointNetDevice> nd1 = ndFace->GetNetDevice ()->GetObject<PointToPointNetDevice> ();
- if (nd1 == 0) continue;
+ Ptr<PointToPointNetDevice> nd1 = ndFace->GetNetDevice()->GetObject<PointToPointNetDevice>();
+ if (nd1 == 0)
+ continue;
- Ptr<Channel> channel = nd1->GetChannel ();
- if (channel == 0) continue;
+ Ptr<Channel> channel = nd1->GetChannel();
+ if (channel == 0)
+ continue;
- Ptr<PointToPointChannel> ppChannel = DynamicCast<PointToPointChannel> (channel);
+ Ptr<PointToPointChannel> ppChannel = DynamicCast<PointToPointChannel>(channel);
- Ptr<NetDevice> nd2 = ppChannel->GetDevice (0);
- if (nd2->GetNode () == node1)
- nd2 = ppChannel->GetDevice (1);
+ Ptr<NetDevice> nd2 = ppChannel->GetDevice(0);
+ if (nd2->GetNode() == node1)
+ nd2 = ppChannel->GetDevice(1);
- if (nd2->GetNode () == node2)
- {
- Ptr<ndn::Face> face1 = ndn1->GetFaceByNetDevice (nd1);
- Ptr<ndn::Face> face2 = ndn2->GetFaceByNetDevice (nd2);
+ if (nd2->GetNode() == node2) {
+ Ptr<ndn::Face> face1 = ndn1->GetFaceByNetDevice(nd1);
+ Ptr<ndn::Face> face2 = ndn2->GetFaceByNetDevice(nd2);
- face1->SetUp (false);
- face2->SetUp (false);
- break;
- }
+ face1->SetUp(false);
+ face2->SetUp(false);
+ break;
}
+ }
}
void
-LinkControlHelper::FailLinkByName (const std::string &node1, const std::string &node2)
+LinkControlHelper::FailLinkByName(const std::string& node1, const std::string& node2)
{
- FailLink (Names::Find<Node> (node1), Names::Find<Node> (node2));
+ FailLink(Names::Find<Node>(node1), Names::Find<Node>(node2));
}
void
-LinkControlHelper::UpLink (Ptr<Node> node1, Ptr<Node> node2)
+LinkControlHelper::UpLink(Ptr<Node> node1, Ptr<Node> node2)
{
- NS_LOG_FUNCTION (node1 << node2);
+ NS_LOG_FUNCTION(node1 << node2);
- NS_ASSERT (node1 != 0);
- NS_ASSERT (node2 != 0);
-
- Ptr<ndn::L3Protocol> ndn1 = node1->GetObject<ndn::L3Protocol> ();
- Ptr<ndn::L3Protocol> ndn2 = node2->GetObject<ndn::L3Protocol> ();
+ NS_ASSERT(node1 != 0);
+ NS_ASSERT(node2 != 0);
- NS_ASSERT (ndn1 != 0);
- NS_ASSERT (ndn2 != 0);
+ Ptr<ndn::L3Protocol> ndn1 = node1->GetObject<ndn::L3Protocol>();
+ Ptr<ndn::L3Protocol> ndn2 = node2->GetObject<ndn::L3Protocol>();
+
+ NS_ASSERT(ndn1 != 0);
+ NS_ASSERT(ndn2 != 0);
// iterate over all faces to find the right one
- for (uint32_t faceId = 0; faceId < ndn1->GetNFaces (); faceId++)
- {
- Ptr<ndn::NetDeviceFace> ndFace = ndn1->GetFace (faceId)->GetObject<ndn::NetDeviceFace> ();
- if (ndFace == 0) continue;
+ for (uint32_t faceId = 0; faceId < ndn1->GetNFaces(); faceId++) {
+ Ptr<ndn::NetDeviceFace> ndFace = ndn1->GetFace(faceId)->GetObject<ndn::NetDeviceFace>();
+ if (ndFace == 0)
+ continue;
- Ptr<PointToPointNetDevice> nd1 = ndFace->GetNetDevice ()->GetObject<PointToPointNetDevice> ();
- if (nd1 == 0) continue;
+ Ptr<PointToPointNetDevice> nd1 = ndFace->GetNetDevice()->GetObject<PointToPointNetDevice>();
+ if (nd1 == 0)
+ continue;
- Ptr<Channel> channel = nd1->GetChannel ();
- if (channel == 0) continue;
+ Ptr<Channel> channel = nd1->GetChannel();
+ if (channel == 0)
+ continue;
- Ptr<PointToPointChannel> ppChannel = DynamicCast<PointToPointChannel> (channel);
+ Ptr<PointToPointChannel> ppChannel = DynamicCast<PointToPointChannel>(channel);
- Ptr<NetDevice> nd2 = ppChannel->GetDevice (0);
- if (nd2->GetNode () == node1)
- nd2 = ppChannel->GetDevice (1);
+ Ptr<NetDevice> nd2 = ppChannel->GetDevice(0);
+ if (nd2->GetNode() == node1)
+ nd2 = ppChannel->GetDevice(1);
- if (nd2->GetNode () == node2)
- {
- Ptr<ndn::Face> face1 = ndn1->GetFaceByNetDevice (nd1);
- Ptr<ndn::Face> face2 = ndn2->GetFaceByNetDevice (nd2);
+ if (nd2->GetNode() == node2) {
+ Ptr<ndn::Face> face1 = ndn1->GetFaceByNetDevice(nd1);
+ Ptr<ndn::Face> face2 = ndn2->GetFaceByNetDevice(nd2);
- face1->SetUp (true);
- face2->SetUp (true);
- break;
- }
+ face1->SetUp(true);
+ face2->SetUp(true);
+ break;
}
+ }
}
void
-LinkControlHelper::UpLinkByName (const std::string &node1, const std::string &node2)
+LinkControlHelper::UpLinkByName(const std::string& node1, const std::string& node2)
{
- UpLink (Names::Find<Node> (node1), Names::Find<Node> (node2));
+ UpLink(Names::Find<Node>(node1), Names::Find<Node>(node2));
}
-
}
}
diff --git a/helper/ndn-link-control-helper.hpp b/helper/ndn-link-control-helper.hpp
index 1fb3251..6411a39 100644
--- a/helper/ndn-link-control-helper.hpp
+++ b/helper/ndn-link-control-helper.hpp
@@ -30,10 +30,10 @@
/**
* @ingroup ndn-helpers
- * @brief Helper class to control the up or down statuss of an NDN link connecting two specific nodes
+ * @brief Helper class to control the up or down statuss of an NDN link connecting two specific
+ * nodes
*/
-class LinkControlHelper
-{
+class LinkControlHelper {
public:
/**
* @brief Fail NDN link between two nodes
@@ -47,7 +47,7 @@
* @param node2 another node
*/
static void
- FailLink (Ptr<Node> node1, Ptr<Node> node2);
+ FailLink(Ptr<Node> node1, Ptr<Node> node2);
/**
* @brief Fail NDN link between two nodes
@@ -63,7 +63,7 @@
* @param node2 another node's name
*/
static void
- FailLinkByName (const std::string &node1, const std::string &node2);
+ FailLinkByName(const std::string& node1, const std::string& node2);
/**
* @brief Re-enable NDN link between two nodes
@@ -77,8 +77,8 @@
* @param node2 another node
*/
static void
- UpLink (Ptr<Node> node1, Ptr<Node> node2);
-
+ UpLink(Ptr<Node> node1, Ptr<Node> node2);
+
/**
* @brief Re-enable NDN link between two nodes
*
@@ -93,10 +93,9 @@
* @param node2 another node's name
*/
static void
- UpLinkByName (const std::string &node1, const std::string &node2);
+ UpLinkByName(const std::string& node1, const std::string& node2);
}; // end: LinkControlHelper
-
} // ndn
} // ns3
diff --git a/helper/ndn-stack-helper.cpp b/helper/ndn-stack-helper.cpp
index fe736b3..d1c2577 100644
--- a/helper/ndn-stack-helper.cpp
+++ b/helper/ndn-stack-helper.cpp
@@ -58,131 +58,129 @@
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
-NS_LOG_COMPONENT_DEFINE ("ndn.StackHelper");
+NS_LOG_COMPONENT_DEFINE("ndn.StackHelper");
namespace ns3 {
namespace ndn {
-StackHelper::StackHelper ()
- : m_limitsEnabled (false)
- , m_needSetDefaultRoutes (false)
+StackHelper::StackHelper()
+ : m_limitsEnabled(false)
+ , m_needSetDefaultRoutes(false)
{
- m_ndnFactory. SetTypeId ("ns3::ndn::L3Protocol");
- m_strategyFactory. SetTypeId ("ns3::ndn::fw::Flooding");
- m_contentStoreFactory.SetTypeId ("ns3::ndn::cs::Lru");
- m_fibFactory. SetTypeId ("ns3::ndn::fib::Default");
- m_pitFactory. SetTypeId ("ns3::ndn::pit::Persistent");
+ m_ndnFactory.SetTypeId("ns3::ndn::L3Protocol");
+ m_strategyFactory.SetTypeId("ns3::ndn::fw::Flooding");
+ m_contentStoreFactory.SetTypeId("ns3::ndn::cs::Lru");
+ m_fibFactory.SetTypeId("ns3::ndn::fib::Default");
+ m_pitFactory.SetTypeId("ns3::ndn::pit::Persistent");
- m_netDeviceCallbacks.push_back (std::make_pair (PointToPointNetDevice::GetTypeId (), MakeCallback (&StackHelper::PointToPointNetDeviceCallback, this)));
+ m_netDeviceCallbacks.push_back(
+ std::make_pair(PointToPointNetDevice::GetTypeId(),
+ MakeCallback(&StackHelper::PointToPointNetDeviceCallback, this)));
// default callback will be fired if non of others callbacks fit or did the job
}
-StackHelper::~StackHelper ()
+StackHelper::~StackHelper()
{
}
void
-StackHelper::SetStackAttributes (const std::string &attr1, const std::string &value1,
- const std::string &attr2, const std::string &value2,
- const std::string &attr3, const std::string &value3,
- const std::string &attr4, const std::string &value4)
+StackHelper::SetStackAttributes(const std::string& attr1, const std::string& value1,
+ const std::string& attr2, const std::string& value2,
+ const std::string& attr3, const std::string& value3,
+ const std::string& attr4, const std::string& value4)
{
if (attr1 != "")
- m_ndnFactory.Set (attr1, StringValue (value1));
+ m_ndnFactory.Set(attr1, StringValue(value1));
if (attr2 != "")
- m_ndnFactory.Set (attr2, StringValue (value2));
+ m_ndnFactory.Set(attr2, StringValue(value2));
if (attr3 != "")
- m_ndnFactory.Set (attr3, StringValue (value3));
+ m_ndnFactory.Set(attr3, StringValue(value3));
if (attr4 != "")
- m_ndnFactory.Set (attr4, StringValue (value4));
+ m_ndnFactory.Set(attr4, StringValue(value4));
}
void
-StackHelper::SetForwardingStrategy (const std::string &strategy,
- const std::string &attr1, const std::string &value1,
- const std::string &attr2, const std::string &value2,
- const std::string &attr3, const std::string &value3,
- const std::string &attr4, const std::string &value4)
+StackHelper::SetForwardingStrategy(const std::string& strategy, const std::string& attr1,
+ const std::string& value1, const std::string& attr2,
+ const std::string& value2, const std::string& attr3,
+ const std::string& value3, const std::string& attr4,
+ const std::string& value4)
{
- m_strategyFactory.SetTypeId (strategy);
+ m_strategyFactory.SetTypeId(strategy);
if (attr1 != "")
- m_strategyFactory.Set (attr1, StringValue (value1));
+ m_strategyFactory.Set(attr1, StringValue(value1));
if (attr2 != "")
- m_strategyFactory.Set (attr2, StringValue (value2));
+ m_strategyFactory.Set(attr2, StringValue(value2));
if (attr3 != "")
- m_strategyFactory.Set (attr3, StringValue (value3));
+ m_strategyFactory.Set(attr3, StringValue(value3));
if (attr4 != "")
- m_strategyFactory.Set (attr4, StringValue (value4));
+ m_strategyFactory.Set(attr4, StringValue(value4));
}
void
-StackHelper::SetContentStore (const std::string &contentStore,
- const std::string &attr1, const std::string &value1,
- const std::string &attr2, const std::string &value2,
- const std::string &attr3, const std::string &value3,
- const std::string &attr4, const std::string &value4)
+StackHelper::SetContentStore(const std::string& contentStore, const std::string& attr1,
+ const std::string& value1, const std::string& attr2,
+ const std::string& value2, const std::string& attr3,
+ const std::string& value3, const std::string& attr4,
+ const std::string& value4)
{
- m_contentStoreFactory.SetTypeId (contentStore);
+ m_contentStoreFactory.SetTypeId(contentStore);
if (attr1 != "")
- m_contentStoreFactory.Set (attr1, StringValue (value1));
+ m_contentStoreFactory.Set(attr1, StringValue(value1));
if (attr2 != "")
- m_contentStoreFactory.Set (attr2, StringValue (value2));
+ m_contentStoreFactory.Set(attr2, StringValue(value2));
if (attr3 != "")
- m_contentStoreFactory.Set (attr3, StringValue (value3));
+ m_contentStoreFactory.Set(attr3, StringValue(value3));
if (attr4 != "")
- m_contentStoreFactory.Set (attr4, StringValue (value4));
+ m_contentStoreFactory.Set(attr4, StringValue(value4));
}
void
-StackHelper::SetPit (const std::string &pitClass,
- const std::string &attr1, const std::string &value1,
- const std::string &attr2, const std::string &value2,
- const std::string &attr3, const std::string &value3,
- const std::string &attr4, const std::string &value4)
+StackHelper::SetPit(const std::string& pitClass, const std::string& attr1,
+ const std::string& value1, const std::string& attr2, const std::string& value2,
+ const std::string& attr3, const std::string& value3, const std::string& attr4,
+ const std::string& value4)
{
- m_pitFactory.SetTypeId (pitClass);
+ m_pitFactory.SetTypeId(pitClass);
if (attr1 != "")
- m_pitFactory.Set (attr1, StringValue (value1));
+ m_pitFactory.Set(attr1, StringValue(value1));
if (attr2 != "")
- m_pitFactory.Set (attr2, StringValue (value2));
+ m_pitFactory.Set(attr2, StringValue(value2));
if (attr3 != "")
- m_pitFactory.Set (attr3, StringValue (value3));
+ m_pitFactory.Set(attr3, StringValue(value3));
if (attr4 != "")
- m_pitFactory.Set (attr4, StringValue (value4));
+ m_pitFactory.Set(attr4, StringValue(value4));
}
void
-StackHelper::SetFib (const std::string &fibClass,
- const std::string &attr1, const std::string &value1,
- const std::string &attr2, const std::string &value2,
- const std::string &attr3, const std::string &value3,
- const std::string &attr4, const std::string &value4)
+StackHelper::SetFib(const std::string& fibClass, const std::string& attr1,
+ const std::string& value1, const std::string& attr2, const std::string& value2,
+ const std::string& attr3, const std::string& value3, const std::string& attr4,
+ const std::string& value4)
{
- m_fibFactory.SetTypeId (fibClass);
+ m_fibFactory.SetTypeId(fibClass);
if (attr1 != "")
- m_fibFactory.Set (attr1, StringValue (value1));
+ m_fibFactory.Set(attr1, StringValue(value1));
if (attr2 != "")
- m_fibFactory.Set (attr2, StringValue (value2));
+ m_fibFactory.Set(attr2, StringValue(value2));
if (attr3 != "")
- m_fibFactory.Set (attr3, StringValue (value3));
+ m_fibFactory.Set(attr3, StringValue(value3));
if (attr4 != "")
- m_fibFactory.Set (attr4, StringValue (value4));
+ m_fibFactory.Set(attr4, StringValue(value4));
}
void
-StackHelper::SetDefaultRoutes (bool needSet)
+StackHelper::SetDefaultRoutes(bool needSet)
{
- NS_LOG_FUNCTION (this << needSet);
+ NS_LOG_FUNCTION(this << needSet);
m_needSetDefaultRoutes = needSet;
}
void
-StackHelper::EnableLimits (bool enable/* = true*/,
- Time avgRtt/*=Seconds(0.1)*/,
- uint32_t avgData/*=1100*/,
- uint32_t avgInterest/*=40*/)
+StackHelper::EnableLimits(bool enable /* = true*/, Time avgRtt /*=Seconds(0.1)*/,
+ uint32_t avgData /*=1100*/, uint32_t avgInterest /*=40*/)
{
- NS_LOG_INFO ("EnableLimits: " << enable);
+ NS_LOG_INFO("EnableLimits: " << enable);
m_limitsEnabled = enable;
m_avgRtt = avgRtt;
m_avgDataSize = avgData;
@@ -190,276 +188,277 @@
}
Ptr<FaceContainer>
-StackHelper::Install (const NodeContainer &c) const
+StackHelper::Install(const NodeContainer& c) const
{
- Ptr<FaceContainer> faces = Create<FaceContainer> ();
- for (NodeContainer::Iterator i = c.Begin (); i != c.End (); ++i)
- {
- faces->AddAll (Install (*i));
- }
+ Ptr<FaceContainer> faces = Create<FaceContainer>();
+ for (NodeContainer::Iterator i = c.Begin(); i != c.End(); ++i) {
+ faces->AddAll(Install(*i));
+ }
return faces;
}
Ptr<FaceContainer>
-StackHelper::InstallAll () const
+StackHelper::InstallAll() const
{
- return Install (NodeContainer::GetGlobal ());
+ return Install(NodeContainer::GetGlobal());
}
Ptr<FaceContainer>
-StackHelper::Install (Ptr<Node> node) const
+StackHelper::Install(Ptr<Node> node) const
{
- // NS_ASSERT_MSG (m_forwarding, "SetForwardingHelper() should be set prior calling Install() method");
- Ptr<FaceContainer> faces = Create<FaceContainer> ();
+ // NS_ASSERT_MSG (m_forwarding, "SetForwardingHelper() should be set prior calling Install()
+ // method");
+ Ptr<FaceContainer> faces = Create<FaceContainer>();
- if (node->GetObject<L3Protocol> () != 0)
- {
- NS_FATAL_ERROR ("StackHelper::Install (): Installing "
- "a NdnStack to a node with an existing Ndn object");
- return 0;
- }
+ if (node->GetObject<L3Protocol>() != 0) {
+ NS_FATAL_ERROR("StackHelper::Install (): Installing "
+ "a NdnStack to a node with an existing Ndn object");
+ return 0;
+ }
// Create L3Protocol
- Ptr<L3Protocol> ndn = m_ndnFactory.Create<L3Protocol> ();
+ Ptr<L3Protocol> ndn = m_ndnFactory.Create<L3Protocol>();
// Create and aggregate FIB
- Ptr<Fib> fib = m_fibFactory.Create<Fib> ();
- ndn->AggregateObject (fib);
+ Ptr<Fib> fib = m_fibFactory.Create<Fib>();
+ ndn->AggregateObject(fib);
// Create and aggregate PIT
- ndn->AggregateObject (m_pitFactory.Create<Pit> ());
+ ndn->AggregateObject(m_pitFactory.Create<Pit>());
// Create and aggregate forwarding strategy
- ndn->AggregateObject (m_strategyFactory.Create<ForwardingStrategy> ());
+ ndn->AggregateObject(m_strategyFactory.Create<ForwardingStrategy>());
// Create and aggregate content store
- ndn->AggregateObject (m_contentStoreFactory.Create<ContentStore> ());
+ ndn->AggregateObject(m_contentStoreFactory.Create<ContentStore>());
// Aggregate L3Protocol on node
- node->AggregateObject (ndn);
+ node->AggregateObject(ndn);
- for (uint32_t index=0; index < node->GetNDevices (); index++)
- {
- Ptr<NetDevice> device = node->GetDevice (index);
- // This check does not make sense: LoopbackNetDevice is installed only if IP stack is installed,
- // Normally, ndnSIM works without IP stack, so no reason to check
- // if (DynamicCast<LoopbackNetDevice> (device) != 0)
- // continue; // don't create face for a LoopbackNetDevice
+ for (uint32_t index = 0; index < node->GetNDevices(); index++) {
+ Ptr<NetDevice> device = node->GetDevice(index);
+ // This check does not make sense: LoopbackNetDevice is installed only if IP stack is installed,
+ // Normally, ndnSIM works without IP stack, so no reason to check
+ // if (DynamicCast<LoopbackNetDevice> (device) != 0)
+ // continue; // don't create face for a LoopbackNetDevice
- Ptr<NetDeviceFace> face;
+ Ptr<NetDeviceFace> face;
- for (std::list< std::pair<TypeId, NetDeviceFaceCreateCallback> >::const_iterator item = m_netDeviceCallbacks.begin ();
- item != m_netDeviceCallbacks.end ();
- item++)
- {
- if (device->GetInstanceTypeId () == item->first ||
- device->GetInstanceTypeId ().IsChildOf (item->first))
- {
- face = item->second (node, ndn, device);
- if (face != 0)
- break;
- }
- }
- if (face == 0)
- {
- face = DefaultNetDeviceCallback (node, ndn, device);
- }
-
- if (m_needSetDefaultRoutes)
- {
- // default route with lowest priority possible
- AddRoute (node, "/", StaticCast<Face> (face), std::numeric_limits<int32_t>::max ());
- }
-
- face->SetUp ();
- faces->Add (face);
+ for (std::list<std::pair<TypeId, NetDeviceFaceCreateCallback>>::const_iterator item =
+ m_netDeviceCallbacks.begin();
+ item != m_netDeviceCallbacks.end(); item++) {
+ if (device->GetInstanceTypeId() == item->first
+ || device->GetInstanceTypeId().IsChildOf(item->first)) {
+ face = item->second(node, ndn, device);
+ if (face != 0)
+ break;
+ }
}
+ if (face == 0) {
+ face = DefaultNetDeviceCallback(node, ndn, device);
+ }
+
+ if (m_needSetDefaultRoutes) {
+ // default route with lowest priority possible
+ AddRoute(node, "/", StaticCast<Face>(face), std::numeric_limits<int32_t>::max());
+ }
+
+ face->SetUp();
+ faces->Add(face);
+ }
return faces;
}
void
-StackHelper::AddNetDeviceFaceCreateCallback (TypeId netDeviceType, StackHelper::NetDeviceFaceCreateCallback callback)
+StackHelper::AddNetDeviceFaceCreateCallback(TypeId netDeviceType,
+ StackHelper::NetDeviceFaceCreateCallback callback)
{
- m_netDeviceCallbacks.push_back (std::make_pair (netDeviceType, callback));
+ m_netDeviceCallbacks.push_back(std::make_pair(netDeviceType, callback));
}
void
-StackHelper::UpdateNetDeviceFaceCreateCallback (TypeId netDeviceType, NetDeviceFaceCreateCallback callback)
+StackHelper::UpdateNetDeviceFaceCreateCallback(TypeId netDeviceType,
+ NetDeviceFaceCreateCallback callback)
{
- for (NetDeviceCallbackList::iterator i = m_netDeviceCallbacks.begin (); i != m_netDeviceCallbacks.end (); i++)
- {
- if (i->first == netDeviceType)
- {
- i->second = callback;
- return;
- }
+ for (NetDeviceCallbackList::iterator i = m_netDeviceCallbacks.begin();
+ i != m_netDeviceCallbacks.end(); i++) {
+ if (i->first == netDeviceType) {
+ i->second = callback;
+ return;
}
+ }
}
void
-StackHelper::RemoveNetDeviceFaceCreateCallback (TypeId netDeviceType, NetDeviceFaceCreateCallback callback)
+StackHelper::RemoveNetDeviceFaceCreateCallback(TypeId netDeviceType,
+ NetDeviceFaceCreateCallback callback)
{
- for (NetDeviceCallbackList::iterator i = m_netDeviceCallbacks.begin (); i != m_netDeviceCallbacks.end (); i++)
- {
- if (i->first == netDeviceType)
- {
- m_netDeviceCallbacks.erase (i);
- return;
- }
+ for (NetDeviceCallbackList::iterator i = m_netDeviceCallbacks.begin();
+ i != m_netDeviceCallbacks.end(); i++) {
+ if (i->first == netDeviceType) {
+ m_netDeviceCallbacks.erase(i);
+ return;
}
+ }
}
Ptr<NetDeviceFace>
-StackHelper::DefaultNetDeviceCallback (Ptr<Node> node, Ptr<L3Protocol> ndn, Ptr<NetDevice> netDevice) const
+StackHelper::DefaultNetDeviceCallback(Ptr<Node> node, Ptr<L3Protocol> ndn,
+ Ptr<NetDevice> netDevice) const
{
- NS_LOG_DEBUG ("Creating default NetDeviceFace on node " << node->GetId ());
+ NS_LOG_DEBUG("Creating default NetDeviceFace on node " << node->GetId());
- Ptr<NetDeviceFace> face = CreateObject<NetDeviceFace> (node, netDevice);
+ Ptr<NetDeviceFace> face = CreateObject<NetDeviceFace>(node, netDevice);
- ndn->AddFace (face);
- NS_LOG_LOGIC ("Node " << node->GetId () << ": added NetDeviceFace as face #" << *face);
+ ndn->AddFace(face);
+ NS_LOG_LOGIC("Node " << node->GetId() << ": added NetDeviceFace as face #" << *face);
return face;
}
Ptr<NetDeviceFace>
-StackHelper::PointToPointNetDeviceCallback (Ptr<Node> node, Ptr<L3Protocol> ndn, Ptr<NetDevice> device) const
+StackHelper::PointToPointNetDeviceCallback(Ptr<Node> node, Ptr<L3Protocol> ndn,
+ Ptr<NetDevice> device) const
{
- NS_LOG_DEBUG ("Creating point-to-point NetDeviceFace on node " << node->GetId ());
+ NS_LOG_DEBUG("Creating point-to-point NetDeviceFace on node " << node->GetId());
- Ptr<NetDeviceFace> face = CreateObject<NetDeviceFace> (node, device);
+ Ptr<NetDeviceFace> face = CreateObject<NetDeviceFace>(node, device);
- ndn->AddFace (face);
- NS_LOG_LOGIC ("Node " << node->GetId () << ": added NetDeviceFace as face #" << *face);
+ ndn->AddFace(face);
+ NS_LOG_LOGIC("Node " << node->GetId() << ": added NetDeviceFace as face #" << *face);
- if (m_limitsEnabled)
- {
- Ptr<Limits> limits = face->GetObject<Limits> ();
- if (limits == 0)
- {
- NS_FATAL_ERROR ("Limits are enabled, but the selected forwarding strategy does not support limits. Please revise your scenario");
- exit (1);
- }
-
- NS_LOG_INFO ("Limits are enabled");
- Ptr<PointToPointNetDevice> p2p = DynamicCast<PointToPointNetDevice> (device);
- if (p2p != 0)
- {
- // Setup bucket filtering
- // Assume that we know average data packet size, and this size is equal default size
- // Set maximum buckets (averaging over 1 second)
-
- DataRateValue dataRate; device->GetAttribute ("DataRate", dataRate);
- TimeValue linkDelay; device->GetChannel ()->GetAttribute ("Delay", linkDelay);
-
- NS_LOG_INFO("DataRate for this link is " << dataRate.Get());
-
- double maxInterestPackets = 1.0 * dataRate.Get ().GetBitRate () / 8.0 / (m_avgDataSize + m_avgInterestSize);
- // NS_LOG_INFO ("Max packets per second: " << maxInterestPackets);
- // NS_LOG_INFO ("Max burst: " << m_avgRtt.ToDouble (Time::S) * maxInterestPackets);
- NS_LOG_INFO ("MaxLimit: " << (int)(m_avgRtt.ToDouble (Time::S) * maxInterestPackets));
-
- // Set max to BDP
- limits->SetLimits (maxInterestPackets, m_avgRtt.ToDouble (Time::S));
- limits->SetLinkDelay (linkDelay.Get ().ToDouble (Time::S));
- }
+ if (m_limitsEnabled) {
+ Ptr<Limits> limits = face->GetObject<Limits>();
+ if (limits == 0) {
+ NS_FATAL_ERROR("Limits are enabled, but the selected forwarding strategy does not support "
+ "limits. Please revise your scenario");
+ exit(1);
}
+ NS_LOG_INFO("Limits are enabled");
+ Ptr<PointToPointNetDevice> p2p = DynamicCast<PointToPointNetDevice>(device);
+ if (p2p != 0) {
+ // Setup bucket filtering
+ // Assume that we know average data packet size, and this size is equal default size
+ // Set maximum buckets (averaging over 1 second)
+
+ DataRateValue dataRate;
+ device->GetAttribute("DataRate", dataRate);
+ TimeValue linkDelay;
+ device->GetChannel()->GetAttribute("Delay", linkDelay);
+
+ NS_LOG_INFO("DataRate for this link is " << dataRate.Get());
+
+ double maxInterestPackets =
+ 1.0 * dataRate.Get().GetBitRate() / 8.0 / (m_avgDataSize + m_avgInterestSize);
+ // NS_LOG_INFO ("Max packets per second: " << maxInterestPackets);
+ // NS_LOG_INFO ("Max burst: " << m_avgRtt.ToDouble (Time::S) * maxInterestPackets);
+ NS_LOG_INFO("MaxLimit: " << (int)(m_avgRtt.ToDouble(Time::S) * maxInterestPackets));
+
+ // Set max to BDP
+ limits->SetLimits(maxInterestPackets, m_avgRtt.ToDouble(Time::S));
+ limits->SetLinkDelay(linkDelay.Get().ToDouble(Time::S));
+ }
+ }
+
return face;
}
-
Ptr<FaceContainer>
-StackHelper::Install (const std::string &nodeName) const
+StackHelper::Install(const std::string& nodeName) const
{
- Ptr<Node> node = Names::Find<Node> (nodeName);
- return Install (node);
+ Ptr<Node> node = Names::Find<Node>(nodeName);
+ return Install(node);
}
-
void
-StackHelper::AddRoute (Ptr<Node> node, const std::string &prefix, Ptr<Face> face, int32_t metric)
+StackHelper::AddRoute(Ptr<Node> node, const std::string& prefix, Ptr<Face> face, int32_t metric)
{
- NS_LOG_LOGIC ("[" << node->GetId () << "]$ route add " << prefix << " via " << *face << " metric " << metric);
+ NS_LOG_LOGIC("[" << node->GetId() << "]$ route add " << prefix << " via " << *face << " metric "
+ << metric);
- Ptr<Fib> fib = node->GetObject<Fib> ();
+ Ptr<Fib> fib = node->GetObject<Fib>();
NameValue prefixValue;
- prefixValue.DeserializeFromString (prefix, MakeNameChecker ());
- fib->Add (prefixValue.Get (), face, metric);
+ prefixValue.DeserializeFromString(prefix, MakeNameChecker());
+ fib->Add(prefixValue.Get(), face, metric);
}
void
-StackHelper::AddRoute (Ptr<Node> node, const std::string &prefix, uint32_t faceId, int32_t metric)
+StackHelper::AddRoute(Ptr<Node> node, const std::string& prefix, uint32_t faceId, int32_t metric)
{
- Ptr<L3Protocol> ndn = node->GetObject<L3Protocol> ();
- NS_ASSERT_MSG (ndn != 0, "Ndn stack should be installed on the node");
+ Ptr<L3Protocol> ndn = node->GetObject<L3Protocol>();
+ NS_ASSERT_MSG(ndn != 0, "Ndn stack should be installed on the node");
- Ptr<Face> face = ndn->GetFace (faceId);
- NS_ASSERT_MSG (face != 0, "Face with ID [" << faceId << "] does not exist on node [" << node->GetId () << "]");
+ Ptr<Face> face = ndn->GetFace(faceId);
+ NS_ASSERT_MSG(face != 0, "Face with ID [" << faceId << "] does not exist on node ["
+ << node->GetId() << "]");
- AddRoute (node, prefix, face, metric);
+ AddRoute(node, prefix, face, metric);
}
void
-StackHelper::AddRoute (const std::string &nodeName, const std::string &prefix, uint32_t faceId, int32_t metric)
+StackHelper::AddRoute(const std::string& nodeName, const std::string& prefix, uint32_t faceId,
+ int32_t metric)
{
- Ptr<Node> node = Names::Find<Node> (nodeName);
- NS_ASSERT_MSG (node != 0, "Node [" << nodeName << "] does not exist");
+ Ptr<Node> node = Names::Find<Node>(nodeName);
+ NS_ASSERT_MSG(node != 0, "Node [" << nodeName << "] does not exist");
- Ptr<L3Protocol> ndn = node->GetObject<L3Protocol> ();
- NS_ASSERT_MSG (ndn != 0, "Ndn stack should be installed on the node");
+ Ptr<L3Protocol> ndn = node->GetObject<L3Protocol>();
+ NS_ASSERT_MSG(ndn != 0, "Ndn stack should be installed on the node");
- Ptr<Face> face = ndn->GetFace (faceId);
- NS_ASSERT_MSG (face != 0, "Face with ID [" << faceId << "] does not exist on node [" << nodeName << "]");
+ Ptr<Face> face = ndn->GetFace(faceId);
+ NS_ASSERT_MSG(face != 0, "Face with ID [" << faceId << "] does not exist on node [" << nodeName
+ << "]");
- AddRoute (node, prefix, face, metric);
+ AddRoute(node, prefix, face, metric);
}
void
-StackHelper::AddRoute (Ptr<Node> node, const std::string &prefix, Ptr<Node> otherNode, int32_t metric)
+StackHelper::AddRoute(Ptr<Node> node, const std::string& prefix, Ptr<Node> otherNode,
+ int32_t metric)
{
- for (uint32_t deviceId = 0; deviceId < node->GetNDevices (); deviceId ++)
- {
- Ptr<PointToPointNetDevice> netDevice = DynamicCast<PointToPointNetDevice> (node->GetDevice (deviceId));
- if (netDevice == 0)
- continue;
+ for (uint32_t deviceId = 0; deviceId < node->GetNDevices(); deviceId++) {
+ Ptr<PointToPointNetDevice> netDevice =
+ DynamicCast<PointToPointNetDevice>(node->GetDevice(deviceId));
+ if (netDevice == 0)
+ continue;
- Ptr<Channel> channel = netDevice->GetChannel ();
- if (channel == 0)
- continue;
+ Ptr<Channel> channel = netDevice->GetChannel();
+ if (channel == 0)
+ continue;
- if (channel->GetDevice (0)->GetNode () == otherNode ||
- channel->GetDevice (1)->GetNode () == otherNode)
- {
- Ptr<L3Protocol> ndn = node->GetObject<L3Protocol> ();
- NS_ASSERT_MSG (ndn != 0, "Ndn stack should be installed on the node");
+ if (channel->GetDevice(0)->GetNode() == otherNode
+ || channel->GetDevice(1)->GetNode() == otherNode) {
+ Ptr<L3Protocol> ndn = node->GetObject<L3Protocol>();
+ NS_ASSERT_MSG(ndn != 0, "Ndn stack should be installed on the node");
- Ptr<Face> face = ndn->GetFaceByNetDevice (netDevice);
- NS_ASSERT_MSG (face != 0, "There is no face associated with the p2p link");
+ Ptr<Face> face = ndn->GetFaceByNetDevice(netDevice);
+ NS_ASSERT_MSG(face != 0, "There is no face associated with the p2p link");
- AddRoute (node, prefix, face, metric);
+ AddRoute(node, prefix, face, metric);
- return;
- }
+ return;
}
+ }
- NS_FATAL_ERROR ("Cannot add route: Node# " << node->GetId () << " and Node# " << otherNode->GetId () << " are not connected");
+ NS_FATAL_ERROR("Cannot add route: Node# " << node->GetId() << " and Node# " << otherNode->GetId()
+ << " are not connected");
}
void
-StackHelper::AddRoute (const std::string &nodeName, const std::string &prefix, const std::string &otherNodeName, int32_t metric)
+StackHelper::AddRoute(const std::string& nodeName, const std::string& prefix,
+ const std::string& otherNodeName, int32_t metric)
{
- Ptr<Node> node = Names::Find<Node> (nodeName);
- NS_ASSERT_MSG (node != 0, "Node [" << nodeName << "] does not exist");
+ Ptr<Node> node = Names::Find<Node>(nodeName);
+ NS_ASSERT_MSG(node != 0, "Node [" << nodeName << "] does not exist");
- Ptr<Node> otherNode = Names::Find<Node> (otherNodeName);
- NS_ASSERT_MSG (otherNode != 0, "Node [" << otherNodeName << "] does not exist");
+ Ptr<Node> otherNode = Names::Find<Node>(otherNodeName);
+ NS_ASSERT_MSG(otherNode != 0, "Node [" << otherNodeName << "] does not exist");
- AddRoute (node, prefix, otherNode, metric);
+ AddRoute(node, prefix, otherNode, metric);
}
-
} // namespace ndn
} // namespace ns3
diff --git a/helper/ndn-stack-helper.hpp b/helper/ndn-stack-helper.hpp
index dc11bcf..155c22d 100644
--- a/helper/ndn-stack-helper.hpp
+++ b/helper/ndn-stack-helper.hpp
@@ -59,8 +59,7 @@
* attribute or a set of functionality that may be of interest to many other
* classes.
*/
-class StackHelper
-{
+class StackHelper {
public:
/**
* \brief Create a new NdnStackHelper with a default NDN_FLOODING forwarding stategy
@@ -70,17 +69,16 @@
/**
* \brief Destroy the NdnStackHelper
*/
- virtual ~StackHelper ();
+ virtual ~StackHelper();
/**
* @brief Set parameters of NdnL3Protocol
*/
void
- SetStackAttributes (const std::string &attr1 = "", const std::string &value1 = "",
- const std::string &attr2 = "", const std::string &value2 = "",
- const std::string &attr3 = "", const std::string &value3 = "",
- const std::string &attr4 = "", const std::string &value4 = "");
-
+ SetStackAttributes(const std::string& attr1 = "", const std::string& value1 = "",
+ const std::string& attr2 = "", const std::string& value2 = "",
+ const std::string& attr3 = "", const std::string& value3 = "",
+ const std::string& attr4 = "", const std::string& value4 = "");
/**
* @brief Set forwarding strategy class and its attributes
@@ -91,75 +89,79 @@
* Other strategies can be implemented, inheriting ns3::NdnForwardingStrategy class
*/
void
- SetForwardingStrategy (const std::string &forwardingStrategyClass,
- const std::string &attr1 = "", const std::string &value1 = "",
- const std::string &attr2 = "", const std::string &value2 = "",
- const std::string &attr3 = "", const std::string &value3 = "",
- const std::string &attr4 = "", const std::string &value4 = "");
+ SetForwardingStrategy(const std::string& forwardingStrategyClass, const std::string& attr1 = "",
+ const std::string& value1 = "", const std::string& attr2 = "",
+ const std::string& value2 = "", const std::string& attr3 = "",
+ const std::string& value3 = "", const std::string& attr4 = "",
+ const std::string& value4 = "");
/**
* @brief Set content store class and its attributes
* @param contentStoreClass string, representing class of the content store
*/
void
- SetContentStore (const std::string &contentStoreClass,
- const std::string &attr1 = "", const std::string &value1 = "",
- const std::string &attr2 = "", const std::string &value2 = "",
- const std::string &attr3 = "", const std::string &value3 = "",
- const std::string &attr4 = "", const std::string &value4 = "");
+ SetContentStore(const std::string& contentStoreClass, const std::string& attr1 = "",
+ const std::string& value1 = "", const std::string& attr2 = "",
+ const std::string& value2 = "", const std::string& attr3 = "",
+ const std::string& value3 = "", const std::string& attr4 = "",
+ const std::string& value4 = "");
/**
* @brief Set PIT class and its attributes
* @param pitClass string, representing class of PIT
*/
void
- SetPit (const std::string &pitClass,
- const std::string &attr1 = "", const std::string &value1 = "",
- const std::string &attr2 = "", const std::string &value2 = "",
- const std::string &attr3 = "", const std::string &value3 = "",
- const std::string &attr4 = "", const std::string &value4 = "");
+ SetPit(const std::string& pitClass, const std::string& attr1 = "", const std::string& value1 = "",
+ const std::string& attr2 = "", const std::string& value2 = "",
+ const std::string& attr3 = "", const std::string& value3 = "",
+ const std::string& attr4 = "", const std::string& value4 = "");
/**
* @brief Set FIB class and its attributes
* @param pitClass string, representing class of FIB
*/
void
- SetFib (const std::string &fibClass,
- const std::string &attr1 = "", const std::string &value1 = "",
- const std::string &attr2 = "", const std::string &value2 = "",
- const std::string &attr3 = "", const std::string &value3 = "",
- const std::string &attr4 = "", const std::string &value4 = "");
+ SetFib(const std::string& fibClass, const std::string& attr1 = "", const std::string& value1 = "",
+ const std::string& attr2 = "", const std::string& value2 = "",
+ const std::string& attr3 = "", const std::string& value3 = "",
+ const std::string& attr4 = "", const std::string& value4 = "");
- typedef Callback< Ptr<NetDeviceFace>, Ptr<Node>, Ptr<L3Protocol>, Ptr<NetDevice> > NetDeviceFaceCreateCallback;
+ typedef Callback<Ptr<NetDeviceFace>, Ptr<Node>, Ptr<L3Protocol>, Ptr<NetDevice>>
+ NetDeviceFaceCreateCallback;
/**
- * @brief Add callback to create and configure instance of the face, based on supplied Ptr<Node> and Ptr<NetDevice>
+ * @brief Add callback to create and configure instance of the face, based on supplied Ptr<Node>
+ *and Ptr<NetDevice>
*
* It is possible to set up several callbacks for different NetDevice types.
*
- * Currently, there is only one specialized callback for PointToPointNetDevice, which creates face and sets limits (if enabled)
+ * Currently, there is only one specialized callback for PointToPointNetDevice, which creates face
+ *and sets limits (if enabled)
* based on PointToPoint link parameters
*
- * If none of the callbacks fit the TypeId of NetDevice, a default callback is used (DefaultNetDeviceCallback)
+ * If none of the callbacks fit the TypeId of NetDevice, a default callback is used
+ *(DefaultNetDeviceCallback)
*/
void
- AddNetDeviceFaceCreateCallback (TypeId netDeviceType, NetDeviceFaceCreateCallback callback);
+ AddNetDeviceFaceCreateCallback(TypeId netDeviceType, NetDeviceFaceCreateCallback callback);
/**
- * @brief Update callback to create and configure instance of the face, based on supplied Ptr<Node> and Ptr<NetDevice>
+ * @brief Update callback to create and configure instance of the face, based on supplied
+ *Ptr<Node> and Ptr<NetDevice>
*
* It is possible to set up several callbacks for different NetDevice types.
*
* Using this method, it is possible to override Face creation for PointToPointNetDevices
*/
void
- UpdateNetDeviceFaceCreateCallback (TypeId netDeviceType, NetDeviceFaceCreateCallback callback);
+ UpdateNetDeviceFaceCreateCallback(TypeId netDeviceType, NetDeviceFaceCreateCallback callback);
/**
- * @brief Remove callback to create and configure instance of the face, based on supplied Ptr<Node> and Ptr<NetDevice>
+ * @brief Remove callback to create and configure instance of the face, based on supplied
+ * Ptr<Node> and Ptr<NetDevice>
*/
void
- RemoveNetDeviceFaceCreateCallback (TypeId netDeviceType, NetDeviceFaceCreateCallback callback);
+ RemoveNetDeviceFaceCreateCallback(TypeId netDeviceType, NetDeviceFaceCreateCallback callback);
/**
* @brief Enable Interest limits (disabled by default)
@@ -170,7 +172,8 @@
* @param avgInterest Average size of interest packets (including all headers)
*/
void
- EnableLimits (bool enable = true, Time avgRtt=Seconds(0.1), uint32_t avgData=1100, uint32_t avgInterest=40);
+ EnableLimits(bool enable = true, Time avgRtt = Seconds(0.1), uint32_t avgData = 1100,
+ uint32_t avgInterest = 40);
/**
* \brief Install Ndn stack on the node
@@ -184,7 +187,7 @@
* to NdnFaceContainer object
*/
Ptr<FaceContainer>
- Install (const std::string &nodeName) const;
+ Install(const std::string& nodeName) const;
/**
* \brief Install Ndn stack on the node
@@ -198,7 +201,7 @@
* to FaceContainer object
*/
Ptr<FaceContainer>
- Install (Ptr<Node> node) const;
+ Install(Ptr<Node> node) const;
/**
* \brief Install Ndn stack on each node in the input container
@@ -213,7 +216,7 @@
* to FaceContainer object
*/
Ptr<FaceContainer>
- Install (const NodeContainer &c) const;
+ Install(const NodeContainer& c) const;
/**
* \brief Install Ndn stack on all nodes in the simulation
@@ -222,7 +225,7 @@
* to FaceContainer object
*/
Ptr<FaceContainer>
- InstallAll () const;
+ InstallAll() const;
/**
* \brief Add forwarding entry to FIB
@@ -233,7 +236,7 @@
* \param metric Routing metric
*/
static void
- AddRoute (const std::string &nodeName, const std::string &prefix, uint32_t faceId, int32_t metric);
+ AddRoute(const std::string& nodeName, const std::string& prefix, uint32_t faceId, int32_t metric);
/**
* \brief Add forwarding entry to FIB
@@ -244,7 +247,7 @@
* \param metric Routing metric
*/
static void
- AddRoute (Ptr<Node> node, const std::string &prefix, uint32_t faceId, int32_t metric);
+ AddRoute(Ptr<Node> node, const std::string& prefix, uint32_t faceId, int32_t metric);
/**
* \brief Add forwarding entry to FIB
@@ -255,7 +258,7 @@
* \param metric Routing metric
*/
static void
- AddRoute (Ptr<Node> node, const std::string &prefix, Ptr<Face> face, int32_t metric);
+ AddRoute(Ptr<Node> node, const std::string& prefix, Ptr<Face> face, int32_t metric);
/**
* @brief Add forwarding entry to FIB (work only with point-to-point links)
@@ -266,35 +269,39 @@
* \param metric Routing metric
*/
static void
- AddRoute (Ptr<Node> node, const std::string &prefix, Ptr<Node> otherNode, int32_t metric);
+ AddRoute(Ptr<Node> node, const std::string& prefix, Ptr<Node> otherNode, int32_t metric);
/**
* @brief Add forwarding entry to FIB (work only with point-to-point links)
*
* \param nodeName Node name (refer to ns3::Names)
* \param prefix Routing prefix
- * \param otherNode The other node name, to which interests (will be used to infer face id (refer to ns3::Names)
+ * \param otherNode The other node name, to which interests (will be used to infer face id (refer
+ *to ns3::Names)
* \param metric Routing metric
*/
static void
- AddRoute (const std::string &nodeName, const std::string &prefix, const std::string &otherNodeName, int32_t metric);
+ AddRoute(const std::string& nodeName, const std::string& prefix, const std::string& otherNodeName,
+ int32_t metric);
/**
* \brief Set flag indicating necessity to install default routes in FIB
*/
void
- SetDefaultRoutes (bool needSet);
+ SetDefaultRoutes(bool needSet);
private:
Ptr<NetDeviceFace>
- DefaultNetDeviceCallback (Ptr<Node> node, Ptr<L3Protocol> ndn, Ptr<NetDevice> netDevice) const;
+ DefaultNetDeviceCallback(Ptr<Node> node, Ptr<L3Protocol> ndn, Ptr<NetDevice> netDevice) const;
Ptr<NetDeviceFace>
- PointToPointNetDeviceCallback (Ptr<Node> node, Ptr<L3Protocol> ndn, Ptr<NetDevice> netDevice) const;
+ PointToPointNetDeviceCallback(Ptr<Node> node, Ptr<L3Protocol> ndn,
+ Ptr<NetDevice> netDevice) const;
private:
- StackHelper (const StackHelper &);
- StackHelper &operator = (const StackHelper &o);
+ StackHelper(const StackHelper&);
+ StackHelper&
+ operator=(const StackHelper& o);
private:
ObjectFactory m_ndnFactory;
@@ -303,13 +310,13 @@
ObjectFactory m_pitFactory;
ObjectFactory m_fibFactory;
- bool m_limitsEnabled;
- Time m_avgRtt;
+ bool m_limitsEnabled;
+ Time m_avgRtt;
uint32_t m_avgDataSize;
uint32_t m_avgInterestSize;
- bool m_needSetDefaultRoutes;
+ bool m_needSetDefaultRoutes;
- typedef std::list< std::pair<TypeId, NetDeviceFaceCreateCallback> > NetDeviceCallbackList;
+ typedef std::list<std::pair<TypeId, NetDeviceFaceCreateCallback>> NetDeviceCallbackList;
NetDeviceCallbackList m_netDeviceCallbacks;
};
diff --git a/model/cs/content-store-impl.cpp b/model/cs/content-store-impl.cpp
index 225d137..b4d2eae 100644
--- a/model/cs/content-store-impl.cpp
+++ b/model/cs/content-store-impl.cpp
@@ -27,14 +27,14 @@
#include "../../utils/trie/multi-policy.hpp"
#include "../../utils/trie/aggregate-stats-policy.hpp"
-#define NS_OBJECT_ENSURE_REGISTERED_TEMPL(type, templ) \
- static struct X ## type ## templ ## RegistrationClass \
- { \
- X ## type ## templ ## RegistrationClass () { \
- ns3::TypeId tid = type<templ>::GetTypeId (); \
- tid.GetParent (); \
- } \
- } x_ ## type ## templ ## RegistrationVariable
+#define NS_OBJECT_ENSURE_REGISTERED_TEMPL(type, templ) \
+ static struct X##type##templ##RegistrationClass { \
+ X##type##templ##RegistrationClass() \
+ { \
+ ns3::TypeId tid = type<templ>::GetTypeId(); \
+ tid.GetParent(); \
+ } \
+ } x_##type##templ##RegistrationVariable
namespace ns3 {
namespace ndn {
@@ -69,15 +69,15 @@
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreImpl, fifo_policy_traits);
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreImpl, lfu_policy_traits);
-
-typedef multi_policy_traits< boost::mpl::vector2< lru_policy_traits,
- aggregate_stats_policy_traits > > LruWithCountsTraits;
-typedef multi_policy_traits< boost::mpl::vector2< random_policy_traits,
- aggregate_stats_policy_traits > > RandomWithCountsTraits;
-typedef multi_policy_traits< boost::mpl::vector2< fifo_policy_traits,
- aggregate_stats_policy_traits > > FifoWithCountsTraits;
-typedef multi_policy_traits< boost::mpl::vector2< lfu_policy_traits,
- aggregate_stats_policy_traits > > LfuWithCountsTraits;
+typedef multi_policy_traits<boost::mpl::vector2<lru_policy_traits, aggregate_stats_policy_traits>>
+ LruWithCountsTraits;
+typedef multi_policy_traits<boost::mpl::vector2<random_policy_traits,
+ aggregate_stats_policy_traits>>
+ RandomWithCountsTraits;
+typedef multi_policy_traits<boost::mpl::vector2<fifo_policy_traits, aggregate_stats_policy_traits>>
+ FifoWithCountsTraits;
+typedef multi_policy_traits<boost::mpl::vector2<lfu_policy_traits, aggregate_stats_policy_traits>>
+ LfuWithCountsTraits;
template class ContentStoreImpl<LruWithCountsTraits>;
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreImpl, LruWithCountsTraits);
@@ -95,25 +95,28 @@
// /**
// * \brief Content Store implementing LRU cache replacement policy
// */
-class Lru : public ContentStoreImpl<lru_policy_traits> { };
+class Lru : public ContentStoreImpl<lru_policy_traits> {
+};
/**
* \brief Content Store implementing FIFO cache replacement policy
*/
-class Fifo : public ContentStoreImpl<fifo_policy_traits> { };
+class Fifo : public ContentStoreImpl<fifo_policy_traits> {
+};
/**
* \brief Content Store implementing Random cache replacement policy
*/
-class Random : public ContentStoreImpl<random_policy_traits> { };
+class Random : public ContentStoreImpl<random_policy_traits> {
+};
/**
* \brief Content Store implementing Least Frequently Used cache replacement policy
*/
-class Lfu : public ContentStoreImpl<lfu_policy_traits> { };
+class Lfu : public ContentStoreImpl<lfu_policy_traits> {
+};
#endif
-
} // namespace cs
} // namespace ndn
} // namespace ns3
diff --git a/model/cs/content-store-impl.hpp b/model/cs/content-store-impl.hpp
index 1254bb2..b35fdb4 100644
--- a/model/cs/content-store-impl.hpp
+++ b/model/cs/content-store-impl.hpp
@@ -43,292 +43,293 @@
* @brief Cache entry implementation with additional references to the base container
*/
template<class CS>
-class EntryImpl : public Entry
-{
+class EntryImpl : public Entry {
public:
typedef Entry base_type;
public:
- EntryImpl (Ptr<ContentStore> cs, Ptr<const Data> data)
- : Entry (cs, data)
- , item_ (0)
+ EntryImpl(Ptr<ContentStore> cs, Ptr<const Data> data)
+ : Entry(cs, data)
+ , item_(0)
{
}
void
- SetTrie (typename CS::super::iterator item)
+ SetTrie(typename CS::super::iterator item)
{
item_ = item;
}
- typename CS::super::iterator to_iterator () { return item_; }
- typename CS::super::const_iterator to_iterator () const { return item_; }
+ typename CS::super::iterator
+ to_iterator()
+ {
+ return item_;
+ }
+ typename CS::super::const_iterator
+ to_iterator() const
+ {
+ return item_;
+ }
private:
typename CS::super::iterator item_;
};
-
-
/**
* @ingroup ndn-cs
* @brief Base implementation of NDN content store
*/
template<class Policy>
-class ContentStoreImpl : public ContentStore,
- protected ndnSIM::trie_with_policy< Name,
- ndnSIM::smart_pointer_payload_traits< EntryImpl< ContentStoreImpl< Policy > >, Entry >,
- Policy >
-{
+class ContentStoreImpl
+ : public ContentStore,
+ protected ndnSIM::
+ trie_with_policy<Name,
+ ndnSIM::smart_pointer_payload_traits<EntryImpl<ContentStoreImpl<Policy>>,
+ Entry>,
+ Policy> {
public:
- typedef ndnSIM::trie_with_policy< Name,
- ndnSIM::smart_pointer_payload_traits< EntryImpl< ContentStoreImpl< Policy > >, Entry >,
- Policy > super;
+ typedef ndnSIM::
+ trie_with_policy<Name, ndnSIM::smart_pointer_payload_traits<EntryImpl<ContentStoreImpl<Policy>>,
+ Entry>,
+ Policy> super;
- typedef EntryImpl< ContentStoreImpl< Policy > > entry;
+ typedef EntryImpl<ContentStoreImpl<Policy>> entry;
static TypeId
- GetTypeId ();
+ GetTypeId();
- ContentStoreImpl () { };
- virtual ~ContentStoreImpl () { };
+ ContentStoreImpl(){};
+ virtual ~ContentStoreImpl(){};
// from ContentStore
virtual inline Ptr<Data>
- Lookup (Ptr<const Interest> interest);
+ Lookup(Ptr<const Interest> interest);
virtual inline bool
- Add (Ptr<const Data> data);
+ Add(Ptr<const Data> data);
// virtual bool
// Remove (Ptr<Interest> header);
virtual inline void
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
virtual uint32_t
- GetSize () const;
+ GetSize() const;
virtual Ptr<Entry>
- Begin ();
+ Begin();
virtual Ptr<Entry>
- End ();
+ End();
- virtual Ptr<Entry>
- Next (Ptr<Entry>);
+ virtual Ptr<Entry> Next(Ptr<Entry>);
- const typename super::policy_container &
- GetPolicy () const { return super::getPolicy (); }
+ const typename super::policy_container&
+ GetPolicy() const
+ {
+ return super::getPolicy();
+ }
- typename super::policy_container &
- GetPolicy () { return super::getPolicy (); }
-
+ typename super::policy_container&
+ GetPolicy()
+ {
+ return super::getPolicy();
+ }
+
private:
void
- SetMaxSize (uint32_t maxSize);
+ SetMaxSize(uint32_t maxSize);
uint32_t
- GetMaxSize () const;
+ GetMaxSize() const;
private:
static LogComponent g_log; ///< @brief Logging variable
- /// @brief trace of for entry additions (fired every time entry is successfully added to the cache): first parameter is pointer to the CS entry
- TracedCallback< Ptr<const Entry> > m_didAddEntry;
+ /// @brief trace of for entry additions (fired every time entry is successfully added to the
+ /// cache): first parameter is pointer to the CS entry
+ TracedCallback<Ptr<const Entry>> m_didAddEntry;
};
//////////////////////////////////////////
////////// Implementation ////////////////
//////////////////////////////////////////
-
template<class Policy>
-LogComponent ContentStoreImpl< Policy >::g_log = LogComponent (("ndn.cs." + Policy::GetName ()).c_str ());
-
+LogComponent
+ ContentStoreImpl<Policy>::g_log = LogComponent(("ndn.cs." + Policy::GetName()).c_str());
template<class Policy>
TypeId
-ContentStoreImpl< Policy >::GetTypeId ()
+ContentStoreImpl<Policy>::GetTypeId()
{
- static TypeId tid = TypeId (("ns3::ndn::cs::"+Policy::GetName ()).c_str ())
- .SetGroupName ("Ndn")
- .SetParent<ContentStore> ()
- .AddConstructor< ContentStoreImpl< Policy > > ()
- .AddAttribute ("MaxSize",
- "Set maximum number of entries in ContentStore. If 0, limit is not enforced",
- StringValue ("100"),
- MakeUintegerAccessor (&ContentStoreImpl< Policy >::GetMaxSize,
- &ContentStoreImpl< Policy >::SetMaxSize),
- MakeUintegerChecker<uint32_t> ())
+ static TypeId tid =
+ TypeId(("ns3::ndn::cs::" + Policy::GetName()).c_str())
+ .SetGroupName("Ndn")
+ .SetParent<ContentStore>()
+ .AddConstructor<ContentStoreImpl<Policy>>()
+ .AddAttribute("MaxSize",
+ "Set maximum number of entries in ContentStore. If 0, limit is not enforced",
+ StringValue("100"), MakeUintegerAccessor(&ContentStoreImpl<Policy>::GetMaxSize,
+ &ContentStoreImpl<Policy>::SetMaxSize),
+ MakeUintegerChecker<uint32_t>())
- .AddTraceSource ("DidAddEntry", "Trace fired every time entry is successfully added to the cache",
- MakeTraceSourceAccessor (&ContentStoreImpl< Policy >::m_didAddEntry))
- ;
+ .AddTraceSource("DidAddEntry",
+ "Trace fired every time entry is successfully added to the cache",
+ MakeTraceSourceAccessor(&ContentStoreImpl<Policy>::m_didAddEntry));
return tid;
}
-struct isNotExcluded
-{
- inline
- isNotExcluded (const Exclude &exclude)
- : m_exclude (exclude)
+struct isNotExcluded {
+ inline isNotExcluded(const Exclude& exclude)
+ : m_exclude(exclude)
{
}
-
+
bool
- operator () (const name::Component &comp) const
+ operator()(const name::Component& comp) const
{
- return !m_exclude.isExcluded (comp);
+ return !m_exclude.isExcluded(comp);
}
private:
- const Exclude &m_exclude;
+ const Exclude& m_exclude;
};
template<class Policy>
Ptr<Data>
-ContentStoreImpl<Policy>::Lookup (Ptr<const Interest> interest)
+ContentStoreImpl<Policy>::Lookup(Ptr<const Interest> interest)
{
- NS_LOG_FUNCTION (this << interest->GetName ());
+ NS_LOG_FUNCTION(this << interest->GetName());
typename super::const_iterator node;
- if (interest->GetExclude () == 0)
- {
- node = this->deepest_prefix_match (interest->GetName ());
- }
- else
- {
- node = this->deepest_prefix_match_if_next_level (interest->GetName (),
- isNotExcluded (*interest->GetExclude ()));
- }
+ if (interest->GetExclude() == 0) {
+ node = this->deepest_prefix_match(interest->GetName());
+ }
+ else {
+ node = this->deepest_prefix_match_if_next_level(interest->GetName(),
+ isNotExcluded(*interest->GetExclude()));
+ }
- if (node != this->end ())
- {
- this->m_cacheHitsTrace (interest, node->payload ()->GetData ());
+ if (node != this->end()) {
+ this->m_cacheHitsTrace(interest, node->payload()->GetData());
- Ptr<Data> copy = Create<Data> (*node->payload ()->GetData ());
- ConstCast<Packet> (copy->GetPayload ())->RemoveAllPacketTags ();
- return copy;
- }
- else
- {
- this->m_cacheMissesTrace (interest);
- return 0;
- }
+ Ptr<Data> copy = Create<Data>(*node->payload()->GetData());
+ ConstCast<Packet>(copy->GetPayload())->RemoveAllPacketTags();
+ return copy;
+ }
+ else {
+ this->m_cacheMissesTrace(interest);
+ return 0;
+ }
}
template<class Policy>
bool
-ContentStoreImpl<Policy>::Add (Ptr<const Data> data)
+ContentStoreImpl<Policy>::Add(Ptr<const Data> data)
{
- NS_LOG_FUNCTION (this << data->GetName ());
+ NS_LOG_FUNCTION(this << data->GetName());
- Ptr< entry > newEntry = Create< entry > (this, data);
- std::pair< typename super::iterator, bool > result = super::insert (data->GetName (), newEntry);
+ Ptr<entry> newEntry = Create<entry>(this, data);
+ std::pair<typename super::iterator, bool> result = super::insert(data->GetName(), newEntry);
- if (result.first != super::end ())
- {
- if (result.second)
- {
- newEntry->SetTrie (result.first);
+ if (result.first != super::end()) {
+ if (result.second) {
+ newEntry->SetTrie(result.first);
- m_didAddEntry (newEntry);
- return true;
- }
- else
- {
- // should we do anything?
- // update payload? add new payload?
- return false;
- }
+ m_didAddEntry(newEntry);
+ return true;
}
+ else {
+ // should we do anything?
+ // update payload? add new payload?
+ return false;
+ }
+ }
else
return false; // cannot insert entry
}
template<class Policy>
void
-ContentStoreImpl<Policy>::Print (std::ostream &os) const
+ContentStoreImpl<Policy>::Print(std::ostream& os) const
{
- for (typename super::policy_container::const_iterator item = this->getPolicy ().begin ();
- item != this->getPolicy ().end ();
- item++)
- {
- os << item->payload ()->GetName () << std::endl;
- }
+ for (typename super::policy_container::const_iterator item = this->getPolicy().begin();
+ item != this->getPolicy().end(); item++) {
+ os << item->payload()->GetName() << std::endl;
+ }
}
template<class Policy>
void
-ContentStoreImpl<Policy>::SetMaxSize (uint32_t maxSize)
+ContentStoreImpl<Policy>::SetMaxSize(uint32_t maxSize)
{
- this->getPolicy ().set_max_size (maxSize);
+ this->getPolicy().set_max_size(maxSize);
}
template<class Policy>
uint32_t
-ContentStoreImpl<Policy>::GetMaxSize () const
+ContentStoreImpl<Policy>::GetMaxSize() const
{
- return this->getPolicy ().get_max_size ();
+ return this->getPolicy().get_max_size();
}
template<class Policy>
uint32_t
-ContentStoreImpl<Policy>::GetSize () const
+ContentStoreImpl<Policy>::GetSize() const
{
- return this->getPolicy ().size ();
+ return this->getPolicy().size();
}
template<class Policy>
Ptr<Entry>
-ContentStoreImpl<Policy>::Begin ()
+ContentStoreImpl<Policy>::Begin()
{
- typename super::parent_trie::recursive_iterator item (super::getTrie ()), end (0);
- for (; item != end; item++)
- {
- if (item->payload () == 0) continue;
- break;
- }
+ typename super::parent_trie::recursive_iterator item(super::getTrie()), end(0);
+ for (; item != end; item++) {
+ if (item->payload() == 0)
+ continue;
+ break;
+ }
if (item == end)
- return End ();
+ return End();
else
- return item->payload ();
+ return item->payload();
}
template<class Policy>
Ptr<Entry>
-ContentStoreImpl<Policy>::End ()
+ContentStoreImpl<Policy>::End()
{
return 0;
}
template<class Policy>
Ptr<Entry>
-ContentStoreImpl<Policy>::Next (Ptr<Entry> from)
+ContentStoreImpl<Policy>::Next(Ptr<Entry> from)
{
- if (from == 0) return 0;
+ if (from == 0)
+ return 0;
- typename super::parent_trie::recursive_iterator
- item (*StaticCast< entry > (from)->to_iterator ()),
- end (0);
+ typename super::parent_trie::recursive_iterator item(*StaticCast<entry>(from)->to_iterator()),
+ end(0);
- for (item++; item != end; item++)
- {
- if (item->payload () == 0) continue;
- break;
- }
+ for (item++; item != end; item++) {
+ if (item->payload() == 0)
+ continue;
+ break;
+ }
if (item == end)
- return End ();
+ return End();
else
- return item->payload ();
+ return item->payload();
}
-
} // namespace cs
} // namespace ndn
} // namespace ns3
diff --git a/model/cs/content-store-nocache.cpp b/model/cs/content-store-nocache.cpp
index 61515c1..85505d1 100644
--- a/model/cs/content-store-nocache.cpp
+++ b/model/cs/content-store-nocache.cpp
@@ -17,7 +17,7 @@
*
* Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
* Ilya Moiseenko <iliamo@cs.ucla.edu>
- *
+ *
*/
#include "content-store-nocache.hpp"
@@ -25,72 +25,70 @@
#include "ns3/log.h"
#include "ns3/packet.h"
-NS_LOG_COMPONENT_DEFINE ("ndn.cs.Nocache");
+NS_LOG_COMPONENT_DEFINE("ndn.cs.Nocache");
namespace ns3 {
namespace ndn {
namespace cs {
-NS_OBJECT_ENSURE_REGISTERED (Nocache);
+NS_OBJECT_ENSURE_REGISTERED(Nocache);
-TypeId
-Nocache::GetTypeId (void)
+TypeId
+Nocache::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::cs::Nocache")
- .SetGroupName ("Ndn")
- .SetParent<ContentStore> ()
- .AddConstructor< Nocache > ()
- ;
+ static TypeId tid = TypeId("ns3::ndn::cs::Nocache")
+ .SetGroupName("Ndn")
+ .SetParent<ContentStore>()
+ .AddConstructor<Nocache>();
return tid;
}
-Nocache::Nocache ()
+Nocache::Nocache()
{
}
-Nocache::~Nocache ()
+Nocache::~Nocache()
{
}
Ptr<Data>
-Nocache::Lookup (Ptr<const Interest> interest)
+Nocache::Lookup(Ptr<const Interest> interest)
{
- this->m_cacheMissesTrace (interest);
+ this->m_cacheMissesTrace(interest);
return 0;
}
bool
-Nocache::Add (Ptr<const Data> data)
+Nocache::Add(Ptr<const Data> data)
{
return false;
}
void
-Nocache::Print (std::ostream &os) const
+Nocache::Print(std::ostream& os) const
{
}
uint32_t
-Nocache::GetSize () const
+Nocache::GetSize() const
{
return 0;
}
Ptr<cs::Entry>
-Nocache::Begin ()
+Nocache::Begin()
{
return 0;
}
Ptr<cs::Entry>
-Nocache::End ()
+Nocache::End()
{
return 0;
}
-Ptr<cs::Entry>
-Nocache::Next (Ptr<cs::Entry>)
+Ptr<cs::Entry> Nocache::Next(Ptr<cs::Entry>)
{
return 0;
}
diff --git a/model/cs/content-store-nocache.hpp b/model/cs/content-store-nocache.hpp
index ac7ced7..5745821 100644
--- a/model/cs/content-store-nocache.hpp
+++ b/model/cs/content-store-nocache.hpp
@@ -20,7 +20,7 @@
*/
#ifndef NDN_CONTENT_STORE_NOCACHE_H
-#define NDN_CONTENT_STORE_NOCACHE_H
+#define NDN_CONTENT_STORE_NOCACHE_H
#include "ns3/ndnSIM/model/cs/ndn-content-store.hpp"
@@ -32,49 +32,45 @@
* @ingroup ndn-cs
* @brief Implementation of ContentStore that completely disables caching
*/
-class Nocache : public ContentStore
-{
+class Nocache : public ContentStore {
public:
/**
* \brief Interface ID
*
* \return interface ID
*/
- static
- TypeId GetTypeId ();
+ static TypeId
+ GetTypeId();
/**
* @brief Default constructor
*/
- Nocache ();
-
+ Nocache();
+
/**
* @brief Virtual destructor
*/
- virtual
- ~Nocache ();
+ virtual ~Nocache();
virtual Ptr<Data>
- Lookup (Ptr<const Interest> interest);
+ Lookup(Ptr<const Interest> interest);
virtual bool
- Add (Ptr<const Data> data);
+ Add(Ptr<const Data> data);
virtual void
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
virtual uint32_t
- GetSize () const;
+ GetSize() const;
virtual Ptr<cs::Entry>
- Begin ();
+ Begin();
virtual Ptr<cs::Entry>
- End ();
+ End();
- virtual Ptr<cs::Entry>
- Next (Ptr<cs::Entry>);
-
+ virtual Ptr<cs::Entry> Next(Ptr<cs::Entry>);
};
} // namespace cs
diff --git a/model/cs/content-store-with-freshness.cpp b/model/cs/content-store-with-freshness.cpp
index e132a78..3fa39b9 100644
--- a/model/cs/content-store-with-freshness.cpp
+++ b/model/cs/content-store-with-freshness.cpp
@@ -25,14 +25,14 @@
#include "../../utils/trie/fifo-policy.hpp"
#include "../../utils/trie/lfu-policy.hpp"
-#define NS_OBJECT_ENSURE_REGISTERED_TEMPL(type, templ) \
- static struct X ## type ## templ ## RegistrationClass \
- { \
- X ## type ## templ ## RegistrationClass () { \
- ns3::TypeId tid = type<templ>::GetTypeId (); \
- tid.GetParent (); \
- } \
- } x_ ## type ## templ ## RegistrationVariable
+#define NS_OBJECT_ENSURE_REGISTERED_TEMPL(type, templ) \
+ static struct X##type##templ##RegistrationClass { \
+ X##type##templ##RegistrationClass() \
+ { \
+ ns3::TypeId tid = type<templ>::GetTypeId(); \
+ tid.GetParent(); \
+ } \
+ } x_##type##templ##RegistrationVariable
namespace ns3 {
namespace ndn {
@@ -62,7 +62,6 @@
**/
template class ContentStoreWithFreshness<lfu_policy_traits>;
-
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithFreshness, lru_policy_traits);
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithFreshness, random_policy_traits);
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithFreshness, fifo_policy_traits);
@@ -73,26 +72,29 @@
// /**
// * \brief Content Store with freshness implementing LRU cache replacement policy
// */
-class Freshness::Lru : public ContentStoreWithFreshness<lru_policy_traits> { };
+class Freshness::Lru : public ContentStoreWithFreshness<lru_policy_traits> {
+};
/**
* \brief Content Store with freshness implementing FIFO cache replacement policy
*/
-class Freshness::Fifo : public ContentStoreWithFreshness<fifo_policy_traits> { };
+class Freshness::Fifo : public ContentStoreWithFreshness<fifo_policy_traits> {
+};
/**
* \brief Content Store with freshness implementing Random cache replacement policy
*/
-class Freshness::Random : public ContentStoreWithFreshness<random_policy_traits> { };
+class Freshness::Random : public ContentStoreWithFreshness<random_policy_traits> {
+};
/**
* \brief Content Store with freshness implementing Least Frequently Used cache replacement policy
*/
-class Freshness::Lfu : public ContentStoreWithFreshness<lfu_policy_traits> { };
+class Freshness::Lfu : public ContentStoreWithFreshness<lfu_policy_traits> {
+};
#endif
-
} // namespace cs
} // namespace ndn
} // namespace ns3
diff --git a/model/cs/content-store-with-freshness.hpp b/model/cs/content-store-with-freshness.hpp
index 2bd74de..07aa56f 100644
--- a/model/cs/content-store-with-freshness.hpp
+++ b/model/cs/content-store-with-freshness.hpp
@@ -37,29 +37,34 @@
* @brief Special content store realization that honors Freshness parameter in Data packets
*/
template<class Policy>
-class ContentStoreWithFreshness :
- public ContentStoreImpl< ndnSIM::multi_policy_traits< boost::mpl::vector2< Policy, ndnSIM::freshness_policy_traits > > >
-{
+class ContentStoreWithFreshness
+ : public ContentStoreImpl<ndnSIM::
+ multi_policy_traits<boost::mpl::
+ vector2<Policy,
+ ndnSIM::freshness_policy_traits>>> {
public:
- typedef ContentStoreImpl< ndnSIM::multi_policy_traits< boost::mpl::vector2< Policy, ndnSIM::freshness_policy_traits > > > super;
+ typedef ContentStoreImpl<ndnSIM::multi_policy_traits<boost::mpl::
+ vector2<Policy,
+ ndnSIM::freshness_policy_traits>>>
+ super;
typedef typename super::policy_container::template index<1>::type freshness_policy_container;
static TypeId
- GetTypeId ();
+ GetTypeId();
virtual inline void
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
virtual inline bool
- Add (Ptr<const Data> data);
+ Add(Ptr<const Data> data);
private:
inline void
- CleanExpired ();
+ CleanExpired();
inline void
- RescheduleCleaning ();
+ RescheduleCleaning();
private:
static LogComponent g_log; ///< @brief Logging variable
@@ -72,20 +77,18 @@
////////// Implementation ////////////////
//////////////////////////////////////////
-
template<class Policy>
-LogComponent
-ContentStoreWithFreshness< Policy >::g_log = LogComponent (("ndn.cs.Freshness." + Policy::GetName ()).c_str ());
-
+LogComponent ContentStoreWithFreshness<Policy>::g_log = LogComponent(("ndn.cs.Freshness."
+ + Policy::GetName()).c_str());
template<class Policy>
TypeId
-ContentStoreWithFreshness< Policy >::GetTypeId ()
+ContentStoreWithFreshness<Policy>::GetTypeId()
{
- static TypeId tid = TypeId (("ns3::ndn::cs::Freshness::"+Policy::GetName ()).c_str ())
- .SetGroupName ("Ndn")
- .SetParent<super> ()
- .template AddConstructor< ContentStoreWithFreshness< Policy > > ()
+ static TypeId tid = TypeId(("ns3::ndn::cs::Freshness::" + Policy::GetName()).c_str())
+ .SetGroupName("Ndn")
+ .SetParent<super>()
+ .template AddConstructor<ContentStoreWithFreshness<Policy>>()
// trace stuff here
;
@@ -93,95 +96,93 @@
return tid;
}
-
template<class Policy>
inline bool
-ContentStoreWithFreshness< Policy >::Add (Ptr<const Data> data)
+ContentStoreWithFreshness<Policy>::Add(Ptr<const Data> data)
{
- bool ok = super::Add (data);
- if (!ok) return false;
+ bool ok = super::Add(data);
+ if (!ok)
+ return false;
- NS_LOG_DEBUG (data->GetName () << " added to cache");
- RescheduleCleaning ();
+ NS_LOG_DEBUG(data->GetName() << " added to cache");
+ RescheduleCleaning();
return true;
}
template<class Policy>
inline void
-ContentStoreWithFreshness< Policy >::RescheduleCleaning ()
+ContentStoreWithFreshness<Policy>::RescheduleCleaning()
{
- const freshness_policy_container &freshness = this->getPolicy ().template get<freshness_policy_container> ();
+ const freshness_policy_container& freshness =
+ this->getPolicy().template get<freshness_policy_container>();
- if (freshness.size () > 0)
+ if (freshness.size() > 0) {
+ Time nextStateTime =
+ freshness_policy_container::policy_base::get_freshness(&(*freshness.begin()));
+
+ if (m_scheduledCleaningTime.IsZero() || // if not yet scheduled
+ m_scheduledCleaningTime > nextStateTime) // if new item expire sooner than already scheduled
{
- Time nextStateTime = freshness_policy_container::policy_base::get_freshness (&(*freshness.begin ()));
+ if (m_cleanEvent.IsRunning()) {
+ Simulator::Remove(m_cleanEvent); // just canceling would not clean up list of events
+ }
- if (m_scheduledCleaningTime.IsZero () || // if not yet scheduled
- m_scheduledCleaningTime > nextStateTime) // if new item expire sooner than already scheduled
- {
- if (m_cleanEvent.IsRunning ())
- {
- Simulator::Remove (m_cleanEvent); // just canceling would not clean up list of events
- }
-
- // NS_LOG_DEBUG ("Next event in: " << (nextStateTime - Now ()).ToDouble (Time::S) << "s");
- m_cleanEvent = Simulator::Schedule (nextStateTime - Now (), &ContentStoreWithFreshness< Policy >::CleanExpired, this);
- m_scheduledCleaningTime = nextStateTime;
- }
+ // NS_LOG_DEBUG ("Next event in: " << (nextStateTime - Now ()).ToDouble (Time::S) << "s");
+ m_cleanEvent = Simulator::Schedule(nextStateTime - Now(),
+ &ContentStoreWithFreshness<Policy>::CleanExpired, this);
+ m_scheduledCleaningTime = nextStateTime;
}
- else
- {
- if (m_cleanEvent.IsRunning ())
- {
- Simulator::Remove (m_cleanEvent); // just canceling would not clean up list of events
- }
+ }
+ else {
+ if (m_cleanEvent.IsRunning()) {
+ Simulator::Remove(m_cleanEvent); // just canceling would not clean up list of events
}
+ }
}
-
template<class Policy>
inline void
-ContentStoreWithFreshness< Policy >::CleanExpired ()
+ContentStoreWithFreshness<Policy>::CleanExpired()
{
- freshness_policy_container &freshness = this->getPolicy ().template get<freshness_policy_container> ();
+ freshness_policy_container& freshness =
+ this->getPolicy().template get<freshness_policy_container>();
- // NS_LOG_LOGIC (">> Cleaning: Total number of items:" << this->getPolicy ().size () << ", items with freshness: " << freshness.size ());
- Time now = Simulator::Now ();
+ // NS_LOG_LOGIC (">> Cleaning: Total number of items:" << this->getPolicy ().size () << ", items
+ // with freshness: " << freshness.size ());
+ Time now = Simulator::Now();
- while (!freshness.empty ())
+ while (!freshness.empty()) {
+ typename freshness_policy_container::iterator entry = freshness.begin();
+
+ if (freshness_policy_container::policy_base::get_freshness(&(*entry))
+ <= now) // is the record stale?
{
- typename freshness_policy_container::iterator entry = freshness.begin ();
-
- if (freshness_policy_container::policy_base::get_freshness (&(*entry)) <= now) // is the record stale?
- {
- super::erase (&(*entry));
- }
- else
- break; // nothing else to do. All later records will not be stale
+ super::erase(&(*entry));
}
- // NS_LOG_LOGIC ("<< Cleaning: Total number of items:" << this->getPolicy ().size () << ", items with freshness: " << freshness.size ());
+ else
+ break; // nothing else to do. All later records will not be stale
+ }
+ // NS_LOG_LOGIC ("<< Cleaning: Total number of items:" << this->getPolicy ().size () << ", items
+ // with freshness: " << freshness.size ());
- m_scheduledCleaningTime = Time ();
- RescheduleCleaning ();
+ m_scheduledCleaningTime = Time();
+ RescheduleCleaning();
}
template<class Policy>
void
-ContentStoreWithFreshness< Policy >::Print (std::ostream &os) const
+ContentStoreWithFreshness<Policy>::Print(std::ostream& os) const
{
- // const freshness_policy_container &freshness = this->getPolicy ().template get<freshness_policy_container> ();
+ // const freshness_policy_container &freshness = this->getPolicy ().template
+ // get<freshness_policy_container> ();
- for (typename super::policy_container::const_iterator item = this->getPolicy ().begin ();
- item != this->getPolicy ().end ();
- item++)
- {
- Time ttl = freshness_policy_container::policy_base::get_freshness (&(*item)) - Simulator::Now ();
- os << item->payload ()->GetName () << "(left: " << ttl.ToDouble (Time::S) << "s)" << std::endl;
- }
+ for (typename super::policy_container::const_iterator item = this->getPolicy().begin();
+ item != this->getPolicy().end(); item++) {
+ Time ttl = freshness_policy_container::policy_base::get_freshness(&(*item)) - Simulator::Now();
+ os << item->payload()->GetName() << "(left: " << ttl.ToDouble(Time::S) << "s)" << std::endl;
+ }
}
-
-
} // namespace cs
} // namespace ndn
} // namespace ns3
diff --git a/model/cs/content-store-with-probability.cpp b/model/cs/content-store-with-probability.cpp
index bf5c181..313cb36 100644
--- a/model/cs/content-store-with-probability.cpp
+++ b/model/cs/content-store-with-probability.cpp
@@ -25,14 +25,14 @@
#include "../../utils/trie/fifo-policy.hpp"
#include "../../utils/trie/lfu-policy.hpp"
-#define NS_OBJECT_ENSURE_REGISTERED_TEMPL(type, templ) \
- static struct X ## type ## templ ## RegistrationClass \
- { \
- X ## type ## templ ## RegistrationClass () { \
- ns3::TypeId tid = type<templ>::GetTypeId (); \
- tid.GetParent (); \
- } \
- } x_ ## type ## templ ## RegistrationVariable
+#define NS_OBJECT_ENSURE_REGISTERED_TEMPL(type, templ) \
+ static struct X##type##templ##RegistrationClass { \
+ X##type##templ##RegistrationClass() \
+ { \
+ ns3::TypeId tid = type<templ>::GetTypeId(); \
+ tid.GetParent(); \
+ } \
+ } x_##type##templ##RegistrationVariable
namespace ns3 {
namespace ndn {
@@ -62,7 +62,6 @@
**/
template class ContentStoreWithProbability<lfu_policy_traits>;
-
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithProbability, lru_policy_traits);
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithProbability, random_policy_traits);
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithProbability, fifo_policy_traits);
@@ -73,26 +72,29 @@
// /**
// * \brief Content Store with freshness implementing LRU cache replacement policy
// */
-class Probability::Lru : public ContentStoreWithProbability<lru_policy_traits> { };
+class Probability::Lru : public ContentStoreWithProbability<lru_policy_traits> {
+};
/**
* \brief Content Store with freshness implementing FIFO cache replacement policy
*/
-class Probability::Fifo : public ContentStoreWithProbability<fifo_policy_traits> { };
+class Probability::Fifo : public ContentStoreWithProbability<fifo_policy_traits> {
+};
/**
* \brief Content Store with freshness implementing Random cache replacement policy
*/
-class Probability::Random : public ContentStoreWithProbability<random_policy_traits> { };
+class Probability::Random : public ContentStoreWithProbability<random_policy_traits> {
+};
/**
* \brief Content Store with freshness implementing Least Frequently Used cache replacement policy
*/
-class Probability::Lfu : public ContentStoreWithProbability<lfu_policy_traits> { };
+class Probability::Lfu : public ContentStoreWithProbability<lfu_policy_traits> {
+};
#endif
-
} // namespace cs
} // namespace ndn
} // namespace ns3
diff --git a/model/cs/content-store-with-probability.hpp b/model/cs/content-store-with-probability.hpp
index 55266e8..cca50c1 100644
--- a/model/cs/content-store-with-probability.hpp
+++ b/model/cs/content-store-with-probability.hpp
@@ -39,34 +39,33 @@
* @brief Special content store realization that honors Freshness parameter in Data packets
*/
template<class Policy>
-class ContentStoreWithProbability :
- public ContentStoreImpl< ndnSIM::multi_policy_traits< boost::mpl::vector2< ndnSIM::probability_policy_traits, Policy > > >
-{
+class ContentStoreWithProbability
+ : public ContentStoreImpl<ndnSIM::multi_policy_traits<boost::mpl::
+ vector2<ndnSIM::probability_policy_traits,
+ Policy>>> {
public:
- typedef ContentStoreImpl< ndnSIM::multi_policy_traits< boost::mpl::vector2< ndnSIM::probability_policy_traits, Policy > > > super;
+ typedef ContentStoreImpl<ndnSIM::multi_policy_traits<boost::mpl::
+ vector2<ndnSIM::probability_policy_traits,
+ Policy>>> super;
typedef typename super::policy_container::template index<0>::type probability_policy_container;
- ContentStoreWithProbability () {};
-
- static TypeId
- GetTypeId ();
-private:
+ ContentStoreWithProbability(){};
- void SetCacheProbability (double probability)
+ static TypeId
+ GetTypeId();
+
+private:
+ void
+ SetCacheProbability(double probability)
{
- this->getPolicy ()
- .template get<probability_policy_container> ()
- .set_probability (probability);
+ this->getPolicy().template get<probability_policy_container>().set_probability(probability);
}
double
- GetCacheProbability () const
+ GetCacheProbability() const
{
- return
- this->getPolicy ()
- .template get<probability_policy_container> ()
- .get_probability ();
+ return this->getPolicy().template get<probability_policy_container>().get_probability();
}
};
@@ -76,26 +75,25 @@
template<class Policy>
TypeId
-ContentStoreWithProbability< Policy >::GetTypeId ()
+ContentStoreWithProbability<Policy>::GetTypeId()
{
- static TypeId tid = TypeId (("ns3::ndn::cs::Probability::"+Policy::GetName ()).c_str ())
- .SetGroupName ("Ndn")
- .SetParent<super> ()
- .template AddConstructor< ContentStoreWithProbability< Policy > > ()
+ static TypeId tid =
+ TypeId(("ns3::ndn::cs::Probability::" + Policy::GetName()).c_str())
+ .SetGroupName("Ndn")
+ .SetParent<super>()
+ .template AddConstructor<ContentStoreWithProbability<Policy>>()
- .AddAttribute ("CacheProbability",
- "Set probability of caching in ContentStore. "
- "If 1, every content is cached. If 0, no content is cached.",
- DoubleValue (1.0),//(+)
- MakeDoubleAccessor (&ContentStoreWithProbability< Policy >::GetCacheProbability,
- &ContentStoreWithProbability< Policy >::SetCacheProbability),
- MakeDoubleChecker<double> ())
- ;
+ .AddAttribute("CacheProbability",
+ "Set probability of caching in ContentStore. "
+ "If 1, every content is cached. If 0, no content is cached.",
+ DoubleValue(1.0), //(+)
+ MakeDoubleAccessor(&ContentStoreWithProbability<Policy>::GetCacheProbability,
+ &ContentStoreWithProbability<Policy>::SetCacheProbability),
+ MakeDoubleChecker<double>());
return tid;
}
-
} // namespace cs
} // namespace ndn
} // namespace ns3
diff --git a/model/cs/content-store-with-stats.cpp b/model/cs/content-store-with-stats.cpp
index 7d6e567..1a44e37 100644
--- a/model/cs/content-store-with-stats.cpp
+++ b/model/cs/content-store-with-stats.cpp
@@ -25,14 +25,14 @@
#include "../../utils/trie/fifo-policy.hpp"
#include "../../utils/trie/lfu-policy.hpp"
-#define NS_OBJECT_ENSURE_REGISTERED_TEMPL(type, templ) \
- static struct X ## type ## templ ## RegistrationClass \
- { \
- X ## type ## templ ## RegistrationClass () { \
- ns3::TypeId tid = type<templ>::GetTypeId (); \
- tid.GetParent (); \
- } \
- } x_ ## type ## templ ## RegistrationVariable
+#define NS_OBJECT_ENSURE_REGISTERED_TEMPL(type, templ) \
+ static struct X##type##templ##RegistrationClass { \
+ X##type##templ##RegistrationClass() \
+ { \
+ ns3::TypeId tid = type<templ>::GetTypeId(); \
+ tid.GetParent(); \
+ } \
+ } x_##type##templ##RegistrationVariable
namespace ns3 {
namespace ndn {
@@ -68,31 +68,33 @@
NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithStats, lfu_policy_traits);
-
#ifdef DOXYGEN
// /**
// * \brief Content Store with stats implementing LRU cache replacement policy
// */
-class Stats::Lru : public ContentStoreWithStats<lru_policy_traits> { };
+class Stats::Lru : public ContentStoreWithStats<lru_policy_traits> {
+};
/**
* \brief Content Store with stats implementing FIFO cache replacement policy
*/
-class Stats::Fifo : public ContentStoreWithStats<fifo_policy_traits> { };
+class Stats::Fifo : public ContentStoreWithStats<fifo_policy_traits> {
+};
/**
* \brief Content Store with stats implementing Random cache replacement policy
*/
-class Stats::Random : public ContentStoreWithStats<random_policy_traits> { };
+class Stats::Random : public ContentStoreWithStats<random_policy_traits> {
+};
/**
* \brief Content Store with stats implementing Least Frequently Used cache replacement policy
*/
-class Stats::Lfu : public ContentStoreWithStats<lfu_policy_traits> { };
+class Stats::Lfu : public ContentStoreWithStats<lfu_policy_traits> {
+};
#endif
-
} // namespace cs
} // namespace ndn
} // namespace ns3
diff --git a/model/cs/content-store-with-stats.hpp b/model/cs/content-store-with-stats.hpp
index 542b88c..b5f7540 100644
--- a/model/cs/content-store-with-stats.hpp
+++ b/model/cs/content-store-with-stats.hpp
@@ -37,54 +37,62 @@
* @brief Special content store realization that provides ability to track stats of CS operations
*/
template<class Policy>
-class ContentStoreWithStats :
- public ContentStoreImpl< ndnSIM::multi_policy_traits< boost::mpl::vector2< Policy, ndnSIM::lifetime_stats_policy_traits > > >
-{
+class ContentStoreWithStats
+ : public ContentStoreImpl<ndnSIM::
+ multi_policy_traits<boost::mpl::
+ vector2<Policy,
+ ndnSIM::
+ lifetime_stats_policy_traits>>> {
public:
- typedef ContentStoreImpl< ndnSIM::multi_policy_traits< boost::mpl::vector2< Policy, ndnSIM::lifetime_stats_policy_traits > > > super;
+ typedef ContentStoreImpl<ndnSIM::
+ multi_policy_traits<boost::mpl::
+ vector2<Policy,
+ ndnSIM::lifetime_stats_policy_traits>>>
+ super;
typedef typename super::policy_container::template index<1>::type lifetime_stats_container;
- ContentStoreWithStats ()
+ ContentStoreWithStats()
{
// connect traceback to the policy
- super::getPolicy ().template get<1> ().set_traced_callback (&m_willRemoveEntry);
+ super::getPolicy().template get<1>().set_traced_callback(&m_willRemoveEntry);
}
static TypeId
- GetTypeId ();
+ GetTypeId();
virtual inline void
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
private:
static LogComponent g_log; ///< @brief Logging variable
- /// @brief trace of for entry removal: first parameter is pointer to the CS entry, second is how long entry was in the cache
- TracedCallback< Ptr<const Entry>, Time > m_willRemoveEntry;
+ /// @brief trace of for entry removal: first parameter is pointer to the CS entry, second is how
+ /// long entry was in the cache
+ TracedCallback<Ptr<const Entry>, Time> m_willRemoveEntry;
};
//////////////////////////////////////////
////////// Implementation ////////////////
//////////////////////////////////////////
-
template<class Policy>
-LogComponent
-ContentStoreWithStats< Policy >::g_log = LogComponent (("ndn.cs.Stats." + Policy::GetName ()).c_str ());
-
+LogComponent ContentStoreWithStats<Policy>::g_log = LogComponent(("ndn.cs.Stats."
+ + Policy::GetName()).c_str());
template<class Policy>
TypeId
-ContentStoreWithStats< Policy >::GetTypeId ()
+ContentStoreWithStats<Policy>::GetTypeId()
{
- static TypeId tid = TypeId (("ns3::ndn::cs::Stats::"+Policy::GetName ()).c_str ())
- .SetGroupName ("Ndn")
- .SetParent<super> ()
- .template AddConstructor< ContentStoreWithStats< Policy > > ()
+ static TypeId tid =
+ TypeId(("ns3::ndn::cs::Stats::" + Policy::GetName()).c_str())
+ .SetGroupName("Ndn")
+ .SetParent<super>()
+ .template AddConstructor<ContentStoreWithStats<Policy>>()
- .AddTraceSource ("WillRemoveEntry", "Trace called just before content store entry will be removed",
- MakeTraceSourceAccessor (&ContentStoreWithStats< Policy >::m_willRemoveEntry))
+ .AddTraceSource("WillRemoveEntry",
+ "Trace called just before content store entry will be removed",
+ MakeTraceSourceAccessor(&ContentStoreWithStats<Policy>::m_willRemoveEntry))
// trace stuff here
;
@@ -94,21 +102,18 @@
template<class Policy>
void
-ContentStoreWithStats< Policy >::Print (std::ostream &os) const
+ContentStoreWithStats<Policy>::Print(std::ostream& os) const
{
- // const freshness_policy_container &freshness = this->getPolicy ().template get<freshness_policy_container> ();
+ // const freshness_policy_container &freshness = this->getPolicy ().template
+ // get<freshness_policy_container> ();
- for (typename super::policy_container::const_iterator item = this->getPolicy ().begin ();
- item != this->getPolicy ().end ();
- item++)
- {
- Time alive = lifetime_stats_container::policy_base::get_time (&(*item)) - Simulator::Now ();
- os << item->payload ()->GetName () << "(alive: " << alive.ToDouble (Time::S) << "s)" << std::endl;
- }
+ for (typename super::policy_container::const_iterator item = this->getPolicy().begin();
+ item != this->getPolicy().end(); item++) {
+ Time alive = lifetime_stats_container::policy_base::get_time(&(*item)) - Simulator::Now();
+ os << item->payload()->GetName() << "(alive: " << alive.ToDouble(Time::S) << "s)" << std::endl;
+ }
}
-
-
} // namespace cs
} // namespace ndn
} // namespace ns3
diff --git a/model/cs/custom-policies/freshness-policy.hpp b/model/cs/custom-policies/freshness-policy.hpp
index b85635e..999c61d 100644
--- a/model/cs/custom-policies/freshness-policy.hpp
+++ b/model/cs/custom-policies/freshness-policy.hpp
@@ -35,126 +35,127 @@
/**
* @brief Traits for freshness policy
*/
-struct freshness_policy_traits
-{
+struct freshness_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return "Freshness"; }
-
- struct policy_hook_type : public boost::intrusive::set_member_hook<> { Time timeWhenShouldExpire; };
-
- template<class Container>
- struct container_hook
+ static std::string
+ GetName()
{
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+ return "Freshness";
+ }
+
+ struct policy_hook_type : public boost::intrusive::set_member_hook<> {
+ Time timeWhenShouldExpire;
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- static Time& get_freshness (typename Container::iterator item)
+ template<class Container>
+ struct container_hook {
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ static Time&
+ get_freshness(typename Container::iterator item)
{
- return static_cast<typename policy_container::value_traits::hook_type*>
- (policy_container::value_traits::to_node_ptr(*item))->timeWhenShouldExpire;
+ return static_cast<typename policy_container::value_traits::hook_type*>(
+ policy_container::value_traits::to_node_ptr(*item))->timeWhenShouldExpire;
}
- static const Time& get_freshness (typename Container::const_iterator item)
+ static const Time&
+ get_freshness(typename Container::const_iterator item)
{
- return static_cast<const typename policy_container::value_traits::hook_type*>
- (policy_container::value_traits::to_node_ptr(*item))->timeWhenShouldExpire;
+ return static_cast<const typename policy_container::value_traits::hook_type*>(
+ policy_container::value_traits::to_node_ptr(*item))->timeWhenShouldExpire;
}
template<class Key>
- struct MemberHookLess
- {
- bool operator () (const Key &a, const Key &b) const
+ struct MemberHookLess {
+ bool
+ operator()(const Key& a, const Key& b) const
{
- return get_freshness (&a) < get_freshness (&b);
+ return get_freshness(&a) < get_freshness(&b);
}
};
- typedef boost::intrusive::multiset< Container,
- boost::intrusive::compare< MemberHookLess< Container > >,
- Hook > policy_container;
+ typedef boost::intrusive::multiset<Container,
+ boost::intrusive::compare<MemberHookLess<Container>>,
+ Hook> policy_container;
-
- class type : public policy_container
- {
+ class type : public policy_container {
public:
typedef policy policy_base; // to get access to get_freshness methods from outside
typedef Container parent_trie;
- type (Base &base)
- : base_ (base)
- , max_size_ (100)
+ type(Base& base)
+ : base_(base)
+ , max_size_(100)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
// do nothing
}
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
// get_time (item) = Simulator::Now ();
- Time freshness = item->payload ()->GetData ()->GetFreshness ();
- if (!freshness.IsZero ())
- {
- get_freshness (item) = Simulator::Now () + freshness;
+ Time freshness = item->payload()->GetData()->GetFreshness();
+ if (!freshness.IsZero()) {
+ get_freshness(item) = Simulator::Now() + freshness;
- // push item only if freshness is non zero. otherwise, this payload is not controlled by the policy
- // note that .size() on this policy would return only number of items with non-infinite freshness policy
- policy_container::insert (*item);
- }
+ // push item only if freshness is non zero. otherwise, this payload is not controlled by
+ // the policy
+ // note that .size() on this policy would return only number of items with non-infinite
+ // freshness policy
+ policy_container::insert(*item);
+ }
return true;
}
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
// do nothing. it's random policy
}
inline void
- erase (typename parent_trie::iterator item)
+ erase(typename parent_trie::iterator item)
{
- if (!item->payload ()->GetData ()->GetFreshness ().IsZero ())
- {
- // erase only if freshness is non zero (otherwise an item is not in the policy
- policy_container::erase (policy_container::s_iterator_to (*item));
- }
+ if (!item->payload()->GetData()->GetFreshness().IsZero()) {
+ // erase only if freshness is non zero (otherwise an item is not in the policy
+ policy_container::erase(policy_container::s_iterator_to(*item));
+ }
}
inline void
- clear ()
+ clear()
{
- policy_container::clear ();
+ policy_container::clear();
}
inline void
- set_max_size (size_t max_size)
+ set_max_size(size_t max_size)
{
max_size_ = max_size;
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
return max_size_;
}
private:
- type () : base_(*((Base*)0)) { };
+ type()
+ : base_(*((Base*)0)){};
private:
- Base &base_;
+ Base& base_;
size_t max_size_;
};
};
diff --git a/model/cs/custom-policies/lifetime-stats-policy.hpp b/model/cs/custom-policies/lifetime-stats-policy.hpp
index 905f532..1102ef1 100644
--- a/model/cs/custom-policies/lifetime-stats-policy.hpp
+++ b/model/cs/custom-policies/lifetime-stats-policy.hpp
@@ -35,119 +35,122 @@
/**
* @brief Traits for lifetime stats policy
*/
-struct lifetime_stats_policy_traits
-{
+struct lifetime_stats_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return "LifetimeStats"; }
-
- struct policy_hook_type : public boost::intrusive::list_member_hook<> { Time timeWhenAdded; };
-
- template<class Container>
- struct container_hook
+ static std::string
+ GetName()
{
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+ return "LifetimeStats";
+ }
+
+ struct policy_hook_type : public boost::intrusive::list_member_hook<> {
+ Time timeWhenAdded;
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- typedef typename boost::intrusive::list< Container, Hook > policy_container;
-
- static Time& get_time (typename Container::iterator item)
+ template<class Container>
+ struct container_hook {
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ typedef typename boost::intrusive::list<Container, Hook> policy_container;
+
+ static Time&
+ get_time(typename Container::iterator item)
{
- return static_cast<typename policy_container::value_traits::hook_type*>
- (policy_container::value_traits::to_node_ptr(*item))->timeWhenAdded;
- }
-
- static const Time& get_time (typename Container::const_iterator item)
- {
- return static_cast<const typename policy_container::value_traits::hook_type*>
- (policy_container::value_traits::to_node_ptr(*item))->timeWhenAdded;
+ return static_cast<typename policy_container::value_traits::hook_type*>(
+ policy_container::value_traits::to_node_ptr(*item))->timeWhenAdded;
}
- class type : public policy_container
+ static const Time&
+ get_time(typename Container::const_iterator item)
{
+ return static_cast<const typename policy_container::value_traits::hook_type*>(
+ policy_container::value_traits::to_node_ptr(*item))->timeWhenAdded;
+ }
+
+ class type : public policy_container {
public:
typedef policy policy_base; // to get access to get_time methods from outside
typedef Container parent_trie;
- type (Base &base)
- : base_ (base)
- , max_size_ (100)
- , m_willRemoveEntry (0)
+ type(Base& base)
+ : base_(base)
+ , max_size_(100)
+ , m_willRemoveEntry(0)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
// do nothing. it's random policy
}
-
- inline bool
- insert (typename parent_trie::iterator item)
- {
- get_time (item) = Simulator::Now ();
- policy_container::push_back (*item);
+ inline bool
+ insert(typename parent_trie::iterator item)
+ {
+ get_time(item) = Simulator::Now();
+
+ policy_container::push_back(*item);
return true;
}
-
+
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
// do nothing. it's random policy
}
-
- inline void
- erase (typename parent_trie::iterator item)
- {
- Time lifetime = Simulator::Now () - get_time (item);
- if (m_willRemoveEntry != 0)
- {
- (*m_willRemoveEntry) (item->payload (), lifetime);
- }
-
- policy_container::erase (policy_container::s_iterator_to (*item));
+ inline void
+ erase(typename parent_trie::iterator item)
+ {
+ Time lifetime = Simulator::Now() - get_time(item);
+
+ if (m_willRemoveEntry != 0) {
+ (*m_willRemoveEntry)(item->payload(), lifetime);
+ }
+
+ policy_container::erase(policy_container::s_iterator_to(*item));
}
inline void
- clear ()
+ clear()
{
- policy_container::clear ();
+ policy_container::clear();
}
inline void
- set_max_size (size_t max_size)
+ set_max_size(size_t max_size)
{
max_size_ = max_size;
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
return max_size_;
}
void
- set_traced_callback (TracedCallback< typename parent_trie::payload_traits::const_base_type, Time > *callback)
+ set_traced_callback(
+ TracedCallback<typename parent_trie::payload_traits::const_base_type, Time>* callback)
{
m_willRemoveEntry = callback;
}
-
+
private:
- type () : base_(*((Base*)0)) { };
-
+ type()
+ : base_(*((Base*)0)){};
+
private:
- Base &base_;
+ Base& base_;
size_t max_size_;
- TracedCallback< typename parent_trie::payload_traits::const_base_type, Time > *m_willRemoveEntry;
+ TracedCallback<typename parent_trie::payload_traits::const_base_type, Time>*
+ m_willRemoveEntry;
};
};
};
diff --git a/model/cs/custom-policies/probability-policy.hpp b/model/cs/custom-policies/probability-policy.hpp
index 0c3088c..57d6835 100644
--- a/model/cs/custom-policies/probability-policy.hpp
+++ b/model/cs/custom-policies/probability-policy.hpp
@@ -33,109 +33,106 @@
/**
* @brief Traits for freshness policy
*/
-struct probability_policy_traits
-{
- static std::string GetName () { return "ProbabilityImpl"; }
-
- struct policy_hook_type : public boost::intrusive::list_member_hook<> {};
-
- template<class Container>
- struct container_hook
+struct probability_policy_traits {
+ static std::string
+ GetName()
{
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+ return "ProbabilityImpl";
+ }
+
+ struct policy_hook_type : public boost::intrusive::list_member_hook<> {
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- typedef typename boost::intrusive::list< Container, Hook > policy_container;
-
- class type : public policy_container
- {
+ template<class Container>
+ struct container_hook {
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ typedef typename boost::intrusive::list<Container, Hook> policy_container;
+
+ class type : public policy_container {
public:
typedef policy policy_base; // to get access to get_freshness methods from outside
typedef Container parent_trie;
- type (Base &base)
- : base_ (base)
- , max_size_ (100)
- , probability_ (1.0)
+ type(Base& base)
+ : base_(base)
+ , max_size_(100)
+ , probability_(1.0)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
}
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- if (ns3_rand_.GetValue () < probability_)
- {
- policy_container::push_back (*item);
+ if (ns3_rand_.GetValue() < probability_) {
+ policy_container::push_back(*item);
- // allow caching
- return true;
- }
- else
- {
- // don't allow caching
- return false;
- }
+ // allow caching
+ return true;
+ }
+ else {
+ // don't allow caching
+ return false;
+ }
}
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
// do nothing. it's random policy
}
inline void
- erase (typename parent_trie::iterator item)
+ erase(typename parent_trie::iterator item)
{
- policy_container::erase (policy_container::s_iterator_to (*item));
+ policy_container::erase(policy_container::s_iterator_to(*item));
}
inline void
- clear ()
+ clear()
{
- policy_container::clear ();
+ policy_container::clear();
}
inline void
- set_max_size (size_t max_size)
+ set_max_size(size_t max_size)
{
max_size_ = max_size;
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
return max_size_;
}
inline void
- set_probability (double probability)
+ set_probability(double probability)
{
probability_ = probability;
}
inline double
- get_probability () const
+ get_probability() const
{
return probability_;
- }
+ }
private:
- type () : base_(*((Base*)0)) { };
+ type()
+ : base_(*((Base*)0)){};
private:
- Base &base_;
+ Base& base_;
size_t max_size_;
double probability_;
UniformVariable ns3_rand_;
diff --git a/model/cs/ndn-content-store.cpp b/model/cs/ndn-content-store.cpp
index 4d3bb65..3588eb9 100644
--- a/model/cs/ndn-content-store.cpp
+++ b/model/cs/ndn-content-store.cpp
@@ -17,7 +17,7 @@
*
* Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
* Ilya Moiseenko <iliamo@cs.ucla.edu>
- *
+ *
*/
#include "ndn-content-store.hpp"
@@ -25,32 +25,31 @@
#include "ns3/log.h"
#include "ns3/packet.h"
-NS_LOG_COMPONENT_DEFINE ("ndn.cs.ContentStore");
+NS_LOG_COMPONENT_DEFINE("ndn.cs.ContentStore");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (ContentStore);
+NS_OBJECT_ENSURE_REGISTERED(ContentStore);
TypeId
-ContentStore::GetTypeId (void)
+ContentStore::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::ContentStore")
- .SetGroupName ("Ndn")
- .SetParent<Object> ()
+ static TypeId tid =
+ TypeId("ns3::ndn::ContentStore")
+ .SetGroupName("Ndn")
+ .SetParent<Object>()
- .AddTraceSource ("CacheHits", "Trace called every time there is a cache hit",
- MakeTraceSourceAccessor (&ContentStore::m_cacheHitsTrace))
+ .AddTraceSource("CacheHits", "Trace called every time there is a cache hit",
+ MakeTraceSourceAccessor(&ContentStore::m_cacheHitsTrace))
- .AddTraceSource ("CacheMisses", "Trace called every time there is a cache miss",
- MakeTraceSourceAccessor (&ContentStore::m_cacheMissesTrace))
- ;
+ .AddTraceSource("CacheMisses", "Trace called every time there is a cache miss",
+ MakeTraceSourceAccessor(&ContentStore::m_cacheMissesTrace));
return tid;
}
-
-ContentStore::~ContentStore ()
+ContentStore::~ContentStore()
{
}
@@ -58,31 +57,30 @@
//////////////////////////////////////////////////////////////////////
-Entry::Entry (Ptr<ContentStore> cs, Ptr<const Data> data)
- : m_cs (cs)
- , m_data (data)
+Entry::Entry(Ptr<ContentStore> cs, Ptr<const Data> data)
+ : m_cs(cs)
+ , m_data(data)
{
}
const Name&
-Entry::GetName () const
+Entry::GetName() const
{
- return m_data->GetName ();
+ return m_data->GetName();
}
Ptr<const Data>
-Entry::GetData () const
+Entry::GetData() const
{
return m_data;
}
Ptr<ContentStore>
-Entry::GetContentStore ()
+Entry::GetContentStore()
{
return m_cs;
}
-
} // namespace cs
} // namespace ndn
} // namespace ns3
diff --git a/model/cs/ndn-content-store.hpp b/model/cs/ndn-content-store.hpp
index ae7c059..23266c4 100644
--- a/model/cs/ndn-content-store.hpp
+++ b/model/cs/ndn-content-store.hpp
@@ -20,7 +20,7 @@
*/
#ifndef NDN_CONTENT_STORE_H
-#define NDN_CONTENT_STORE_H
+#define NDN_CONTENT_STORE_H
#include "ns3/object.h"
#include "ns3/ptr.h"
@@ -54,8 +54,7 @@
* @ingroup ndn-cs
* @brief NDN content store entry
*/
-class Entry : public SimpleRefCount<Entry>
-{
+class Entry : public SimpleRefCount<Entry> {
public:
/**
* \brief Construct content store entry
@@ -66,27 +65,27 @@
* The constructor will make a copy of the supplied packet and calls
* RemoveHeader and RemoveTail on the copy.
*/
- Entry (Ptr<ContentStore> cs, Ptr<const Data> data);
+ Entry(Ptr<ContentStore> cs, Ptr<const Data> data);
/**
* \brief Get prefix of the stored entry
* \returns prefix of the stored entry
*/
const Name&
- GetName () const;
+ GetName() const;
/**
* \brief Get Data of the stored entry
* \returns Data of the stored entry
*/
Ptr<const Data>
- GetData () const;
+ GetData() const;
/**
* @brief Get pointer to access store, to which this entry is added
*/
Ptr<ContentStore>
- GetContentStore ();
+ GetContentStore();
private:
Ptr<ContentStore> m_cs; ///< \brief content store to which entry is added
@@ -95,29 +94,26 @@
} // namespace cs
-
/**
* @ingroup ndn-cs
* \brief Base class for NDN content store
*
* Particular implementations should implement Lookup, Add, and Print methods
*/
-class ContentStore : public Object
-{
+class ContentStore : public Object {
public:
/**
* \brief Interface ID
*
* \return interface ID
*/
- static
- TypeId GetTypeId ();
+ static TypeId
+ GetTypeId();
/**
* @brief Virtual destructor
*/
- virtual
- ~ContentStore ();
+ virtual ~ContentStore();
/**
* \brief Find corresponding CS entry for the given interest
@@ -129,7 +125,7 @@
* used entries index, \see m_contentStore
*/
virtual Ptr<Data>
- Lookup (Ptr<const Interest> interest) = 0;
+ Lookup(Ptr<const Interest> interest) = 0;
/**
* \brief Add a new content to the content store.
@@ -140,7 +136,7 @@
* @returns true if an existing entry was updated, false otherwise
*/
virtual bool
- Add (Ptr<const Data> data) = 0;
+ Add(Ptr<const Data> data) = 0;
// /*
// * \brief Add a new content to the content store.
@@ -155,32 +151,30 @@
* \brief Print out content store entries
*/
virtual void
- Print (std::ostream &os) const = 0;
-
+ Print(std::ostream& os) const = 0;
/**
* @brief Get number of entries in content store
*/
virtual uint32_t
- GetSize () const = 0;
+ GetSize() const = 0;
/**
* @brief Return first element of content store (no order guaranteed)
*/
virtual Ptr<cs::Entry>
- Begin () = 0;
+ Begin() = 0;
/**
* @brief Return item next after last (no order guaranteed)
*/
virtual Ptr<cs::Entry>
- End () = 0;
+ End() = 0;
/**
* @brief Advance the iterator
*/
- virtual Ptr<cs::Entry>
- Next (Ptr<cs::Entry>) = 0;
+ virtual Ptr<cs::Entry> Next(Ptr<cs::Entry>) = 0;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
@@ -190,29 +184,28 @@
* @brief Static call to cheat python bindings
*/
static inline Ptr<ContentStore>
- GetContentStore (Ptr<Object> node);
+ GetContentStore(Ptr<Object> node);
protected:
TracedCallback<Ptr<const Interest>,
- Ptr<const Data> > m_cacheHitsTrace; ///< @brief trace of cache hits
+ Ptr<const Data>> m_cacheHitsTrace; ///< @brief trace of cache hits
- TracedCallback<Ptr<const Interest> > m_cacheMissesTrace; ///< @brief trace of cache misses
+ TracedCallback<Ptr<const Interest>> m_cacheMissesTrace; ///< @brief trace of cache misses
};
inline std::ostream&
-operator<< (std::ostream &os, const ContentStore &cs)
+operator<<(std::ostream& os, const ContentStore& cs)
{
- cs.Print (os);
+ cs.Print(os);
return os;
}
inline Ptr<ContentStore>
-ContentStore::GetContentStore (Ptr<Object> node)
+ContentStore::GetContentStore(Ptr<Object> node)
{
- return node->GetObject<ContentStore> ();
+ return node->GetObject<ContentStore>();
}
-
} // namespace ndn
} // namespace ns3
diff --git a/model/ndn-app-face.cpp b/model/ndn-app-face.cpp
index 9125e2c..d267f6b 100644
--- a/model/ndn-app-face.cpp
+++ b/model/ndn-app-face.cpp
@@ -34,45 +34,42 @@
#include "ndn-interest.hpp"
#include "ndn-data.hpp"
-NS_LOG_COMPONENT_DEFINE ("ndn.AppFace");
+NS_LOG_COMPONENT_DEFINE("ndn.AppFace");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (AppFace);
+NS_OBJECT_ENSURE_REGISTERED(AppFace);
TypeId
-AppFace::GetTypeId ()
+AppFace::GetTypeId()
{
- static TypeId tid = TypeId ("ns3::ndn::AppFace")
- .SetParent<Face> ()
- .SetGroupName ("Ndn")
- ;
+ static TypeId tid = TypeId("ns3::ndn::AppFace").SetParent<Face>().SetGroupName("Ndn");
return tid;
}
-AppFace::AppFace (Ptr<App> app)
- : Face (app->GetNode ())
- , m_app (app)
+AppFace::AppFace(Ptr<App> app)
+ : Face(app->GetNode())
+ , m_app(app)
{
- NS_LOG_FUNCTION (this << app);
-
- NS_ASSERT (m_app != 0);
- SetFlags (Face::APPLICATION);
+ NS_LOG_FUNCTION(this << app);
+
+ NS_ASSERT(m_app != 0);
+ SetFlags(Face::APPLICATION);
}
-AppFace::~AppFace ()
+AppFace::~AppFace()
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
}
-AppFace::AppFace ()
- : Face (0)
+AppFace::AppFace()
+ : Face(0)
{
}
-AppFace::AppFace (const AppFace &)
- : Face (0)
+AppFace::AppFace(const AppFace&)
+ : Face(0)
{
}
@@ -83,39 +80,37 @@
}
bool
-AppFace::SendInterest (Ptr<const Interest> interest)
+AppFace::SendInterest(Ptr<const Interest> interest)
{
- NS_LOG_FUNCTION (this << interest);
+ NS_LOG_FUNCTION(this << interest);
- if (!IsUp ())
- {
- return false;
- }
+ if (!IsUp()) {
+ return false;
+ }
- if (interest->GetNack () > 0)
- m_app->OnNack (interest);
+ if (interest->GetNack() > 0)
+ m_app->OnNack(interest);
else
- m_app->OnInterest (interest);
-
+ m_app->OnInterest(interest);
+
return true;
}
bool
-AppFace::SendData (Ptr<const Data> data)
+AppFace::SendData(Ptr<const Data> data)
{
- NS_LOG_FUNCTION (this << data);
+ NS_LOG_FUNCTION(this << data);
- if (!IsUp ())
- {
- return false;
- }
+ if (!IsUp()) {
+ return false;
+ }
- m_app->OnData (data);
+ m_app->OnData(data);
return true;
}
std::ostream&
-AppFace::Print (std::ostream& os) const
+AppFace::Print(std::ostream& os) const
{
os << "dev=local(" << GetId() << ")";
return os;
@@ -123,4 +118,3 @@
} // namespace ndn
} // namespace ns3
-
diff --git a/model/ndn-app-face.hpp b/model/ndn-app-face.hpp
index 3663be0..6d8be19 100644
--- a/model/ndn-app-face.hpp
+++ b/model/ndn-app-face.hpp
@@ -49,35 +49,35 @@
*
* \see AppFace, NdnNetDeviceFace, NdnIpv4Face, NdnUdpFace
*/
-class AppFace : public Face
-{
+class AppFace : public Face {
public:
static TypeId
- GetTypeId ();
+ GetTypeId();
/**
* \brief Default constructor
*/
- AppFace (Ptr<App> app);
+ AppFace(Ptr<App> app);
virtual ~AppFace();
-
+
////////////////////////////////////////////////////////////////////
// methods overloaded from Face
virtual bool
- SendInterest (Ptr<const Interest> interest);
+ SendInterest(Ptr<const Interest> interest);
virtual bool
- SendData (Ptr<const Data> data);
+ SendData(Ptr<const Data> data);
public:
virtual std::ostream&
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
////////////////////////////////////////////////////////////////////
-
+
private:
- AppFace ();
- AppFace (const AppFace &); ///< \brief Disabled copy constructor
- AppFace& operator= (const AppFace &); ///< \brief Disabled copy operator
+ AppFace();
+ AppFace(const AppFace&); ///< \brief Disabled copy constructor
+ AppFace&
+ operator=(const AppFace&); ///< \brief Disabled copy operator
private:
Ptr<App> m_app;
diff --git a/model/ndn-common.hpp b/model/ndn-common.hpp
index 8bfc4f9..f5da38b 100644
--- a/model/ndn-common.hpp
+++ b/model/ndn-common.hpp
@@ -1,10 +1,10 @@
/** -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
+/*
* Copyright (c) 2013, Regents of the University of California
* Alexander Afanasyev
- *
+ *
* BSD license, See the doc/LICENSE file for more information
- *
+ *
* Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
@@ -16,8 +16,12 @@
#define NDNSIM_MODE 1
-#define NDN_NAMESPACE_BEGIN namespace ns3 { namespace ndn {
-#define NDN_NAMESPACE_END } /*ndn*/ } /*ns3*/
+#define NDN_NAMESPACE_BEGIN \
+ namespace ns3 { \
+ namespace ndn {
+#define NDN_NAMESPACE_END \
+ } /*ndn*/ \
+ } /*ns3*/
/**
* @brief NS-3 namespace
@@ -29,22 +33,19 @@
*/
namespace ndn {
}
-
}
NDN_NAMESPACE_BEGIN
typedef Time TimeInterval;
-namespace time
-{
+namespace time {
inline Time
-NowUnixTimestamp ()
+NowUnixTimestamp()
{
- return Simulator::Now ();
+ return Simulator::Now();
}
-
}
NDN_NAMESPACE_END
diff --git a/model/ndn-face.cpp b/model/ndn-face.cpp
index 6b23dd7..505c2b4 100644
--- a/model/ndn-face.cpp
+++ b/model/ndn-face.cpp
@@ -39,25 +39,24 @@
#include <boost/ref.hpp>
-NS_LOG_COMPONENT_DEFINE ("ndn.Face");
+NS_LOG_COMPONENT_DEFINE("ndn.Face");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (Face);
+NS_OBJECT_ENSURE_REGISTERED(Face);
TypeId
-Face::GetTypeId ()
+Face::GetTypeId()
{
- static TypeId tid = TypeId ("ns3::ndn::Face")
- .SetParent<Object> ()
- .SetGroupName ("Ndn")
- .AddAttribute ("Id", "Face id (unique integer for the Ndn stack on this node)",
- TypeId::ATTR_GET, // allow only getting it.
- UintegerValue (0),
- MakeUintegerAccessor (&Face::m_id),
- MakeUintegerChecker<uint32_t> ())
- ;
+ static TypeId tid =
+ TypeId("ns3::ndn::Face")
+ .SetParent<Object>()
+ .SetGroupName("Ndn")
+ .AddAttribute("Id", "Face id (unique integer for the Ndn stack on this node)",
+ TypeId::ATTR_GET, // allow only getting it.
+ UintegerValue(0), MakeUintegerAccessor(&Face::m_id),
+ MakeUintegerChecker<uint32_t>());
return tid;
}
@@ -66,26 +65,26 @@
* with no IP addresses. Before becoming useable, the user must
* invoke SetUp on them once an Ndn address and mask have been set.
*/
-Face::Face (Ptr<Node> node)
- : m_node (node)
- , m_upstreamInterestHandler (MakeNullCallback< void, Ptr<Face>, Ptr<Interest> > ())
- , m_upstreamDataHandler (MakeNullCallback< void, Ptr<Face>, Ptr<Data> > ())
- , m_ifup (false)
- , m_id ((uint32_t)-1)
- , m_metric (0)
- , m_flags (0)
+Face::Face(Ptr<Node> node)
+ : m_node(node)
+ , m_upstreamInterestHandler(MakeNullCallback<void, Ptr<Face>, Ptr<Interest>>())
+ , m_upstreamDataHandler(MakeNullCallback<void, Ptr<Face>, Ptr<Data>>())
+ , m_ifup(false)
+ , m_id((uint32_t)-1)
+ , m_metric(0)
+ , m_flags(0)
{
- NS_LOG_FUNCTION (this << node);
+ NS_LOG_FUNCTION(this << node);
- NS_ASSERT_MSG (node != 0, "node cannot be NULL. Check the code");
+ NS_ASSERT_MSG(node != 0, "node cannot be NULL. Check the code");
}
-Face::~Face ()
+Face::~Face()
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
}
-Face::Face (const Face &)
+Face::Face(const Face&)
{
}
@@ -95,152 +94,146 @@
}
Ptr<Node>
-Face::GetNode () const
+Face::GetNode() const
{
return m_node;
}
void
-Face::RegisterProtocolHandlers (const InterestHandler &interestHandler, const DataHandler &dataHandler)
+Face::RegisterProtocolHandlers(const InterestHandler& interestHandler,
+ const DataHandler& dataHandler)
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
m_upstreamInterestHandler = interestHandler;
m_upstreamDataHandler = dataHandler;
}
void
-Face::UnRegisterProtocolHandlers ()
+Face::UnRegisterProtocolHandlers()
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
- m_upstreamInterestHandler = MakeNullCallback< void, Ptr<Face>, Ptr<Interest> > ();
- m_upstreamDataHandler = MakeNullCallback< void, Ptr<Face>, Ptr<Data> > ();
-}
-
-
-bool
-Face::SendInterest (Ptr<const Interest> interest)
-{
- NS_LOG_FUNCTION (this << boost::cref (*this) << interest->GetName ());
-
- if (!IsUp ())
- {
- return false;
- }
-
- return Send (Wire::FromInterest (interest));
+ m_upstreamInterestHandler = MakeNullCallback<void, Ptr<Face>, Ptr<Interest>>();
+ m_upstreamDataHandler = MakeNullCallback<void, Ptr<Face>, Ptr<Data>>();
}
bool
-Face::SendData (Ptr<const Data> data)
+Face::SendInterest(Ptr<const Interest> interest)
{
- NS_LOG_FUNCTION (this << data);
+ NS_LOG_FUNCTION(this << boost::cref(*this) << interest->GetName());
- if (!IsUp ())
- {
- return false;
- }
+ if (!IsUp()) {
+ return false;
+ }
- return Send (Wire::FromData (data));
+ return Send(Wire::FromInterest(interest));
}
bool
-Face::Send (Ptr<Packet> packet)
+Face::SendData(Ptr<const Data> data)
+{
+ NS_LOG_FUNCTION(this << data);
+
+ if (!IsUp()) {
+ return false;
+ }
+
+ return Send(Wire::FromData(data));
+}
+
+bool
+Face::Send(Ptr<Packet> packet)
{
FwHopCountTag hopCount;
- bool tagExists = packet->RemovePacketTag (hopCount);
- if (tagExists)
- {
- hopCount.Increment ();
- packet->AddPacketTag (hopCount);
- }
+ bool tagExists = packet->RemovePacketTag(hopCount);
+ if (tagExists) {
+ hopCount.Increment();
+ packet->AddPacketTag(hopCount);
+ }
return true;
}
bool
-Face::Receive (Ptr<const Packet> p)
+Face::Receive(Ptr<const Packet> p)
{
- NS_LOG_FUNCTION (this << p << p->GetSize ());
+ NS_LOG_FUNCTION(this << p << p->GetSize());
- if (!IsUp ())
- {
- // no tracing here. If we were off while receiving, we shouldn't even know that something was there
+ if (!IsUp()) {
+ // no tracing here. If we were off while receiving, we shouldn't even know that something was
+ // there
+ return false;
+ }
+
+ Ptr<Packet> packet = p->Copy(); // give upper layers a rw copy of the packet
+ try {
+ HeaderHelper::Type type = HeaderHelper::GetNdnHeaderType(packet);
+ switch (type) {
+ case HeaderHelper::INTEREST_NDNSIM:
+ return ReceiveInterest(Wire::ToInterest(packet, Wire::WIRE_FORMAT_NDNSIM));
+ case HeaderHelper::INTEREST_CCNB:
+ return ReceiveInterest(Wire::ToInterest(packet, Wire::WIRE_FORMAT_CCNB));
+ case HeaderHelper::CONTENT_OBJECT_NDNSIM:
+ return ReceiveData(Wire::ToData(packet, Wire::WIRE_FORMAT_NDNSIM));
+ case HeaderHelper::CONTENT_OBJECT_CCNB:
+ return ReceiveData(Wire::ToData(packet, Wire::WIRE_FORMAT_CCNB));
+ default:
+ NS_FATAL_ERROR("Not supported NDN header");
return false;
}
- Ptr<Packet> packet = p->Copy (); // give upper layers a rw copy of the packet
- try
- {
- HeaderHelper::Type type = HeaderHelper::GetNdnHeaderType (packet);
- switch (type)
- {
- case HeaderHelper::INTEREST_NDNSIM:
- return ReceiveInterest (Wire::ToInterest (packet, Wire::WIRE_FORMAT_NDNSIM));
- case HeaderHelper::INTEREST_CCNB:
- return ReceiveInterest (Wire::ToInterest (packet, Wire::WIRE_FORMAT_CCNB));
- case HeaderHelper::CONTENT_OBJECT_NDNSIM:
- return ReceiveData (Wire::ToData (packet, Wire::WIRE_FORMAT_NDNSIM));
- case HeaderHelper::CONTENT_OBJECT_CCNB:
- return ReceiveData (Wire::ToData (packet, Wire::WIRE_FORMAT_CCNB));
- default:
- NS_FATAL_ERROR ("Not supported NDN header");
- return false;
- }
-
- // exception will be thrown if packet is not recognized
- }
- catch (UnknownHeaderException)
- {
- NS_FATAL_ERROR ("Unknown NDN header. Should not happen");
- return false;
- }
+ // exception will be thrown if packet is not recognized
+ }
+ catch (UnknownHeaderException) {
+ NS_FATAL_ERROR("Unknown NDN header. Should not happen");
+ return false;
+ }
return false;
}
bool
-Face::ReceiveInterest (Ptr<Interest> interest)
+Face::ReceiveInterest(Ptr<Interest> interest)
{
- if (!IsUp ())
- {
- // no tracing here. If we were off while receiving, we shouldn't even know that something was there
- return false;
- }
+ if (!IsUp()) {
+ // no tracing here. If we were off while receiving, we shouldn't even know that something was
+ // there
+ return false;
+ }
- m_upstreamInterestHandler (this, interest);
+ m_upstreamInterestHandler(this, interest);
return true;
}
bool
-Face::ReceiveData (Ptr<Data> data)
+Face::ReceiveData(Ptr<Data> data)
{
- if (!IsUp ())
- {
- // no tracing here. If we were off while receiving, we shouldn't even know that something was there
- return false;
- }
+ if (!IsUp()) {
+ // no tracing here. If we were off while receiving, we shouldn't even know that something was
+ // there
+ return false;
+ }
- m_upstreamDataHandler (this, data);
+ m_upstreamDataHandler(this, data);
return true;
}
void
-Face::SetMetric (uint16_t metric)
+Face::SetMetric(uint16_t metric)
{
- NS_LOG_FUNCTION (metric);
+ NS_LOG_FUNCTION(metric);
m_metric = metric;
}
uint16_t
-Face::GetMetric (void) const
+Face::GetMetric(void) const
{
return m_metric;
}
void
-Face::SetFlags (uint32_t flags)
+Face::SetFlags(uint32_t flags)
{
m_flags = flags;
}
@@ -248,8 +241,9 @@
bool
Face::operator== (const Face &face) const
{
- NS_ASSERT_MSG (m_node->GetId () == face.m_node->GetId (),
- "Faces of different nodes should not be compared to each other: " << *this << " == " << face);
+ NS_ASSERT_MSG(m_node->GetId() == face.m_node->GetId(),
+ "Faces of different nodes should not be compared to each other: " << *this << " == "
+ << face);
return (m_id == face.m_id);
}
@@ -257,26 +251,26 @@
bool
Face::operator< (const Face &face) const
{
- NS_ASSERT_MSG (m_node->GetId () == face.m_node->GetId (),
- "Faces of different nodes should not be compared to each other: " << *this << " == " << face);
+ NS_ASSERT_MSG(m_node->GetId() == face.m_node->GetId(),
+ "Faces of different nodes should not be compared to each other: " << *this << " == "
+ << face);
return (m_id < face.m_id);
}
std::ostream&
-Face::Print (std::ostream &os) const
+Face::Print(std::ostream& os) const
{
- os << "id=" << GetId ();
+ os << "id=" << GetId();
return os;
}
std::ostream&
-operator<< (std::ostream& os, const Face &face)
+operator<<(std::ostream& os, const Face& face)
{
- face.Print (os);
+ face.Print(os);
return os;
}
} // namespace ndn
} // namespace ns3
-
diff --git a/model/ndn-face.hpp b/model/ndn-face.hpp
index bf0a9b2..b8cd098 100644
--- a/model/ndn-face.hpp
+++ b/model/ndn-face.hpp
@@ -55,12 +55,10 @@
*
* \see ndn::AppFace, ndn::NetDeviceFace
*/
-class Face :
- public Object
-{
+class Face : public Object {
public:
static TypeId
- GetTypeId ();
+ GetTypeId();
/**
* \brief NDN protocol handlers
@@ -68,20 +66,20 @@
* \param face Face from which packet has been received
* \param packet Original packet
*/
- typedef Callback<void, Ptr<Face>, Ptr<Interest> > InterestHandler;
- typedef Callback<void, Ptr<Face>, Ptr<Data> > DataHandler;
+ typedef Callback<void, Ptr<Face>, Ptr<Interest>> InterestHandler;
+ typedef Callback<void, Ptr<Face>, Ptr<Data>> DataHandler;
/**
* \brief Default constructor
*/
- Face (Ptr<Node> node);
+ Face(Ptr<Node> node);
virtual ~Face();
/**
* @brief Get node to which this face is associated
*/
Ptr<Node>
- GetNode () const;
+ GetNode() const;
////////////////////////////////////////////////////////////////////
@@ -91,7 +89,7 @@
* This method should call protocol-dependent registration function
*/
virtual void
- RegisterProtocolHandlers (const InterestHandler &interestHandler, const DataHandler &dataHandler);
+ RegisterProtocolHandlers(const InterestHandler& interestHandler, const DataHandler& dataHandler);
/**
* \brief Un-Register callback to call when new packet arrives on the face
@@ -99,7 +97,7 @@
* This method should call protocol-dependent registration function
*/
virtual void
- UnRegisterProtocolHandlers ();
+ UnRegisterProtocolHandlers();
/**
* @brief Send out interest through the face
@@ -109,7 +107,7 @@
* @returns true if interest is considered to be send out (enqueued)
*/
virtual bool
- SendInterest (Ptr<const Interest> interest);
+ SendInterest(Ptr<const Interest> interest);
/**
* @brief Send out Dat packet through the face
@@ -119,7 +117,7 @@
* @returns true if Data packet is considered to be send out (enqueued)
*/
virtual bool
- SendData (Ptr<const Data> data);
+ SendData(Ptr<const Data> data);
/**
* \brief Receive interest from application or another node and forward it up to the NDN stack
@@ -127,7 +125,7 @@
* By default it is called from inside Receive method, but can be used directly, if appropriate
*/
virtual bool
- ReceiveInterest (Ptr<Interest> interest);
+ ReceiveInterest(Ptr<Interest> interest);
/**
* \brief Receive Data packet from application or another node and forward it up to the NDN stack
@@ -135,7 +133,7 @@
* By default it is called from inside Receive method, but can be used directly, if appropriate
*/
virtual bool
- ReceiveData (Ptr<Data> data);
+ ReceiveData(Ptr<Data> data);
////////////////////////////////////////////////////////////////////
/**
@@ -144,7 +142,7 @@
* \param metric configured routing metric (cost) of this face
*/
virtual void
- SetMetric (uint16_t metric);
+ SetMetric(uint16_t metric);
/**
* \brief Get routing/forwarding metric assigned to the face
@@ -152,7 +150,7 @@
* \returns configured routing/forwarding metric (cost) of this face
*/
virtual uint16_t
- GetMetric (void) const;
+ GetMetric(void) const;
/**
* These are face states and may be distinct from actual lower-layer
@@ -164,39 +162,39 @@
* \brief Enable or disable this face
*/
inline void
- SetUp (bool up = true);
+ SetUp(bool up = true);
/**
* \brief Returns true if this face is enabled, false otherwise.
*/
inline bool
- IsUp () const;
+ IsUp() const;
/**
* @brief Get face flags
*
- * Face flags may indicate various properties of the face. For example, if the face is an application face,
+ * Face flags may indicate various properties of the face. For example, if the face is an
+ *application face,
* than the returned flags have Face::APPLICATION bit set.
*
* @see ndn::Face::Flags for the list of currently defined face flags
*/
inline uint32_t
- GetFlags () const;
+ GetFlags() const;
/**
* @brief List of currently defined face flags
*/
- enum Flags
- {
- APPLICATION = 1 ///< @brief An application face
- };
+ enum Flags {
+ APPLICATION = 1 ///< @brief An application face
+ };
/**
* @brief Print information about the face into the stream
* @param os stream to write information to
*/
virtual std::ostream&
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
/**
* \brief Set face Id
@@ -206,7 +204,7 @@
* \param id id to set
*/
inline void
- SetId (uint32_t id);
+ SetId(uint32_t id);
/**
* \brief Get face Id
@@ -216,7 +214,7 @@
* \returns id id to set
*/
inline uint32_t
- GetId () const;
+ GetId() const;
/**
* \brief Compare two faces. Only two faces on the same node could be compared.
@@ -224,7 +222,7 @@
* Internal index is used for comparison.
*/
bool
- operator== (const Face &face) const;
+ operator==(const Face& face) const;
/**
* \brief Compare two faces. Only two faces on the same node could be compared.
@@ -232,7 +230,7 @@
* Internal index is used for comparison.
*/
inline bool
- operator!= (const Face &face) const;
+ operator!=(const Face& face) const;
/**
* \brief Compare two faces. Only two faces on the same node could be compared.
@@ -240,30 +238,31 @@
* Internal index is used for comparison.
*/
bool
- operator< (const Face &face) const;
+ operator<(const Face& face) const;
protected:
/**
* @brief Send packet down to the stack (towards app or network)
*/
virtual bool
- Send (Ptr<Packet> packet);
+ Send(Ptr<Packet> packet);
/**
* @brief Send packet up to the stack (towards forwarding strategy)
*/
virtual bool
- Receive (Ptr<const Packet> p);
+ Receive(Ptr<const Packet> p);
/**
* @brief Set face flags
*/
void
- SetFlags (uint32_t flags);
+ SetFlags(uint32_t flags);
private:
- Face (const Face &); ///< \brief Disabled copy constructor
- Face& operator= (const Face &); ///< \brief Disabled copy operator
+ Face(const Face&); ///< \brief Disabled copy constructor
+ Face&
+ operator=(const Face&); ///< \brief Disabled copy operator
protected:
Ptr<Node> m_node; ///< \brief Smart pointer to Node
@@ -272,46 +271,46 @@
InterestHandler m_upstreamInterestHandler;
DataHandler m_upstreamDataHandler;
bool m_ifup;
- uint32_t m_id; ///< \brief id of the interface in NDN stack (per-node uniqueness)
+ uint32_t m_id; ///< \brief id of the interface in NDN stack (per-node uniqueness)
uint16_t m_metric; ///< \brief metric of the face
- uint32_t m_flags; ///< @brief faces flags (e.g., APPLICATION)
+ uint32_t m_flags; ///< @brief faces flags (e.g., APPLICATION)
};
std::ostream&
-operator<< (std::ostream& os, const Face &face);
+operator<<(std::ostream& os, const Face& face);
inline bool
-Face::IsUp (void) const
+Face::IsUp(void) const
{
return m_ifup;
}
inline void
-Face::SetUp (bool up/* = true*/)
+Face::SetUp(bool up /* = true*/)
{
m_ifup = up;
}
inline uint32_t
-Face::GetFlags () const
+Face::GetFlags() const
{
return m_flags;
}
inline bool
-operator < (const Ptr<Face> &lhs, const Ptr<Face> &rhs)
+operator<(const Ptr<Face>& lhs, const Ptr<Face>& rhs)
{
return *lhs < *rhs;
}
void
-Face::SetId (uint32_t id)
+Face::SetId(uint32_t id)
{
m_id = id;
}
uint32_t
-Face::GetId () const
+Face::GetId() const
{
return m_id;
}
diff --git a/model/ndn-global-router.cpp b/model/ndn-global-router.cpp
index e29c055..f44a088 100644
--- a/model/ndn-global-router.cpp
+++ b/model/ndn-global-router.cpp
@@ -33,66 +33,62 @@
uint32_t GlobalRouter::m_idCounter = 0;
-NS_OBJECT_ENSURE_REGISTERED (GlobalRouter);
+NS_OBJECT_ENSURE_REGISTERED(GlobalRouter);
-TypeId
-GlobalRouter::GetTypeId ()
+TypeId
+GlobalRouter::GetTypeId()
{
- static TypeId tid = TypeId ("ns3::ndn::GlobalRouter")
- .SetGroupName ("Ndn")
- .SetParent<Object> ()
- ;
+ static TypeId tid = TypeId("ns3::ndn::GlobalRouter").SetGroupName("Ndn").SetParent<Object>();
return tid;
}
-GlobalRouter::GlobalRouter ()
+GlobalRouter::GlobalRouter()
{
m_id = m_idCounter;
- m_idCounter ++;
+ m_idCounter++;
}
void
-GlobalRouter::NotifyNewAggregate ()
+GlobalRouter::NotifyNewAggregate()
{
- if (m_ndn == 0)
- {
- m_ndn = GetObject<L3Protocol> ();
- }
- Object::NotifyNewAggregate ();
+ if (m_ndn == 0) {
+ m_ndn = GetObject<L3Protocol>();
+ }
+ Object::NotifyNewAggregate();
}
uint32_t
-GlobalRouter::GetId () const
+GlobalRouter::GetId() const
{
return m_id;
}
Ptr<L3Protocol>
-GlobalRouter::GetL3Protocol () const
+GlobalRouter::GetL3Protocol() const
{
return m_ndn;
}
void
-GlobalRouter::AddLocalPrefix (Ptr< Name > prefix)
+GlobalRouter::AddLocalPrefix(Ptr<Name> prefix)
{
- m_localPrefixes.push_back (prefix);
+ m_localPrefixes.push_back(prefix);
}
void
-GlobalRouter::AddIncidency (Ptr< Face > face, Ptr< GlobalRouter > gr)
+GlobalRouter::AddIncidency(Ptr<Face> face, Ptr<GlobalRouter> gr)
{
- m_incidencies.push_back (make_tuple (this, face, gr));
+ m_incidencies.push_back(make_tuple(this, face, gr));
}
-GlobalRouter::IncidencyList &
-GlobalRouter::GetIncidencies ()
+GlobalRouter::IncidencyList&
+GlobalRouter::GetIncidencies()
{
return m_incidencies;
}
-const GlobalRouter::LocalPrefixList &
-GlobalRouter::GetLocalPrefixes () const
+const GlobalRouter::LocalPrefixList&
+GlobalRouter::GetLocalPrefixes() const
{
return m_localPrefixes;
}
diff --git a/model/ndn-global-router.hpp b/model/ndn-global-router.hpp
index dad2180..f680db7 100644
--- a/model/ndn-global-router.hpp
+++ b/model/ndn-global-router.hpp
@@ -43,53 +43,52 @@
* @ingroup ndn
* @brief Class representing global router interface for ndnSIM
*/
-class GlobalRouter : public Object
-{
+class GlobalRouter : public Object {
public:
/**
* @brief Graph edge
*/
- typedef boost::tuple< Ptr< GlobalRouter >, Ptr< Face >, Ptr< GlobalRouter > > Incidency;
+ typedef boost::tuple<Ptr<GlobalRouter>, Ptr<Face>, Ptr<GlobalRouter>> Incidency;
/**
* @brief List of graph edges
*/
- typedef std::list< Incidency > IncidencyList;
+ typedef std::list<Incidency> IncidencyList;
/**
* @brief List of locally exported prefixes
*/
- typedef std::list< Ptr<Name> > LocalPrefixList;
-
+ typedef std::list<Ptr<Name>> LocalPrefixList;
+
/**
* \brief Interface ID
*
* \return interface ID
*/
static TypeId
- GetTypeId ();
+ GetTypeId();
/**
* @brief Default constructor
*/
- GlobalRouter ();
+ GlobalRouter();
/**
* @brief Get numeric ID of the node (internally assigned)
*/
uint32_t
- GetId () const;
+ GetId() const;
/**
* @brief Helper function to get smart pointer to ndn::L3Protocol object (basically, self)
*/
Ptr<L3Protocol>
- GetL3Protocol () const;
+ GetL3Protocol() const;
/**
* @brief Add new locally exported prefix
* @param prefix Prefix
*/
void
- AddLocalPrefix (Ptr< Name > prefix);
+ AddLocalPrefix(Ptr<Name> prefix);
/**
* @brief Add edge to the node
@@ -97,28 +96,29 @@
* @param ndn GlobalRouter of another node
*/
void
- AddIncidency (Ptr< Face > face, Ptr< GlobalRouter > ndn);
+ AddIncidency(Ptr<Face> face, Ptr<GlobalRouter> ndn);
/**
* @brief Get list of edges that are connected to this node
*/
- IncidencyList &
- GetIncidencies ();
+ IncidencyList&
+ GetIncidencies();
/**
* @brief Get list of locally exported prefixes
*/
- const LocalPrefixList &
- GetLocalPrefixes () const;
+ const LocalPrefixList&
+ GetLocalPrefixes() const;
// ??
protected:
virtual void
- NotifyNewAggregate (); ///< @brief Notify when the object is aggregated to another object (e.g., Node)
-
+ NotifyNewAggregate(); ///< @brief Notify when the object is aggregated to another object (e.g.,
+ /// Node)
+
private:
uint32_t m_id;
-
+
Ptr<L3Protocol> m_ndn;
LocalPrefixList m_localPrefixes;
IncidencyList m_incidencies;
@@ -127,19 +127,15 @@
};
inline bool
-operator == (const GlobalRouter::Incidency &a,
- const GlobalRouter::Incidency &b)
+operator==(const GlobalRouter::Incidency& a, const GlobalRouter::Incidency& b)
{
- return a.get<0> () == b.get<0> () &&
- a.get<1> () == b.get<1> () &&
- a.get<2> () == b.get<2> ();
+ return a.get<0>() == b.get<0>() && a.get<1>() == b.get<1>() && a.get<2>() == b.get<2>();
}
inline bool
-operator != (const GlobalRouter::Incidency &a,
- const GlobalRouter::Incidency &b)
+operator!=(const GlobalRouter::Incidency& a, const GlobalRouter::Incidency& b)
{
- return ! (a == b);
+ return !(a == b);
}
} // namespace ndn
diff --git a/model/ndn-l3-protocol.cpp b/model/ndn-l3-protocol.cpp
index 5ab8cba..d7505e7 100644
--- a/model/ndn-l3-protocol.cpp
+++ b/model/ndn-l3-protocol.cpp
@@ -43,7 +43,7 @@
#include <boost/foreach.hpp>
-NS_LOG_COMPONENT_DEFINE ("ndn.L3Protocol");
+NS_LOG_COMPONENT_DEFINE("ndn.L3Protocol");
namespace ns3 {
namespace ndn {
@@ -51,32 +51,31 @@
const uint16_t L3Protocol::ETHERNET_FRAME_TYPE = 0x7777;
const uint16_t L3Protocol::IP_STACK_PORT = 9695;
-NS_OBJECT_ENSURE_REGISTERED (L3Protocol);
+NS_OBJECT_ENSURE_REGISTERED(L3Protocol);
TypeId
-L3Protocol::GetTypeId (void)
+L3Protocol::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::L3Protocol")
- .SetGroupName ("ndn")
- .SetParent<Object> ()
- .AddConstructor<L3Protocol> ()
- .AddAttribute ("FaceList", "List of faces associated with ndn stack",
- ObjectVectorValue (),
- MakeObjectVectorAccessor (&L3Protocol::m_faces),
- MakeObjectVectorChecker<Face> ())
- ;
+ static TypeId tid =
+ TypeId("ns3::ndn::L3Protocol")
+ .SetGroupName("ndn")
+ .SetParent<Object>()
+ .AddConstructor<L3Protocol>()
+ .AddAttribute("FaceList", "List of faces associated with ndn stack", ObjectVectorValue(),
+ MakeObjectVectorAccessor(&L3Protocol::m_faces),
+ MakeObjectVectorChecker<Face>());
return tid;
}
-L3Protocol::L3Protocol ()
-: m_faceCounter (0)
+L3Protocol::L3Protocol()
+ : m_faceCounter(0)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
-L3Protocol::~L3Protocol ()
+L3Protocol::~L3Protocol()
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
/*
@@ -84,137 +83,135 @@
* by setting the node in the ndn stack
*/
void
-L3Protocol::NotifyNewAggregate ()
+L3Protocol::NotifyNewAggregate()
{
// not really efficient, but this will work only once
- if (m_node == 0)
- {
- m_node = GetObject<Node> ();
- if (m_node != 0)
- {
- NS_ASSERT_MSG (m_forwardingStrategy != 0,
- "Forwarding strategy should be aggregated before L3Protocol");
- }
+ if (m_node == 0) {
+ m_node = GetObject<Node>();
+ if (m_node != 0) {
+ NS_ASSERT_MSG(m_forwardingStrategy != 0,
+ "Forwarding strategy should be aggregated before L3Protocol");
}
- if (m_forwardingStrategy == 0)
- {
- m_forwardingStrategy = GetObject<ForwardingStrategy> ();
- }
+ }
+ if (m_forwardingStrategy == 0) {
+ m_forwardingStrategy = GetObject<ForwardingStrategy>();
+ }
- Object::NotifyNewAggregate ();
+ Object::NotifyNewAggregate();
}
void
-L3Protocol::DoDispose (void)
+L3Protocol::DoDispose(void)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
// for (FaceList::iterator i = m_faces.begin (); i != m_faces.end (); ++i)
// {
// *i = 0;
// }
- m_faces.clear ();
+ m_faces.clear();
m_node = 0;
// Force delete on objects
m_forwardingStrategy = 0; // there is a reference to PIT stored in here
- Object::DoDispose ();
+ Object::DoDispose();
}
uint32_t
-L3Protocol::AddFace (const Ptr<Face> &face)
+L3Protocol::AddFace(const Ptr<Face>& face)
{
- NS_LOG_FUNCTION (this << &face);
+ NS_LOG_FUNCTION(this << &face);
- face->SetId (m_faceCounter); // sets a unique ID of the face. This ID serves only informational purposes
+ face->SetId(
+ m_faceCounter); // sets a unique ID of the face. This ID serves only informational purposes
// ask face to register in lower-layer stack
- face->RegisterProtocolHandlers (MakeCallback (&ForwardingStrategy::OnInterest, m_forwardingStrategy),
- MakeCallback (&ForwardingStrategy::OnData, m_forwardingStrategy));
+ face->RegisterProtocolHandlers(MakeCallback(&ForwardingStrategy::OnInterest,
+ m_forwardingStrategy),
+ MakeCallback(&ForwardingStrategy::OnData, m_forwardingStrategy));
- m_faces.push_back (face);
+ m_faces.push_back(face);
m_faceCounter++;
- m_forwardingStrategy->AddFace (face); // notify that face is added
- return face->GetId ();
+ m_forwardingStrategy->AddFace(face); // notify that face is added
+ return face->GetId();
}
void
-L3Protocol::RemoveFace (Ptr<Face> face)
+L3Protocol::RemoveFace(Ptr<Face> face)
{
- NS_LOG_FUNCTION (this << boost::cref (*face));
+ NS_LOG_FUNCTION(this << boost::cref(*face));
// ask face to register in lower-layer stack
- face->UnRegisterProtocolHandlers ();
- Ptr<Pit> pit = GetObject<Pit> ();
+ face->UnRegisterProtocolHandlers();
+ Ptr<Pit> pit = GetObject<Pit>();
// just to be on a safe side. Do the process in two steps
- std::list< Ptr<pit::Entry> > entriesToRemoves;
- for (Ptr<pit::Entry> pitEntry = pit->Begin (); pitEntry != 0; pitEntry = pit->Next (pitEntry))
- {
- pitEntry->RemoveAllReferencesToFace (face);
+ std::list<Ptr<pit::Entry>> entriesToRemoves;
+ for (Ptr<pit::Entry> pitEntry = pit->Begin(); pitEntry != 0; pitEntry = pit->Next(pitEntry)) {
+ pitEntry->RemoveAllReferencesToFace(face);
- // If this face is the only for the associated FIB entry, then FIB entry will be removed soon.
- // Thus, we have to remove the whole PIT entry
- if (pitEntry->GetFibEntry ()->m_faces.size () == 1 &&
- pitEntry->GetFibEntry ()->m_faces.begin ()->GetFace () == face)
- {
- entriesToRemoves.push_back (pitEntry);
- }
+ // If this face is the only for the associated FIB entry, then FIB entry will be removed soon.
+ // Thus, we have to remove the whole PIT entry
+ if (pitEntry->GetFibEntry()->m_faces.size() == 1
+ && pitEntry->GetFibEntry()->m_faces.begin()->GetFace() == face) {
+ entriesToRemoves.push_back(pitEntry);
}
- BOOST_FOREACH (Ptr<pit::Entry> removedEntry, entriesToRemoves)
- {
- pit->MarkErased (removedEntry);
- }
+ }
+ BOOST_FOREACH (Ptr<pit::Entry> removedEntry, entriesToRemoves) {
+ pit->MarkErased(removedEntry);
+ }
- FaceList::iterator face_it = find (m_faces.begin(), m_faces.end(), face);
- if (face_it == m_faces.end ())
- {
- return;
- }
- m_faces.erase (face_it);
+ FaceList::iterator face_it = find(m_faces.begin(), m_faces.end(), face);
+ if (face_it == m_faces.end()) {
+ return;
+ }
+ m_faces.erase(face_it);
- GetObject<Fib> ()->RemoveFromAll (face);
- m_forwardingStrategy->RemoveFace (face); // notify that face is removed
+ GetObject<Fib>()->RemoveFromAll(face);
+ m_forwardingStrategy->RemoveFace(face); // notify that face is removed
}
Ptr<Face>
-L3Protocol::GetFace (uint32_t index) const
+L3Protocol::GetFace(uint32_t index) const
{
- NS_ASSERT (0 <= index && index < m_faces.size ());
+ NS_ASSERT(0 <= index && index < m_faces.size());
return m_faces[index];
}
Ptr<Face>
-L3Protocol::GetFaceById (uint32_t index) const
+L3Protocol::GetFaceById(uint32_t index) const
{
- BOOST_FOREACH (const Ptr<Face> &face, m_faces) // this function is not supposed to be called often, so linear search is fine
- {
- if (face->GetId () == index)
- return face;
- }
+ BOOST_FOREACH (const Ptr<Face>& face, m_faces) // this function is not supposed to be called
+ // often, so linear search is fine
+ {
+ if (face->GetId() == index)
+ return face;
+ }
return 0;
}
Ptr<Face>
-L3Protocol::GetFaceByNetDevice (Ptr<NetDevice> netDevice) const
+L3Protocol::GetFaceByNetDevice(Ptr<NetDevice> netDevice) const
{
- BOOST_FOREACH (const Ptr<Face> &face, m_faces) // this function is not supposed to be called often, so linear search is fine
- {
- Ptr<NetDeviceFace> netDeviceFace = DynamicCast<NetDeviceFace> (face);
- if (netDeviceFace == 0) continue;
+ BOOST_FOREACH (const Ptr<Face>& face, m_faces) // this function is not supposed to be called
+ // often, so linear search is fine
+ {
+ Ptr<NetDeviceFace> netDeviceFace = DynamicCast<NetDeviceFace>(face);
+ if (netDeviceFace == 0)
+ continue;
- if (netDeviceFace->GetNetDevice () == netDevice)
- return face;
- }
+ if (netDeviceFace->GetNetDevice() == netDevice)
+ return face;
+ }
return 0;
}
uint32_t
-L3Protocol::GetNFaces (void) const
+L3Protocol::GetNFaces(void) const
{
- return m_faces.size ();
+ return m_faces.size();
}
-} //namespace ndn
-} //namespace ns3
+} // namespace ndn
+} // namespace ns3
diff --git a/model/ndn-l3-protocol.hpp b/model/ndn-l3-protocol.hpp
index 552bd19..5b71e3a 100644
--- a/model/ndn-l3-protocol.hpp
+++ b/model/ndn-l3-protocol.hpp
@@ -53,7 +53,7 @@
* the NDN stack implementation:
* -# register a face (Face-derived object) for use by the NDN
* layer
- *
+ *
* Each Face-derived object has conceptually a single NDN
* interface associated with it.
*
@@ -61,18 +61,17 @@
*
* \see Face, ForwardingStrategy
*/
-class L3Protocol :
- public Object
-{
+class L3Protocol : public Object {
public:
- typedef std::vector<Ptr<Face> > FaceList;
+ typedef std::vector<Ptr<Face>> FaceList;
/**
* \brief Interface ID
*
* \return interface ID
*/
- static TypeId GetTypeId ();
+ static TypeId
+ GetTypeId();
static const uint16_t ETHERNET_FRAME_TYPE; ///< @brief Ethernet Frame Type of Ndn
static const uint16_t IP_STACK_PORT; ///< @brief TCP/UDP port for NDN stack
@@ -82,7 +81,7 @@
* \brief Default constructor. Creates an empty stack without forwarding strategy set
*/
L3Protocol();
- virtual ~L3Protocol ();
+ virtual ~L3Protocol();
/**
* \brief Add face to Ndn stack
@@ -90,19 +89,19 @@
* \param face smart pointer to NdnFace-derived object
* (NdnLocalFace, NdnNetDeviceFace, NdnUdpFace) \returns the
* index of the Ndn interface added.
- *
+ *
* \see NdnLocalFace, NdnNetDeviceFace, NdnUdpFace
*/
virtual uint32_t
- AddFace (const Ptr<Face> &face);
-
+ AddFace(const Ptr<Face>& face);
+
/**
* \brief Get current number of faces added to Ndn stack
*
* \returns the number of faces
*/
virtual uint32_t
- GetNFaces () const;
+ GetNFaces() const;
/**
* \brief Get face by face index
@@ -110,48 +109,55 @@
* \returns The NdnFace associated with the Ndn face number.
*/
virtual Ptr<Face>
- GetFace (uint32_t face) const;
-
+ GetFace(uint32_t face) const;
+
/**
* \brief Get face by face ID
* \param face The face ID number
* \returns The NdnFace associated with the Ndn face number.
*/
virtual Ptr<Face>
- GetFaceById (uint32_t face) const;
+ GetFaceById(uint32_t face) const;
/**
* \brief Remove face from ndn stack (remove callbacks)
*/
virtual void
- RemoveFace (Ptr<Face> face);
+ RemoveFace(Ptr<Face> face);
/**
* \brief Get face for NetDevice
*/
virtual Ptr<Face>
- GetFaceByNetDevice (Ptr<NetDevice> netDevice) const;
+ GetFaceByNetDevice(Ptr<NetDevice> netDevice) const;
protected:
- virtual void DoDispose (void); ///< @brief Do cleanup
+ virtual void
+ DoDispose(void); ///< @brief Do cleanup
/**
- * This function will notify other components connected to the node that a new stack member is now connected
- * This will be used to notify Layer 3 protocol of layer 4 protocol stack to connect them together.
+ * This function will notify other components connected to the node that a new stack member is now
+ * connected
+ * This will be used to notify Layer 3 protocol of layer 4 protocol stack to connect them
+ * together.
*/
- virtual void NotifyNewAggregate ();
+ virtual void
+ NotifyNewAggregate();
private:
- L3Protocol(const L3Protocol &); ///< copy constructor is disabled
- L3Protocol &operator = (const L3Protocol &); ///< copy operator is disabled
-
+ L3Protocol(const L3Protocol&); ///< copy constructor is disabled
+ L3Protocol&
+ operator=(const L3Protocol&); ///< copy operator is disabled
+
private:
- uint32_t m_faceCounter; ///< \brief counter of faces. Increased every time a new face is added to the stack
+ uint32_t m_faceCounter; ///< \brief counter of faces. Increased every time a new face is added to
+ /// the stack
FaceList m_faces; ///< \brief list of faces that belongs to ndn stack on this node
// These objects are aggregated, but for optimization, get them here
Ptr<Node> m_node; ///< \brief node on which ndn stack is installed
- Ptr<ForwardingStrategy> m_forwardingStrategy; ///< \brief smart pointer to the selected forwarding strategy
+ Ptr<ForwardingStrategy>
+ m_forwardingStrategy; ///< \brief smart pointer to the selected forwarding strategy
};
} // namespace ndn
diff --git a/model/ndn-net-device-face.cpp b/model/ndn-net-device-face.cpp
index af4baa0..31d57fc 100644
--- a/model/ndn-net-device-face.cpp
+++ b/model/ndn-net-device-face.cpp
@@ -33,20 +33,17 @@
#include "ns3/channel.h"
#include "ns3/ndn-name.hpp"
-NS_LOG_COMPONENT_DEFINE ("ndn.NetDeviceFace");
+NS_LOG_COMPONENT_DEFINE("ndn.NetDeviceFace");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (NetDeviceFace);
+NS_OBJECT_ENSURE_REGISTERED(NetDeviceFace);
TypeId
-NetDeviceFace::GetTypeId ()
+NetDeviceFace::GetTypeId()
{
- static TypeId tid = TypeId ("ns3::ndn::NetDeviceFace")
- .SetParent<Face> ()
- .SetGroupName ("Ndn")
- ;
+ static TypeId tid = TypeId("ns3::ndn::NetDeviceFace").SetParent<Face>().SetGroupName("Ndn");
return tid;
}
@@ -54,20 +51,20 @@
* By default, Ndn face are created in the "down" state. Before
* becoming useable, the user must invoke SetUp on the face
*/
-NetDeviceFace::NetDeviceFace (Ptr<Node> node, const Ptr<NetDevice> &netDevice)
- : Face (node)
- , m_netDevice (netDevice)
+NetDeviceFace::NetDeviceFace(Ptr<Node> node, const Ptr<NetDevice>& netDevice)
+ : Face(node)
+ , m_netDevice(netDevice)
{
- NS_LOG_FUNCTION (this << netDevice);
+ NS_LOG_FUNCTION(this << netDevice);
- SetMetric (1); // default metric
+ SetMetric(1); // default metric
- NS_ASSERT_MSG (m_netDevice != 0, "NetDeviceFace needs to be assigned a valid NetDevice");
+ NS_ASSERT_MSG(m_netDevice != 0, "NetDeviceFace needs to be assigned a valid NetDevice");
}
-NetDeviceFace::~NetDeviceFace ()
+NetDeviceFace::~NetDeviceFace()
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
}
NetDeviceFace& NetDeviceFace::operator= (const NetDeviceFace &)
@@ -76,84 +73,85 @@
}
Ptr<NetDevice>
-NetDeviceFace::GetNetDevice () const
+NetDeviceFace::GetNetDevice() const
{
return m_netDevice;
}
void
-NetDeviceFace::RegisterProtocolHandlers (const InterestHandler &interestHandler, const DataHandler &dataHandler)
+NetDeviceFace::RegisterProtocolHandlers(const InterestHandler& interestHandler,
+ const DataHandler& dataHandler)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
- Face::RegisterProtocolHandlers (interestHandler, dataHandler);
+ Face::RegisterProtocolHandlers(interestHandler, dataHandler);
- m_node->RegisterProtocolHandler (MakeCallback (&NetDeviceFace::ReceiveFromNetDevice, this),
- L3Protocol::ETHERNET_FRAME_TYPE, m_netDevice, true/*promiscuous mode*/);
+ m_node->RegisterProtocolHandler(MakeCallback(&NetDeviceFace::ReceiveFromNetDevice, this),
+ L3Protocol::ETHERNET_FRAME_TYPE, m_netDevice,
+ true /*promiscuous mode*/);
}
void
-NetDeviceFace:: UnRegisterProtocolHandlers ()
+NetDeviceFace::UnRegisterProtocolHandlers()
{
- m_node->UnregisterProtocolHandler (MakeCallback (&NetDeviceFace::ReceiveFromNetDevice, this));
- Face::UnRegisterProtocolHandlers ();
+ m_node->UnregisterProtocolHandler(MakeCallback(&NetDeviceFace::ReceiveFromNetDevice, this));
+ Face::UnRegisterProtocolHandlers();
}
bool
-NetDeviceFace::Send (Ptr<Packet> packet)
+NetDeviceFace::Send(Ptr<Packet> packet)
{
- if (!Face::Send (packet))
- {
- return false;
- }
-
- NS_LOG_FUNCTION (this << packet);
+ if (!Face::Send(packet)) {
+ return false;
+ }
- NS_ASSERT_MSG (packet->GetSize () <= m_netDevice->GetMtu (),
- "Packet size " << packet->GetSize () << " exceeds device MTU "
- << m_netDevice->GetMtu ()
- << " for Ndn; fragmentation not supported");
+ NS_LOG_FUNCTION(this << packet);
- bool ok = m_netDevice->Send (packet, m_netDevice->GetBroadcast (),
- L3Protocol::ETHERNET_FRAME_TYPE);
+ NS_ASSERT_MSG(packet->GetSize() <= m_netDevice->GetMtu(),
+ "Packet size " << packet->GetSize() << " exceeds device MTU "
+ << m_netDevice->GetMtu() << " for Ndn; fragmentation not supported");
+
+ bool ok = m_netDevice->Send(packet, m_netDevice->GetBroadcast(), L3Protocol::ETHERNET_FRAME_TYPE);
return ok;
}
// callback
void
-NetDeviceFace::ReceiveFromNetDevice (Ptr<NetDevice> device,
- Ptr<const Packet> p,
- uint16_t protocol,
- const Address &from,
- const Address &to,
- NetDevice::PacketType packetType)
+NetDeviceFace::ReceiveFromNetDevice(Ptr<NetDevice> device, Ptr<const Packet> p, uint16_t protocol,
+ const Address& from, const Address& to,
+ NetDevice::PacketType packetType)
{
- NS_LOG_FUNCTION (device << p << protocol << from << to << packetType);
- Receive (p);
+ NS_LOG_FUNCTION(device << p << protocol << from << to << packetType);
+ Receive(p);
}
-
std::ostream&
-NetDeviceFace::Print (std::ostream& os) const
+NetDeviceFace::Print(std::ostream& os) const
{
#ifdef NS3_LOG_ENABLE
- os << "dev[" << GetNode ()->GetId () << "]=net(" << GetId ();
+ os << "dev[" << GetNode()->GetId() << "]=net(" << GetId();
- if (DynamicCast<PointToPointNetDevice> (m_netDevice))
- {
- // extra debugging information which available ONLY for PointToPointNetDevice's
- os << ",";
- os << DynamicCast<PointToPointNetDevice> (m_netDevice)->GetChannel ()->GetDevice (0)->GetNode ()->GetId ();
- os << "-";
- os << DynamicCast<PointToPointNetDevice> (m_netDevice)->GetChannel ()->GetDevice (1)->GetNode ()->GetId ();
- }
+ if (DynamicCast<PointToPointNetDevice>(m_netDevice)) {
+ // extra debugging information which available ONLY for PointToPointNetDevice's
+ os << ",";
+ os << DynamicCast<PointToPointNetDevice>(m_netDevice)
+ ->GetChannel()
+ ->GetDevice(0)
+ ->GetNode()
+ ->GetId();
+ os << "-";
+ os << DynamicCast<PointToPointNetDevice>(m_netDevice)
+ ->GetChannel()
+ ->GetDevice(1)
+ ->GetNode()
+ ->GetId();
+ }
os << ")";
#else
- os << "dev=net(" << GetId () << ")";
+ os << "dev=net(" << GetId() << ")";
#endif
return os;
}
} // namespace ndnsim
} // namespace ns3
-
diff --git a/model/ndn-net-device-face.hpp b/model/ndn-net-device-face.hpp
index 6bf231c..5bc8e3a 100644
--- a/model/ndn-net-device-face.hpp
+++ b/model/ndn-net-device-face.hpp
@@ -26,7 +26,7 @@
namespace ns3 {
namespace ndn {
-
+
/**
* \ingroup ndn-face
* \brief Implementation of layer-2 (Ethernet) Ndn face
@@ -41,11 +41,10 @@
*
* \see NdnAppFace, NdnNetDeviceFace, NdnIpv4Face, NdnUdpFace
*/
-class NetDeviceFace : public Face
-{
+class NetDeviceFace : public Face {
public:
static TypeId
- GetTypeId ();
+ GetTypeId();
/**
* \brief Constructor
@@ -54,27 +53,27 @@
* @param netDevice a smart pointer to NetDevice object to which
* this face will be associate
*/
- NetDeviceFace (Ptr<Node> node, const Ptr<NetDevice> &netDevice);
+ NetDeviceFace(Ptr<Node> node, const Ptr<NetDevice>& netDevice);
virtual ~NetDeviceFace();
////////////////////////////////////////////////////////////////////
// methods overloaded from NdnFace
virtual void
- RegisterProtocolHandlers (const InterestHandler &interestHandler, const DataHandler &dataHandler);
+ RegisterProtocolHandlers(const InterestHandler& interestHandler, const DataHandler& dataHandler);
virtual void
- UnRegisterProtocolHandlers ();
-
+ UnRegisterProtocolHandlers();
+
protected:
virtual bool
- Send (Ptr<Packet> p);
+ Send(Ptr<Packet> p);
public:
/**
* @brief Print out name of the NdnFace to the stream
*/
virtual std::ostream&
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
////////////////////////////////////////////////////////////////////
/**
@@ -82,19 +81,18 @@
*
* \returns smart pointer to NetDevice associated with the face
*/
- Ptr<NetDevice> GetNetDevice () const;
+ Ptr<NetDevice>
+ GetNetDevice() const;
private:
- NetDeviceFace (const NetDeviceFace &); ///< \brief Disabled copy constructor
- NetDeviceFace& operator= (const NetDeviceFace &); ///< \brief Disabled copy operator
+ NetDeviceFace(const NetDeviceFace&); ///< \brief Disabled copy constructor
+ NetDeviceFace&
+ operator=(const NetDeviceFace&); ///< \brief Disabled copy operator
/// \brief callback from lower layers
- void ReceiveFromNetDevice (Ptr<NetDevice> device,
- Ptr<const Packet> p,
- uint16_t protocol,
- const Address &from,
- const Address &to,
- NetDevice::PacketType packetType);
+ void
+ ReceiveFromNetDevice(Ptr<NetDevice> device, Ptr<const Packet> p, uint16_t protocol,
+ const Address& from, const Address& to, NetDevice::PacketType packetType);
private:
Ptr<NetDevice> m_netDevice; ///< \brief Smart pointer to NetDevice
@@ -103,4 +101,4 @@
} // namespace ndn
} // namespace ns3
-#endif //NDN_NET_DEVICE_FACE_H
+#endif // NDN_NET_DEVICE_FACE_H
diff --git a/plugins/ip-faces/ndn-ip-face-stack.cpp b/plugins/ip-faces/ndn-ip-face-stack.cpp
index 17a0253..3481b94 100644
--- a/plugins/ip-faces/ndn-ip-face-stack.cpp
+++ b/plugins/ip-faces/ndn-ip-face-stack.cpp
@@ -34,192 +34,186 @@
#include "ns3/udp-socket-factory.h"
#include "ns3/simulator.h"
-NS_LOG_COMPONENT_DEFINE ("ndn.IpFaceStack");
+NS_LOG_COMPONENT_DEFINE("ndn.IpFaceStack");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (IpFaceStack);
+NS_OBJECT_ENSURE_REGISTERED(IpFaceStack);
-const Callback< void, Ptr<Face> > IpFaceStack::NULL_CREATE_CALLBACK = MakeNullCallback< void, Ptr<Face> > ();
+const Callback<void, Ptr<Face>> IpFaceStack::NULL_CREATE_CALLBACK =
+ MakeNullCallback<void, Ptr<Face>>();
TypeId
-IpFaceStack::GetTypeId (void)
+IpFaceStack::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::IpFaceStack")
- .SetGroupName ("Ndn")
- .SetParent<Object> ()
- .AddConstructor<IpFaceStack> ()
+ static TypeId tid =
+ TypeId("ns3::ndn::IpFaceStack")
+ .SetGroupName("Ndn")
+ .SetParent<Object>()
+ .AddConstructor<IpFaceStack>()
- .AddAttribute ("EnableTCP", "Enable ability to create TCP faces",
- BooleanValue (true),
- MakeBooleanAccessor (&IpFaceStack::m_enableTcp),
- MakeBooleanChecker ())
+ .AddAttribute("EnableTCP", "Enable ability to create TCP faces", BooleanValue(true),
+ MakeBooleanAccessor(&IpFaceStack::m_enableTcp), MakeBooleanChecker())
- .AddAttribute ("EnableUDP", "Enable ability to create UDP faces",
- BooleanValue (true),
- MakeBooleanAccessor (&IpFaceStack::m_enableUdp),
- MakeBooleanChecker ())
- ;
+ .AddAttribute("EnableUDP", "Enable ability to create UDP faces", BooleanValue(true),
+ MakeBooleanAccessor(&IpFaceStack::m_enableUdp), MakeBooleanChecker());
return tid;
}
-IpFaceStack::IpFaceStack ()
+IpFaceStack::IpFaceStack()
{
}
-IpFaceStack::~IpFaceStack ()
+IpFaceStack::~IpFaceStack()
{
}
void
-IpFaceStack::NotifyNewAggregate ()
+IpFaceStack::NotifyNewAggregate()
{
- if (m_node == 0)
- {
- m_node = GetObject<Node> ();
- if (m_node != 0)
- {
- Simulator::ScheduleWithContext (m_node->GetId (), Seconds (0.1), &IpFaceStack::StartServer, this);
- }
+ if (m_node == 0) {
+ m_node = GetObject<Node>();
+ if (m_node != 0) {
+ Simulator::ScheduleWithContext(m_node->GetId(), Seconds(0.1), &IpFaceStack::StartServer,
+ this);
}
+ }
}
// Application Methods
void
-IpFaceStack::StartServer () // Called at time specified by Start
+IpFaceStack::StartServer() // Called at time specified by Start
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
- if (m_enableTcp)
- {
- m_tcpServer = Socket::CreateSocket (m_node, TcpSocketFactory::GetTypeId ());
+ if (m_enableTcp) {
+ m_tcpServer = Socket::CreateSocket(m_node, TcpSocketFactory::GetTypeId());
- m_tcpServer->Bind (InetSocketAddress (Ipv4Address::GetAny (), L3Protocol::IP_STACK_PORT));
- m_tcpServer->Listen ();
+ m_tcpServer->Bind(InetSocketAddress(Ipv4Address::GetAny(), L3Protocol::IP_STACK_PORT));
+ m_tcpServer->Listen();
- m_tcpServer->SetAcceptCallback (MakeCallback (&IpFaceStack::OnTcpConnectionRequest, this),
- MakeCallback (&IpFaceStack::OnTcpConnectionAccept, this));
- }
+ m_tcpServer->SetAcceptCallback(MakeCallback(&IpFaceStack::OnTcpConnectionRequest, this),
+ MakeCallback(&IpFaceStack::OnTcpConnectionAccept, this));
+ }
- if (m_enableUdp)
- {
- m_udpServer = Socket::CreateSocket (m_node, UdpSocketFactory::GetTypeId ());
- m_udpServer->Bind (InetSocketAddress (Ipv4Address::GetAny (), L3Protocol::IP_STACK_PORT));
+ if (m_enableUdp) {
+ m_udpServer = Socket::CreateSocket(m_node, UdpSocketFactory::GetTypeId());
+ m_udpServer->Bind(InetSocketAddress(Ipv4Address::GetAny(), L3Protocol::IP_STACK_PORT));
- m_udpServer->SetRecvCallback (MakeCallback (&IpFaceStack::OnUdpPacket, this));
- }
+ m_udpServer->SetRecvCallback(MakeCallback(&IpFaceStack::OnUdpPacket, this));
+ }
}
bool
-IpFaceStack::OnTcpConnectionRequest (Ptr< Socket > sock, const Address &addr)
+IpFaceStack::OnTcpConnectionRequest(Ptr<Socket> sock, const Address& addr)
{
- NS_LOG_FUNCTION (this << sock << InetSocketAddress::ConvertFrom (addr));
+ NS_LOG_FUNCTION(this << sock << InetSocketAddress::ConvertFrom(addr));
return true; // accept all connections from anybody
}
void
-IpFaceStack::OnTcpConnectionAccept (Ptr<Socket> socket, const Address &addr)
+IpFaceStack::OnTcpConnectionAccept(Ptr<Socket> socket, const Address& addr)
{
- NS_LOG_FUNCTION (this << socket << InetSocketAddress::ConvertFrom (addr));
+ NS_LOG_FUNCTION(this << socket << InetSocketAddress::ConvertFrom(addr));
- Ptr<L3Protocol> ndn = m_node->GetObject<L3Protocol> ();
- Ptr<TcpFace> face = CreateObject<TcpFace> (m_node, socket, InetSocketAddress::ConvertFrom (addr).GetIpv4 ());
+ Ptr<L3Protocol> ndn = m_node->GetObject<L3Protocol>();
+ Ptr<TcpFace> face =
+ CreateObject<TcpFace>(m_node, socket, InetSocketAddress::ConvertFrom(addr).GetIpv4());
- ndn->AddFace (face);
- face->SetUp (true);
+ ndn->AddFace(face);
+ face->SetUp(true);
- socket->SetCloseCallbacks (MakeCallback (&TcpFace::OnTcpConnectionClosed, face),
- MakeCallback (&TcpFace::OnTcpConnectionClosed, face));
+ socket->SetCloseCallbacks(MakeCallback(&TcpFace::OnTcpConnectionClosed, face),
+ MakeCallback(&TcpFace::OnTcpConnectionClosed, face));
}
void
-IpFaceStack::OnUdpPacket (Ptr< Socket > socket)
+IpFaceStack::OnUdpPacket(Ptr<Socket> socket)
{
- NS_LOG_FUNCTION (this << socket);
+ NS_LOG_FUNCTION(this << socket);
Ptr<Packet> packet;
Address from;
- while ((packet = socket->RecvFrom (from)))
- {
- Ptr<UdpFace> face = CreateOrGetUdpFace (InetSocketAddress::ConvertFrom (from).GetIpv4 ());
- face->ReceiveFromUdp (packet);
- }
+ while ((packet = socket->RecvFrom(from))) {
+ Ptr<UdpFace> face = CreateOrGetUdpFace(InetSocketAddress::ConvertFrom(from).GetIpv4());
+ face->ReceiveFromUdp(packet);
+ }
}
Ptr<TcpFace>
-IpFaceStack::GetTcpFaceByAddress (const Ipv4Address &address)
+IpFaceStack::GetTcpFaceByAddress(const Ipv4Address& address)
{
- TcpFaceMap::iterator i = m_tcpFaceMap.find (address);
- if (i != m_tcpFaceMap.end ())
+ TcpFaceMap::iterator i = m_tcpFaceMap.find(address);
+ if (i != m_tcpFaceMap.end())
return i->second;
else
return 0;
}
void
-IpFaceStack::DestroyTcpFace (Ptr<TcpFace> face)
+IpFaceStack::DestroyTcpFace(Ptr<TcpFace> face)
{
- m_tcpFaceMap.erase (face->GetAddress ());
+ m_tcpFaceMap.erase(face->GetAddress());
}
Ptr<UdpFace>
-IpFaceStack::GetUdpFaceByAddress (const Ipv4Address &address)
+IpFaceStack::GetUdpFaceByAddress(const Ipv4Address& address)
{
- UdpFaceMap::iterator i = m_udpFaceMap.find (address);
- if (i != m_udpFaceMap.end ())
+ UdpFaceMap::iterator i = m_udpFaceMap.find(address);
+ if (i != m_udpFaceMap.end())
return i->second;
else
return 0;
}
Ptr<TcpFace>
-IpFaceStack::CreateOrGetTcpFace (Ipv4Address address, Callback< void, Ptr<Face> > onCreate)
+IpFaceStack::CreateOrGetTcpFace(Ipv4Address address, Callback<void, Ptr<Face>> onCreate)
{
- NS_LOG_FUNCTION (address);
+ NS_LOG_FUNCTION(address);
- TcpFaceMap::iterator i = m_tcpFaceMap.find (address);
- if (i != m_tcpFaceMap.end ())
+ TcpFaceMap::iterator i = m_tcpFaceMap.find(address);
+ if (i != m_tcpFaceMap.end())
return i->second;
- Ptr<Socket> socket = Socket::CreateSocket (m_node, TcpSocketFactory::GetTypeId ());
- Ptr<TcpFace> face = CreateObject<TcpFace> (m_node, socket, address);
+ Ptr<Socket> socket = Socket::CreateSocket(m_node, TcpSocketFactory::GetTypeId());
+ Ptr<TcpFace> face = CreateObject<TcpFace>(m_node, socket, address);
- face->SetCreateCallback (onCreate);
+ face->SetCreateCallback(onCreate);
- socket->SetConnectCallback (MakeCallback (&TcpFace::OnConnect, face),
- MakeNullCallback< void, Ptr< Socket > > ());
- socket->Connect (InetSocketAddress (address, L3Protocol::IP_STACK_PORT));
+ socket->SetConnectCallback(MakeCallback(&TcpFace::OnConnect, face),
+ MakeNullCallback<void, Ptr<Socket>>());
+ socket->Connect(InetSocketAddress(address, L3Protocol::IP_STACK_PORT));
- m_tcpFaceMap.insert (std::make_pair (address, face));
+ m_tcpFaceMap.insert(std::make_pair(address, face));
return face;
}
Ptr<UdpFace>
-IpFaceStack::CreateOrGetUdpFace (Ipv4Address address)
+IpFaceStack::CreateOrGetUdpFace(Ipv4Address address)
{
- NS_LOG_FUNCTION (address);
+ NS_LOG_FUNCTION(address);
- UdpFaceMap::iterator i = m_udpFaceMap.find (address);
- if (i != m_udpFaceMap.end ())
+ UdpFaceMap::iterator i = m_udpFaceMap.find(address);
+ if (i != m_udpFaceMap.end())
return i->second;
- Ptr<Socket> socket = Socket::CreateSocket (m_node, UdpSocketFactory::GetTypeId ());
- socket->Bind (InetSocketAddress (Ipv4Address::GetAny (), L3Protocol::IP_STACK_PORT)); // not sure if it going to work...
+ Ptr<Socket> socket = Socket::CreateSocket(m_node, UdpSocketFactory::GetTypeId());
+ socket->Bind(InetSocketAddress(Ipv4Address::GetAny(),
+ L3Protocol::IP_STACK_PORT)); // not sure if it going to work...
// socket->Bind ();
- socket->Connect (InetSocketAddress (address, L3Protocol::IP_STACK_PORT));
+ socket->Connect(InetSocketAddress(address, L3Protocol::IP_STACK_PORT));
- Ptr<UdpFace> face = CreateObject<UdpFace> (m_node, socket, address);
- Ptr<L3Protocol> ndn = m_node->GetObject<L3Protocol> ();
+ Ptr<UdpFace> face = CreateObject<UdpFace>(m_node, socket, address);
+ Ptr<L3Protocol> ndn = m_node->GetObject<L3Protocol>();
- ndn->AddFace (face);
- face->SetUp (true);
+ ndn->AddFace(face);
+ face->SetUp(true);
- m_udpFaceMap.insert (std::make_pair (address, face));
+ m_udpFaceMap.insert(std::make_pair(address, face));
return face;
}
-
} // namespace ndn
} // namespace ns3
diff --git a/plugins/ip-faces/ndn-ip-face-stack.hpp b/plugins/ip-faces/ndn-ip-face-stack.hpp
index 6eb6ff3..a9322c6 100644
--- a/plugins/ip-faces/ndn-ip-face-stack.hpp
+++ b/plugins/ip-faces/ndn-ip-face-stack.hpp
@@ -46,74 +46,76 @@
*
* The class implements virtual calls onInterest, onNack, and onData
*/
-class IpFaceStack: public Object
-{
+class IpFaceStack : public Object {
public:
- static TypeId GetTypeId ();
+ static TypeId
+ GetTypeId();
/**
* @brief Default constructor
*/
- IpFaceStack ();
- virtual ~IpFaceStack ();
+ IpFaceStack();
+ virtual ~IpFaceStack();
/**
* @brief Lookup TcpFace for a given address
*/
Ptr<TcpFace>
- GetTcpFaceByAddress (const Ipv4Address &addr);
+ GetTcpFaceByAddress(const Ipv4Address& addr);
/**
* @brief Destroy TcpFace, e.g., after TCP connection got dropped
*/
void
- DestroyTcpFace (Ptr<TcpFace> face);
+ DestroyTcpFace(Ptr<TcpFace> face);
/**
* @brief Lookup UdpFace for a given address
*/
Ptr<UdpFace>
- GetUdpFaceByAddress (const Ipv4Address &addr);
+ GetUdpFaceByAddress(const Ipv4Address& addr);
/**
* @brief Method allowing creation and lookup of faces
*
- * All created UDP faces are stored internally in the map, and if the same face is created, it will simply be looked up
+ * All created UDP faces are stored internally in the map, and if the same face is created, it
+ *will simply be looked up
*/
Ptr<TcpFace>
- CreateOrGetTcpFace (Ipv4Address address,
- Callback< void, Ptr<Face> > onCreate = NULL_CREATE_CALLBACK);
+ CreateOrGetTcpFace(Ipv4Address address,
+ Callback<void, Ptr<Face>> onCreate = NULL_CREATE_CALLBACK);
/**
* @brief Method allowing creation and lookup of faces
*
- * All created TCP faces are stored internally in the map, and if the same face is created, it will simply be looked up
+ * All created TCP faces are stored internally in the map, and if the same face is created, it
+ *will simply be looked up
*/
Ptr<UdpFace>
- CreateOrGetUdpFace (Ipv4Address address);
+ CreateOrGetUdpFace(Ipv4Address address);
protected:
void
- NotifyNewAggregate ();
+ NotifyNewAggregate();
private:
void
- StartServer ();
+ StartServer();
bool
- OnTcpConnectionRequest (Ptr< Socket > sock, const Address &addr);
+ OnTcpConnectionRequest(Ptr<Socket> sock, const Address& addr);
void
- OnTcpConnectionAccept (Ptr< Socket > sock, const Address &addr);
+ OnTcpConnectionAccept(Ptr<Socket> sock, const Address& addr);
void
- OnTcpConnectionClosed (Ptr< Socket > sock);
+ OnTcpConnectionClosed(Ptr<Socket> sock);
void
- OnUdpPacket (Ptr< Socket > sock);
+ OnUdpPacket(Ptr<Socket> sock);
public:
- const static Callback< void, Ptr<Face> > NULL_CREATE_CALLBACK;
+ const static Callback<void, Ptr<Face>> NULL_CREATE_CALLBACK;
protected:
Ptr<Node> m_node;
@@ -124,8 +126,8 @@
Ptr<Socket> m_tcpServer;
Ptr<Socket> m_udpServer;
- typedef std::map< Ipv4Address, Ptr<TcpFace> > TcpFaceMap;
- typedef std::map< Ipv4Address, Ptr<UdpFace> > UdpFaceMap;
+ typedef std::map<Ipv4Address, Ptr<TcpFace>> TcpFaceMap;
+ typedef std::map<Ipv4Address, Ptr<UdpFace>> UdpFaceMap;
TcpFaceMap m_tcpFaceMap;
UdpFaceMap m_udpFaceMap;
};
diff --git a/plugins/ip-faces/ndn-ip-faces-helper.cpp b/plugins/ip-faces/ndn-ip-faces-helper.cpp
index 4194b68..f265262 100644
--- a/plugins/ip-faces/ndn-ip-faces-helper.cpp
+++ b/plugins/ip-faces/ndn-ip-faces-helper.cpp
@@ -29,7 +29,7 @@
#include "ndn-tcp-face.hpp"
#include "ndn-udp-face.hpp"
-NS_LOG_COMPONENT_DEFINE ("ndn.IpFacesHelper");
+NS_LOG_COMPONENT_DEFINE("ndn.IpFacesHelper");
using namespace std;
@@ -37,44 +37,40 @@
namespace ndn {
void
-IpFacesHelper::Install (Ptr<Node> node)
+IpFacesHelper::Install(Ptr<Node> node)
{
- Ptr<IpFaceStack> stack = CreateObject<IpFaceStack> ();
- node->AggregateObject (stack);
+ Ptr<IpFaceStack> stack = CreateObject<IpFaceStack>();
+ node->AggregateObject(stack);
}
void
-IpFacesHelper::Install (const NodeContainer &nodes)
+IpFacesHelper::Install(const NodeContainer& nodes)
{
- for (NodeContainer::Iterator node = nodes.Begin ();
- node != nodes.End ();
- node ++)
- {
- Install (*node);
- }
+ for (NodeContainer::Iterator node = nodes.Begin(); node != nodes.End(); node++) {
+ Install(*node);
+ }
}
void
-IpFacesHelper::InstallAll ()
+IpFacesHelper::InstallAll()
{
- Install (NodeContainer::GetGlobal ());
+ Install(NodeContainer::GetGlobal());
}
-
-struct TcpPrefixRegistrator : SimpleRefCount<TcpPrefixRegistrator>
-{
- TcpPrefixRegistrator (Ptr<Node> node, const std::string &prefix, int16_t metric)
- : m_node (node)
- , m_prefix (prefix)
- , m_metric (metric)
+struct TcpPrefixRegistrator : SimpleRefCount<TcpPrefixRegistrator> {
+ TcpPrefixRegistrator(Ptr<Node> node, const std::string& prefix, int16_t metric)
+ : m_node(node)
+ , m_prefix(prefix)
+ , m_metric(metric)
{
}
void
- Run (Ptr<Face> face)
+ Run(Ptr<Face> face)
{
- ndn::StackHelper::AddRoute (m_node, m_prefix, face, m_metric);
+ ndn::StackHelper::AddRoute(m_node, m_prefix, face, m_metric);
}
+
private:
Ptr<Node> m_node;
std::string m_prefix;
@@ -82,43 +78,45 @@
};
static void
-ScheduledCreateTcp (Ptr<Node> node, Ipv4Address address, const std::string &prefix, int16_t metric)
+ScheduledCreateTcp(Ptr<Node> node, Ipv4Address address, const std::string& prefix, int16_t metric)
{
- Ptr<IpFaceStack> stack = node->GetObject<IpFaceStack> ();
- NS_ASSERT_MSG (stack != 0, "ndn::IpFaceStack needs to be installed on the node");
+ Ptr<IpFaceStack> stack = node->GetObject<IpFaceStack>();
+ NS_ASSERT_MSG(stack != 0, "ndn::IpFaceStack needs to be installed on the node");
- Ptr<Face> face = stack->GetTcpFaceByAddress (address);
- if (face == 0)
- {
- Ptr<TcpPrefixRegistrator> registrator = Create<TcpPrefixRegistrator> (node, prefix, metric);
- stack->CreateOrGetTcpFace (address, MakeCallback (&TcpPrefixRegistrator::Run, registrator));
- }
- else
- {
- ndn::StackHelper::AddRoute (node, prefix, face, metric);
- }
+ Ptr<Face> face = stack->GetTcpFaceByAddress(address);
+ if (face == 0) {
+ Ptr<TcpPrefixRegistrator> registrator = Create<TcpPrefixRegistrator>(node, prefix, metric);
+ stack->CreateOrGetTcpFace(address, MakeCallback(&TcpPrefixRegistrator::Run, registrator));
+ }
+ else {
+ ndn::StackHelper::AddRoute(node, prefix, face, metric);
+ }
}
void
-IpFacesHelper::CreateTcpFace (const Time &when, Ptr<Node> node, Ipv4Address address, const std::string &prefix, int16_t metric/* = 1*/)
+IpFacesHelper::CreateTcpFace(const Time& when, Ptr<Node> node, Ipv4Address address,
+ const std::string& prefix, int16_t metric /* = 1*/)
{
- Simulator::ScheduleWithContext (node->GetId (), when, ScheduledCreateTcp, node, address, prefix, metric);
+ Simulator::ScheduleWithContext(node->GetId(), when, ScheduledCreateTcp, node, address, prefix,
+ metric);
}
static void
-ScheduledCreateUdp (Ptr<Node> node, Ipv4Address address, const std::string &prefix, int16_t metric)
+ScheduledCreateUdp(Ptr<Node> node, Ipv4Address address, const std::string& prefix, int16_t metric)
{
- Ptr<IpFaceStack> stack = node->GetObject<IpFaceStack> ();
- NS_ASSERT_MSG (stack != 0, "ndn::IpFaceStack needs to be installed on the node");
+ Ptr<IpFaceStack> stack = node->GetObject<IpFaceStack>();
+ NS_ASSERT_MSG(stack != 0, "ndn::IpFaceStack needs to be installed on the node");
- Ptr<Face> face = stack->CreateOrGetUdpFace (address);
- ndn::StackHelper::AddRoute (node, prefix, face, metric);
+ Ptr<Face> face = stack->CreateOrGetUdpFace(address);
+ ndn::StackHelper::AddRoute(node, prefix, face, metric);
}
void
-IpFacesHelper::CreateUdpFace (const Time &when, Ptr<Node> node, Ipv4Address address, const std::string &prefix, int16_t metric/* = 1*/)
+IpFacesHelper::CreateUdpFace(const Time& when, Ptr<Node> node, Ipv4Address address,
+ const std::string& prefix, int16_t metric /* = 1*/)
{
- Simulator::ScheduleWithContext (node->GetId (), when, ScheduledCreateUdp, node, address, prefix, metric);
+ Simulator::ScheduleWithContext(node->GetId(), when, ScheduledCreateUdp, node, address, prefix,
+ metric);
}
} // namespace ndn
diff --git a/plugins/ip-faces/ndn-ip-faces-helper.hpp b/plugins/ip-faces/ndn-ip-faces-helper.hpp
index 873fd8e..928a766 100644
--- a/plugins/ip-faces/ndn-ip-faces-helper.hpp
+++ b/plugins/ip-faces/ndn-ip-faces-helper.hpp
@@ -38,32 +38,32 @@
* @ingroup ndn-helpers
* @brief Helper for NDN IP-based face creation
*/
-class IpFacesHelper
-{
+class IpFacesHelper {
public:
/**
* @brief Install IpFaceStack interface on a node
* @param node Node to install IpFaceStack interface
*/
static void
- Install (Ptr<Node> node);
+ Install(Ptr<Node> node);
/**
* @brief Install IpFaceStack interface on nodes
* @param nodes NodeContainer to install IpFaceStack interface
*/
static void
- Install (const NodeContainer &nodes);
+ Install(const NodeContainer& nodes);
/**
* @brief Install IpFaceStack interface on all nodes
*/
static void
- InstallAll ();
+ InstallAll();
/**
* @brief Create TCP face
- * @param when Time when to create face (use `Seconds (0)' if face should be created right away)
+ * @param when Time when to create face (use `Seconds (0)' if face should be created right
+ *away)
* @param node Node to add TCP face (will initiate connection)
* @param address IP address to connect (using standard 9695 port)
* @param prefix Prefix to associate with the face
@@ -76,13 +76,15 @@
* update FIB with requested prefix
*/
static void
- CreateTcpFace (const Time &when, Ptr<Node> node, Ipv4Address address, const std::string &prefix, int16_t metric = 1);
+ CreateTcpFace(const Time& when, Ptr<Node> node, Ipv4Address address, const std::string& prefix,
+ int16_t metric = 1);
/**
* @brief Create TCP face
*/
static void
- CreateUdpFace (const Time &when, Ptr<Node> node, Ipv4Address address, const std::string &prefix, int16_t metric = 1);
+ CreateUdpFace(const Time& when, Ptr<Node> node, Ipv4Address address, const std::string& prefix,
+ int16_t metric = 1);
};
} // namespace ndn
diff --git a/plugins/ip-faces/ndn-tcp-face.cpp b/plugins/ip-faces/ndn-tcp-face.cpp
index 27e58b8..701ad64 100644
--- a/plugins/ip-faces/ndn-tcp-face.cpp
+++ b/plugins/ip-faces/ndn-tcp-face.cpp
@@ -34,73 +34,70 @@
using namespace std;
-NS_LOG_COMPONENT_DEFINE ("ndn.TcpFace");
+NS_LOG_COMPONENT_DEFINE("ndn.TcpFace");
namespace ns3 {
namespace ndn {
-class TcpBoundaryHeader : public Header
-{
+class TcpBoundaryHeader : public Header {
public:
- static TypeId GetTypeId (void)
+ static TypeId
+ GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::TcpFace::BoundaryHeader")
- .SetGroupName ("Ndn")
- .SetParent<Header> ()
- ;
+ static TypeId tid =
+ TypeId("ns3::ndn::TcpFace::BoundaryHeader").SetGroupName("Ndn").SetParent<Header>();
return tid;
}
- TcpBoundaryHeader ()
- : m_length (0)
+ TcpBoundaryHeader()
+ : m_length(0)
{
}
-
- TcpBoundaryHeader (Ptr<Packet> packet)
- : m_length (packet->GetSize ())
- {
-
- }
- TcpBoundaryHeader (uint32_t length)
- : m_length (length)
+ TcpBoundaryHeader(Ptr<Packet> packet)
+ : m_length(packet->GetSize())
+ {
+ }
+
+ TcpBoundaryHeader(uint32_t length)
+ : m_length(length)
{
}
uint32_t
- GetLength () const
+ GetLength() const
{
return m_length;
}
-
+
virtual TypeId
- GetInstanceTypeId (void) const
+ GetInstanceTypeId(void) const
{
- return TcpBoundaryHeader::GetTypeId ();
+ return TcpBoundaryHeader::GetTypeId();
}
-
+
virtual void
- Print (std::ostream &os) const
+ Print(std::ostream& os) const
{
os << "[" << m_length << "]";
}
-
+
virtual uint32_t
- GetSerializedSize (void) const
+ GetSerializedSize(void) const
{
return 4;
}
-
+
virtual void
- Serialize (Buffer::Iterator start) const
+ Serialize(Buffer::Iterator start) const
{
- start.WriteU32 (m_length);
+ start.WriteU32(m_length);
}
-
+
virtual uint32_t
- Deserialize (Buffer::Iterator start)
+ Deserialize(Buffer::Iterator start)
{
- m_length = start.ReadU32 ();
+ m_length = start.ReadU32();
return 4;
}
@@ -108,15 +105,12 @@
uint32_t m_length;
};
-NS_OBJECT_ENSURE_REGISTERED (TcpFace);
+NS_OBJECT_ENSURE_REGISTERED(TcpFace);
TypeId
-TcpFace::GetTypeId ()
+TcpFace::GetTypeId()
{
- static TypeId tid = TypeId ("ns3::ndn::TcpFace")
- .SetParent<Face> ()
- .SetGroupName ("Ndn")
- ;
+ static TypeId tid = TypeId("ns3::ndn::TcpFace").SetParent<Face>().SetGroupName("Ndn");
return tid;
}
@@ -124,18 +118,18 @@
* By default, Ndn face are created in the "down" state. Before
* becoming useable, the user must invoke SetUp on the face
*/
-TcpFace::TcpFace (Ptr<Node> node, Ptr<Socket> socket, Ipv4Address address)
- : Face (node)
- , m_socket (socket)
- , m_address (address)
- , m_pendingPacketLength (0)
+TcpFace::TcpFace(Ptr<Node> node, Ptr<Socket> socket, Ipv4Address address)
+ : Face(node)
+ , m_socket(socket)
+ , m_address(address)
+ , m_pendingPacketLength(0)
{
- SetMetric (1); // default metric
+ SetMetric(1); // default metric
}
-TcpFace::~TcpFace ()
+TcpFace::~TcpFace()
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
}
TcpFace& TcpFace::operator= (const TcpFace &)
@@ -144,143 +138,137 @@
}
void
-TcpFace::RegisterProtocolHandlers (const InterestHandler &interestHandler, const DataHandler &dataHandler)
+TcpFace::RegisterProtocolHandlers(const InterestHandler& interestHandler,
+ const DataHandler& dataHandler)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
- Face::RegisterProtocolHandlers (interestHandler, dataHandler);
- m_socket->SetRecvCallback (MakeCallback (&TcpFace::ReceiveFromTcp, this));
+ Face::RegisterProtocolHandlers(interestHandler, dataHandler);
+ m_socket->SetRecvCallback(MakeCallback(&TcpFace::ReceiveFromTcp, this));
}
void
-TcpFace::UnRegisterProtocolHandlers ()
+TcpFace::UnRegisterProtocolHandlers()
{
- m_socket->SetRecvCallback (MakeNullCallback< void, Ptr<Socket> > ());
- Face::UnRegisterProtocolHandlers ();
+ m_socket->SetRecvCallback(MakeNullCallback<void, Ptr<Socket>>());
+ Face::UnRegisterProtocolHandlers();
}
bool
-TcpFace::Send (Ptr<Packet> packet)
+TcpFace::Send(Ptr<Packet> packet)
{
- if (!Face::Send (packet))
- {
- return false;
- }
-
- NS_LOG_FUNCTION (this << packet);
+ if (!Face::Send(packet)) {
+ return false;
+ }
- Ptr<Packet> boundary = Create<Packet> ();
- TcpBoundaryHeader hdr (packet);
- boundary->AddHeader (hdr);
-
- m_socket->Send (boundary);
- m_socket->Send (packet);
+ NS_LOG_FUNCTION(this << packet);
+
+ Ptr<Packet> boundary = Create<Packet>();
+ TcpBoundaryHeader hdr(packet);
+ boundary->AddHeader(hdr);
+
+ m_socket->Send(boundary);
+ m_socket->Send(packet);
return true;
}
void
-TcpFace::ReceiveFromTcp (Ptr< Socket > clientSocket)
+TcpFace::ReceiveFromTcp(Ptr<Socket> clientSocket)
{
- NS_LOG_FUNCTION (this << clientSocket);
+ NS_LOG_FUNCTION(this << clientSocket);
TcpBoundaryHeader hdr;
- if (m_pendingPacketLength > 0)
- {
- if (clientSocket->GetRxAvailable () >= m_pendingPacketLength)
- {
- Ptr<Packet> realPacket = clientSocket->Recv (m_pendingPacketLength, 0);
- NS_LOG_DEBUG ("+++ Expected " << m_pendingPacketLength << " bytes, got " << realPacket->GetSize () << " bytes");
- if (realPacket == 0)
- return;
-
- Receive (realPacket);
- }
- else
- return; // still not ready
+ if (m_pendingPacketLength > 0) {
+ if (clientSocket->GetRxAvailable() >= m_pendingPacketLength) {
+ Ptr<Packet> realPacket = clientSocket->Recv(m_pendingPacketLength, 0);
+ NS_LOG_DEBUG("+++ Expected " << m_pendingPacketLength << " bytes, got "
+ << realPacket->GetSize() << " bytes");
+ if (realPacket == 0)
+ return;
+
+ Receive(realPacket);
}
-
+ else
+ return; // still not ready
+ }
+
m_pendingPacketLength = 0;
-
- while (clientSocket->GetRxAvailable () >= hdr.GetSerializedSize ())
- {
- Ptr<Packet> boundary = clientSocket->Recv (hdr.GetSerializedSize (), 0);
- if (boundary == 0)
- return; // no idea why it would happen...
- NS_LOG_DEBUG ("Expected 4 bytes, got " << boundary->GetSize () << " bytes");
-
- boundary->RemoveHeader (hdr);
- NS_LOG_DEBUG ("Header specifies length: " << hdr.GetLength ());
- m_pendingPacketLength = hdr.GetLength ();
-
- if (clientSocket->GetRxAvailable () >= hdr.GetLength ())
- {
- Ptr<Packet> realPacket = clientSocket->Recv (hdr.GetLength (), 0);
- if (realPacket == 0)
- {
- NS_LOG_DEBUG ("Got nothing, but requested at least " << hdr.GetLength ());
- return;
- }
-
- NS_LOG_DEBUG ("Receiving data " << hdr.GetLength () << " bytes, got " << realPacket->GetSize () << " bytes");
+ while (clientSocket->GetRxAvailable() >= hdr.GetSerializedSize()) {
+ Ptr<Packet> boundary = clientSocket->Recv(hdr.GetSerializedSize(), 0);
+ if (boundary == 0)
+ return; // no idea why it would happen...
- Receive (realPacket);
- m_pendingPacketLength = 0;
- }
- else
- {
- return;
- }
+ NS_LOG_DEBUG("Expected 4 bytes, got " << boundary->GetSize() << " bytes");
+
+ boundary->RemoveHeader(hdr);
+ NS_LOG_DEBUG("Header specifies length: " << hdr.GetLength());
+ m_pendingPacketLength = hdr.GetLength();
+
+ if (clientSocket->GetRxAvailable() >= hdr.GetLength()) {
+ Ptr<Packet> realPacket = clientSocket->Recv(hdr.GetLength(), 0);
+ if (realPacket == 0) {
+ NS_LOG_DEBUG("Got nothing, but requested at least " << hdr.GetLength());
+ return;
+ }
+
+ NS_LOG_DEBUG("Receiving data " << hdr.GetLength() << " bytes, got " << realPacket->GetSize()
+ << " bytes");
+
+ Receive(realPacket);
+ m_pendingPacketLength = 0;
}
+ else {
+ return;
+ }
+ }
}
void
-TcpFace::OnTcpConnectionClosed (Ptr<Socket> socket)
+TcpFace::OnTcpConnectionClosed(Ptr<Socket> socket)
{
- NS_LOG_FUNCTION (this << socket);
- GetNode ()->GetObject<IpFaceStack> ()->DestroyTcpFace (this);
+ NS_LOG_FUNCTION(this << socket);
+ GetNode()->GetObject<IpFaceStack>()->DestroyTcpFace(this);
}
Ipv4Address
-TcpFace::GetAddress () const
+TcpFace::GetAddress() const
{
return m_address;
}
void
-TcpFace::SetCreateCallback (Callback< void, Ptr<Face> > callback)
+TcpFace::SetCreateCallback(Callback<void, Ptr<Face>> callback)
{
m_onCreateCallback = callback;
}
void
-TcpFace::OnConnect (Ptr<Socket> socket)
+TcpFace::OnConnect(Ptr<Socket> socket)
{
- NS_LOG_FUNCTION (this << socket);
+ NS_LOG_FUNCTION(this << socket);
- Ptr<L3Protocol> ndn = GetNode ()->GetObject<L3Protocol> ();
-
- ndn->AddFace (this);
- this->SetUp (true);
+ Ptr<L3Protocol> ndn = GetNode()->GetObject<L3Protocol>();
- socket->SetCloseCallbacks (MakeCallback (&TcpFace::OnTcpConnectionClosed, this),
- MakeCallback (&TcpFace::OnTcpConnectionClosed, this));
+ ndn->AddFace(this);
+ this->SetUp(true);
- if (!m_onCreateCallback.IsNull ())
- {
- m_onCreateCallback (this);
- m_onCreateCallback = IpFaceStack::NULL_CREATE_CALLBACK;
- }
+ socket->SetCloseCallbacks(MakeCallback(&TcpFace::OnTcpConnectionClosed, this),
+ MakeCallback(&TcpFace::OnTcpConnectionClosed, this));
+
+ if (!m_onCreateCallback.IsNull()) {
+ m_onCreateCallback(this);
+ m_onCreateCallback = IpFaceStack::NULL_CREATE_CALLBACK;
+ }
}
-
+
std::ostream&
-TcpFace::Print (std::ostream& os) const
+TcpFace::Print(std::ostream& os) const
{
- os << "dev=tcp(" << GetId () << ", " << m_address << ")";
+ os << "dev=tcp(" << GetId() << ", " << m_address << ")";
return os;
}
} // namespace ndn
} // namespace ns3
-
diff --git a/plugins/ip-faces/ndn-tcp-face.hpp b/plugins/ip-faces/ndn-tcp-face.hpp
index 249fd6a..0543bd5 100644
--- a/plugins/ip-faces/ndn-tcp-face.hpp
+++ b/plugins/ip-faces/ndn-tcp-face.hpp
@@ -30,70 +30,70 @@
namespace ns3 {
namespace ndn {
-
+
/**
* \ingroup ndn-face
* \brief Implementation of TCP/IP NDN face
*
* \see NdnAppFace, NdnNetDeviceFace, NdnIpv4Face, NdnUdpFace
*/
-class TcpFace : public Face
-{
+class TcpFace : public Face {
public:
static TypeId
- GetTypeId ();
-
+ GetTypeId();
+
/**
* \brief Constructor
*
* @param node Node associated with the face
*/
- TcpFace (Ptr<Node> node, Ptr<Socket> socket, Ipv4Address address);
+ TcpFace(Ptr<Node> node, Ptr<Socket> socket, Ipv4Address address);
virtual ~TcpFace();
void
- OnTcpConnectionClosed (Ptr<Socket> socket);
+ OnTcpConnectionClosed(Ptr<Socket> socket);
Ipv4Address
- GetAddress () const;
+ GetAddress() const;
static Ptr<TcpFace>
- GetFaceByAddress (const Ipv4Address &addr);
+ GetFaceByAddress(const Ipv4Address& addr);
void
- SetCreateCallback (Callback< void, Ptr<Face> > callback);
+ SetCreateCallback(Callback<void, Ptr<Face>> callback);
void
- OnConnect (Ptr<Socket> socket);
+ OnConnect(Ptr<Socket> socket);
////////////////////////////////////////////////////////////////////
// methods overloaded from ndn::Face
virtual void
- RegisterProtocolHandlers (const InterestHandler &interestHandler, const DataHandler &dataHandler);
+ RegisterProtocolHandlers(const InterestHandler& interestHandler, const DataHandler& dataHandler);
virtual void
- UnRegisterProtocolHandlers ();
+ UnRegisterProtocolHandlers();
virtual std::ostream&
- Print (std::ostream &os) const;
-
+ Print(std::ostream& os) const;
+
protected:
// also from ndn::Face
virtual bool
- Send (Ptr<Packet> p);
+ Send(Ptr<Packet> p);
-private:
- TcpFace (const TcpFace &); ///< \brief Disabled copy constructor
- TcpFace& operator= (const TcpFace &); ///< \brief Disabled copy operator
+private:
+ TcpFace(const TcpFace&); ///< \brief Disabled copy constructor
+ TcpFace&
+ operator=(const TcpFace&); ///< \brief Disabled copy operator
void
- ReceiveFromTcp (Ptr< Socket > clientSocket);
+ ReceiveFromTcp(Ptr<Socket> clientSocket);
private:
Ptr<Socket> m_socket;
Ipv4Address m_address;
uint32_t m_pendingPacketLength;
- Callback< void, Ptr<Face> > m_onCreateCallback;
+ Callback<void, Ptr<Face>> m_onCreateCallback;
};
} // namespace ndn
diff --git a/plugins/ip-faces/ndn-udp-face.cpp b/plugins/ip-faces/ndn-udp-face.cpp
index 03d8ee4..fed972c 100644
--- a/plugins/ip-faces/ndn-udp-face.cpp
+++ b/plugins/ip-faces/ndn-udp-face.cpp
@@ -32,20 +32,17 @@
using namespace std;
-NS_LOG_COMPONENT_DEFINE ("ndn.UdpFace");
+NS_LOG_COMPONENT_DEFINE("ndn.UdpFace");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (UdpFace);
+NS_OBJECT_ENSURE_REGISTERED(UdpFace);
TypeId
-UdpFace::GetTypeId ()
+UdpFace::GetTypeId()
{
- static TypeId tid = TypeId ("ns3::ndn::UdpFace")
- .SetParent<Face> ()
- .SetGroupName ("Ndn")
- ;
+ static TypeId tid = TypeId("ns3::ndn::UdpFace").SetParent<Face>().SetGroupName("Ndn");
return tid;
}
@@ -53,17 +50,17 @@
* By default, Ndn face are created in the "down" state. Before
* becoming useable, the user must invoke SetUp on the face
*/
-UdpFace::UdpFace (Ptr<Node> node, Ptr<Socket> socket, Ipv4Address address)
- : Face (node)
- , m_socket (socket)
- , m_address (address)
+UdpFace::UdpFace(Ptr<Node> node, Ptr<Socket> socket, Ipv4Address address)
+ : Face(node)
+ , m_socket(socket)
+ , m_address(address)
{
- SetMetric (1); // default metric
+ SetMetric(1); // default metric
}
-UdpFace::~UdpFace ()
+UdpFace::~UdpFace()
{
- NS_LOG_FUNCTION_NOARGS ();
+ NS_LOG_FUNCTION_NOARGS();
}
UdpFace& UdpFace::operator= (const UdpFace &)
@@ -72,35 +69,34 @@
}
bool
-UdpFace::ReceiveFromUdp (Ptr<const Packet> p)
+UdpFace::ReceiveFromUdp(Ptr<const Packet> p)
{
- return Face::Receive (p);
+ return Face::Receive(p);
}
bool
-UdpFace::Send (Ptr<Packet> packet)
+UdpFace::Send(Ptr<Packet> packet)
{
- if (!Face::Send (packet))
- {
- return false;
- }
-
- NS_LOG_FUNCTION (this << packet);
- m_socket->Send (packet);
+ if (!Face::Send(packet)) {
+ return false;
+ }
+
+ NS_LOG_FUNCTION(this << packet);
+ m_socket->Send(packet);
return true;
}
Ipv4Address
-UdpFace::GetAddress () const
+UdpFace::GetAddress() const
{
return m_address;
}
std::ostream&
-UdpFace::Print (std::ostream& os) const
+UdpFace::Print(std::ostream& os) const
{
- os << "dev=udp(" << GetId () << "," << GetAddress () << ")";
+ os << "dev=udp(" << GetId() << "," << GetAddress() << ")";
return os;
}
diff --git a/plugins/ip-faces/ndn-udp-face.hpp b/plugins/ip-faces/ndn-udp-face.hpp
index 207eac0..f0c3293 100644
--- a/plugins/ip-faces/ndn-udp-face.hpp
+++ b/plugins/ip-faces/ndn-udp-face.hpp
@@ -29,46 +29,46 @@
namespace ns3 {
namespace ndn {
-
+
/**
* \ingroup ndn-face
* \brief Implementation of UDP/IP NDN face
*
* \see ndn::AppFace, ndn::NetDeviceFace, ndn::Ipv4Face, ndn::TcpFace
*/
-class UdpFace : public Face
-{
+class UdpFace : public Face {
public:
static TypeId
- GetTypeId ();
-
+ GetTypeId();
+
/**
* \brief Constructor
*
* @param node Node associated with the face
*/
- UdpFace (Ptr<Node> node, Ptr<Socket> socket, Ipv4Address address);
+ UdpFace(Ptr<Node> node, Ptr<Socket> socket, Ipv4Address address);
virtual ~UdpFace();
Ipv4Address
- GetAddress () const;
+ GetAddress() const;
virtual bool
- ReceiveFromUdp (Ptr<const Packet> p);
+ ReceiveFromUdp(Ptr<const Packet> p);
////////////////////////////////////////////////////////////////////
// methods overloaded from ndn::Face
virtual std::ostream&
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
protected:
// also from ndn::Face
virtual bool
- Send (Ptr<Packet> p);
+ Send(Ptr<Packet> p);
-private:
- UdpFace (const UdpFace &); ///< \brief Disabled copy constructor
- UdpFace& operator= (const UdpFace &); ///< \brief Disabled copy operator
+private:
+ UdpFace(const UdpFace&); ///< \brief Disabled copy constructor
+ UdpFace&
+ operator=(const UdpFace&); ///< \brief Disabled copy operator
private:
Ptr<Socket> m_socket;
diff --git a/plugins/topology/annotated-topology-reader.cpp b/plugins/topology/annotated-topology-reader.cpp
index 7160dab..c64d823 100644
--- a/plugins/topology/annotated-topology-reader.cpp
+++ b/plugins/topology/annotated-topology-reader.cpp
@@ -62,520 +62,500 @@
namespace ns3 {
-NS_LOG_COMPONENT_DEFINE ("AnnotatedTopologyReader");
+NS_LOG_COMPONENT_DEFINE("AnnotatedTopologyReader");
-AnnotatedTopologyReader::AnnotatedTopologyReader (const std::string &path, double scale/*=1.0*/)
- : m_path (path)
- , m_randX (0, 100.0)
- , m_randY (0, 100.0)
- , m_scale (scale)
- , m_requiredPartitions (1)
+AnnotatedTopologyReader::AnnotatedTopologyReader(const std::string& path, double scale /*=1.0*/)
+ : m_path(path)
+ , m_randX(0, 100.0)
+ , m_randY(0, 100.0)
+ , m_scale(scale)
+ , m_requiredPartitions(1)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
- SetMobilityModel ("ns3::ConstantPositionMobilityModel");
+ SetMobilityModel("ns3::ConstantPositionMobilityModel");
}
void
-AnnotatedTopologyReader::SetBoundingBox (double ulx, double uly, double lrx, double lry)
+AnnotatedTopologyReader::SetBoundingBox(double ulx, double uly, double lrx, double lry)
{
- NS_LOG_FUNCTION (this << ulx << uly << lrx << lry);
+ NS_LOG_FUNCTION(this << ulx << uly << lrx << lry);
- m_randX = UniformVariable (ulx, lrx);
- m_randY = UniformVariable (uly, lry);
+ m_randX = UniformVariable(ulx, lrx);
+ m_randY = UniformVariable(uly, lry);
}
void
-AnnotatedTopologyReader::SetMobilityModel (const std::string &model)
+AnnotatedTopologyReader::SetMobilityModel(const std::string& model)
{
- NS_LOG_FUNCTION (this << model);
- m_mobilityFactory.SetTypeId (model);
+ NS_LOG_FUNCTION(this << model);
+ m_mobilityFactory.SetTypeId(model);
}
-AnnotatedTopologyReader::~AnnotatedTopologyReader ()
+AnnotatedTopologyReader::~AnnotatedTopologyReader()
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
Ptr<Node>
-AnnotatedTopologyReader::CreateNode (const std::string name, uint32_t systemId)
+AnnotatedTopologyReader::CreateNode(const std::string name, uint32_t systemId)
{
- NS_LOG_FUNCTION (this << name);
- m_requiredPartitions = std::max (m_requiredPartitions, systemId + 1);
+ NS_LOG_FUNCTION(this << name);
+ m_requiredPartitions = std::max(m_requiredPartitions, systemId + 1);
- Ptr<Node> node = CreateObject<Node> (systemId);
+ Ptr<Node> node = CreateObject<Node>(systemId);
- Names::Add (m_path, name, node);
- m_nodes.Add (node);
+ Names::Add(m_path, name, node);
+ m_nodes.Add(node);
return node;
}
Ptr<Node>
-AnnotatedTopologyReader::CreateNode (const std::string name, double posX, double posY, uint32_t systemId)
+AnnotatedTopologyReader::CreateNode(const std::string name, double posX, double posY,
+ uint32_t systemId)
{
- NS_LOG_FUNCTION (this << name << posX << posY);
- m_requiredPartitions = std::max (m_requiredPartitions, systemId + 1);
+ NS_LOG_FUNCTION(this << name << posX << posY);
+ m_requiredPartitions = std::max(m_requiredPartitions, systemId + 1);
- Ptr<Node> node = CreateObject<Node> (systemId);
- Ptr<MobilityModel> loc = DynamicCast<MobilityModel> (m_mobilityFactory.Create ());
- node->AggregateObject (loc);
+ Ptr<Node> node = CreateObject<Node>(systemId);
+ Ptr<MobilityModel> loc = DynamicCast<MobilityModel>(m_mobilityFactory.Create());
+ node->AggregateObject(loc);
- loc->SetPosition (Vector (posX, posY, 0));
+ loc->SetPosition(Vector(posX, posY, 0));
- Names::Add (m_path, name, node);
- m_nodes.Add (node);
+ Names::Add(m_path, name, node);
+ m_nodes.Add(node);
return node;
}
NodeContainer
-AnnotatedTopologyReader::GetNodes () const
+AnnotatedTopologyReader::GetNodes() const
{
return m_nodes;
}
const std::list<TopologyReader::Link>&
-AnnotatedTopologyReader::GetLinks () const
+AnnotatedTopologyReader::GetLinks() const
{
return m_linksList;
}
NodeContainer
-AnnotatedTopologyReader::Read (void)
+AnnotatedTopologyReader::Read(void)
{
ifstream topgen;
- topgen.open (GetFileName ().c_str ());
+ topgen.open(GetFileName().c_str());
- if ( !topgen.is_open () || !topgen.good () )
- {
- NS_FATAL_ERROR ("Cannot open file " << GetFileName () << " for reading");
- return m_nodes;
+ if (!topgen.is_open() || !topgen.good()) {
+ NS_FATAL_ERROR("Cannot open file " << GetFileName() << " for reading");
+ return m_nodes;
+ }
+
+ while (!topgen.eof()) {
+ string line;
+ getline(topgen, line);
+
+ if (line == "router")
+ break;
+ }
+
+ if (topgen.eof()) {
+ NS_FATAL_ERROR("Topology file " << GetFileName() << " does not have \"router\" section");
+ return m_nodes;
+ }
+
+ while (!topgen.eof()) {
+ string line;
+ getline(topgen, line);
+ if (line[0] == '#')
+ continue; // comments
+ if (line == "link")
+ break; // stop reading nodes
+
+ istringstream lineBuffer(line);
+ string name, city;
+ double latitude = 0, longitude = 0;
+ uint32_t systemId = 0;
+
+ lineBuffer >> name >> city >> latitude >> longitude >> systemId;
+ if (name.empty())
+ continue;
+
+ Ptr<Node> node;
+
+ if (abs(latitude) > 0.001 && abs(latitude) > 0.001)
+ node = CreateNode(name, m_scale * longitude, -m_scale * latitude, systemId);
+ else {
+ UniformVariable var(0, 200);
+ node = CreateNode(name, var.GetValue(), var.GetValue(), systemId);
+ // node = CreateNode (name, systemId);
}
+ }
- while (!topgen.eof ())
- {
- string line;
- getline (topgen, line);
+ map<string, set<string>> processedLinks; // to eliminate duplications
- if (line == "router") break;
- }
-
- if (topgen.eof ())
- {
- NS_FATAL_ERROR ("Topology file " << GetFileName () << " does not have \"router\" section");
- return m_nodes;
- }
-
- while (!topgen.eof ())
- {
- string line;
- getline (topgen,line);
- if (line[0] == '#') continue; // comments
- if (line=="link") break; // stop reading nodes
-
- istringstream lineBuffer (line);
- string name, city;
- double latitude = 0, longitude = 0;
- uint32_t systemId = 0;
-
- lineBuffer >> name >> city >> latitude >> longitude >> systemId;
- if (name.empty ()) continue;
-
- Ptr<Node> node;
-
- if (abs(latitude) > 0.001 && abs(latitude) > 0.001)
- node = CreateNode (name, m_scale*longitude, -m_scale*latitude, systemId);
- else
- {
- UniformVariable var (0,200);
- node = CreateNode (name, var.GetValue (), var.GetValue (), systemId);
- // node = CreateNode (name, systemId);
- }
- }
-
- map<string, set<string> > processedLinks; // to eliminate duplications
-
- if (topgen.eof ())
- {
- NS_LOG_ERROR ("Topology file " << GetFileName () << " does not have \"link\" section");
- return m_nodes;
- }
+ if (topgen.eof()) {
+ NS_LOG_ERROR("Topology file " << GetFileName() << " does not have \"link\" section");
+ return m_nodes;
+ }
// SeekToSection ("link");
- while (!topgen.eof ())
- {
- string line;
- getline (topgen,line);
- if (line == "") continue;
- if (line[0] == '#') continue; // comments
+ while (!topgen.eof()) {
+ string line;
+ getline(topgen, line);
+ if (line == "")
+ continue;
+ if (line[0] == '#')
+ continue; // comments
- // NS_LOG_DEBUG ("Input: [" << line << "]");
+ // NS_LOG_DEBUG ("Input: [" << line << "]");
- istringstream lineBuffer (line);
- string from, to, capacity, metric, delay, maxPackets, lossRate;
+ istringstream lineBuffer(line);
+ string from, to, capacity, metric, delay, maxPackets, lossRate;
- lineBuffer >> from >> to >> capacity >> metric >> delay >> maxPackets >> lossRate;
+ lineBuffer >> from >> to >> capacity >> metric >> delay >> maxPackets >> lossRate;
- if (processedLinks[to].size () != 0 &&
- processedLinks[to].find (from) != processedLinks[to].end ())
- {
- continue; // duplicated link
- }
- processedLinks[from].insert (to);
-
- Ptr<Node> fromNode = Names::Find<Node> (m_path, from);
- NS_ASSERT_MSG (fromNode != 0, from << " node not found");
- Ptr<Node> toNode = Names::Find<Node> (m_path, to);
- NS_ASSERT_MSG (toNode != 0, to << " node not found");
-
- Link link (fromNode, from, toNode, to);
-
- link.SetAttribute ("DataRate", capacity);
- link.SetAttribute ("OSPF", metric);
-
- if (!delay.empty ())
- link.SetAttribute ("Delay", delay);
- if (!maxPackets.empty ())
- link.SetAttribute ("MaxPackets", maxPackets);
-
- // Saran Added lossRate
- if (!lossRate.empty ())
- link.SetAttribute ("LossRate", lossRate);
-
- AddLink (link);
- NS_LOG_DEBUG ("New link " << from << " <==> " << to << " / " << capacity << " with " << metric << " metric (" << delay << ", " << maxPackets << ", " << lossRate << ")");
+ if (processedLinks[to].size() != 0
+ && processedLinks[to].find(from) != processedLinks[to].end()) {
+ continue; // duplicated link
}
+ processedLinks[from].insert(to);
- NS_LOG_INFO ("Annotated topology created with " << m_nodes.GetN () << " nodes and " << LinksSize () << " links");
- topgen.close ();
+ Ptr<Node> fromNode = Names::Find<Node>(m_path, from);
+ NS_ASSERT_MSG(fromNode != 0, from << " node not found");
+ Ptr<Node> toNode = Names::Find<Node>(m_path, to);
+ NS_ASSERT_MSG(toNode != 0, to << " node not found");
- ApplySettings ();
+ Link link(fromNode, from, toNode, to);
+
+ link.SetAttribute("DataRate", capacity);
+ link.SetAttribute("OSPF", metric);
+
+ if (!delay.empty())
+ link.SetAttribute("Delay", delay);
+ if (!maxPackets.empty())
+ link.SetAttribute("MaxPackets", maxPackets);
+
+ // Saran Added lossRate
+ if (!lossRate.empty())
+ link.SetAttribute("LossRate", lossRate);
+
+ AddLink(link);
+ NS_LOG_DEBUG("New link " << from << " <==> " << to << " / " << capacity << " with " << metric
+ << " metric (" << delay << ", " << maxPackets << ", " << lossRate
+ << ")");
+ }
+
+ NS_LOG_INFO("Annotated topology created with " << m_nodes.GetN() << " nodes and " << LinksSize()
+ << " links");
+ topgen.close();
+
+ ApplySettings();
return m_nodes;
}
void
-AnnotatedTopologyReader::AssignIpv4Addresses (Ipv4Address base)
+AnnotatedTopologyReader::AssignIpv4Addresses(Ipv4Address base)
{
- Ipv4AddressHelper address (base, Ipv4Mask ("/24"));
+ Ipv4AddressHelper address(base, Ipv4Mask("/24"));
- BOOST_FOREACH (const Link &link, m_linksList)
- {
- address.Assign (NetDeviceContainer (link.GetFromNetDevice (),
- link.GetToNetDevice ()));
+ BOOST_FOREACH (const Link& link, m_linksList) {
+ address.Assign(NetDeviceContainer(link.GetFromNetDevice(), link.GetToNetDevice()));
- base = Ipv4Address (base.Get () + 256);
- address.SetBase (base, Ipv4Mask ("/24"));
- }
+ base = Ipv4Address(base.Get() + 256);
+ address.SetBase(base, Ipv4Mask("/24"));
+ }
}
void
-AnnotatedTopologyReader::ApplyOspfMetric ()
+AnnotatedTopologyReader::ApplyOspfMetric()
{
- BOOST_FOREACH (const Link &link, m_linksList)
+ BOOST_FOREACH (const Link& link, m_linksList) {
+ NS_LOG_DEBUG("OSPF: " << link.GetAttribute("OSPF"));
+ uint16_t metric = boost::lexical_cast<uint16_t>(link.GetAttribute("OSPF"));
+
{
- NS_LOG_DEBUG ("OSPF: " << link.GetAttribute ("OSPF"));
- uint16_t metric = boost::lexical_cast<uint16_t> (link.GetAttribute ("OSPF"));
+ Ptr<Ipv4> ipv4 = link.GetFromNode()->GetObject<Ipv4>();
+ if (ipv4 != 0) {
+ int32_t interfaceId = ipv4->GetInterfaceForDevice(link.GetFromNetDevice());
+ NS_ASSERT(interfaceId >= 0);
- {
- Ptr<Ipv4> ipv4 = link.GetFromNode ()->GetObject<Ipv4> ();
- if (ipv4 != 0)
- {
- int32_t interfaceId = ipv4->GetInterfaceForDevice (link.GetFromNetDevice ());
- NS_ASSERT (interfaceId >= 0);
-
- ipv4->SetMetric (interfaceId,metric);
- }
-
- Ptr<ndn::L3Protocol> ndn = link.GetFromNode ()->GetObject<ndn::L3Protocol> ();
- if (ndn != 0)
- {
- Ptr<ndn::Face> face = ndn->GetFaceByNetDevice (link.GetFromNetDevice ());
- NS_ASSERT (face != 0);
-
- face->SetMetric (metric);
- }
+ ipv4->SetMetric(interfaceId, metric);
}
- {
- Ptr<Ipv4> ipv4 = link.GetToNode ()->GetObject<Ipv4> ();
- if (ipv4 != 0)
- {
- int32_t interfaceId = ipv4->GetInterfaceForDevice (link.GetToNetDevice ());
- NS_ASSERT (interfaceId >= 0);
+ Ptr<ndn::L3Protocol> ndn = link.GetFromNode()->GetObject<ndn::L3Protocol>();
+ if (ndn != 0) {
+ Ptr<ndn::Face> face = ndn->GetFaceByNetDevice(link.GetFromNetDevice());
+ NS_ASSERT(face != 0);
- ipv4->SetMetric (interfaceId,metric);
- }
-
- Ptr<ndn::L3Protocol> ndn = link.GetToNode ()->GetObject<ndn::L3Protocol> ();
- if (ndn != 0)
- {
- Ptr<ndn::Face> face = ndn->GetFaceByNetDevice (link.GetToNetDevice ());
- NS_ASSERT (face != 0);
-
- face->SetMetric (metric);
- }
+ face->SetMetric(metric);
}
}
+
+ {
+ Ptr<Ipv4> ipv4 = link.GetToNode()->GetObject<Ipv4>();
+ if (ipv4 != 0) {
+ int32_t interfaceId = ipv4->GetInterfaceForDevice(link.GetToNetDevice());
+ NS_ASSERT(interfaceId >= 0);
+
+ ipv4->SetMetric(interfaceId, metric);
+ }
+
+ Ptr<ndn::L3Protocol> ndn = link.GetToNode()->GetObject<ndn::L3Protocol>();
+ if (ndn != 0) {
+ Ptr<ndn::Face> face = ndn->GetFaceByNetDevice(link.GetToNetDevice());
+ NS_ASSERT(face != 0);
+
+ face->SetMetric(metric);
+ }
+ }
+ }
}
void
-AnnotatedTopologyReader::ApplySettings ()
+AnnotatedTopologyReader::ApplySettings()
{
#ifdef NS3_MPI
- if (MpiInterface::IsEnabled () &&
- MpiInterface::GetSize () != m_requiredPartitions)
- {
- std::cerr << "MPI interface is enabled, but number of partitions (" << MpiInterface::GetSize ()
- << ") is not equal to number of partitions in the topology (" << m_requiredPartitions << ")";
- exit (-1);
- }
+ if (MpiInterface::IsEnabled() && MpiInterface::GetSize() != m_requiredPartitions) {
+ std::cerr << "MPI interface is enabled, but number of partitions (" << MpiInterface::GetSize()
+ << ") is not equal to number of partitions in the topology (" << m_requiredPartitions
+ << ")";
+ exit(-1);
+ }
#endif
PointToPointHelper p2p;
- BOOST_FOREACH (Link &link, m_linksList)
- {
- // cout << "Link: " << Findlink.GetFromNode () << ", " << link.GetToNode () << endl;
- string tmp;
+ BOOST_FOREACH (Link& link, m_linksList) {
+ // cout << "Link: " << Findlink.GetFromNode () << ", " << link.GetToNode () << endl;
+ string tmp;
- ////////////////////////////////////////////////
- if (link.GetAttributeFailSafe ("MaxPackets", tmp))
- {
- NS_LOG_INFO ("MaxPackets = " + link.GetAttribute ("MaxPackets"));
+ ////////////////////////////////////////////////
+ if (link.GetAttributeFailSafe("MaxPackets", tmp)) {
+ NS_LOG_INFO("MaxPackets = " + link.GetAttribute("MaxPackets"));
- try
- {
- uint32_t maxPackets = boost::lexical_cast<uint32_t> (link.GetAttribute ("MaxPackets"));
+ try {
+ uint32_t maxPackets = boost::lexical_cast<uint32_t>(link.GetAttribute("MaxPackets"));
- // compatibility mode. Only DropTailQueue is supported
- p2p.SetQueue ("ns3::DropTailQueue",
- "MaxPackets", UintegerValue (maxPackets));
- }
- catch (...)
- {
- typedef boost::tokenizer<boost::escaped_list_separator<char> > tokenizer;
- tokenizer tok (link.GetAttribute ("MaxPackets"));
+ // compatibility mode. Only DropTailQueue is supported
+ p2p.SetQueue("ns3::DropTailQueue", "MaxPackets", UintegerValue(maxPackets));
+ }
+ catch (...) {
+ typedef boost::tokenizer<boost::escaped_list_separator<char>> tokenizer;
+ tokenizer tok(link.GetAttribute("MaxPackets"));
- tokenizer::iterator token = tok.begin ();
- p2p.SetQueue (*token);
+ tokenizer::iterator token = tok.begin();
+ p2p.SetQueue(*token);
- for (token ++; token != tok.end (); token ++)
- {
- boost::escaped_list_separator<char> separator ('\\', '=', '\"');
- tokenizer attributeTok (*token, separator);
+ for (token++; token != tok.end(); token++) {
+ boost::escaped_list_separator<char> separator('\\', '=', '\"');
+ tokenizer attributeTok(*token, separator);
- tokenizer::iterator attributeToken = attributeTok.begin ();
+ tokenizer::iterator attributeToken = attributeTok.begin();
- string attribute = *attributeToken;
- attributeToken++;
+ string attribute = *attributeToken;
+ attributeToken++;
- if (attributeToken == attributeTok.end ())
- {
- NS_LOG_ERROR ("Queue attribute [" << *token << "] should be in form <Attribute>=<Value>");
- continue;
- }
+ if (attributeToken == attributeTok.end()) {
+ NS_LOG_ERROR("Queue attribute [" << *token
+ << "] should be in form <Attribute>=<Value>");
+ continue;
+ }
- string value = *attributeToken;
+ string value = *attributeToken;
- p2p.SetQueueAttribute (attribute, StringValue (value));
- }
- }
+ p2p.SetQueueAttribute(attribute, StringValue(value));
}
-
- if (link.GetAttributeFailSafe ("DataRate", tmp))
- {
- NS_LOG_INFO ("DataRate = " + link.GetAttribute("DataRate"));
- p2p.SetDeviceAttribute ("DataRate", StringValue (link.GetAttribute ("DataRate")));
- }
-
- if (link.GetAttributeFailSafe ("Delay", tmp))
- {
- NS_LOG_INFO ("Delay = " + link.GetAttribute("Delay"));
- p2p.SetChannelAttribute ("Delay", StringValue (link.GetAttribute ("Delay")));
- }
-
- NetDeviceContainer nd = p2p.Install(link.GetFromNode (), link.GetToNode ());
- link.SetNetDevices (nd.Get (0), nd.Get (1));
-
- ////////////////////////////////////////////////
- if (link.GetAttributeFailSafe ("LossRate", tmp))
- {
- NS_LOG_INFO ("LinkError = " + link.GetAttribute("LossRate"));
-
- typedef boost::tokenizer<boost::escaped_list_separator<char> > tokenizer;
- tokenizer tok (link.GetAttribute("LossRate"));
-
- tokenizer::iterator token = tok.begin ();
- ObjectFactory factory (*token);
-
- for (token ++; token != tok.end (); token ++)
- {
- boost::escaped_list_separator<char> separator ('\\', '=', '\"');
- tokenizer attributeTok (*token, separator);
-
- tokenizer::iterator attributeToken = attributeTok.begin ();
-
- string attribute = *attributeToken;
- attributeToken++;
-
- if (attributeToken == attributeTok.end ())
- {
- NS_LOG_ERROR ("ErrorModel attribute [" << *token << "] should be in form <Attribute>=<Value>");
- continue;
- }
-
- string value = *attributeToken;
-
- factory.Set (attribute, StringValue (value));
- }
-
- nd.Get (0)->SetAttribute ("ReceiveErrorModel", PointerValue (factory.Create<ErrorModel> ()));
- nd.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (factory.Create<ErrorModel> ()));
- }
+ }
}
+
+ if (link.GetAttributeFailSafe("DataRate", tmp)) {
+ NS_LOG_INFO("DataRate = " + link.GetAttribute("DataRate"));
+ p2p.SetDeviceAttribute("DataRate", StringValue(link.GetAttribute("DataRate")));
+ }
+
+ if (link.GetAttributeFailSafe("Delay", tmp)) {
+ NS_LOG_INFO("Delay = " + link.GetAttribute("Delay"));
+ p2p.SetChannelAttribute("Delay", StringValue(link.GetAttribute("Delay")));
+ }
+
+ NetDeviceContainer nd = p2p.Install(link.GetFromNode(), link.GetToNode());
+ link.SetNetDevices(nd.Get(0), nd.Get(1));
+
+ ////////////////////////////////////////////////
+ if (link.GetAttributeFailSafe("LossRate", tmp)) {
+ NS_LOG_INFO("LinkError = " + link.GetAttribute("LossRate"));
+
+ typedef boost::tokenizer<boost::escaped_list_separator<char>> tokenizer;
+ tokenizer tok(link.GetAttribute("LossRate"));
+
+ tokenizer::iterator token = tok.begin();
+ ObjectFactory factory(*token);
+
+ for (token++; token != tok.end(); token++) {
+ boost::escaped_list_separator<char> separator('\\', '=', '\"');
+ tokenizer attributeTok(*token, separator);
+
+ tokenizer::iterator attributeToken = attributeTok.begin();
+
+ string attribute = *attributeToken;
+ attributeToken++;
+
+ if (attributeToken == attributeTok.end()) {
+ NS_LOG_ERROR("ErrorModel attribute [" << *token
+ << "] should be in form <Attribute>=<Value>");
+ continue;
+ }
+
+ string value = *attributeToken;
+
+ factory.Set(attribute, StringValue(value));
+ }
+
+ nd.Get(0)->SetAttribute("ReceiveErrorModel", PointerValue(factory.Create<ErrorModel>()));
+ nd.Get(1)->SetAttribute("ReceiveErrorModel", PointerValue(factory.Create<ErrorModel>()));
+ }
+ }
}
void
-AnnotatedTopologyReader::SaveTopology (const std::string &file)
+AnnotatedTopologyReader::SaveTopology(const std::string& file)
{
- ofstream os (file.c_str (), ios::trunc);
+ ofstream os(file.c_str(), ios::trunc);
os << "# any empty lines and lines starting with '#' symbol is ignored\n"
<< "\n"
- << "# The file should contain exactly two sections: router and link, each starting with the corresponding keyword\n"
+ << "# The file should contain exactly two sections: router and link, each starting with the "
+ "corresponding keyword\n"
<< "\n"
- << "# router section defines topology nodes and their relative positions (e.g., to use in visualizer)\n"
+ << "# router section defines topology nodes and their relative positions (e.g., to use in "
+ "visualizer)\n"
<< "router\n"
<< "\n"
<< "# each line in this section represents one router and should have the following data\n"
<< "# node comment yPos xPos\n";
- for (NodeContainer::Iterator node = m_nodes.Begin ();
- node != m_nodes.End ();
- node++)
- {
- std::string name = Names::FindName (*node);
- Ptr<MobilityModel> mobility = (*node)->GetObject<MobilityModel> ();
- Vector position = mobility->GetPosition ();
+ for (NodeContainer::Iterator node = m_nodes.Begin(); node != m_nodes.End(); node++) {
+ std::string name = Names::FindName(*node);
+ Ptr<MobilityModel> mobility = (*node)->GetObject<MobilityModel>();
+ Vector position = mobility->GetPosition();
- os << name << "\t" << "NA" << "\t" << -position.y << "\t" << position.x << "\n";
- }
+ os << name << "\t"
+ << "NA"
+ << "\t" << -position.y << "\t" << position.x << "\n";
+ }
- os << "# link section defines point-to-point links between nodes and characteristics of these links\n"
- << "\n"
- << "link\n"
- << "\n"
- << "# Each line should be in the following format (only first two are required, the rest can be omitted)\n"
- << "# srcNode dstNode bandwidth metric delay queue\n"
- << "# bandwidth: link bandwidth\n"
- << "# metric: routing metric\n"
- << "# delay: link delay\n"
- << "# queue: MaxPackets for transmission queue on the link (both directions)\n"
- << "# error: comma-separated list, specifying class for ErrorModel and necessary attributes\n";
+ os
+ << "# link section defines point-to-point links between nodes and characteristics of these "
+ "links\n"
+ << "\n"
+ << "link\n"
+ << "\n"
+ << "# Each line should be in the following format (only first two are required, the rest can "
+ "be omitted)\n"
+ << "# srcNode dstNode bandwidth metric delay queue\n"
+ << "# bandwidth: link bandwidth\n"
+ << "# metric: routing metric\n"
+ << "# delay: link delay\n"
+ << "# queue: MaxPackets for transmission queue on the link (both directions)\n"
+ << "# error: comma-separated list, specifying class for ErrorModel and necessary attributes\n";
- for (std::list<Link>::const_iterator link = m_linksList.begin ();
- link != m_linksList.end ();
- link ++)
- {
- os << Names::FindName (link->GetFromNode ()) << "\t";
- os << Names::FindName (link->GetToNode ()) << "\t";
+ for (std::list<Link>::const_iterator link = m_linksList.begin(); link != m_linksList.end();
+ link++) {
+ os << Names::FindName(link->GetFromNode()) << "\t";
+ os << Names::FindName(link->GetToNode()) << "\t";
- string tmp;
- if (link->GetAttributeFailSafe ("DataRate", tmp))
- os << link->GetAttribute("DataRate") << "\t";
- else
- NS_FATAL_ERROR ("DataRate must be specified for the link");
+ string tmp;
+ if (link->GetAttributeFailSafe("DataRate", tmp))
+ os << link->GetAttribute("DataRate") << "\t";
+ else
+ NS_FATAL_ERROR("DataRate must be specified for the link");
- if (link->GetAttributeFailSafe ("OSPF", tmp))
- os << link->GetAttribute("OSPF") << "\t";
- else
- os << "1\t";
+ if (link->GetAttributeFailSafe("OSPF", tmp))
+ os << link->GetAttribute("OSPF") << "\t";
+ else
+ os << "1\t";
- if (link->GetAttributeFailSafe ("Delay", tmp))
- {
- os << link->GetAttribute("Delay") << "\t";
+ if (link->GetAttributeFailSafe("Delay", tmp)) {
+ os << link->GetAttribute("Delay") << "\t";
- if (link->GetAttributeFailSafe ("MaxPackets", tmp))
- {
- os << link->GetAttribute("MaxPackets") << "\t";
+ if (link->GetAttributeFailSafe("MaxPackets", tmp)) {
+ os << link->GetAttribute("MaxPackets") << "\t";
- if (link->GetAttributeFailSafe ("LossRate", tmp))
- {
- os << link->GetAttribute ("LossRate") << "\t";
- }
- }
+ if (link->GetAttributeFailSafe("LossRate", tmp)) {
+ os << link->GetAttribute("LossRate") << "\t";
}
- os << "\n";
+ }
}
+ os << "\n";
+ }
}
-
-template <class Names>
+template<class Names>
class name_writer {
public:
- name_writer(Names _names) : names(_names) {}
+ name_writer(Names _names)
+ : names(_names)
+ {
+ }
- template <class VertexOrEdge>
- void operator()(std::ostream& out, const VertexOrEdge& v) const {
+ template<class VertexOrEdge>
+ void
+ operator()(std::ostream& out, const VertexOrEdge& v) const
+ {
// out << "[label=\"" << names[v] << "\",style=filled,fillcolor=\"" << colors[v] << "\"]";
out << "[shape=\"circle\",width=0.1,label=\"\",style=filled,fillcolor=\"green\"]";
}
+
private:
Names names;
};
-template <class Names>
+template<class Names>
inline name_writer<Names>
-make_name_writer(Names n) {
+make_name_writer(Names n)
+{
return name_writer<Names>(n);
}
-
void
-AnnotatedTopologyReader::SaveGraphviz (const std::string &file)
+AnnotatedTopologyReader::SaveGraphviz(const std::string& file)
{
typedef boost::adjacency_list_traits<boost::setS, boost::setS, boost::undirectedS> Traits;
- typedef boost::property< boost::vertex_name_t, std::string, boost::property
- < boost::vertex_index_t, uint32_t > > nodeProperty;
+ typedef boost::property<boost::vertex_name_t, std::string,
+ boost::property<boost::vertex_index_t, uint32_t>> nodeProperty;
typedef boost::no_property edgeProperty;
- typedef boost::adjacency_list< boost::setS, boost::setS, boost::undirectedS,
- nodeProperty, edgeProperty > Graph;
+ typedef boost::adjacency_list<boost::setS, boost::setS, boost::undirectedS, nodeProperty,
+ edgeProperty> Graph;
typedef map<string, Traits::vertex_descriptor> node_map_t;
node_map_t graphNodes;
- Graph graph;
+ Graph graph;
- for (NodeContainer::Iterator node = m_nodes.Begin ();
- node != m_nodes.End ();
- node++)
- {
- std::pair<node_map_t::iterator, bool>
- retval = graphNodes.insert (make_pair (Names::FindName (*node),
- add_vertex (nodeProperty (Names::FindName (*node)), graph)));
- // NS_ASSERT (ok == true);
+ for (NodeContainer::Iterator node = m_nodes.Begin(); node != m_nodes.End(); node++) {
+ std::pair<node_map_t::iterator, bool> retval = graphNodes.insert(
+ make_pair(Names::FindName(*node), add_vertex(nodeProperty(Names::FindName(*node)), graph)));
+ // NS_ASSERT (ok == true);
- put (boost::vertex_index, graph, retval.first->second, (*node)->GetId ());
- }
+ put(boost::vertex_index, graph, retval.first->second, (*node)->GetId());
+ }
- for (std::list<Link>::const_iterator link = m_linksList.begin ();
- link != m_linksList.end ();
- link ++)
- {
- node_map_t::iterator from = graphNodes.find (Names::FindName (link->GetFromNode ()));
- node_map_t::iterator to = graphNodes.find (Names::FindName (link->GetToNode ()));
+ for (std::list<Link>::const_iterator link = m_linksList.begin(); link != m_linksList.end();
+ link++) {
+ node_map_t::iterator from = graphNodes.find(Names::FindName(link->GetFromNode()));
+ node_map_t::iterator to = graphNodes.find(Names::FindName(link->GetToNode()));
- // add_edge (node->second, otherNode->second, m_graph);
- boost::add_edge (from->second, to->second, graph);
- }
+ // add_edge (node->second, otherNode->second, m_graph);
+ boost::add_edge(from->second, to->second, graph);
+ }
- ofstream of (file.c_str ());
- boost::property_map<Graph, boost::vertex_name_t>::type names = get (boost::vertex_name, graph);
- write_graphviz (of, graph, make_name_writer (names));
+ ofstream of(file.c_str());
+ boost::property_map<Graph, boost::vertex_name_t>::type names = get(boost::vertex_name, graph);
+ write_graphviz(of, graph, make_name_writer(names));
}
-
-
}
diff --git a/plugins/topology/annotated-topology-reader.hpp b/plugins/topology/annotated-topology-reader.hpp
index 27815fa..d8679ed 100644
--- a/plugins/topology/annotated-topology-reader.hpp
+++ b/plugins/topology/annotated-topology-reader.hpp
@@ -25,15 +25,14 @@
#include "ns3/random-variable.h"
#include "ns3/object-factory.h"
-namespace ns3
-{
-
+namespace ns3 {
+
/**
- * \brief This class reads annotated topology and apply settings to the corresponding nodes and links
+ * \brief This class reads annotated topology and apply settings to the corresponding nodes and
+ *links
*
*/
-class AnnotatedTopologyReader : public TopologyReader
-{
+class AnnotatedTopologyReader : public TopologyReader {
public:
/**
* \brief Constructor
@@ -43,9 +42,9 @@
*
* \see ns3::Names class
*/
- AnnotatedTopologyReader (const std::string &path="", double scale=1.0);
- virtual ~AnnotatedTopologyReader ();
-
+ AnnotatedTopologyReader(const std::string& path = "", double scale = 1.0);
+ virtual ~AnnotatedTopologyReader();
+
/**
* \brief Main annotated topology reading function.
*
@@ -54,20 +53,20 @@
* \return the container of the nodes created (or empty container if there was an error)
*/
virtual NodeContainer
- Read ();
+ Read();
/**
* \brief Get nodes read by the reader
*/
virtual NodeContainer
- GetNodes () const;
-
+ GetNodes() const;
+
/**
* \brief Get links read by the reader
- */
+ */
virtual const std::list<Link>&
- GetLinks () const;
-
+ GetLinks() const;
+
/**
* \brief Assign IPv4 addresses to all links
*
@@ -78,7 +77,7 @@
* \param base Starting IPv4 address (second link will have base+256)
*/
virtual void
- AssignIpv4Addresses (Ipv4Address base);
+ AssignIpv4Addresses(Ipv4Address base);
/**
* \brief Set bounding box where nodes will be randomly places (if positions are unspecified)
@@ -88,55 +87,57 @@
* \param lry Lower right y coordinate
*/
virtual void
- SetBoundingBox (double ulx, double uly, double lrx, double lry);
+ SetBoundingBox(double ulx, double uly, double lrx, double lry);
/**
* \brief Set mobility model to be used on nodes
* \param model class name of the model
*/
virtual void
- SetMobilityModel (const std::string &model);
+ SetMobilityModel(const std::string& model);
/**
* \brief Apply OSPF metric on Ipv4 (if exists) and Ccnx (if exists) stacks
*/
virtual void
- ApplyOspfMetric ();
+ ApplyOspfMetric();
/**
* \brief Save positions (e.g., after manual modification using visualizer)
*/
virtual void
- SaveTopology (const std::string &file);
+ SaveTopology(const std::string& file);
/**
* \brief Save topology in graphviz format (.dot file)
*/
virtual void
- SaveGraphviz (const std::string &file);
-
+ SaveGraphviz(const std::string& file);
+
protected:
Ptr<Node>
- CreateNode (const std::string name, uint32_t systemId);
+ CreateNode(const std::string name, uint32_t systemId);
Ptr<Node>
- CreateNode (const std::string name, double posX, double posY, uint32_t systemId);
-
+ CreateNode(const std::string name, double posX, double posY, uint32_t systemId);
+
protected:
/**
* \brief This method applies setting to corresponding nodes and links
* NetDeviceContainer must be allocated
* NodeContainer from Read method
*/
- void ApplySettings ();
-
+ void
+ ApplySettings();
+
protected:
std::string m_path;
NodeContainer m_nodes;
private:
- AnnotatedTopologyReader (const AnnotatedTopologyReader&);
- AnnotatedTopologyReader& operator= (const AnnotatedTopologyReader&);
+ AnnotatedTopologyReader(const AnnotatedTopologyReader&);
+ AnnotatedTopologyReader&
+ operator=(const AnnotatedTopologyReader&);
UniformVariable m_randX;
UniformVariable m_randY;
@@ -146,9 +147,6 @@
uint32_t m_requiredPartitions;
};
-
}
#endif
-
-
diff --git a/plugins/topology/rocketfuel-map-reader.cpp b/plugins/topology/rocketfuel-map-reader.cpp
index c9949d8..774ce8f 100644
--- a/plugins/topology/rocketfuel-map-reader.cpp
+++ b/plugins/topology/rocketfuel-map-reader.cpp
@@ -59,28 +59,28 @@
using namespace std;
using namespace boost;
-NS_LOG_COMPONENT_DEFINE ("RocketfuelMapReader");
+NS_LOG_COMPONENT_DEFINE("RocketfuelMapReader");
namespace ns3 {
-RocketfuelMapReader::RocketfuelMapReader (const std::string &path/*=""*/, double scale/*=1.0*/, const std::string &referenceOspfRate)
- : AnnotatedTopologyReader (path, scale)
- , m_referenceOspfRate (boost::lexical_cast<DataRate> (referenceOspfRate))
+RocketfuelMapReader::RocketfuelMapReader(const std::string& path /*=""*/, double scale /*=1.0*/,
+ const std::string& referenceOspfRate)
+ : AnnotatedTopologyReader(path, scale)
+ , m_referenceOspfRate(boost::lexical_cast<DataRate>(referenceOspfRate))
{
}
-RocketfuelMapReader::~RocketfuelMapReader ()
+RocketfuelMapReader::~RocketfuelMapReader()
{
}
NodeContainer
-RocketfuelMapReader::Read ()
+RocketfuelMapReader::Read()
{
- NS_FATAL_ERROR ("Deprecated call. Use the other overloaded method instead");
- return NodeContainer ();
+ NS_FATAL_ERROR("Deprecated call. Use the other overloaded method instead");
+ return NodeContainer();
}
-
/* uid @loc [+] [bb] (num_neigh) [&ext] -> <nuid-1> <nuid-2> ... {-euid} ... =name[!] rn */
#define REGMATCH_MAX 16
@@ -90,49 +90,46 @@
#define SPACE "[ \t]+"
#define MAYSPACE "[ \t]*"
-#define ROCKETFUEL_MAPS_LINE \
-START "(-*[0-9]+)" SPACE "(@[?A-Za-z0-9,+]+)" SPACE \
-"(\\+)*" MAYSPACE "(bb)*" MAYSPACE \
-"\\(([0-9]+)\\)" SPACE "(&[0-9]+)*" MAYSPACE \
-"->" MAYSPACE "(<[0-9 \t<>]+>)*" MAYSPACE \
-"(\\{-[0-9\\{\\} \t-]+\\})*" SPACE \
-"=([A-Za-z0-9.!-]+)" SPACE "r([0-9])" \
-MAYSPACE END
+#define ROCKETFUEL_MAPS_LINE \
+ START "(-*[0-9]+)" SPACE "(@[?A-Za-z0-9,+]+)" SPACE "(\\+)*" MAYSPACE "(bb)*" MAYSPACE \
+ "\\(([0-9]+)\\)" SPACE "(&[0-9]+)*" MAYSPACE "->" MAYSPACE "(<[0-9 \t<>]+>)*" MAYSPACE \
+ "(\\{-[0-9\\{\\} \t-]+\\})*" SPACE "=([A-Za-z0-9.!-]+)" SPACE "r([0-9])" MAYSPACE END
void
-RocketfuelMapReader::CreateLink (string nodeName1, string nodeName2,
- double averageRtt,
- const string &minBw, const string &maxBw,
- const string &minDelay, const string &maxDelay)
+RocketfuelMapReader::CreateLink(string nodeName1, string nodeName2, double averageRtt,
+ const string& minBw, const string& maxBw, const string& minDelay,
+ const string& maxDelay)
{
- Ptr<Node> node1 = Names::Find<Node> (m_path, nodeName1);
- Ptr<Node> node2 = Names::Find<Node> (m_path, nodeName2);
- Link link (node1, nodeName1, node2, nodeName2);
+ Ptr<Node> node1 = Names::Find<Node>(m_path, nodeName1);
+ Ptr<Node> node2 = Names::Find<Node>(m_path, nodeName2);
+ Link link(node1, nodeName1, node2, nodeName2);
- DataRate randBandwidth
- (m_randVar.GetInteger (static_cast<uint32_t> (lexical_cast<DataRate> (minBw).GetBitRate ()),
- static_cast<uint32_t> (lexical_cast<DataRate> (maxBw).GetBitRate ())));
+ DataRate randBandwidth(
+ m_randVar.GetInteger(static_cast<uint32_t>(lexical_cast<DataRate>(minBw).GetBitRate()),
+ static_cast<uint32_t>(lexical_cast<DataRate>(maxBw).GetBitRate())));
- int32_t metric = std::max (1, static_cast<int32_t> (1.0 * m_referenceOspfRate.GetBitRate () / randBandwidth.GetBitRate ()));
+ int32_t metric = std::max(1, static_cast<int32_t>(1.0 * m_referenceOspfRate.GetBitRate()
+ / randBandwidth.GetBitRate()));
Time randDelay =
- Time::FromDouble ((m_randVar.GetValue (lexical_cast<Time> (minDelay).ToDouble (Time::US),
- lexical_cast<Time> (maxDelay).ToDouble (Time::US))),
- Time::US);
+ Time::FromDouble((m_randVar.GetValue(lexical_cast<Time>(minDelay).ToDouble(Time::US),
+ lexical_cast<Time>(maxDelay).ToDouble(Time::US))),
+ Time::US);
- uint32_t queue = ceil (averageRtt * (randBandwidth.GetBitRate () / 8.0 / 1100.0));
+ uint32_t queue = ceil(averageRtt * (randBandwidth.GetBitRate() / 8.0 / 1100.0));
- link.SetAttribute ("DataRate", boost::lexical_cast<string> (randBandwidth));
- link.SetAttribute ("OSPF", boost::lexical_cast<string> (metric));
- link.SetAttribute ("Delay", boost::lexical_cast<string> (ceil (randDelay.ToDouble (Time::US)))+"us");
- link.SetAttribute ("MaxPackets", boost::lexical_cast<string> (queue));
+ link.SetAttribute("DataRate", boost::lexical_cast<string>(randBandwidth));
+ link.SetAttribute("OSPF", boost::lexical_cast<string>(metric));
+ link.SetAttribute("Delay",
+ boost::lexical_cast<string>(ceil(randDelay.ToDouble(Time::US))) + "us");
+ link.SetAttribute("MaxPackets", boost::lexical_cast<string>(queue));
- AddLink (link);
+ AddLink(link);
}
// NodeContainer
void
-RocketfuelMapReader::GenerateFromMapsFile (int argc, char *argv[])
+RocketfuelMapReader::GenerateFromMapsFile(int argc, char* argv[])
{
string uid;
string loc;
@@ -144,7 +141,7 @@
int num_neigh_s = 0;
unsigned int num_neigh = 0;
int radius = 0;
- vector <string> neigh_list;
+ vector<string> neigh_list;
uid = argv[0];
loc = argv[1];
@@ -159,136 +156,125 @@
// bb = true;
// }
- num_neigh_s = ::atoi (argv[4]);
- if (num_neigh_s < 0)
- {
+ num_neigh_s = ::atoi(argv[4]);
+ if (num_neigh_s < 0) {
num_neigh = 0;
- NS_LOG_WARN ("Negative number of neighbors given");
+ NS_LOG_WARN("Negative number of neighbors given");
}
- else
- {
+ else {
num_neigh = num_neigh_s;
}
/* neighbors */
- if (argv[6])
- {
- char *nbr;
- char *stringp = argv[6];
- while ((nbr = strsep (&stringp, " \t")) != NULL)
- {
- nbr[strlen (nbr) - 1] = '\0';
- neigh_list.push_back (nbr + 1);
+ if (argv[6]) {
+ char* nbr;
+ char* stringp = argv[6];
+ while ((nbr = strsep(&stringp, " \t")) != NULL) {
+ nbr[strlen(nbr) - 1] = '\0';
+ neigh_list.push_back(nbr + 1);
}
}
- if (num_neigh != neigh_list.size ())
- {
- NS_LOG_WARN ("Given number of neighbors = " << num_neigh << " != size of neighbors list = " << neigh_list.size ());
+ if (num_neigh != neigh_list.size()) {
+ NS_LOG_WARN("Given number of neighbors = " << num_neigh << " != size of neighbors list = "
+ << neigh_list.size());
}
/* externs */
- if (argv[7])
- {
+ if (argv[7]) {
// euid = argv[7];
}
/* name */
- if (argv[8])
- {
+ if (argv[8]) {
name = argv[8];
}
- radius = ::atoi (&argv[9][1]);
- if (radius > 0)
- {
+ radius = ::atoi(&argv[9][1]);
+ if (radius > 0) {
return;
}
// Create node and link
- if (uid.empty ())
+ if (uid.empty())
return;
+ node_map_t::iterator node = m_graphNodes.find(uid);
+ if (node == m_graphNodes.end()) {
+ bool ok;
+ tie(node, ok) = m_graphNodes.insert(make_pair(uid, add_vertex(nodeProperty(uid), m_graph)));
+ NS_ASSERT(ok == true);
- node_map_t::iterator node = m_graphNodes.find (uid);
- if (node == m_graphNodes.end ())
- {
+ put(vertex_index, m_graph, node->second, m_maxNodeId);
+ m_maxNodeId++;
+ }
+
+ for (uint32_t i = 0; i < neigh_list.size(); ++i) {
+ nuid = neigh_list[i];
+
+ if (nuid.empty()) {
+ continue;
+ }
+
+ node_map_t::iterator otherNode = m_graphNodes.find(nuid);
+ if (otherNode == m_graphNodes.end()) {
bool ok;
- tie (node, ok) = m_graphNodes.insert (make_pair (uid, add_vertex (nodeProperty (uid), m_graph)));
- NS_ASSERT (ok == true);
+ tie(otherNode, ok) =
+ m_graphNodes.insert(make_pair(nuid, add_vertex(nodeProperty(nuid), m_graph)));
+ NS_ASSERT(ok == true);
- put (vertex_index, m_graph, node->second, m_maxNodeId);
- m_maxNodeId ++;
+ put(vertex_index, m_graph, otherNode->second, m_maxNodeId);
+ m_maxNodeId++;
}
- for (uint32_t i = 0; i < neigh_list.size (); ++i)
- {
- nuid = neigh_list[i];
-
- if (nuid.empty ())
- {
- continue;
- }
-
- node_map_t::iterator otherNode = m_graphNodes.find (nuid);
- if (otherNode == m_graphNodes.end ())
- {
- bool ok;
- tie (otherNode, ok) = m_graphNodes.insert (make_pair (nuid, add_vertex(nodeProperty (nuid), m_graph)));
- NS_ASSERT (ok == true);
-
- put (vertex_index, m_graph, otherNode->second, m_maxNodeId);
- m_maxNodeId ++;
- }
-
- // cout << node->second << " <-> " << otherNode->second << endl;
- // parallel edges are disabled in the graph, so no need to worry
- add_edge (node->second, otherNode->second, m_graph);
- }
+ // cout << node->second << " <-> " << otherNode->second << endl;
+ // parallel edges are disabled in the graph, so no need to worry
+ add_edge(node->second, otherNode->second, m_graph);
+ }
}
-void RocketfuelMapReader::assignGw (Traits::vertex_descriptor vertex, uint32_t degree, node_type_t nodeType)
+void
+RocketfuelMapReader::assignGw(Traits::vertex_descriptor vertex, uint32_t degree,
+ node_type_t nodeType)
{
graph_traits<Graph>::adjacency_iterator u, endu;
- for (tie (u, endu) = adjacent_vertices (vertex, m_graph); u != endu; u++)
- {
- if (get (vertex_rank, m_graph, *u) != UNKNOWN)
- continue;
+ for (tie(u, endu) = adjacent_vertices(vertex, m_graph); u != endu; u++) {
+ if (get(vertex_rank, m_graph, *u) != UNKNOWN)
+ continue;
- put (vertex_rank, m_graph, *u, nodeType);
- put (vertex_color, m_graph, *u, "green");
+ put(vertex_rank, m_graph, *u, nodeType);
+ put(vertex_color, m_graph, *u, "green");
- uint32_t u_degree = out_degree (*u, m_graph);
- if (u_degree < degree)
- assignGw (*u, degree, BACKBONE);
- }
+ uint32_t u_degree = out_degree(*u, m_graph);
+ if (u_degree < degree)
+ assignGw(*u, degree, BACKBONE);
+ }
};
void
-RocketfuelMapReader::AssignClients (uint32_t clientDegree, uint32_t gwDegree)
+RocketfuelMapReader::AssignClients(uint32_t clientDegree, uint32_t gwDegree)
{
graph_traits<Graph>::vertex_iterator v, endv;
- for (tie(v, endv) = vertices(m_graph); v != endv; v++)
- {
- uint32_t degree = out_degree (*v, m_graph);
- if (degree == clientDegree)
- {
- put (vertex_rank, m_graph, *v, CLIENT);
- put (vertex_color, m_graph, *v, "red");
+ for (tie(v, endv) = vertices(m_graph); v != endv; v++) {
+ uint32_t degree = out_degree(*v, m_graph);
+ if (degree == clientDegree) {
+ put(vertex_rank, m_graph, *v, CLIENT);
+ put(vertex_color, m_graph, *v, "red");
- assignGw (*v, gwDegree+1, GATEWAY);
- }
+ assignGw(*v, gwDegree + 1, GATEWAY);
}
+ }
};
NodeContainer
-RocketfuelMapReader::Read (RocketfuelParams params, bool keepOneComponent/*=true*/, bool connectBackbones/*=true*/)
+RocketfuelMapReader::Read(RocketfuelParams params, bool keepOneComponent /*=true*/,
+ bool connectBackbones /*=true*/)
{
m_maxNodeId = 0;
ifstream topgen;
- topgen.open (GetFileName ().c_str ());
- //NodeContainer nodes;
+ topgen.open(GetFileName().c_str());
+ // NodeContainer nodes;
UniformVariable var;
istringstream lineBuffer;
@@ -296,42 +282,38 @@
int lineNumber = 0;
char errbuf[512];
- if (!topgen.is_open ())
- {
- NS_LOG_WARN ("Couldn't open the file " << GetFileName ());
+ if (!topgen.is_open()) {
+ NS_LOG_WARN("Couldn't open the file " << GetFileName());
return m_nodes;
}
- while (!topgen.eof ())
- {
+ while (!topgen.eof()) {
int ret;
int argc;
- char *argv[REGMATCH_MAX];
- char *buf;
+ char* argv[REGMATCH_MAX];
+ char* buf;
lineNumber++;
- line.clear ();
- lineBuffer.clear ();
+ line.clear();
+ lineBuffer.clear();
- getline (topgen, line);
- buf = (char *)line.c_str ();
+ getline(topgen, line);
+ buf = (char*)line.c_str();
regmatch_t regmatch[REGMATCH_MAX];
regex_t regex;
- ret = regcomp (®ex, ROCKETFUEL_MAPS_LINE, REG_EXTENDED | REG_NEWLINE);
- if (ret != 0)
- {
- regerror (ret, ®ex, errbuf, sizeof (errbuf));
- regfree (®ex);
+ ret = regcomp(®ex, ROCKETFUEL_MAPS_LINE, REG_EXTENDED | REG_NEWLINE);
+ if (ret != 0) {
+ regerror(ret, ®ex, errbuf, sizeof(errbuf));
+ regfree(®ex);
continue;
}
- ret = regexec (®ex, buf, REGMATCH_MAX, regmatch, 0);
- if (ret == REG_NOMATCH)
- {
- NS_LOG_WARN ("match failed (maps file): %s" << buf);
- regfree (®ex);
+ ret = regexec(®ex, buf, REGMATCH_MAX, regmatch, 0);
+ if (ret == REG_NOMATCH) {
+ NS_LOG_WARN("match failed (maps file): %s" << buf);
+ regfree(®ex);
continue;
}
@@ -339,345 +321,304 @@
argc = 0;
/* regmatch[0] is the entire strings that matched */
- for (int i = 1; i < REGMATCH_MAX; i++)
- {
- if (regmatch[i].rm_so == -1)
- {
+ for (int i = 1; i < REGMATCH_MAX; i++) {
+ if (regmatch[i].rm_so == -1) {
argv[i - 1] = NULL;
}
- else
- {
+ else {
line[regmatch[i].rm_eo] = '\0';
argv[i - 1] = &line[regmatch[i].rm_so];
argc = i;
}
}
- GenerateFromMapsFile (argc, argv);
- regfree (®ex);
+ GenerateFromMapsFile(argc, argv);
+ regfree(®ex);
}
- if (keepOneComponent)
- {
- NS_LOG_DEBUG ("Before eliminating disconnected nodes: " << num_vertices(m_graph));
- KeepOnlyBiggestConnectedComponent ();
- NS_LOG_DEBUG ("After eliminating disconnected nodes: " << num_vertices(m_graph));
- }
+ if (keepOneComponent) {
+ NS_LOG_DEBUG("Before eliminating disconnected nodes: " << num_vertices(m_graph));
+ KeepOnlyBiggestConnectedComponent();
+ NS_LOG_DEBUG("After eliminating disconnected nodes: " << num_vertices(m_graph));
+ }
- for (int clientDegree = 1; clientDegree <= params.clientNodeDegrees; clientDegree++)
- {
- AssignClients (clientDegree, std::min (clientDegree, 3));
- }
+ for (int clientDegree = 1; clientDegree <= params.clientNodeDegrees; clientDegree++) {
+ AssignClients(clientDegree, std::min(clientDegree, 3));
+ }
graph_traits<Graph>::vertex_iterator v, endv;
- for (tie(v, endv) = vertices(m_graph); v != endv; v++)
- {
- node_type_t type = get (vertex_rank, m_graph, *v);
- if (type == UNKNOWN)
- {
- put (vertex_rank, m_graph, *v, BACKBONE);
- put (vertex_color, m_graph, *v, "blue");
- }
+ for (tie(v, endv) = vertices(m_graph); v != endv; v++) {
+ node_type_t type = get(vertex_rank, m_graph, *v);
+ if (type == UNKNOWN) {
+ put(vertex_rank, m_graph, *v, BACKBONE);
+ put(vertex_color, m_graph, *v, "blue");
}
+ }
- if (connectBackbones)
- {
- ConnectBackboneRouters ();
- }
+ if (connectBackbones) {
+ ConnectBackboneRouters();
+ }
graph_traits<Graph>::edge_iterator e, ende;
- for (tie (e, ende) = edges (m_graph); e != ende; )
- {
- Traits::vertex_descriptor
- u = source (*e, m_graph),
- v = target (*e, m_graph);
+ for (tie(e, ende) = edges(m_graph); e != ende;) {
+ Traits::vertex_descriptor u = source(*e, m_graph), v = target(*e, m_graph);
- node_type_t
- u_type = get (vertex_rank, m_graph, u),
- v_type = get (vertex_rank, m_graph, v);
+ node_type_t u_type = get(vertex_rank, m_graph, u), v_type = get(vertex_rank, m_graph, v);
- if (u_type == BACKBONE && v_type == BACKBONE)
- {
- // ok
- }
- else if ((u_type == GATEWAY && v_type == BACKBONE) ||
- (u_type == BACKBONE && v_type == GATEWAY ))
- {
- // ok
- }
- else if (u_type == GATEWAY && v_type == GATEWAY)
- {
- // ok
- }
- else if ((u_type == GATEWAY && v_type == CLIENT) ||
- (u_type == CLIENT && v_type == GATEWAY ))
- {
- // ok
- }
- else
- {
- // not ok
- NS_LOG_DEBUG ("Wrong link type between nodes: " << u_type << " <-> " << v_type << " (deleting the link)");
-
- graph_traits<Graph>::edge_iterator tmp = e;
- tmp++;
-
- remove_edge (*e, m_graph);
- e = tmp;
- continue;
- }
- e++;
+ if (u_type == BACKBONE && v_type == BACKBONE) {
+ // ok
}
-
- if (keepOneComponent)
- {
- NS_LOG_DEBUG ("Before 2 eliminating disconnected nodes: " << num_vertices(m_graph));
- KeepOnlyBiggestConnectedComponent ();
- NS_LOG_DEBUG ("After 2 eliminating disconnected nodes: " << num_vertices(m_graph));
+ else if ((u_type == GATEWAY && v_type == BACKBONE)
+ || (u_type == BACKBONE && v_type == GATEWAY)) {
+ // ok
}
-
- for (tie(v, endv) = vertices(m_graph); v != endv; v++)
- {
- string nodeName = get (vertex_name, m_graph, *v);
- Ptr<Node> node = CreateNode (nodeName, 0);
-
- node_type_t type = get (vertex_rank, m_graph, *v);
- switch (type)
- {
- case BACKBONE:
- Names::Rename (nodeName, "bb-" + nodeName);
- put (vertex_name, m_graph, *v, "bb-" + nodeName);
- m_backboneRouters.Add (node);
- break;
- case CLIENT:
- Names::Rename (nodeName, "leaf-" + nodeName);
- put (vertex_name, m_graph, *v, "leaf-" + nodeName);
- m_customerRouters.Add (node);
- break;
- case GATEWAY:
- Names::Rename (nodeName, "gw-" + nodeName);
- put (vertex_name, m_graph, *v, "gw-" + nodeName);
- m_gatewayRouters.Add (node);
- break;
- case UNKNOWN:
- NS_FATAL_ERROR ("Should not happen");
- break;
- }
+ else if (u_type == GATEWAY && v_type == GATEWAY) {
+ // ok
}
-
- for (tie (e, ende) = edges (m_graph); e != ende; e++)
- {
- Traits::vertex_descriptor
- u = source (*e, m_graph),
- v = target (*e, m_graph);
-
- node_type_t
- u_type = get (vertex_rank, m_graph, u),
- v_type = get (vertex_rank, m_graph, v);
-
- string
- u_name = get (vertex_name, m_graph, u),
- v_name = get (vertex_name, m_graph, v);
-
- if (u_type == BACKBONE && v_type == BACKBONE)
- {
- CreateLink (u_name, v_name,
- params.averageRtt,
- params.minb2bBandwidth, params.maxb2bBandwidth,
- params.minb2bDelay, params.maxb2bDelay);
- }
- else if ((u_type == GATEWAY && v_type == BACKBONE) ||
- (u_type == BACKBONE && v_type == GATEWAY ))
- {
- CreateLink (u_name, v_name,
- params.averageRtt,
- params.minb2gBandwidth, params.maxb2gBandwidth,
- params.minb2gDelay, params.maxb2gDelay);
- }
- else if (u_type == GATEWAY && v_type == GATEWAY)
- {
- CreateLink (u_name, v_name,
- params.averageRtt,
- params.minb2gBandwidth, params.maxb2gBandwidth,
- params.minb2gDelay, params.maxb2gDelay);
- }
- else if ((u_type == GATEWAY && v_type == CLIENT) ||
- (u_type == CLIENT && v_type == GATEWAY ))
- {
- CreateLink (u_name, v_name,
- params.averageRtt,
- params.ming2cBandwidth, params.maxg2cBandwidth,
- params.ming2cDelay, params.maxg2cDelay);
- }
- else
- {
- NS_FATAL_ERROR ("Wrong link type between nodes: " << u_type << " <-> " << v_type);
- }
+ else if ((u_type == GATEWAY && v_type == CLIENT) || (u_type == CLIENT && v_type == GATEWAY)) {
+ // ok
}
+ else {
+ // not ok
+ NS_LOG_DEBUG("Wrong link type between nodes: " << u_type << " <-> " << v_type
+ << " (deleting the link)");
- ApplySettings ();
+ graph_traits<Graph>::edge_iterator tmp = e;
+ tmp++;
- NS_LOG_INFO ("Clients: " << m_customerRouters.GetN ());
- NS_LOG_INFO ("Gateways: " << m_gatewayRouters.GetN ());
- NS_LOG_INFO ("Backbones: " << m_backboneRouters.GetN ());
- NS_LOG_INFO ("Links: " << GetLinks ().size ());
+ remove_edge(*e, m_graph);
+ e = tmp;
+ continue;
+ }
+ e++;
+ }
+
+ if (keepOneComponent) {
+ NS_LOG_DEBUG("Before 2 eliminating disconnected nodes: " << num_vertices(m_graph));
+ KeepOnlyBiggestConnectedComponent();
+ NS_LOG_DEBUG("After 2 eliminating disconnected nodes: " << num_vertices(m_graph));
+ }
+
+ for (tie(v, endv) = vertices(m_graph); v != endv; v++) {
+ string nodeName = get(vertex_name, m_graph, *v);
+ Ptr<Node> node = CreateNode(nodeName, 0);
+
+ node_type_t type = get(vertex_rank, m_graph, *v);
+ switch (type) {
+ case BACKBONE:
+ Names::Rename(nodeName, "bb-" + nodeName);
+ put(vertex_name, m_graph, *v, "bb-" + nodeName);
+ m_backboneRouters.Add(node);
+ break;
+ case CLIENT:
+ Names::Rename(nodeName, "leaf-" + nodeName);
+ put(vertex_name, m_graph, *v, "leaf-" + nodeName);
+ m_customerRouters.Add(node);
+ break;
+ case GATEWAY:
+ Names::Rename(nodeName, "gw-" + nodeName);
+ put(vertex_name, m_graph, *v, "gw-" + nodeName);
+ m_gatewayRouters.Add(node);
+ break;
+ case UNKNOWN:
+ NS_FATAL_ERROR("Should not happen");
+ break;
+ }
+ }
+
+ for (tie(e, ende) = edges(m_graph); e != ende; e++) {
+ Traits::vertex_descriptor u = source(*e, m_graph), v = target(*e, m_graph);
+
+ node_type_t u_type = get(vertex_rank, m_graph, u), v_type = get(vertex_rank, m_graph, v);
+
+ string u_name = get(vertex_name, m_graph, u), v_name = get(vertex_name, m_graph, v);
+
+ if (u_type == BACKBONE && v_type == BACKBONE) {
+ CreateLink(u_name, v_name, params.averageRtt, params.minb2bBandwidth, params.maxb2bBandwidth,
+ params.minb2bDelay, params.maxb2bDelay);
+ }
+ else if ((u_type == GATEWAY && v_type == BACKBONE)
+ || (u_type == BACKBONE && v_type == GATEWAY)) {
+ CreateLink(u_name, v_name, params.averageRtt, params.minb2gBandwidth, params.maxb2gBandwidth,
+ params.minb2gDelay, params.maxb2gDelay);
+ }
+ else if (u_type == GATEWAY && v_type == GATEWAY) {
+ CreateLink(u_name, v_name, params.averageRtt, params.minb2gBandwidth, params.maxb2gBandwidth,
+ params.minb2gDelay, params.maxb2gDelay);
+ }
+ else if ((u_type == GATEWAY && v_type == CLIENT) || (u_type == CLIENT && v_type == GATEWAY)) {
+ CreateLink(u_name, v_name, params.averageRtt, params.ming2cBandwidth, params.maxg2cBandwidth,
+ params.ming2cDelay, params.maxg2cDelay);
+ }
+ else {
+ NS_FATAL_ERROR("Wrong link type between nodes: " << u_type << " <-> " << v_type);
+ }
+ }
+
+ ApplySettings();
+
+ NS_LOG_INFO("Clients: " << m_customerRouters.GetN());
+ NS_LOG_INFO("Gateways: " << m_gatewayRouters.GetN());
+ NS_LOG_INFO("Backbones: " << m_backboneRouters.GetN());
+ NS_LOG_INFO("Links: " << GetLinks().size());
return m_nodes;
}
-const NodeContainer &
-RocketfuelMapReader::GetBackboneRouters () const
+const NodeContainer&
+RocketfuelMapReader::GetBackboneRouters() const
{
return m_backboneRouters;
}
-const NodeContainer &
-RocketfuelMapReader::GetGatewayRouters () const
+const NodeContainer&
+RocketfuelMapReader::GetGatewayRouters() const
{
return m_gatewayRouters;
}
-const NodeContainer &
-RocketfuelMapReader::GetCustomerRouters () const
+const NodeContainer&
+RocketfuelMapReader::GetCustomerRouters() const
{
return m_customerRouters;
}
-
-static
-void nodeWriter (std::ostream &os, NodeContainer& m)
+static void
+nodeWriter(std::ostream& os, NodeContainer& m)
{
- for (NodeContainer::Iterator node = m.Begin ();
- node != m.End ();
- node ++)
- {
- std::string name = Names::FindName (*node);
+ for (NodeContainer::Iterator node = m.Begin(); node != m.End(); node++) {
+ std::string name = Names::FindName(*node);
- os << name << "\t" << "NA" << "\t" << 0 << "\t" << 0 << "\n";
- }
+ os << name << "\t"
+ << "NA"
+ << "\t" << 0 << "\t" << 0 << "\n";
+ }
};
void
-RocketfuelMapReader::SaveTopology (const std::string &file)
+RocketfuelMapReader::SaveTopology(const std::string& file)
{
- ofstream os (file.c_str (), ios::trunc);
+ ofstream os(file.c_str(), ios::trunc);
os << "# any empty lines and lines starting with '#' symbol is ignored\n"
<< "\n"
- << "# The file should contain exactly two sections: router and link, each starting with the corresponding keyword\n"
+ << "# The file should contain exactly two sections: router and link, each starting with the "
+ "corresponding keyword\n"
<< "\n"
- << "# router section defines topology nodes and their relative positions (e.g., to use in visualizer)\n"
+ << "# router section defines topology nodes and their relative positions (e.g., to use in "
+ "visualizer)\n"
<< "router\n"
<< "\n"
<< "# each line in this section represents one router and should have the following data\n"
<< "# node comment yPos xPos\n";
- nodeWriter (os, m_backboneRouters);
- nodeWriter (os, m_gatewayRouters);
- nodeWriter (os, m_customerRouters);
+ nodeWriter(os, m_backboneRouters);
+ nodeWriter(os, m_gatewayRouters);
+ nodeWriter(os, m_customerRouters);
- os << "# link section defines point-to-point links between nodes and characteristics of these links\n"
+ os << "# link section defines point-to-point links between nodes and characteristics of these "
+ "links\n"
<< "\n"
<< "link\n"
<< "\n"
- << "# Each line should be in the following format (only first two are required, the rest can be omitted)\n"
+ << "# Each line should be in the following format (only first two are required, the rest can "
+ "be omitted)\n"
<< "# srcNode dstNode bandwidth metric delay queue\n"
<< "# bandwidth: link bandwidth\n"
<< "# metric: routing metric\n"
<< "# delay: link delay\n"
<< "# queue: MaxPackets for transmission queue on the link (both directions)\n";
- for (std::list<Link>::iterator link = m_linksList.begin ();
- link != m_linksList.end ();
- link ++)
- {
- string src = Names::FindName (link->GetFromNode ());
- string dst = Names::FindName (link->GetToNode ());
- os << src << "\t";
- os << dst << "\t";
+ for (std::list<Link>::iterator link = m_linksList.begin(); link != m_linksList.end(); link++) {
+ string src = Names::FindName(link->GetFromNode());
+ string dst = Names::FindName(link->GetToNode());
+ os << src << "\t";
+ os << dst << "\t";
- string tmp;
- if (link->GetAttributeFailSafe ("DataRate", tmp))
- os << link->GetAttribute("DataRate") << "\t";
- else
- NS_FATAL_ERROR ("DataRate must be specified for the link");
+ string tmp;
+ if (link->GetAttributeFailSafe("DataRate", tmp))
+ os << link->GetAttribute("DataRate") << "\t";
+ else
+ NS_FATAL_ERROR("DataRate must be specified for the link");
- if (link->GetAttributeFailSafe ("OSPF", tmp))
- os << link->GetAttribute("OSPF") << "\t";
- else
- {
- DataRate rate = boost::lexical_cast<DataRate> (link->GetAttribute("DataRate"));
+ if (link->GetAttributeFailSafe("OSPF", tmp))
+ os << link->GetAttribute("OSPF") << "\t";
+ else {
+ DataRate rate = boost::lexical_cast<DataRate>(link->GetAttribute("DataRate"));
- int32_t cost = std::max (1, static_cast<int32_t> (1.0 * m_referenceOspfRate.GetBitRate () / rate.GetBitRate ()));
+ int32_t cost = std::max(1, static_cast<int32_t>(1.0 * m_referenceOspfRate.GetBitRate()
+ / rate.GetBitRate()));
- os << cost << "\t";
- }
-
- if (link->GetAttributeFailSafe ("Delay", tmp))
- {
- os << link->GetAttribute("Delay") << "\t";
-
- if (link->GetAttributeFailSafe ("MaxPackets", tmp))
- {
- os << link->GetAttribute("MaxPackets") << "\t";
- }
- }
- os << "\n";
+ os << cost << "\t";
}
+
+ if (link->GetAttributeFailSafe("Delay", tmp)) {
+ os << link->GetAttribute("Delay") << "\t";
+
+ if (link->GetAttributeFailSafe("MaxPackets", tmp)) {
+ os << link->GetAttribute("MaxPackets") << "\t";
+ }
+ }
+ os << "\n";
+ }
}
-
-template <class Names, class Colors>
+template<class Names, class Colors>
class name_color_writer {
public:
- name_color_writer(Names _names, Colors _colors) : names(_names), colors(_colors) {}
+ name_color_writer(Names _names, Colors _colors)
+ : names(_names)
+ , colors(_colors)
+ {
+ }
- template <class VertexOrEdge>
- void operator()(std::ostream& out, const VertexOrEdge& v) const {
+ template<class VertexOrEdge>
+ void
+ operator()(std::ostream& out, const VertexOrEdge& v) const
+ {
// out << "[label=\"" << names[v] << "\",style=filled,fillcolor=\"" << colors[v] << "\"]";
out << "[shape=\"circle\",width=0.1,label=\"\",style=filled,fillcolor=\"" << colors[v] << "\"]";
}
+
private:
Names names;
Colors colors;
};
-template <class Names, class Colors>
+template<class Names, class Colors>
inline name_color_writer<Names, Colors>
-make_name_color_writer(Names n, Colors c) {
+make_name_color_writer(Names n, Colors c)
+{
return name_color_writer<Names, Colors>(n, c);
}
-
void
-RocketfuelMapReader::SaveGraphviz (const std::string &file)
+RocketfuelMapReader::SaveGraphviz(const std::string& file)
{
- ofstream of (file.c_str ());
- property_map<Graph, vertex_name_t>::type names = get (vertex_name, m_graph);
- property_map<Graph, vertex_color_t>::type colors = get (vertex_color, m_graph);
- write_graphviz(of, m_graph, make_name_color_writer (names, colors));
+ ofstream of(file.c_str());
+ property_map<Graph, vertex_name_t>::type names = get(vertex_name, m_graph);
+ property_map<Graph, vertex_color_t>::type colors = get(vertex_color, m_graph);
+ write_graphviz(of, m_graph, make_name_color_writer(names, colors));
}
-
void
-RocketfuelMapReader::KeepOnlyBiggestConnectedComponent ()
+RocketfuelMapReader::KeepOnlyBiggestConnectedComponent()
{
std::map<graph_traits<Graph>::vertex_descriptor, int> temp;
- associative_property_map< std::map<graph_traits<Graph>::vertex_descriptor, int> > components (temp);
+ associative_property_map<std::map<graph_traits<Graph>::vertex_descriptor, int>> components(temp);
// //check if topology has breaks in its structure and trim it if yes
// property_map<Graph, vertex_index1_t>::type components = get (vertex_index1, m_graph);
- int num = connected_components (m_graph, components);
- NS_LOG_DEBUG ("Topology has " << num << " components");
+ int num = connected_components(m_graph, components);
+ NS_LOG_DEBUG("Topology has " << num << " components");
- vector<int> sizes (num, 0);
+ vector<int> sizes(num, 0);
graph_traits<Graph>::vertex_iterator v, endv;
- for (tie(v, endv) = vertices(m_graph); v != endv; v++)
- {
- sizes[ get (components, *v) ] ++;
- }
- int largestComponent = max_element (sizes.begin (), sizes.end ()) - sizes.begin ();
+ for (tie(v, endv) = vertices(m_graph); v != endv; v++) {
+ sizes[get(components, *v)]++;
+ }
+ int largestComponent = max_element(sizes.begin(), sizes.end()) - sizes.begin();
// cout << "Largest: " << largestComponent << endl;
// for (int i =0 ; i < num; i++) cout << sizes[i] << " ";
@@ -686,111 +627,99 @@
////////////////////////////////////////////////////
// remove nodes and edges from smaller components //
////////////////////////////////////////////////////
- for (tie(v, endv) = vertices(m_graph); v != endv; v++)
- {
- if (get (components, *v) == largestComponent)
- continue;
+ for (tie(v, endv) = vertices(m_graph); v != endv; v++) {
+ if (get(components, *v) == largestComponent)
+ continue;
- clear_vertex (*v, m_graph);
+ clear_vertex(*v, m_graph);
+ }
+
+ // this works only if vertices are organized in listS or setS (iterator is not invalidated on
+ // remove)
+ for (tie(v, endv) = vertices(m_graph); v != endv;) {
+ if (get(components, *v) == largestComponent) {
+ v++;
+ continue;
}
- // this works only if vertices are organized in listS or setS (iterator is not invalidated on remove)
- for (tie(v, endv) = vertices(m_graph); v != endv; )
- {
- if (get (components, *v) == largestComponent)
- {
- v++;
- continue;
- }
+ graph_traits<Graph>::vertex_iterator tmp = v;
+ tmp++;
- graph_traits<Graph>::vertex_iterator tmp = v;
- tmp++;
-
- remove_vertex (*v, m_graph);
- v = tmp;
- }
+ remove_vertex(*v, m_graph);
+ v = tmp;
+ }
int index = 0;
// renumber nodes
- for (tie(v, endv) = vertices(m_graph); v != endv; v++)
- {
- put (vertex_index, m_graph, *v, index++);
- }
+ for (tie(v, endv) = vertices(m_graph); v != endv; v++) {
+ put(vertex_index, m_graph, *v, index++);
+ }
}
void
-RocketfuelMapReader::ConnectBackboneRouters ()
+RocketfuelMapReader::ConnectBackboneRouters()
{
// not the tricky part. we want backbone to be a fully connected component,
// so traffic doesn't bounce from backbone to gateway and back
- typedef adjacency_list< setS, setS, boost::undirectedS,
- property<vertex_name_t, Traits::vertex_descriptor, property
- < vertex_index_t, int, property
- < vertex_index1_t, int > > > > BbGraph;
+ typedef adjacency_list<setS, setS, boost::undirectedS,
+ property<vertex_name_t, Traits::vertex_descriptor,
+ property<vertex_index_t, int, property<vertex_index1_t, int>>>>
+ BbGraph;
BbGraph bbGraph;
map<Traits::vertex_descriptor, graph_traits<BbGraph>::vertex_descriptor> nodeMap;
int index = 0;
graph_traits<Graph>::vertex_iterator v, endv;
- for (tie(v, endv) = vertices(m_graph); v != endv; v++)
- {
- node_type_t type = get (vertex_rank, m_graph, *v);
- if (type == BACKBONE)
- {
- graph_traits<BbGraph>::vertex_descriptor newv = add_vertex (*v, bbGraph);
- put (vertex_index, bbGraph, newv, index++);
- nodeMap[*v] = newv;
- }
+ for (tie(v, endv) = vertices(m_graph); v != endv; v++) {
+ node_type_t type = get(vertex_rank, m_graph, *v);
+ if (type == BACKBONE) {
+ graph_traits<BbGraph>::vertex_descriptor newv = add_vertex(*v, bbGraph);
+ put(vertex_index, bbGraph, newv, index++);
+ nodeMap[*v] = newv;
}
+ }
graph_traits<BbGraph>::vertex_iterator bb, endBb;
- for (tie (bb, endBb) = vertices (bbGraph); bb != endBb; bb++)
- {
- Traits::vertex_descriptor actualVertex = get (vertex_name, bbGraph, *bb);
+ for (tie(bb, endBb) = vertices(bbGraph); bb != endBb; bb++) {
+ Traits::vertex_descriptor actualVertex = get(vertex_name, bbGraph, *bb);
- graph_traits<Graph>::adjacency_iterator u, endu;
- for (tie (u, endu) = adjacent_vertices (actualVertex, m_graph); u != endu; u++)
- {
- if (nodeMap.find (*u) != nodeMap.end ())
- {
- add_edge (nodeMap [actualVertex], nodeMap[*u], bbGraph);
- }
- }
+ graph_traits<Graph>::adjacency_iterator u, endu;
+ for (tie(u, endu) = adjacent_vertices(actualVertex, m_graph); u != endu; u++) {
+ if (nodeMap.find(*u) != nodeMap.end()) {
+ add_edge(nodeMap[actualVertex], nodeMap[*u], bbGraph);
+ }
}
+ }
- property_map<BbGraph, vertex_index1_t>::type components = get (vertex_index1, bbGraph);
+ property_map<BbGraph, vertex_index1_t>::type components = get(vertex_index1, bbGraph);
- int num = connected_components (bbGraph, components);
- NS_LOG_DEBUG ("Backbone has " << num << " components");
+ int num = connected_components(bbGraph, components);
+ NS_LOG_DEBUG("Backbone has " << num << " components");
if (num == 1)
return; // nothing to do
- vector< vector<graph_traits<BbGraph>::vertex_descriptor> > subgraphs (num);
- for (tie (bb, endBb) = vertices (bbGraph); bb != endBb; bb++)
- {
- int component = get (vertex_index1, bbGraph, *bb);
- subgraphs [component].push_back (*bb);
- }
+ vector<vector<graph_traits<BbGraph>::vertex_descriptor>> subgraphs(num);
+ for (tie(bb, endBb) = vertices(bbGraph); bb != endBb; bb++) {
+ int component = get(vertex_index1, bbGraph, *bb);
+ subgraphs[component].push_back(*bb);
+ }
UniformVariable randVar;
- for (int i = 1; i < num; i++)
- {
- int node1 = randVar.GetInteger (0, subgraphs[i-1].size ()-1);
- int node2 = randVar.GetInteger (0, subgraphs[i].size ()-1);
+ for (int i = 1; i < num; i++) {
+ int node1 = randVar.GetInteger(0, subgraphs[i - 1].size() - 1);
+ int node2 = randVar.GetInteger(0, subgraphs[i].size() - 1);
- Traits::vertex_descriptor
- v1 = get (vertex_name, bbGraph, subgraphs[i-1][node1]),
- v2 = get (vertex_name, bbGraph, subgraphs[i ][node2]);
+ Traits::vertex_descriptor v1 = get(vertex_name, bbGraph, subgraphs[i - 1][node1]),
+ v2 = get(vertex_name, bbGraph, subgraphs[i][node2]);
- NS_LOG_DEBUG ("Connecting " << get (vertex_name, m_graph, v1) << "[" << node1 << "] with "
- << get (vertex_name, m_graph, v2) << "[" << node2 << "]");
+ NS_LOG_DEBUG("Connecting " << get(vertex_name, m_graph, v1) << "[" << node1 << "] with "
+ << get(vertex_name, m_graph, v2) << "[" << node2 << "]");
- add_edge (v1, v2, m_graph);
- }
+ add_edge(v1, v2, m_graph);
+ }
}
-
} /* namespace ns3 */
diff --git a/plugins/topology/rocketfuel-map-reader.hpp b/plugins/topology/rocketfuel-map-reader.hpp
index 99336fc..59879d9 100644
--- a/plugins/topology/rocketfuel-map-reader.hpp
+++ b/plugins/topology/rocketfuel-map-reader.hpp
@@ -35,26 +35,25 @@
namespace ns3 {
-struct RocketfuelParams
-{
+struct RocketfuelParams {
double averageRtt;
- int clientNodeDegrees;
+ int clientNodeDegrees;
- //parameters for links Backbone <->Backbone
+ // parameters for links Backbone <->Backbone
string minb2bBandwidth;
string minb2bDelay;
string maxb2bBandwidth;
string maxb2bDelay;
- //parameters for links Backbone<->Gateway and Gateway <-> Gateway
+ // parameters for links Backbone<->Gateway and Gateway <-> Gateway
string minb2gBandwidth;
string minb2gDelay;
string maxb2gBandwidth;
string maxb2gDelay;
- //parameters for links Gateway <-> Customer
+ // parameters for links Gateway <-> Customer
string ming2cBandwidth;
string ming2cDelay;
@@ -69,33 +68,37 @@
*
* Only map file (.cch) is supported
*
- * In addition to reading specified topology from the .cch file, this class divides nodes into three categories:
+ * In addition to reading specified topology from the .cch file, this class divides nodes into three
+ *categories:
* - client nodes (nodes with degrees less or equal to RocketfuelParams.clientNodeDegrees
* - gateway nodes (nodes that directly connected to client nodes)
* - backbone nodes (all the rest)
*
- * As some of the .cch files do not give a connected network graph, this reader also allows to keep only the largest connected
+ * As some of the .cch files do not give a connected network graph, this reader also allows to keep
+ *only the largest connected
* network graph component.
*/
-class RocketfuelMapReader : public AnnotatedTopologyReader
-{
+class RocketfuelMapReader : public AnnotatedTopologyReader {
public:
- RocketfuelMapReader (const std::string &path="", double scale=1.0, const string &referenceOspfRate="100Mbps");
- virtual ~RocketfuelMapReader ();
+ RocketfuelMapReader(const std::string& path = "", double scale = 1.0,
+ const string& referenceOspfRate = "100Mbps");
+ virtual ~RocketfuelMapReader();
/**
- * @brief Deprecated call. Read (RocketfuelParams params, bool keepOneComponent=true, bool connectBackbones=true) should be used instead
+ * @brief Deprecated call. Read (RocketfuelParams params, bool keepOneComponent=true, bool
+ * connectBackbones=true) should be used instead
*/
- virtual
- NodeContainer
- Read ();
+ virtual NodeContainer
+ Read();
/**
* \brief Main topology reading function.
*
- * @param params parameters specifying range from which link bandwidths and delays should be assigned
+ * @param params parameters specifying range from which link bandwidths and delays should be
+ *assigned
* @param keepOneComponent if true, then only the largest connected component will be kept
- * @param connectBackbones if true, then extra links will be added to ensure connectivity of estimated backbone
+ * @param connectBackbones if true, then extra links will be added to ensure connectivity of
+ *estimated backbone
*
* This method opens an input stream and reads the Rocketfuel-format file.
* Every row represents a topology link (the ids of a couple of nodes),
@@ -105,7 +108,7 @@
* \return the container of the nodes created (or empty container if there was an error)
*/
virtual NodeContainer
- Read (RocketfuelParams params, bool keepOneComponent=true, bool connectBackbones=true);
+ Read(RocketfuelParams params, bool keepOneComponent = true, bool connectBackbones = true);
const NodeContainer&
GetBackboneRouters() const;
@@ -117,31 +120,31 @@
GetCustomerRouters() const;
virtual void
- SaveTopology (const std::string &file);
+ SaveTopology(const std::string& file);
virtual void
- SaveGraphviz (const std::string &file);
+ SaveGraphviz(const std::string& file);
private:
- RocketfuelMapReader (const RocketfuelMapReader&);
- RocketfuelMapReader& operator= (const RocketfuelMapReader&);
+ RocketfuelMapReader(const RocketfuelMapReader&);
+ RocketfuelMapReader&
+ operator=(const RocketfuelMapReader&);
// NodeContainer
void
- GenerateFromMapsFile (int argc, char *argv[]);
+ GenerateFromMapsFile(int argc, char* argv[]);
void
- CreateLink (string nodeName1, string nodeName2,
- double averageRtt,
- const string &minBw, const string &maxBw,
- const string &minDelay, const string &maxDelay);
+ CreateLink(string nodeName1, string nodeName2, double averageRtt, const string& minBw,
+ const string& maxBw, const string& minDelay, const string& maxDelay);
void
- KeepOnlyBiggestConnectedComponent ();
-
- void AssignClients(uint32_t clientDegree, uint32_t gwDegree);
+ KeepOnlyBiggestConnectedComponent();
void
- ConnectBackboneRouters ();
+ AssignClients(uint32_t clientDegree, uint32_t gwDegree);
+
+ void
+ ConnectBackboneRouters();
private:
UniformVariable m_randVar;
@@ -152,33 +155,33 @@
typedef boost::adjacency_list_traits<boost::setS, boost::setS, boost::undirectedS> Traits;
- enum node_type_t {UNKNOWN = 0, CLIENT = 1, GATEWAY = 2, BACKBONE = 3};
+ enum node_type_t { UNKNOWN = 0, CLIENT = 1, GATEWAY = 2, BACKBONE = 3 };
- typedef boost::property< boost::vertex_name_t, std::string, boost::property
- < boost::vertex_index_t, uint32_t, boost::property
- < boost::vertex_rank_t, node_type_t, boost::property
- < boost::vertex_color_t, std::string > > > > nodeProperty;
+ typedef boost::
+ property<boost::vertex_name_t, std::string,
+ boost::property<boost::vertex_index_t, uint32_t,
+ boost::property<boost::vertex_rank_t, node_type_t,
+ boost::property<boost::vertex_color_t, std::string>>>>
+ nodeProperty;
typedef boost::no_property edgeProperty;
- typedef boost::adjacency_list< boost::setS, boost::setS, boost::undirectedS,
- nodeProperty, edgeProperty > Graph;
+ typedef boost::adjacency_list<boost::setS, boost::setS, boost::undirectedS, nodeProperty,
+ edgeProperty> Graph;
typedef map<string, Traits::vertex_descriptor> node_map_t;
node_map_t m_graphNodes;
- Graph m_graph;
- uint32_t m_maxNodeId;
+ Graph m_graph;
+ uint32_t m_maxNodeId;
const DataRate m_referenceOspfRate; // reference rate of OSPF metric calculation
-
private:
void
- assignGw (Traits::vertex_descriptor vertex, uint32_t degree, node_type_t nodeType);
+ assignGw(Traits::vertex_descriptor vertex, uint32_t degree, node_type_t nodeType);
}; // end class RocketfuelMapReader
}; // end namespace ns3
-
#endif /* ROCKETFUEL_MAP_READER_H */
diff --git a/plugins/topology/rocketfuel-weights-reader.cpp b/plugins/topology/rocketfuel-weights-reader.cpp
index 4decb69..8f6f0e0 100644
--- a/plugins/topology/rocketfuel-weights-reader.cpp
+++ b/plugins/topology/rocketfuel-weights-reader.cpp
@@ -51,15 +51,16 @@
using namespace std;
-NS_LOG_COMPONENT_DEFINE ("RocketfuelWeightsReader");
+NS_LOG_COMPONENT_DEFINE("RocketfuelWeightsReader");
namespace ns3 {
-
-RocketfuelWeightsReader::RocketfuelWeightsReader (const std::string &path/*=""*/, double scale/*=1.0*/)
- : AnnotatedTopologyReader (path, scale)
- , m_defaultBandwidth ("100Mbps")
+
+RocketfuelWeightsReader::RocketfuelWeightsReader(const std::string& path /*=""*/,
+ double scale /*=1.0*/)
+ : AnnotatedTopologyReader(path, scale)
+ , m_defaultBandwidth("100Mbps")
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
// TypeId tid;
// bool ok = TypeId::LookupByNameFailSafe ("ns3::SpringMobilityModel", &tid);
@@ -68,133 +69,124 @@
// else
// Use default mobility model (supplied by AnnotatedTopologyReader)
}
-
-RocketfuelWeightsReader::~RocketfuelWeightsReader ()
+
+RocketfuelWeightsReader::~RocketfuelWeightsReader()
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
void
-RocketfuelWeightsReader::SetFileType (uint8_t inputType)
+RocketfuelWeightsReader::SetFileType(uint8_t inputType)
{
m_inputType = inputType;
}
NodeContainer
-RocketfuelWeightsReader::Read ()
+RocketfuelWeightsReader::Read()
{
if (m_inputType == POSITIONS)
- return AnnotatedTopologyReader::Read ();
-
+ return AnnotatedTopologyReader::Read();
+
ifstream topgen;
- topgen.open (GetFileName ().c_str ());
-
- if ( !topgen.is_open () )
- {
- NS_LOG_ERROR ("Cannot open file " << GetFileName () << " for reading");
- return m_nodes;
+ topgen.open(GetFileName().c_str());
+
+ if (!topgen.is_open()) {
+ NS_LOG_ERROR("Cannot open file " << GetFileName() << " for reading");
+ return m_nodes;
+ }
+
+ map<string, set<string>> processedLinks; // to eliminate duplications
+ bool repeatedRun = LinksSize() > 0;
+ std::list<Link>::iterator linkIterator = m_linksList.begin();
+
+ while (!topgen.eof()) {
+ string line;
+ getline(topgen, line);
+ if (line == "")
+ continue;
+ if (line[0] == '#')
+ continue; // comments
+
+ // NS_LOG_DEBUG ("Input: [" << line << "]");
+
+ istringstream lineBuffer(line);
+ string from, to, attribute;
+
+ lineBuffer >> from >> to >> attribute;
+
+ if (processedLinks[to].size() != 0
+ && processedLinks[to].find(from) != processedLinks[to].end()) {
+ continue; // duplicated link
+ }
+ processedLinks[from].insert(to);
+
+ Ptr<Node> fromNode = Names::Find<Node>(m_path, from);
+ if (fromNode == 0) {
+ fromNode = CreateNode(from, 0);
}
- map<string, set<string> > processedLinks; // to eliminate duplications
- bool repeatedRun = LinksSize () > 0;
- std::list<Link>::iterator linkIterator = m_linksList.begin ();
-
- while (!topgen.eof ())
- {
- string line;
- getline (topgen,line);
- if (line == "") continue;
- if (line[0] == '#') continue; // comments
-
- // NS_LOG_DEBUG ("Input: [" << line << "]");
-
- istringstream lineBuffer (line);
- string from, to, attribute;
-
- lineBuffer >> from >> to >> attribute;
-
- if (processedLinks[to].size () != 0 &&
- processedLinks[to].find (from) != processedLinks[to].end ())
- {
- continue; // duplicated link
- }
- processedLinks[from].insert (to);
-
- Ptr<Node> fromNode = Names::Find<Node> (m_path, from);
- if (fromNode == 0)
- {
- fromNode = CreateNode (from, 0);
- }
-
- Ptr<Node> toNode = Names::Find<Node> (m_path, to);
- if (toNode == 0)
- {
- toNode = CreateNode (to, 0);
- }
-
- Link *link;
- if (!repeatedRun)
- link = new Link (fromNode, from, toNode, to);
- else
- {
- NS_ASSERT (linkIterator != m_linksList.end ());
- link = &(*linkIterator);
-
- linkIterator++;
- }
-
- switch (m_inputType)
- {
- case LINKS:
- {
- // links only
- // do nothing
- break;
- }
- case WEIGHTS:
- {
- if (attribute == "")
- attribute = "1";
- uint16_t metric = boost::lexical_cast<uint16_t> (attribute);
- link->SetAttribute ("OSPF", boost::lexical_cast<string> (metric));
- break;
- }
- case LATENCIES:
- if (attribute == "")
- attribute = "1";
-
- link->SetAttribute ("DataRate", m_defaultBandwidth);
- link->SetAttribute ("Delay", attribute+"ms");
- if (!m_queue.empty ())
- {
- link->SetAttribute ("MaxPackets", m_queue);
- }
- break;
- default:
- ; //
- }
-
- NS_LOG_DEBUG ("Link " << from << " <==> " << to << " / " << attribute);
- if (!repeatedRun)
- {
- AddLink (*link);
- delete link;
- }
+ Ptr<Node> toNode = Names::Find<Node>(m_path, to);
+ if (toNode == 0) {
+ toNode = CreateNode(to, 0);
}
-
- topgen.close ();
- if (!repeatedRun)
- {
- NS_LOG_INFO ("Rocketfuel topology created with " << m_nodes.GetN () << " nodes and " << LinksSize () << " links");
+ Link* link;
+ if (!repeatedRun)
+ link = new Link(fromNode, from, toNode, to);
+ else {
+ NS_ASSERT(linkIterator != m_linksList.end());
+ link = &(*linkIterator);
+
+ linkIterator++;
}
+
+ switch (m_inputType) {
+ case LINKS: {
+ // links only
+ // do nothing
+ break;
+ }
+ case WEIGHTS: {
+ if (attribute == "")
+ attribute = "1";
+ uint16_t metric = boost::lexical_cast<uint16_t>(attribute);
+ link->SetAttribute("OSPF", boost::lexical_cast<string>(metric));
+ break;
+ }
+ case LATENCIES:
+ if (attribute == "")
+ attribute = "1";
+
+ link->SetAttribute("DataRate", m_defaultBandwidth);
+ link->SetAttribute("Delay", attribute + "ms");
+ if (!m_queue.empty()) {
+ link->SetAttribute("MaxPackets", m_queue);
+ }
+ break;
+ default:
+ ; //
+ }
+
+ NS_LOG_DEBUG("Link " << from << " <==> " << to << " / " << attribute);
+ if (!repeatedRun) {
+ AddLink(*link);
+ delete link;
+ }
+ }
+
+ topgen.close();
+
+ if (!repeatedRun) {
+ NS_LOG_INFO("Rocketfuel topology created with " << m_nodes.GetN() << " nodes and "
+ << LinksSize() << " links");
+ }
return m_nodes;
}
void
-RocketfuelWeightsReader::Commit ()
+RocketfuelWeightsReader::Commit()
{
- ApplySettings ();
+ ApplySettings();
// SpringMobilityHelper::InstallSprings (LinksBegin (), LinksEnd ());
}
diff --git a/plugins/topology/rocketfuel-weights-reader.hpp b/plugins/topology/rocketfuel-weights-reader.hpp
index 0026311..85f6ab7 100644
--- a/plugins/topology/rocketfuel-weights-reader.hpp
+++ b/plugins/topology/rocketfuel-weights-reader.hpp
@@ -26,7 +26,7 @@
#include "ns3/net-device-container.h"
namespace ns3 {
-
+
// ------------------------------------------------------------
// --------------------------------------------
/**
@@ -36,15 +36,14 @@
*
* Only weights and latencies file is supported
*/
-class RocketfuelWeightsReader : public AnnotatedTopologyReader
-{
+class RocketfuelWeightsReader : public AnnotatedTopologyReader {
public:
- RocketfuelWeightsReader (const std::string &path="", double scale=1.0);
- virtual ~RocketfuelWeightsReader ();
+ RocketfuelWeightsReader(const std::string& path = "", double scale = 1.0);
+ virtual ~RocketfuelWeightsReader();
void
- SetFileType (uint8_t inputType);
-
+ SetFileType(uint8_t inputType);
+
/**
* \brief Main topology reading function.
*
@@ -55,69 +54,62 @@
*
* \return the container of the nodes created (or empty container if there was an error)
*/
- virtual NodeContainer
- Read (void);
+ virtual NodeContainer
+ Read(void);
void
- Commit ();
+ Commit();
- enum
- {
- LINKS,
- WEIGHTS,
- LATENCIES,
- POSITIONS
- };
+ enum { LINKS, WEIGHTS, LATENCIES, POSITIONS };
inline void
- SetDefaultBandwidth (const std::string &bw);
+ SetDefaultBandwidth(const std::string& bw);
inline std::string
- GetDefaultBandwidth () const;
+ GetDefaultBandwidth() const;
inline void
- SetDefaultQueue (const std::string &queue);
+ SetDefaultQueue(const std::string& queue);
inline std::string
- GetDefaultQueue () const;
-
+ GetDefaultQueue() const;
+
private:
- RocketfuelWeightsReader (const RocketfuelWeightsReader&);
- RocketfuelWeightsReader& operator= (const RocketfuelWeightsReader&);
-
+ RocketfuelWeightsReader(const RocketfuelWeightsReader&);
+ RocketfuelWeightsReader&
+ operator=(const RocketfuelWeightsReader&);
+
private:
uint8_t m_inputType;
std::string m_defaultBandwidth; // since the topology files don't provide bandwidth parameter
std::string m_queue;
-
+
}; // end class RocketfuelWeightsReader
inline void
-RocketfuelWeightsReader::SetDefaultBandwidth (const std::string &bw)
+RocketfuelWeightsReader::SetDefaultBandwidth(const std::string& bw)
{
m_defaultBandwidth = bw;
}
inline std::string
-RocketfuelWeightsReader::GetDefaultBandwidth () const
+RocketfuelWeightsReader::GetDefaultBandwidth() const
{
return m_defaultBandwidth;
}
inline void
-RocketfuelWeightsReader::SetDefaultQueue (const std::string &queue)
+RocketfuelWeightsReader::SetDefaultQueue(const std::string& queue)
{
m_queue = queue;
}
inline std::string
-RocketfuelWeightsReader::GetDefaultQueue () const
+RocketfuelWeightsReader::GetDefaultQueue() const
{
return m_queue;
}
-
}; // end namespace ns3
-
#endif /* ROCKETFUEL_TOPOLOGY_WEIGHTS_READER_H */
diff --git a/utils/batches.cpp b/utils/batches.cpp
index 9eb92b3..6f593e3 100644
--- a/utils/batches.cpp
+++ b/utils/batches.cpp
@@ -22,13 +22,13 @@
namespace ns3 {
-ATTRIBUTE_HELPER_CPP (Batches);
+ATTRIBUTE_HELPER_CPP(Batches);
-std::ostream &
-operator << (std::ostream &os, const Batches &batch)
+std::ostream&
+operator<<(std::ostream& os, const Batches& batch)
{
- for (Batches::const_iterator i = batch.begin (); i != batch.end (); i++)
- os << i->get<0> () << " " << i->get<1> () << " ";
+ for (Batches::const_iterator i = batch.begin(); i != batch.end(); i++)
+ os << i->get<0>() << " " << i->get<1>() << " ";
return os;
}
@@ -37,21 +37,18 @@
* \brief Read components from input and add them to components. Will read input stream till eof
* Substrings separated by slashes will become separate components
*/
-std::istream &
-operator >> (std::istream &is, Batches &batch)
+std::istream&
+operator>>(std::istream& is, Batches& batch)
{
Time time;
uint32_t amount;
- while (!is.eof ())
- {
- is >> time >> amount;
- batch.Add (time, amount);
- // std::cout << time << ", " << amount << ". \n";
- }
-
- is.clear ();
+ while (!is.eof()) {
+ is >> time >> amount;
+ batch.Add(time, amount);
+ // std::cout << time << ", " << amount << ". \n";
+ }
+
+ is.clear();
return is;
}
-
-
}
diff --git a/utils/batches.hpp b/utils/batches.hpp
index 526ae29..457210f 100644
--- a/utils/batches.hpp
+++ b/utils/batches.hpp
@@ -31,15 +31,15 @@
/**
* @ingroup ndn-apps
- * @brief Class representing sets of (time, number) tuples with support of reading writing to streams
+ * @brief Class representing sets of (time, number) tuples with support of reading writing to
+ * streams
*/
-class Batches : public std::list<boost::tuple<Time, uint32_t> >
-{
+class Batches : public std::list<boost::tuple<Time, uint32_t>> {
public:
/**
* @brief Default constructor
*/
- Batches () { };
+ Batches(){};
/**
* @brief Add tuple
@@ -47,28 +47,28 @@
* @param amount number for the tuple
*/
void
- Add (const Time &when, uint32_t amount)
+ Add(const Time& when, uint32_t amount)
{
- push_back (boost::make_tuple<Time, uint32_t> (when, amount));
+ push_back(boost::make_tuple<Time, uint32_t>(when, amount));
}
};
-ATTRIBUTE_HELPER_HEADER (Batches);
+ATTRIBUTE_HELPER_HEADER(Batches);
/**
* @brief Output contents of the Batches to the std::ostream
* @param os reference to std::ostream
* @param batch constant reference to Batch object
*/
-std::ostream &
-operator << (std::ostream &os, const Batches &batch);
+std::ostream&
+operator<<(std::ostream& os, const Batches& batch);
/**
* \brief Read components from input and add them to components. Will read input stream till eof
* Substrings separated by slashes will become separate components
*/
-std::istream &
-operator >> (std::istream &is, Batches &batch);
+std::istream&
+operator>>(std::istream& is, Batches& batch);
} // namespace ns3
diff --git a/utils/mem-usage.hpp b/utils/mem-usage.hpp
index a18448a..e58b9ad 100644
--- a/utils/mem-usage.hpp
+++ b/utils/mem-usage.hpp
@@ -42,58 +42,53 @@
* @ingroup ndn-helpers
* @brief Utility class to evaluate current usage of RAM
*/
-class MemUsage
-{
+class MemUsage {
public:
/**
* @brief Get memory utilization in bytes
*/
- static inline
- int64_t
- Get ()
+ static inline int64_t
+ Get()
{
#if defined(__linux__)
-/*
-/proc/[pid]/statm
- Provides information about memory usage, measured in pages. The
- columns are:
+ /*
+ /proc/[pid]/statm
+ Provides information about memory usage, measured in pages. The
+ columns are:
- size (1) total program size
- (same as VmSize in /proc/[pid]/status)
- resident (2) resident set size
- (same as VmRSS in /proc/[pid]/status)
- share (3) shared pages (i.e., backed by a file)
- text (4) text (code)
- lib (5) library (unused in Linux 2.6)
- data (6) data + stack
- dt (7) dirty pages (unused in Linux 2.6)
+ size (1) total program size
+ (same as VmSize in /proc/[pid]/status)
+ resident (2) resident set size
+ (same as VmRSS in /proc/[pid]/status)
+ share (3) shared pages (i.e., backed by a file)
+ text (4) text (code)
+ lib (5) library (unused in Linux 2.6)
+ data (6) data + stack
+ dt (7) dirty pages (unused in Linux 2.6)
-Reference: http://man7.org/linux/man-pages/man5/proc.5.html
-*/
- std::ifstream is ("/proc/self/statm");
- if (!is.bad () && !is.eof ())
- {
- unsigned long vm;
- unsigned long rss;
- is >> vm // the first number: virtual memory
- >> rss; // the second number: resident set size
-
- return rss * getpagesize ();
- }
- else
- {
- return -1;
- }
+ Reference: http://man7.org/linux/man-pages/man5/proc.5.html
+ */
+ std::ifstream is("/proc/self/statm");
+ if (!is.bad() && !is.eof()) {
+ unsigned long vm;
+ unsigned long rss;
+ is >> vm // the first number: virtual memory
+ >> rss; // the second number: resident set size
+
+ return rss * getpagesize();
+ }
+ else {
+ return -1;
+ }
#elif defined(__APPLE__)
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
- if (KERN_SUCCESS != task_info (mach_task_self (),
- TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count))
- {
- return -1; // something is wrong
- }
+ if (KERN_SUCCESS
+ != task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count)) {
+ return -1; // something is wrong
+ }
return t_info.resident_size;
#endif
diff --git a/utils/ndn-fw-hop-count-tag.cpp b/utils/ndn-fw-hop-count-tag.cpp
index f4d65db..027bdfe 100644
--- a/utils/ndn-fw-hop-count-tag.cpp
+++ b/utils/ndn-fw-hop-count-tag.cpp
@@ -24,41 +24,39 @@
namespace ndn {
TypeId
-FwHopCountTag::GetTypeId ()
+FwHopCountTag::GetTypeId()
{
- static TypeId tid = TypeId("ns3::ndn::FwHopCountTag")
- .SetParent<Tag>()
- .AddConstructor<FwHopCountTag>()
- ;
+ static TypeId tid =
+ TypeId("ns3::ndn::FwHopCountTag").SetParent<Tag>().AddConstructor<FwHopCountTag>();
return tid;
}
TypeId
-FwHopCountTag::GetInstanceTypeId () const
+FwHopCountTag::GetInstanceTypeId() const
{
- return FwHopCountTag::GetTypeId ();
+ return FwHopCountTag::GetTypeId();
}
uint32_t
-FwHopCountTag::GetSerializedSize () const
+FwHopCountTag::GetSerializedSize() const
{
return sizeof(uint32_t);
}
void
-FwHopCountTag::Serialize (TagBuffer i) const
+FwHopCountTag::Serialize(TagBuffer i) const
{
- i.WriteU32 (m_hopCount);
-}
-
-void
-FwHopCountTag::Deserialize (TagBuffer i)
-{
- m_hopCount = i.ReadU32 ();
+ i.WriteU32(m_hopCount);
}
void
-FwHopCountTag::Print (std::ostream &os) const
+FwHopCountTag::Deserialize(TagBuffer i)
+{
+ m_hopCount = i.ReadU32();
+}
+
+void
+FwHopCountTag::Print(std::ostream& os) const
{
os << m_hopCount;
}
diff --git a/utils/ndn-fw-hop-count-tag.hpp b/utils/ndn-fw-hop-count-tag.hpp
index f530961..6b4920c 100644
--- a/utils/ndn-fw-hop-count-tag.hpp
+++ b/utils/ndn-fw-hop-count-tag.hpp
@@ -30,56 +30,64 @@
* @ingroup ndn-fw
* @brief Packet tag that is used to track hop count for Interest-Data pairs
*/
-class FwHopCountTag : public Tag
-{
+class FwHopCountTag : public Tag {
public:
static TypeId
- GetTypeId (void);
+ GetTypeId(void);
/**
* @brief Default constructor
*/
- FwHopCountTag () : m_hopCount (0) { };
+ FwHopCountTag()
+ : m_hopCount(0){};
/**
* @brief Destructor
*/
- ~FwHopCountTag () { }
+ ~FwHopCountTag()
+ {
+ }
/**
* @brief Increment hop count
*/
void
- Increment () { m_hopCount ++; }
+ Increment()
+ {
+ m_hopCount++;
+ }
/**
* @brief Get value of hop count
*/
uint32_t
- Get () const { return m_hopCount; }
+ Get() const
+ {
+ return m_hopCount;
+ }
////////////////////////////////////////////////////////
// from ObjectBase
////////////////////////////////////////////////////////
virtual TypeId
- GetInstanceTypeId () const;
-
+ GetInstanceTypeId() const;
+
////////////////////////////////////////////////////////
// from Tag
////////////////////////////////////////////////////////
-
+
virtual uint32_t
- GetSerializedSize () const;
+ GetSerializedSize() const;
virtual void
- Serialize (TagBuffer i) const;
-
- virtual void
- Deserialize (TagBuffer i);
+ Serialize(TagBuffer i) const;
virtual void
- Print (std::ostream &os) const;
-
+ Deserialize(TagBuffer i);
+
+ virtual void
+ Print(std::ostream& os) const;
+
private:
uint32_t m_hopCount;
};
diff --git a/utils/ndn-limits-rate.cpp b/utils/ndn-limits-rate.cpp
index 3d2ebc7..8729231 100644
--- a/utils/ndn-limits-rate.cpp
+++ b/utils/ndn-limits-rate.cpp
@@ -26,134 +26,131 @@
#include "ns3/ndn-face.hpp"
#include "ns3/node.h"
-NS_LOG_COMPONENT_DEFINE ("ndn.Limits.Rate");
+NS_LOG_COMPONENT_DEFINE("ndn.Limits.Rate");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (LimitsRate);
+NS_OBJECT_ENSURE_REGISTERED(LimitsRate);
TypeId
-LimitsRate::GetTypeId ()
+LimitsRate::GetTypeId()
{
- static TypeId tid = TypeId ("ns3::ndn::Limits::Rate")
- .SetGroupName ("Ndn")
- .SetParent <Limits> ()
- .AddConstructor <LimitsRate> ()
+ static TypeId tid =
+ TypeId("ns3::ndn::Limits::Rate")
+ .SetGroupName("Ndn")
+ .SetParent<Limits>()
+ .AddConstructor<LimitsRate>()
- .AddAttribute ("RandomizeLeak", "Randomize start time for token bucket leakage. May be helpful to prevent leak synchronizations",
- TimeValue (Seconds (0.001)),
- MakeTimeAccessor (&LimitsRate::m_leakRandomizationInteral),
- MakeTimeChecker ())
+ .AddAttribute("RandomizeLeak", "Randomize start time for token bucket leakage. May be "
+ "helpful to prevent leak synchronizations",
+ TimeValue(Seconds(0.001)),
+ MakeTimeAccessor(&LimitsRate::m_leakRandomizationInteral), MakeTimeChecker())
;
return tid;
}
void
-LimitsRate::NotifyNewAggregate ()
+LimitsRate::NotifyNewAggregate()
{
- super::NotifyNewAggregate ();
+ super::NotifyNewAggregate();
- if (!m_isLeakScheduled)
- {
- if (GetObject<Face> () != 0)
- {
- NS_ASSERT_MSG (GetObject<Face> ()->GetNode () != 0, "Node object should exist on the face");
+ if (!m_isLeakScheduled) {
+ if (GetObject<Face>() != 0) {
+ NS_ASSERT_MSG(GetObject<Face>()->GetNode() != 0, "Node object should exist on the face");
- m_isLeakScheduled = true;
+ m_isLeakScheduled = true;
- if (!m_leakRandomizationInteral.IsZero ())
- {
- UniformVariable r (0.0, m_leakRandomizationInteral.ToDouble (Time::S));
- Simulator::ScheduleWithContext (GetObject<Face> ()->GetNode ()->GetId (),
- Seconds (r.GetValue ()), &LimitsRate::LeakBucket, this, 0.0);
- }
- else
- {
- Simulator::ScheduleWithContext (GetObject<Face> ()->GetNode ()->GetId (),
- Seconds (0), &LimitsRate::LeakBucket, this, 0.0);
- }
-
- }
+ if (!m_leakRandomizationInteral.IsZero()) {
+ UniformVariable r(0.0, m_leakRandomizationInteral.ToDouble(Time::S));
+ Simulator::ScheduleWithContext(GetObject<Face>()->GetNode()->GetId(), Seconds(r.GetValue()),
+ &LimitsRate::LeakBucket, this, 0.0);
+ }
+ else {
+ Simulator::ScheduleWithContext(GetObject<Face>()->GetNode()->GetId(), Seconds(0),
+ &LimitsRate::LeakBucket, this, 0.0);
+ }
}
+ }
}
void
-LimitsRate::SetLimits (double rate, double delay)
+LimitsRate::SetLimits(double rate, double delay)
{
- super::SetLimits (rate, delay);
+ super::SetLimits(rate, delay);
// maximum allowed burst
- m_bucketMax = GetMaxRate () * GetMaxDelay ();
+ m_bucketMax = GetMaxRate() * GetMaxDelay();
// amount of packets allowed every second (leak rate)
- m_bucketLeak = GetMaxRate ();
+ m_bucketLeak = GetMaxRate();
}
-
void
-LimitsRate::UpdateCurrentLimit (double limit)
+LimitsRate::UpdateCurrentLimit(double limit)
{
- NS_ASSERT_MSG (limit >= 0.0, "Limit should be greater or equal to zero");
+ NS_ASSERT_MSG(limit >= 0.0, "Limit should be greater or equal to zero");
- m_bucketLeak = std::min (limit, GetMaxRate ());
- m_bucketMax = m_bucketLeak * GetMaxDelay ();
+ m_bucketLeak = std::min(limit, GetMaxRate());
+ m_bucketMax = m_bucketLeak * GetMaxDelay();
}
bool
-LimitsRate::IsBelowLimit ()
+LimitsRate::IsBelowLimit()
{
- if (!IsEnabled ()) return true;
+ if (!IsEnabled())
+ return true;
return (m_bucketMax - m_bucket >= 1.0);
}
void
-LimitsRate::BorrowLimit ()
+LimitsRate::BorrowLimit()
{
- if (!IsEnabled ()) return;
+ if (!IsEnabled())
+ return;
- NS_ASSERT_MSG (m_bucketMax - m_bucket >= 1.0, "Should not be possible, unless we IsBelowLimit was not checked correctly");
+ NS_ASSERT_MSG(m_bucketMax - m_bucket >= 1.0,
+ "Should not be possible, unless we IsBelowLimit was not checked correctly");
m_bucket += 1;
}
void
-LimitsRate::ReturnLimit ()
+LimitsRate::ReturnLimit()
{
// do nothing
}
void
-LimitsRate::LeakBucket (double interval)
+LimitsRate::LeakBucket(double interval)
{
const double leak = m_bucketLeak * interval;
#ifdef NS3_LOG_ENABLE
- if (m_bucket>1)
- {
- NS_LOG_DEBUG ("Leak from " << m_bucket << " to " << std::max (0.0, m_bucket - leak));
- }
+ if (m_bucket > 1) {
+ NS_LOG_DEBUG("Leak from " << m_bucket << " to " << std::max(0.0, m_bucket - leak));
+ }
#endif
double bucketOld = m_bucket;
- m_bucket = std::max (0.0, m_bucket - leak);
+ m_bucket = std::max(0.0, m_bucket - leak);
- // calculate interval so next time we will leak by 1.001, unless such interval would be more than 1 second
+ // calculate interval so next time we will leak by 1.001, unless such interval would be more than
+ // 1 second
double newInterval = 1.0;
- if (m_bucketLeak > 1.0)
- {
- newInterval = 1.001 / m_bucketLeak;
- }
+ if (m_bucketLeak > 1.0) {
+ newInterval = 1.001 / m_bucketLeak;
+ }
- if (m_bucketMax - bucketOld < 1.0 &&
- m_bucketMax - m_bucket >= 1.0) // limit number of times this stuff is called
- {
- this->FireAvailableSlotCallback ();
- }
+ if (m_bucketMax - bucketOld < 1.0
+ && m_bucketMax - m_bucket >= 1.0) // limit number of times this stuff is called
+ {
+ this->FireAvailableSlotCallback();
+ }
- Simulator::Schedule (Seconds (newInterval), &LimitsRate::LeakBucket, this, newInterval);
+ Simulator::Schedule(Seconds(newInterval), &LimitsRate::LeakBucket, this, newInterval);
}
} // namespace ndn
diff --git a/utils/ndn-limits-rate.hpp b/utils/ndn-limits-rate.hpp
index 4b8c699..a476247 100644
--- a/utils/ndn-limits-rate.hpp
+++ b/utils/ndn-limits-rate.hpp
@@ -19,7 +19,7 @@
*/
#ifndef _NDN_LIMITS_RATE_H_
-#define _NDN_LIMITS_RATE_H_
+#define _NDN_LIMITS_RATE_H_
#include "ndn-limits.hpp"
#include <ns3/nstime.h>
@@ -31,74 +31,74 @@
* \ingroup ndn-fw
* \brief Structure to manage limits for outstanding interests
*/
-class LimitsRate :
- public Limits
-{
+class LimitsRate : public Limits {
public:
typedef Limits super;
static TypeId
- GetTypeId ();
+ GetTypeId();
/**
* \brief Constructor
* \param prefix smart pointer to the prefix for the FIB entry
*/
- LimitsRate ()
- : m_isLeakScheduled (false)
- , m_bucketMax (0)
- , m_bucketLeak (1)
- , m_bucket (0)
- { }
+ LimitsRate()
+ : m_isLeakScheduled(false)
+ , m_bucketMax(0)
+ , m_bucketLeak(1)
+ , m_bucket(0)
+ {
+ }
- virtual
- ~LimitsRate () { }
+ virtual ~LimitsRate()
+ {
+ }
virtual void
- SetLimits (double rate, double delay);
+ SetLimits(double rate, double delay);
- virtual
- double
- GetMaxLimit () const
+ virtual double
+ GetMaxLimit() const
{
- return GetMaxRate ();
+ return GetMaxRate();
}
/**
* @brief Check if Interest limit is reached (token bucket is not empty)
*/
virtual bool
- IsBelowLimit ();
+ IsBelowLimit();
/**
* @brief Get token from the bucket
*/
virtual void
- BorrowLimit ();
+ BorrowLimit();
/**
* @brief Does nothing (token bucket leakage is time-dependent only)
*/
virtual void
- ReturnLimit ();
+ ReturnLimit();
/**
- * @brief Update normalized amount that should be leaked every second (token bucket leak rate) and leak rate
+ * @brief Update normalized amount that should be leaked every second (token bucket leak rate) and
+ * leak rate
*/
virtual void
- UpdateCurrentLimit (double limit);
+ UpdateCurrentLimit(double limit);
/**
* @brief Get normalized amount that should be leaked every second (token bucket leak rate)
*/
virtual double
- GetCurrentLimit () const
+ GetCurrentLimit() const
{
return m_bucketLeak;
}
virtual double
- GetCurrentLimitRate () const
+ GetCurrentLimitRate() const
{
return m_bucketLeak;
}
@@ -106,7 +106,7 @@
protected:
// from Node
void
- NotifyNewAggregate ();
+ NotifyNewAggregate();
private:
/**
@@ -115,19 +115,21 @@
* @param interval Time interval for leakage. Used to calculate size of the leak
*/
void
- LeakBucket (double interval);
+ LeakBucket(double interval);
private:
bool m_isLeakScheduled;
- double m_bucketMax; ///< \brief Maximum Interest allowance for this face (maximum tokens that can be issued at the same time)
- double m_bucketLeak; ///< \brief Normalized amount that should be leaked every second (token bucket leak rate)
- double m_bucket; ///< \brief Value representing current size of the Interest allowance for this face (current size of token bucket)
+ double m_bucketMax; ///< \brief Maximum Interest allowance for this face (maximum tokens that can
+ /// be issued at the same time)
+ double m_bucketLeak; ///< \brief Normalized amount that should be leaked every second (token
+ /// bucket leak rate)
+ double m_bucket; ///< \brief Value representing current size of the Interest allowance for this
+ /// face (current size of token bucket)
Time m_leakRandomizationInteral;
};
-
} // namespace ndn
} // namespace ns3
diff --git a/utils/ndn-limits-window.cpp b/utils/ndn-limits-window.cpp
index a2630a4..c5c5098 100644
--- a/utils/ndn-limits-window.cpp
+++ b/utils/ndn-limits-window.cpp
@@ -22,66 +22,68 @@
#include "ns3/log.h"
-NS_LOG_COMPONENT_DEFINE ("ndn.Limits.Window");
+NS_LOG_COMPONENT_DEFINE("ndn.Limits.Window");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (LimitsWindow);
+NS_OBJECT_ENSURE_REGISTERED(LimitsWindow);
TypeId
-LimitsWindow::GetTypeId ()
+LimitsWindow::GetTypeId()
{
- static TypeId tid = TypeId ("ns3::ndn::Limits::Window")
- .SetGroupName ("Ndn")
- .SetParent <Limits> ()
- .AddConstructor <LimitsWindow> ()
-
- .AddTraceSource ("CurMaxLimit",
- "Current maximum limit",
- MakeTraceSourceAccessor (&LimitsWindow::m_curMaxLimit))
+ static TypeId tid = TypeId("ns3::ndn::Limits::Window")
+ .SetGroupName("Ndn")
+ .SetParent<Limits>()
+ .AddConstructor<LimitsWindow>()
- .AddTraceSource ("Outstanding",
- "Number of outstanding interests",
- MakeTraceSourceAccessor (&LimitsWindow::m_outstanding))
- ;
+ .AddTraceSource("CurMaxLimit", "Current maximum limit",
+ MakeTraceSourceAccessor(&LimitsWindow::m_curMaxLimit))
+
+ .AddTraceSource("Outstanding", "Number of outstanding interests",
+ MakeTraceSourceAccessor(&LimitsWindow::m_outstanding));
return tid;
}
void
-LimitsWindow::UpdateCurrentLimit (double limit)
+LimitsWindow::UpdateCurrentLimit(double limit)
{
- NS_ASSERT_MSG (limit >= 0.0, "Limit should be greater or equal to zero");
-
- m_curMaxLimit = std::min (limit, GetMaxRate () * GetMaxDelay ());
+ NS_ASSERT_MSG(limit >= 0.0, "Limit should be greater or equal to zero");
+
+ m_curMaxLimit = std::min(limit, GetMaxRate() * GetMaxDelay());
}
bool
-LimitsWindow::IsBelowLimit ()
+LimitsWindow::IsBelowLimit()
{
- if (!IsEnabled ()) return true;
+ if (!IsEnabled())
+ return true;
return (m_curMaxLimit - m_outstanding >= 1.0);
}
void
-LimitsWindow::BorrowLimit ()
+LimitsWindow::BorrowLimit()
{
- if (!IsEnabled ()) return;
+ if (!IsEnabled())
+ return;
- NS_ASSERT_MSG (m_curMaxLimit - m_outstanding >= 1.0, "Should not be possible, unless we IsBelowLimit was not checked correctly");
+ NS_ASSERT_MSG(m_curMaxLimit - m_outstanding >= 1.0,
+ "Should not be possible, unless we IsBelowLimit was not checked correctly");
m_outstanding += 1;
}
void
-LimitsWindow::ReturnLimit ()
+LimitsWindow::ReturnLimit()
{
- if (!IsEnabled ()) return;
+ if (!IsEnabled())
+ return;
- NS_ASSERT_MSG (m_outstanding >= (uint32_t)1, "Should not be possible, unless we decreasing this number twice somewhere");
+ NS_ASSERT_MSG(m_outstanding >= (uint32_t)1,
+ "Should not be possible, unless we decreasing this number twice somewhere");
m_outstanding -= 1;
- FireAvailableSlotCallback ();
+ FireAvailableSlotCallback();
}
} // namespace ndn
diff --git a/utils/ndn-limits-window.hpp b/utils/ndn-limits-window.hpp
index 2fcea6f..b407e02 100644
--- a/utils/ndn-limits-window.hpp
+++ b/utils/ndn-limits-window.hpp
@@ -19,7 +19,7 @@
*/
#ifndef _NDN_LIMITS_WINDOW_H_
-#define _NDN_LIMITS_WINDOW_H_
+#define _NDN_LIMITS_WINDOW_H_
#include "ndn-limits.hpp"
@@ -30,83 +30,81 @@
* \ingroup ndn-fw
* \brief Structure to manage limits for outstanding interests (window-based limiting)
*/
-class LimitsWindow :
- public Limits
-{
+class LimitsWindow : public Limits {
public:
typedef Limits super;
-
+
static TypeId
- GetTypeId ();
-
+ GetTypeId();
+
/**
* @brief Default Constructor
*/
- LimitsWindow ()
- : m_outstanding (0)
- { }
+ LimitsWindow()
+ : m_outstanding(0)
+ {
+ }
/**
* @brief Virtual destructor
*/
- virtual
- ~LimitsWindow () { }
+ virtual ~LimitsWindow()
+ {
+ }
// from ndn::Limits
virtual void
- SetLimits (double rate, double delay)
+ SetLimits(double rate, double delay)
{
- super::SetLimits (rate, delay);
+ super::SetLimits(rate, delay);
- m_curMaxLimit = GetMaxRate () * GetMaxDelay ();
+ m_curMaxLimit = GetMaxRate() * GetMaxDelay();
}
- virtual
- double
- GetMaxLimit () const
- {
- return GetMaxRate () * GetMaxDelay ();
- }
-
- virtual void
- UpdateCurrentLimit (double limit);
-
virtual double
- GetCurrentLimit () const
+ GetMaxLimit() const
+ {
+ return GetMaxRate() * GetMaxDelay();
+ }
+
+ virtual void
+ UpdateCurrentLimit(double limit);
+
+ virtual double
+ GetCurrentLimit() const
{
return m_curMaxLimit;
}
virtual double
- GetCurrentLimitRate () const
+ GetCurrentLimitRate() const
{
- return m_curMaxLimit / GetMaxDelay ();
+ return m_curMaxLimit / GetMaxDelay();
}
-
+
/**
- * @brief Check if current interest window (number of pending interests) if less than maximum
+ * @brief Check if current interest window (number of pending interests) if less than maximum
*/
virtual bool
- IsBelowLimit ();
+ IsBelowLimit();
/**
* @brief Increase current window of outstanding interests
*/
virtual void
- BorrowLimit ();
+ BorrowLimit();
/**
* @brief Decrease current window of outstanding interests
*/
virtual void
- ReturnLimit ();
-
+ ReturnLimit();
+
private:
- TracedValue< double > m_curMaxLimit;
- TracedValue< double > m_outstanding;
+ TracedValue<double> m_curMaxLimit;
+ TracedValue<double> m_outstanding;
};
-
} // namespace ndn
} // namespace ns3
diff --git a/utils/ndn-limits.cpp b/utils/ndn-limits.cpp
index 4519500..037b313 100644
--- a/utils/ndn-limits.cpp
+++ b/utils/ndn-limits.cpp
@@ -24,44 +24,40 @@
#include "ns3/simulator.h"
#include "ns3/random-variable.h"
-NS_LOG_COMPONENT_DEFINE ("ndn.Limits");
+NS_LOG_COMPONENT_DEFINE("ndn.Limits");
namespace ns3 {
namespace ndn {
TypeId
-Limits::GetTypeId ()
+Limits::GetTypeId()
{
- static TypeId tid = TypeId ("ns3::ndn::Limits")
- .SetGroupName ("Ndn")
- .SetParent <Object> ()
-
+ static TypeId tid = TypeId("ns3::ndn::Limits").SetGroupName("Ndn").SetParent<Object>()
+
;
return tid;
}
-Limits::Limits ()
- : m_maxRate (-1)
- , m_maxDelay (1.0)
- , m_handler (MakeNullCallback<void> ())
- , m_linkDelay (0)
+Limits::Limits()
+ : m_maxRate(-1)
+ , m_maxDelay(1.0)
+ , m_handler(MakeNullCallback<void>())
+ , m_linkDelay(0)
{
}
-
void
-Limits::RegisterAvailableSlotCallback (CallbackHandler handler)
+Limits::RegisterAvailableSlotCallback(CallbackHandler handler)
{
m_handler = handler;
}
void
-Limits::FireAvailableSlotCallback ()
+Limits::FireAvailableSlotCallback()
{
- if (!m_handler.IsNull ())
- m_handler ();
+ if (!m_handler.IsNull())
+ m_handler();
}
-
} // namespace ndn
} // namespace ns3
diff --git a/utils/ndn-limits.hpp b/utils/ndn-limits.hpp
index d8f848b..ebb8d15 100644
--- a/utils/ndn-limits.hpp
+++ b/utils/ndn-limits.hpp
@@ -19,7 +19,7 @@
*/
#ifndef _NDN_LIMITS_H_
-#define _NDN_LIMITS_H_
+#define _NDN_LIMITS_H_
#include "ns3/ptr.h"
#include "ns3/object.h"
@@ -30,45 +30,44 @@
/**
* \ingroup ndn-fw
- * \brief Abstract class to manage Interest limits
+ * \brief Abstract class to manage Interest limits
*/
-class Limits :
- public Object
-{
+class Limits : public Object {
public:
typedef Callback<void> CallbackHandler;
static TypeId
- GetTypeId ();
+ GetTypeId();
/**
* @brief Default constructor
*/
- Limits ();
+ Limits();
/**
* @brief Virtual destructor
*/
- virtual
- ~Limits () {}
-
+ virtual ~Limits()
+ {
+ }
+
/**
* @brief Set limit for the number of outstanding interests
* @param rate Maximum rate that needs to be enforced
* @param delay Maximum delay for BDP product for window-based limits
*/
virtual void
- SetLimits (double rate, double delay)
+ SetLimits(double rate, double delay)
{
m_maxRate = rate;
m_maxDelay = delay;
- }
+ }
/**
* @brief Get maximum rate that needs to be enforced
*/
virtual double
- GetMaxRate () const
+ GetMaxRate() const
{
return m_maxRate;
}
@@ -77,7 +76,7 @@
* @brief Get maximum delay for BDP product for window-based limits
*/
virtual double
- GetMaxDelay () const
+ GetMaxDelay() const
{
return m_maxDelay;
}
@@ -85,15 +84,14 @@
/**
* @brief Get maximum limit (interpretation of the limit depends on realization)
*/
- virtual
- double
- GetMaxLimit () const = 0;
+ virtual double
+ GetMaxLimit() const = 0;
/**
* @brief Check whether limits are enabled or not
*/
virtual inline bool
- IsEnabled () const
+ IsEnabled() const
{
return m_maxRate > 0.0;
}
@@ -104,11 +102,12 @@
*
* Note that interpretation of this value may be different in different ndn::Limit realizations
*
- * All realizations will try to guarantee that if limit is larger than previously set value of maximum limit,
+ * All realizations will try to guarantee that if limit is larger than previously set value of
+ *maximum limit,
* then the current limit will be limited to that maximum value
*/
virtual void
- UpdateCurrentLimit (double limit) = 0;
+ UpdateCurrentLimit(double limit) = 0;
/**
* @brief Get value of the current limit
@@ -116,17 +115,18 @@
* Note that interpretation of this value may be different in different ndn::Limit realizations
*/
virtual double
- GetCurrentLimit () const = 0;
+ GetCurrentLimit() const = 0;
/**
* @brief Get value of the current limit in terms of maximum rate that needs to be enforced
*
- * Compared to GetCurrentLimit, this method guarantees that the returned value is maximum number of packets
+ * Compared to GetCurrentLimit, this method guarantees that the returned value is maximum number
+ *of packets
* that can be send out within one second (max "rate")
*/
virtual double
- GetCurrentLimitRate () const = 0;
-
+ GetCurrentLimitRate() const = 0;
+
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
@@ -135,7 +135,7 @@
* @brief Realization-specific method called to check availability of the limit
*/
virtual bool
- IsBelowLimit () = 0;
+ IsBelowLimit() = 0;
/**
* @brief "Borrow" limit
@@ -143,13 +143,13 @@
* IsBelowLimit **must** be true, otherwise assert fail
*/
virtual void
- BorrowLimit () = 0;
+ BorrowLimit() = 0;
/**
* @brief "Return" limit
*/
virtual void
- ReturnLimit () = 0;
+ ReturnLimit() = 0;
/**
* @brief Set link delay (in seconds)
@@ -157,7 +157,7 @@
* This is a supplementary information that may or may not be useful for limits
*/
virtual void
- SetLinkDelay (double delay)
+ SetLinkDelay(double delay)
{
m_linkDelay = delay;
}
@@ -166,11 +166,11 @@
* @brief Get link delay (in seconds)
*/
virtual double
- GetLinkDelay () const
+ GetLinkDelay() const
{
return m_linkDelay;
}
-
+
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
@@ -179,12 +179,12 @@
* @brief Set callback which will be called when exhausted limit gets a new slot
*/
void
- RegisterAvailableSlotCallback (CallbackHandler handler);
+ RegisterAvailableSlotCallback(CallbackHandler handler);
protected:
void
- FireAvailableSlotCallback ();
-
+ FireAvailableSlotCallback();
+
private:
double m_maxRate;
double m_maxDelay;
@@ -193,7 +193,6 @@
double m_linkDelay;
};
-
} // namespace ndn
} // namespace ns3
diff --git a/utils/ndn-rtt-estimator.cpp b/utils/ndn-rtt-estimator.cpp
index 9e63cef..376c4ab 100644
--- a/utils/ndn-rtt-estimator.cpp
+++ b/utils/ndn-rtt-estimator.cpp
@@ -35,220 +35,222 @@
#include "ns3/uinteger.h"
#include "ns3/log.h"
-NS_LOG_COMPONENT_DEFINE ("ndn.RttEstimator");
+NS_LOG_COMPONENT_DEFINE("ndn.RttEstimator");
namespace ns3 {
namespace ndn {
-NS_OBJECT_ENSURE_REGISTERED (RttEstimator);
+NS_OBJECT_ENSURE_REGISTERED(RttEstimator);
TypeId
-RttEstimator::GetTypeId (void)
+RttEstimator::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::RttEstimator")
- .SetParent<Object> ()
- .AddAttribute ("MaxMultiplier",
- "Maximum RTO Multiplier",
- UintegerValue (64),
- MakeUintegerAccessor (&RttEstimator::m_maxMultiplier),
- MakeUintegerChecker<uint16_t> ())
- .AddAttribute ("InitialEstimation",
- "Initial RTT estimation",
- TimeValue (Seconds (1.0)),
- MakeTimeAccessor (&RttEstimator::m_initialEstimatedRtt),
- MakeTimeChecker ())
- .AddAttribute ("MinRTO",
- "Minimum retransmit timeout value",
- TimeValue (Seconds (0.2)), // RFC2988 says min RTO=1 sec, but Linux uses 200ms. See http://www.postel.org/pipermail/end2end-interest/2004-November/004402.html
- MakeTimeAccessor (&RttEstimator::SetMinRto,
- &RttEstimator::GetMinRto),
- MakeTimeChecker ())
- .AddAttribute ("MaxRTO",
- "Maximum retransmit timeout value",
- TimeValue (Seconds (200.0)),
- MakeTimeAccessor (&RttEstimator::SetMaxRto,
- &RttEstimator::GetMaxRto),
- MakeTimeChecker ())
- ;
+ static TypeId tid =
+ TypeId("ns3::ndn::RttEstimator")
+ .SetParent<Object>()
+ .AddAttribute("MaxMultiplier", "Maximum RTO Multiplier", UintegerValue(64),
+ MakeUintegerAccessor(&RttEstimator::m_maxMultiplier),
+ MakeUintegerChecker<uint16_t>())
+ .AddAttribute("InitialEstimation", "Initial RTT estimation", TimeValue(Seconds(1.0)),
+ MakeTimeAccessor(&RttEstimator::m_initialEstimatedRtt), MakeTimeChecker())
+ .AddAttribute("MinRTO", "Minimum retransmit timeout value",
+ TimeValue(
+ Seconds(0.2)), // RFC2988 says min RTO=1 sec, but Linux uses 200ms. See
+ // http://www.postel.org/pipermail/end2end-interest/2004-November/004402.html
+ MakeTimeAccessor(&RttEstimator::SetMinRto, &RttEstimator::GetMinRto),
+ MakeTimeChecker())
+ .AddAttribute("MaxRTO", "Maximum retransmit timeout value", TimeValue(Seconds(200.0)),
+ MakeTimeAccessor(&RttEstimator::SetMaxRto, &RttEstimator::GetMaxRto),
+ MakeTimeChecker());
return tid;
}
void
-RttEstimator::SetMinRto (Time minRto)
+RttEstimator::SetMinRto(Time minRto)
{
- NS_LOG_FUNCTION (this << minRto);
+ NS_LOG_FUNCTION(this << minRto);
m_minRto = minRto;
}
Time
-RttEstimator::GetMinRto (void) const
+RttEstimator::GetMinRto(void) const
{
return m_minRto;
}
void
-RttEstimator::SetMaxRto (Time maxRto)
+RttEstimator::SetMaxRto(Time maxRto)
{
- NS_LOG_FUNCTION (this << maxRto);
+ NS_LOG_FUNCTION(this << maxRto);
m_maxRto = maxRto;
}
Time
-RttEstimator::GetMaxRto (void) const
+RttEstimator::GetMaxRto(void) const
{
return m_maxRto;
}
void
-RttEstimator::SetCurrentEstimate (Time estimate)
+RttEstimator::SetCurrentEstimate(Time estimate)
{
- NS_LOG_FUNCTION (this << estimate);
+ NS_LOG_FUNCTION(this << estimate);
m_currentEstimatedRtt = estimate;
}
Time
-RttEstimator::GetCurrentEstimate (void) const
+RttEstimator::GetCurrentEstimate(void) const
{
return m_currentEstimatedRtt;
}
-
-//RttHistory methods
-RttHistory::RttHistory (SequenceNumber32 s, uint32_t c, Time t)
- : seq (s), count (c), time (t), retx (false)
+// RttHistory methods
+RttHistory::RttHistory(SequenceNumber32 s, uint32_t c, Time t)
+ : seq(s)
+ , count(c)
+ , time(t)
+ , retx(false)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
-RttHistory::RttHistory (const RttHistory& h)
- : seq (h.seq), count (h.count), time (h.time), retx (h.retx)
+RttHistory::RttHistory(const RttHistory& h)
+ : seq(h.seq)
+ , count(h.count)
+ , time(h.time)
+ , retx(h.retx)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
// Base class methods
-RttEstimator::RttEstimator ()
- : m_next (1),
- m_nSamples (0),
- m_multiplier (1),
- m_history ()
+RttEstimator::RttEstimator()
+ : m_next(1)
+ , m_nSamples(0)
+ , m_multiplier(1)
+ , m_history()
{
- NS_LOG_FUNCTION (this);
- //note next=1 everywhere since first segment will have sequence 1
+ NS_LOG_FUNCTION(this);
+ // note next=1 everywhere since first segment will have sequence 1
// We need attributes initialized here, not later, so use the
// ConstructSelf() technique documented in the manual
- ObjectBase::ConstructSelf (AttributeConstructionList ());
+ ObjectBase::ConstructSelf(AttributeConstructionList());
m_currentEstimatedRtt = m_initialEstimatedRtt;
- NS_LOG_DEBUG ("Initialize m_currentEstimatedRtt to " << m_currentEstimatedRtt.GetSeconds () << " sec.");
+ NS_LOG_DEBUG("Initialize m_currentEstimatedRtt to " << m_currentEstimatedRtt.GetSeconds()
+ << " sec.");
}
-RttEstimator::RttEstimator (const RttEstimator& c)
- : Object (c), m_next (c.m_next),
- m_maxMultiplier (c.m_maxMultiplier),
- m_initialEstimatedRtt (c.m_initialEstimatedRtt),
- m_currentEstimatedRtt (c.m_currentEstimatedRtt), m_minRto (c.m_minRto), m_maxRto (c.m_maxRto),
- m_nSamples (c.m_nSamples), m_multiplier (c.m_multiplier),
- m_history (c.m_history)
+RttEstimator::RttEstimator(const RttEstimator& c)
+ : Object(c)
+ , m_next(c.m_next)
+ , m_maxMultiplier(c.m_maxMultiplier)
+ , m_initialEstimatedRtt(c.m_initialEstimatedRtt)
+ , m_currentEstimatedRtt(c.m_currentEstimatedRtt)
+ , m_minRto(c.m_minRto)
+ , m_maxRto(c.m_maxRto)
+ , m_nSamples(c.m_nSamples)
+ , m_multiplier(c.m_multiplier)
+ , m_history(c.m_history)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
-RttEstimator::~RttEstimator ()
+RttEstimator::~RttEstimator()
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
TypeId
-RttEstimator::GetInstanceTypeId (void) const
+RttEstimator::GetInstanceTypeId(void) const
{
- return GetTypeId ();
+ return GetTypeId();
}
-void RttEstimator::SentSeq (SequenceNumber32 seq, uint32_t size)
+void
+RttEstimator::SentSeq(SequenceNumber32 seq, uint32_t size)
{
- NS_LOG_FUNCTION (this << seq << size);
+ NS_LOG_FUNCTION(this << seq << size);
// Note that a particular sequence has been sent
- if (seq == m_next)
- { // This is the next expected one, just log at end
- m_history.push_back (RttHistory (seq, size, Simulator::Now () ));
- m_next = seq + SequenceNumber32 (size); // Update next expected
- }
- else
- { // This is a retransmit, find in list and mark as re-tx
- for (RttHistory_t::iterator i = m_history.begin (); i != m_history.end (); ++i)
- {
- if ((seq >= i->seq) && (seq < (i->seq + SequenceNumber32 (i->count))))
- { // Found it
- i->retx = true;
- // One final test..be sure this re-tx does not extend "next"
- if ((seq + SequenceNumber32 (size)) > m_next)
- {
- m_next = seq + SequenceNumber32 (size);
- i->count = ((seq + SequenceNumber32 (size)) - i->seq); // And update count in hist
- }
- break;
- }
+ if (seq == m_next) { // This is the next expected one, just log at end
+ m_history.push_back(RttHistory(seq, size, Simulator::Now()));
+ m_next = seq + SequenceNumber32(size); // Update next expected
+ }
+ else { // This is a retransmit, find in list and mark as re-tx
+ for (RttHistory_t::iterator i = m_history.begin(); i != m_history.end(); ++i) {
+ if ((seq >= i->seq) && (seq < (i->seq + SequenceNumber32(i->count)))) { // Found it
+ i->retx = true;
+ // One final test..be sure this re-tx does not extend "next"
+ if ((seq + SequenceNumber32(size)) > m_next) {
+ m_next = seq + SequenceNumber32(size);
+ i->count = ((seq + SequenceNumber32(size)) - i->seq); // And update count in hist
}
+ break;
+ }
}
+ }
}
-Time RttEstimator::AckSeq (SequenceNumber32 ackSeq)
+Time
+RttEstimator::AckSeq(SequenceNumber32 ackSeq)
{
- NS_LOG_FUNCTION (this << ackSeq);
+ NS_LOG_FUNCTION(this << ackSeq);
// An ack has been received, calculate rtt and log this measurement
// Note we use a linear search (O(n)) for this since for the common
// case the ack'ed packet will be at the head of the list
- Time m = Seconds (0.0);
- if (m_history.size () == 0) return (m); // No pending history, just exit
- RttHistory& h = m_history.front ();
- if (!h.retx && ackSeq >= (h.seq + SequenceNumber32 (h.count)))
- { // Ok to use this sample
- m = Simulator::Now () - h.time; // Elapsed time
- Measurement (m); // Log the measurement
- ResetMultiplier (); // Reset multiplier on valid measurement
- }
+ Time m = Seconds(0.0);
+ if (m_history.size() == 0)
+ return (m); // No pending history, just exit
+ RttHistory& h = m_history.front();
+ if (!h.retx && ackSeq >= (h.seq + SequenceNumber32(h.count))) { // Ok to use this sample
+ m = Simulator::Now() - h.time; // Elapsed time
+ Measurement(m); // Log the measurement
+ ResetMultiplier(); // Reset multiplier on valid measurement
+ }
// Now delete all ack history with seq <= ack
- while(m_history.size () > 0)
- {
- RttHistory& h = m_history.front ();
- if ((h.seq + SequenceNumber32 (h.count)) > ackSeq) break; // Done removing
- m_history.pop_front (); // Remove
- }
+ while (m_history.size() > 0) {
+ RttHistory& h = m_history.front();
+ if ((h.seq + SequenceNumber32(h.count)) > ackSeq)
+ break; // Done removing
+ m_history.pop_front(); // Remove
+ }
return m;
}
-void RttEstimator::ClearSent ()
+void
+RttEstimator::ClearSent()
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
// Clear all history entries
m_next = 1;
- m_history.clear ();
+ m_history.clear();
}
-void RttEstimator::IncreaseMultiplier ()
+void
+RttEstimator::IncreaseMultiplier()
{
- NS_LOG_FUNCTION (this);
- m_multiplier = (m_multiplier*2 < m_maxMultiplier) ? m_multiplier*2 : m_maxMultiplier;
- NS_LOG_DEBUG ("Multiplier increased to " << m_multiplier);
+ NS_LOG_FUNCTION(this);
+ m_multiplier = (m_multiplier * 2 < m_maxMultiplier) ? m_multiplier * 2 : m_maxMultiplier;
+ NS_LOG_DEBUG("Multiplier increased to " << m_multiplier);
}
-void RttEstimator::ResetMultiplier ()
+void
+RttEstimator::ResetMultiplier()
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
m_multiplier = 1;
}
-void RttEstimator::Reset ()
+void
+RttEstimator::Reset()
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
// Reset to initial state
m_next = 1;
m_currentEstimatedRtt = m_initialEstimatedRtt;
- m_history.clear (); // Remove all info from the history
+ m_history.clear(); // Remove all info from the history
m_nSamples = 0;
- ResetMultiplier ();
+ ResetMultiplier();
}
-
} // namespace ndn
} // namespace ns3
diff --git a/utils/ndn-rtt-estimator.hpp b/utils/ndn-rtt-estimator.hpp
index 8da703b..58cc754 100644
--- a/utils/ndn-rtt-estimator.hpp
+++ b/utils/ndn-rtt-estimator.hpp
@@ -42,13 +42,13 @@
*/
class RttHistory {
public:
- RttHistory (SequenceNumber32 s, uint32_t c, Time t);
- RttHistory (const RttHistory& h); // Copy constructor
+ RttHistory(SequenceNumber32 s, uint32_t c, Time t);
+ RttHistory(const RttHistory& h); // Copy constructor
public:
- SequenceNumber32 seq; // First sequence number in packet sent
- uint32_t count; // Number of bytes sent
- Time time; // Time this one was sent
- bool retx; // True if this has been retransmitted
+ SequenceNumber32 seq; // First sequence number in packet sent
+ uint32_t count; // Number of bytes sent
+ Time time; // Time this one was sent
+ bool retx; // True if this has been retransmitted
};
typedef std::deque<RttHistory> RttHistory_t;
@@ -60,110 +60,127 @@
*/
class RttEstimator : public Object {
public:
- static TypeId GetTypeId (void);
+ static TypeId
+ GetTypeId(void);
RttEstimator();
- RttEstimator (const RttEstimator&);
+ RttEstimator(const RttEstimator&);
virtual ~RttEstimator();
- virtual TypeId GetInstanceTypeId (void) const;
+ virtual TypeId
+ GetInstanceTypeId(void) const;
/**
* \brief Note that a particular sequence has been sent
* \param seq the packet sequence number.
* \param size the packet size.
*/
- virtual void SentSeq (SequenceNumber32 seq, uint32_t size);
+ virtual void
+ SentSeq(SequenceNumber32 seq, uint32_t size);
/**
* \brief Note that a particular ack sequence has been received
* \param ackSeq the ack sequence number.
* \return The measured RTT for this ack.
*/
- virtual Time AckSeq (SequenceNumber32 ackSeq);
+ virtual Time
+ AckSeq(SequenceNumber32 ackSeq);
/**
* \brief Clear all history entries
*/
- virtual void ClearSent ();
+ virtual void
+ ClearSent();
/**
* \brief Add a new measurement to the estimator. Pure virtual function.
* \param t the new RTT measure.
*/
- virtual void Measurement (Time t) = 0;
+ virtual void
+ Measurement(Time t) = 0;
/**
* \brief Returns the estimated RTO. Pure virtual function.
* \return the estimated RTO.
*/
- virtual Time RetransmitTimeout () = 0;
+ virtual Time
+ RetransmitTimeout() = 0;
- virtual Ptr<RttEstimator> Copy () const = 0;
+ virtual Ptr<RttEstimator>
+ Copy() const = 0;
/**
* \brief Increase the estimation multiplier up to MaxMultiplier.
*/
- virtual void IncreaseMultiplier ();
+ virtual void
+ IncreaseMultiplier();
/**
* \brief Resets the estimation multiplier to 1.
*/
- virtual void ResetMultiplier ();
+ virtual void
+ ResetMultiplier();
/**
* \brief Resets the estimation to its initial state.
*/
- virtual void Reset ();
+ virtual void
+ Reset();
/**
* \brief Sets the Minimum RTO.
* \param minRto The minimum RTO returned by the estimator.
*/
- void SetMinRto (Time minRto);
+ void
+ SetMinRto(Time minRto);
/**
* \brief Get the Minimum RTO.
* \return The minimum RTO returned by the estimator.
*/
- Time GetMinRto (void) const;
+ Time
+ GetMinRto(void) const;
/**
* \brief Sets the Maximum RTO.
* \param minRto The maximum RTO returned by the estimator.
*/
- void SetMaxRto (Time maxRto);
+ void
+ SetMaxRto(Time maxRto);
/**
* \brief Get the Maximum RTO.
* \return The maximum RTO returned by the estimator.
*/
- Time GetMaxRto (void) const;
+ Time
+ GetMaxRto(void) const;
/**
* \brief Sets the current RTT estimate (forcefully).
* \param estimate The current RTT estimate.
*/
- void SetCurrentEstimate (Time estimate);
+ void
+ SetCurrentEstimate(Time estimate);
/**
* \brief gets the current RTT estimate.
* \return The current RTT estimate.
*/
- Time GetCurrentEstimate (void) const;
+ Time
+ GetCurrentEstimate(void) const;
private:
- SequenceNumber32 m_next; // Next expected sequence to be sent
+ SequenceNumber32 m_next; // Next expected sequence to be sent
uint16_t m_maxMultiplier;
Time m_initialEstimatedRtt;
protected:
- Time m_currentEstimatedRtt; // Current estimate
- Time m_minRto; // minimum value of the timeout
- Time m_maxRto; // maximum value of the timeout
- uint32_t m_nSamples; // Number of samples
- uint16_t m_multiplier; // RTO Multiplier
+ Time m_currentEstimatedRtt; // Current estimate
+ Time m_minRto; // minimum value of the timeout
+ Time m_maxRto; // maximum value of the timeout
+ uint32_t m_nSamples; // Number of samples
+ uint16_t m_multiplier; // RTO Multiplier
RttHistory_t m_history; // List of sent packet
};
diff --git a/utils/ndn-rtt-mean-deviation.cpp b/utils/ndn-rtt-mean-deviation.cpp
index 8e99069..c6c7218 100644
--- a/utils/ndn-rtt-mean-deviation.cpp
+++ b/utils/ndn-rtt-mean-deviation.cpp
@@ -32,7 +32,7 @@
#include "ns3/uinteger.h"
#include "ns3/log.h"
-NS_LOG_COMPONENT_DEFINE ("ndn.RttMeanDeviation");
+NS_LOG_COMPONENT_DEFINE("ndn.RttMeanDeviation");
namespace ns3 {
namespace ndn {
@@ -40,143 +40,147 @@
//---------------------------------------------------------------------------------
// A modified version of Mean-Deviation Estimator optimized for NDN packet delivery
-NS_OBJECT_ENSURE_REGISTERED (RttMeanDeviation);
+NS_OBJECT_ENSURE_REGISTERED(RttMeanDeviation);
TypeId
-RttMeanDeviation::GetTypeId (void)
+RttMeanDeviation::GetTypeId(void)
{
- static TypeId tid = TypeId ("ns3::ndn::RttMeanDeviation")
- .SetParent<RttEstimator> ()
- .AddConstructor<RttMeanDeviation> ()
- .AddAttribute ("Gain",
- "Gain used in estimating the RTT (smoothed RTT), must be 0 < Gain < 1",
- DoubleValue (0.125),
- MakeDoubleAccessor (&RttMeanDeviation::m_gain),
- MakeDoubleChecker<double> ())
- .AddAttribute ("Gain2",
- "Gain2 used in estimating the RTT (variance), must be 0 < Gain2 < 1",
- DoubleValue (0.25),
- MakeDoubleAccessor (&RttMeanDeviation::m_gain2),
- MakeDoubleChecker<double> ())
- ;
+ static TypeId tid =
+ TypeId("ns3::ndn::RttMeanDeviation")
+ .SetParent<RttEstimator>()
+ .AddConstructor<RttMeanDeviation>()
+ .AddAttribute("Gain", "Gain used in estimating the RTT (smoothed RTT), must be 0 < Gain < 1",
+ DoubleValue(0.125), MakeDoubleAccessor(&RttMeanDeviation::m_gain),
+ MakeDoubleChecker<double>())
+ .AddAttribute("Gain2", "Gain2 used in estimating the RTT (variance), must be 0 < Gain2 < 1",
+ DoubleValue(0.25), MakeDoubleAccessor(&RttMeanDeviation::m_gain2),
+ MakeDoubleChecker<double>());
return tid;
}
-RttMeanDeviation::RttMeanDeviation() :
- m_variance (0)
+RttMeanDeviation::RttMeanDeviation()
+ : m_variance(0)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
-RttMeanDeviation::RttMeanDeviation (const RttMeanDeviation& c)
- : RttEstimator (c), m_gain (c.m_gain), m_gain2 (c.m_gain2), m_variance (c.m_variance)
+RttMeanDeviation::RttMeanDeviation(const RttMeanDeviation& c)
+ : RttEstimator(c)
+ , m_gain(c.m_gain)
+ , m_gain2(c.m_gain2)
+ , m_variance(c.m_variance)
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
}
TypeId
-RttMeanDeviation::GetInstanceTypeId (void) const
+RttMeanDeviation::GetInstanceTypeId(void) const
{
- return GetTypeId ();
+ return GetTypeId();
}
-void RttMeanDeviation::Measurement (Time m)
+void
+RttMeanDeviation::Measurement(Time m)
{
- NS_LOG_FUNCTION (this << m);
- if (m_nSamples)
- { // Not first
- Time err (m - m_currentEstimatedRtt);
- double gErr = err.ToDouble (Time::S) * m_gain;
- m_currentEstimatedRtt += Time::FromDouble (gErr, Time::S);
- Time difference = Abs (err) - m_variance;
- NS_LOG_DEBUG ("m_variance += " << Time::FromDouble (difference.ToDouble (Time::S) * m_gain2, Time::S));
- m_variance += Time::FromDouble (difference.ToDouble (Time::S) * m_gain2, Time::S);
- }
- else
- { // First sample
- m_currentEstimatedRtt = m; // Set estimate to current
- //variance = sample / 2; // And variance to current / 2
- // m_variance = m; // try this why????
- m_variance = Seconds (m.ToDouble (Time::S) / 2);
- NS_LOG_DEBUG ("(first sample) m_variance += " << m);
- }
+ NS_LOG_FUNCTION(this << m);
+ if (m_nSamples) { // Not first
+ Time err(m - m_currentEstimatedRtt);
+ double gErr = err.ToDouble(Time::S) * m_gain;
+ m_currentEstimatedRtt += Time::FromDouble(gErr, Time::S);
+ Time difference = Abs(err) - m_variance;
+ NS_LOG_DEBUG(
+ "m_variance += " << Time::FromDouble(difference.ToDouble(Time::S) * m_gain2, Time::S));
+ m_variance += Time::FromDouble(difference.ToDouble(Time::S) * m_gain2, Time::S);
+ }
+ else { // First sample
+ m_currentEstimatedRtt = m; // Set estimate to current
+ // variance = sample / 2; // And variance to current / 2
+ // m_variance = m; // try this why????
+ m_variance = Seconds(m.ToDouble(Time::S) / 2);
+ NS_LOG_DEBUG("(first sample) m_variance += " << m);
+ }
m_nSamples++;
}
-Time RttMeanDeviation::RetransmitTimeout ()
+Time
+RttMeanDeviation::RetransmitTimeout()
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
- double retval = std::min (m_maxRto.ToDouble (Time::S),
- std::max (m_multiplier*m_minRto.ToDouble (Time::S),
- m_multiplier*(m_currentEstimatedRtt.ToDouble (Time::S) + 4 * m_variance.ToDouble (Time::S))));
+ double retval = std::min(m_maxRto.ToDouble(Time::S),
+ std::max(m_multiplier * m_minRto.ToDouble(Time::S),
+ m_multiplier * (m_currentEstimatedRtt.ToDouble(Time::S)
+ + 4 * m_variance.ToDouble(Time::S))));
- NS_LOG_DEBUG ("RetransmitTimeout: return " << retval);
+ NS_LOG_DEBUG("RetransmitTimeout: return " << retval);
- return Seconds (retval);
+ return Seconds(retval);
}
-Ptr<RttEstimator> RttMeanDeviation::Copy () const
+Ptr<RttEstimator>
+RttMeanDeviation::Copy() const
{
- NS_LOG_FUNCTION (this);
- return CopyObject<RttMeanDeviation> (this);
+ NS_LOG_FUNCTION(this);
+ return CopyObject<RttMeanDeviation>(this);
}
-void RttMeanDeviation::Reset ()
+void
+RttMeanDeviation::Reset()
{
- NS_LOG_FUNCTION (this);
+ NS_LOG_FUNCTION(this);
// Reset to initial state
- m_variance = Seconds (0);
- RttEstimator::Reset ();
+ m_variance = Seconds(0);
+ RttEstimator::Reset();
}
-void RttMeanDeviation::Gain (double g)
+void
+RttMeanDeviation::Gain(double g)
{
- NS_LOG_FUNCTION (this);
- NS_ASSERT_MSG( (g > 0) && (g < 1), "RttMeanDeviation: Gain must be less than 1 and greater than 0" );
+ NS_LOG_FUNCTION(this);
+ NS_ASSERT_MSG((g > 0) && (g < 1),
+ "RttMeanDeviation: Gain must be less than 1 and greater than 0");
m_gain = g;
}
-void RttMeanDeviation::SentSeq (SequenceNumber32 seq, uint32_t size)
-{
- NS_LOG_FUNCTION (this << seq << size);
+void
+RttMeanDeviation::SentSeq(SequenceNumber32 seq, uint32_t size)
+{
+ NS_LOG_FUNCTION(this << seq << size);
RttHistory_t::iterator i;
- for (i = m_history.begin (); i != m_history.end (); ++i)
- {
- if (seq == i->seq)
- { // Found it
- i->retx = true;
- break;
- }
+ for (i = m_history.begin(); i != m_history.end(); ++i) {
+ if (seq == i->seq) { // Found it
+ i->retx = true;
+ break;
+ }
}
// Note that a particular sequence has been sent
if (i == m_history.end())
- m_history.push_back (RttHistory (seq, size, Simulator::Now () ));
+ m_history.push_back(RttHistory(seq, size, Simulator::Now()));
}
-Time RttMeanDeviation::AckSeq (SequenceNumber32 ackSeq)
+Time
+RttMeanDeviation::AckSeq(SequenceNumber32 ackSeq)
{
- NS_LOG_FUNCTION (this << ackSeq);
+ NS_LOG_FUNCTION(this << ackSeq);
// An ack has been received, calculate rtt and log this measurement
// Note we use a linear search (O(n)) for this since for the common
// case the ack'ed packet will be at the head of the list
- Time m = Seconds (0.0);
- if (m_history.size () == 0) return (m); // No pending history, just exit
+ Time m = Seconds(0.0);
+ if (m_history.size() == 0)
+ return (m); // No pending history, just exit
- for (RttHistory_t::iterator i = m_history.begin (); i != m_history.end (); ++i)
- {
- if (ackSeq == i->seq)
- { // Found it
- if (!i->retx) {
- m = Simulator::Now () - i->time;// Elapsed time
- Measurement (m); // Log the measurement
- ResetMultiplier (); // Reset multiplier on valid measurement
- }
- m_history.erase(i);
- break;
+ for (RttHistory_t::iterator i = m_history.begin(); i != m_history.end(); ++i) {
+ if (ackSeq == i->seq) { // Found it
+ if (!i->retx) {
+ m = Simulator::Now() - i->time; // Elapsed time
+ Measurement(m); // Log the measurement
+ ResetMultiplier(); // Reset multiplier on valid measurement
}
+ m_history.erase(i);
+ break;
+ }
}
return m;
@@ -184,4 +188,3 @@
} // namespace ndn
} // namespace ns3
-
diff --git a/utils/ndn-rtt-mean-deviation.hpp b/utils/ndn-rtt-mean-deviation.hpp
index 428bff8..fdb6144 100644
--- a/utils/ndn-rtt-mean-deviation.hpp
+++ b/utils/ndn-rtt-mean-deviation.hpp
@@ -25,7 +25,6 @@
// Georgia Tech Network Simulator - Round Trip Time Estimation Class
// George F. Riley. Georgia Tech, Spring 2002
-
#ifndef NDN_RTT_MEAN_DEVIATION_H
#define NDN_RTT_MEAN_DEVIATION_H
@@ -37,7 +36,8 @@
/**
* \ingroup ndn-apps
*
- * \brief The modified version of "Mean--Deviation" RTT estimator, as discussed by Van Jacobson that better suits NDN communication model
+ * \brief The modified version of "Mean--Deviation" RTT estimator, as discussed by Van Jacobson that
+ *better suits NDN communication model
*
* This class implements the "Mean--Deviation" RTT estimator, as discussed
* by Van Jacobson and Michael J. Karels, in
@@ -46,25 +46,34 @@
*/
class RttMeanDeviation : public RttEstimator {
public:
- static TypeId GetTypeId (void);
+ static TypeId
+ GetTypeId(void);
- RttMeanDeviation ();
- RttMeanDeviation (const RttMeanDeviation&);
+ RttMeanDeviation();
+ RttMeanDeviation(const RttMeanDeviation&);
- virtual TypeId GetInstanceTypeId (void) const;
+ virtual TypeId
+ GetInstanceTypeId(void) const;
- void SentSeq (SequenceNumber32 seq, uint32_t size);
- Time AckSeq (SequenceNumber32 ackSeq);
- void Measurement (Time measure);
- Time RetransmitTimeout ();
- Ptr<RttEstimator> Copy () const;
- void Reset ();
- void Gain (double g);
+ void
+ SentSeq(SequenceNumber32 seq, uint32_t size);
+ Time
+ AckSeq(SequenceNumber32 ackSeq);
+ void
+ Measurement(Time measure);
+ Time
+ RetransmitTimeout();
+ Ptr<RttEstimator>
+ Copy() const;
+ void
+ Reset();
+ void
+ Gain(double g);
private:
- double m_gain; // Filter gain
- double m_gain2; // Filter gain
- Time m_variance; // Current variance
+ double m_gain; // Filter gain
+ double m_gain2; // Filter gain
+ Time m_variance; // Current variance
};
} // namespace ndn
diff --git a/utils/tracers/l2-rate-tracer.cpp b/utils/tracers/l2-rate-tracer.cpp
index 41ae00b..f5c4d22 100644
--- a/utils/tracers/l2-rate-tracer.cpp
+++ b/utils/tracers/l2-rate-tracer.cpp
@@ -34,153 +34,150 @@
using namespace boost;
using namespace std;
-NS_LOG_COMPONENT_DEFINE ("L2RateTracer");
+NS_LOG_COMPONENT_DEFINE("L2RateTracer");
namespace ns3 {
-static std::list< boost::tuple< boost::shared_ptr<std::ostream>, std::list<Ptr<L2RateTracer> > > > g_tracers;
+static std::list<boost::tuple<boost::shared_ptr<std::ostream>, std::list<Ptr<L2RateTracer>>>>
+ g_tracers;
template<class T>
static inline void
-NullDeleter (T *ptr)
+NullDeleter(T* ptr)
{
}
void
-L2RateTracer::Destroy ()
+L2RateTracer::Destroy()
{
- g_tracers.clear ();
+ g_tracers.clear();
}
void
-L2RateTracer::InstallAll (const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
+L2RateTracer::InstallAll(const std::string& file, Time averagingPeriod /* = Seconds (0.5)*/)
{
- std::list<Ptr<L2RateTracer> > tracers;
+ std::list<Ptr<L2RateTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- for (NodeList::Iterator node = NodeList::Begin ();
- node != NodeList::End ();
- node++)
- {
- NS_LOG_DEBUG ("Node: " << lexical_cast<string> ((*node)->GetId ()));
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- Ptr<L2RateTracer> trace = Create<L2RateTracer> (outputStream, *node);
- trace->SetAveragingPeriod (averagingPeriod);
- tracers.push_back (trace);
- }
+ for (NodeList::Iterator node = NodeList::Begin(); node != NodeList::End(); node++) {
+ NS_LOG_DEBUG("Node: " << lexical_cast<string>((*node)->GetId()));
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ Ptr<L2RateTracer> trace = Create<L2RateTracer>(outputStream, *node);
+ trace->SetAveragingPeriod(averagingPeriod);
+ tracers.push_back(trace);
+ }
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
-
-L2RateTracer::L2RateTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node)
- : L2Tracer (node)
- , m_os (os)
+L2RateTracer::L2RateTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node)
+ : L2Tracer(node)
+ , m_os(os)
{
- SetAveragingPeriod (Seconds (1.0));
+ SetAveragingPeriod(Seconds(1.0));
}
-L2RateTracer::~L2RateTracer ()
+L2RateTracer::~L2RateTracer()
{
- m_printEvent.Cancel ();
+ m_printEvent.Cancel();
}
void
-L2RateTracer::SetAveragingPeriod (const Time &period)
+L2RateTracer::SetAveragingPeriod(const Time& period)
{
m_period = period;
- m_printEvent.Cancel ();
- m_printEvent = Simulator::Schedule (m_period, &L2RateTracer::PeriodicPrinter, this);
+ m_printEvent.Cancel();
+ m_printEvent = Simulator::Schedule(m_period, &L2RateTracer::PeriodicPrinter, this);
}
void
-L2RateTracer::PeriodicPrinter ()
+L2RateTracer::PeriodicPrinter()
{
- Print (*m_os);
- Reset ();
+ Print(*m_os);
+ Reset();
- m_printEvent = Simulator::Schedule (m_period, &L2RateTracer::PeriodicPrinter, this);
+ m_printEvent = Simulator::Schedule(m_period, &L2RateTracer::PeriodicPrinter, this);
}
void
-L2RateTracer::PrintHeader (std::ostream &os) const
+L2RateTracer::PrintHeader(std::ostream& os) const
{
- os << "Time" << "\t"
+ os << "Time"
+ << "\t"
- << "Node" << "\t"
- << "Interface" << "\t"
+ << "Node"
+ << "\t"
+ << "Interface"
+ << "\t"
- << "Type" << "\t"
- << "Packets" << "\t"
- << "Kilobytes" << "\t"
- << "PacketsRaw" << "\t"
+ << "Type"
+ << "\t"
+ << "Packets"
+ << "\t"
+ << "Kilobytes"
+ << "\t"
+ << "PacketsRaw"
+ << "\t"
<< "KilobytesRaw";
}
void
-L2RateTracer::Reset ()
+L2RateTracer::Reset()
{
- m_stats.get<0> ().Reset ();
- m_stats.get<1> ().Reset ();
+ m_stats.get<0>().Reset();
+ m_stats.get<1>().Reset();
}
const double alpha = 0.8;
-#define STATS(INDEX) m_stats.get<INDEX> ()
-#define RATE(INDEX, fieldName) STATS(INDEX).fieldName / m_period.ToDouble (Time::S)
+#define STATS(INDEX) m_stats.get<INDEX>()
+#define RATE(INDEX, fieldName) STATS(INDEX).fieldName / m_period.ToDouble(Time::S)
-#define PRINTER(printName, fieldName, interface) \
-STATS(2).fieldName = /*new value*/alpha * RATE(0, fieldName) + /*old value*/(1-alpha) * STATS(2).fieldName; \
-STATS(3).fieldName = /*new value*/alpha * RATE(1, fieldName) / 1024.0 + /*old value*/(1-alpha) * STATS(3).fieldName; \
- \
- os << time.ToDouble (Time::S) << "\t" \
- << m_node << "\t" \
- << interface << "\t" \
- << printName << "\t" \
- << STATS(2).fieldName << "\t" \
- << STATS(3).fieldName << "\t" \
- << STATS(0).fieldName << "\t" \
- << STATS(1).fieldName / 1024.0 << "\n";
+#define PRINTER(printName, fieldName, interface) \
+ STATS(2).fieldName = \
+ /*new value*/ alpha * RATE(0, fieldName) + /*old value*/ (1 - alpha) * STATS(2).fieldName; \
+ STATS(3).fieldName = /*new value*/ alpha * RATE(1, fieldName) / 1024.0 \
+ + /*old value*/ (1 - alpha) * STATS(3).fieldName; \
+ \
+ os << time.ToDouble(Time::S) << "\t" << m_node << "\t" << interface << "\t" << printName << "\t" \
+ << STATS(2).fieldName << "\t" << STATS(3).fieldName << "\t" << STATS(0).fieldName << "\t" \
+ << STATS(1).fieldName / 1024.0 << "\n";
void
-L2RateTracer::Print (std::ostream &os) const
+L2RateTracer::Print(std::ostream& os) const
{
- Time time = Simulator::Now ();
+ Time time = Simulator::Now();
- PRINTER ("Drop", m_drop, "combined");
+ PRINTER("Drop", m_drop, "combined");
}
void
-L2RateTracer::Drop (Ptr<const Packet> packet)
+L2RateTracer::Drop(Ptr<const Packet> packet)
{
// no interface information... this should be part of this L2Tracer object data
- m_stats.get<0> ().m_drop ++;
- m_stats.get<1> ().m_drop += packet->GetSize ();
+ m_stats.get<0>().m_drop++;
+ m_stats.get<1>().m_drop += packet->GetSize();
}
} // namespace ns3
diff --git a/utils/tracers/l2-rate-tracer.hpp b/utils/tracers/l2-rate-tracer.hpp
index 275b213..79f16c4 100644
--- a/utils/tracers/l2-rate-tracer.hpp
+++ b/utils/tracers/l2-rate-tracer.hpp
@@ -38,28 +38,29 @@
*
* @todo Finish implementation
*/
-class L2RateTracer : public L2Tracer
-{
+class L2RateTracer : public L2Tracer {
public:
/**
* @brief Network layer tracer constructor
*/
- L2RateTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node);
- virtual ~L2RateTracer ();
+ L2RateTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node);
+ virtual ~L2RateTracer();
/**
* @brief Helper method to install tracers on all simulation nodes
*
* @param file File to which traces will be written
* @param averagingPeriod Defines averaging period for the rate calculation,
- * as well as how often data will be written into the trace file (default, every half second)
+ * as well as how often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*
*/
static void
- InstallAll (const std::string &file, Time averagingPeriod = Seconds (0.5));
+ InstallAll(const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Explicit request to remove all statically created tracers
@@ -68,26 +69,26 @@
* or if it is desired to do a postprocessing of the resulting data
*/
static void
- Destroy ();
+ Destroy();
void
- SetAveragingPeriod (const Time &period);
+ SetAveragingPeriod(const Time& period);
virtual void
- PrintHeader (std::ostream &os) const;
+ PrintHeader(std::ostream& os) const;
virtual void
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
virtual void
- Drop (Ptr<const Packet>);
+ Drop(Ptr<const Packet>);
private:
void
- PeriodicPrinter ();
+ PeriodicPrinter();
void
- Reset ();
+ Reset();
private:
boost::shared_ptr<std::ostream> m_os;
diff --git a/utils/tracers/l2-tracer.cpp b/utils/tracers/l2-tracer.cpp
index 631db7c..bf1fcf1 100644
--- a/utils/tracers/l2-tracer.cpp
+++ b/utils/tracers/l2-tracer.cpp
@@ -32,31 +32,29 @@
namespace ns3 {
-L2Tracer::L2Tracer (Ptr<Node> node)
-: m_nodePtr (node)
+L2Tracer::L2Tracer(Ptr<Node> node)
+ : m_nodePtr(node)
{
- m_node = boost::lexical_cast<string> (m_nodePtr->GetId ());
+ m_node = boost::lexical_cast<string>(m_nodePtr->GetId());
- Connect ();
+ Connect();
- string name = Names::FindName (node);
- if (!name.empty ())
- {
- m_node = name;
- }
+ string name = Names::FindName(node);
+ if (!name.empty()) {
+ m_node = name;
+ }
}
void
-L2Tracer::Connect ()
+L2Tracer::Connect()
{
- for (uint32_t devId = 0; devId < m_nodePtr->GetNDevices (); devId ++)
- {
- Ptr<PointToPointNetDevice> p2pnd = DynamicCast<PointToPointNetDevice> (m_nodePtr->GetDevice (devId));
- if (p2pnd)
- {
- p2pnd->GetQueue ()->TraceConnectWithoutContext ("Drop", MakeCallback (&L2Tracer::Drop, this));
- }
+ for (uint32_t devId = 0; devId < m_nodePtr->GetNDevices(); devId++) {
+ Ptr<PointToPointNetDevice> p2pnd =
+ DynamicCast<PointToPointNetDevice>(m_nodePtr->GetDevice(devId));
+ if (p2pnd) {
+ p2pnd->GetQueue()->TraceConnectWithoutContext("Drop", MakeCallback(&L2Tracer::Drop, this));
}
+ }
}
} // namespace ns3
diff --git a/utils/tracers/l2-tracer.hpp b/utils/tracers/l2-tracer.hpp
index e6378b5..a2cd3a6 100644
--- a/utils/tracers/l2-tracer.hpp
+++ b/utils/tracers/l2-tracer.hpp
@@ -35,23 +35,22 @@
*
* @todo Finish implementation
*/
-class L2Tracer : public SimpleRefCount<L2Tracer>
-{
+class L2Tracer : public SimpleRefCount<L2Tracer> {
public:
- L2Tracer (Ptr<Node> node);
- virtual ~L2Tracer () { };
+ L2Tracer(Ptr<Node> node);
+ virtual ~L2Tracer(){};
void
- Connect ();
+ Connect();
virtual void
- PrintHeader (std::ostream &os) const = 0;
+ PrintHeader(std::ostream& os) const = 0;
virtual void
- Print (std::ostream &os) const = 0;
+ Print(std::ostream& os) const = 0;
virtual void
- Drop (Ptr<const Packet>) = 0;
+ Drop(Ptr<const Packet>) = 0;
// Rx/Tx is NetDevice specific
// please refer to pyviz.cc in order to extend this tracer
@@ -60,9 +59,9 @@
std::string m_node;
Ptr<Node> m_nodePtr;
- struct Stats
- {
- void Reset ()
+ struct Stats {
+ void
+ Reset()
{
m_in = 0;
m_out = 0;
@@ -76,12 +75,12 @@
};
inline std::ostream&
-operator << (std::ostream &os, const L2Tracer &tracer)
+operator<<(std::ostream& os, const L2Tracer& tracer)
{
os << "# ";
- tracer.PrintHeader (os);
+ tracer.PrintHeader(os);
os << "\n";
- tracer.Print (os);
+ tracer.Print(os);
return os;
}
diff --git a/utils/tracers/ndn-app-delay-tracer.cpp b/utils/tracers/ndn-app-delay-tracer.cpp
index 01a5af4..666f945 100644
--- a/utils/tracers/ndn-app-delay-tracer.cpp
+++ b/utils/tracers/ndn-app-delay-tracer.cpp
@@ -37,162 +37,143 @@
#include <fstream>
-NS_LOG_COMPONENT_DEFINE ("ndn.AppDelayTracer");
+NS_LOG_COMPONENT_DEFINE("ndn.AppDelayTracer");
using namespace std;
namespace ns3 {
namespace ndn {
-static std::list< boost::tuple< boost::shared_ptr<std::ostream>, std::list<Ptr<AppDelayTracer> > > > g_tracers;
+static std::list<boost::tuple<boost::shared_ptr<std::ostream>, std::list<Ptr<AppDelayTracer>>>>
+ g_tracers;
template<class T>
static inline void
-NullDeleter (T *ptr)
+NullDeleter(T* ptr)
{
}
void
-AppDelayTracer::Destroy ()
+AppDelayTracer::Destroy()
{
- g_tracers.clear ();
+ g_tracers.clear();
}
void
-AppDelayTracer::InstallAll (const std::string &file)
+AppDelayTracer::InstallAll(const std::string& file)
{
using namespace boost;
using namespace std;
- std::list<Ptr<AppDelayTracer> > tracers;
+ std::list<Ptr<AppDelayTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- for (NodeList::Iterator node = NodeList::Begin ();
- node != NodeList::End ();
- node++)
- {
- Ptr<AppDelayTracer> trace = Install (*node, outputStream);
- tracers.push_back (trace);
- }
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ for (NodeList::Iterator node = NodeList::Begin(); node != NodeList::End(); node++) {
+ Ptr<AppDelayTracer> trace = Install(*node, outputStream);
+ tracers.push_back(trace);
+ }
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
void
-AppDelayTracer::Install (const NodeContainer &nodes, const std::string &file)
+AppDelayTracer::Install(const NodeContainer& nodes, const std::string& file)
{
using namespace boost;
using namespace std;
- std::list<Ptr<AppDelayTracer> > tracers;
+ std::list<Ptr<AppDelayTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- for (NodeContainer::Iterator node = nodes.Begin ();
- node != nodes.End ();
- node++)
- {
- Ptr<AppDelayTracer> trace = Install (*node, outputStream);
- tracers.push_back (trace);
- }
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ for (NodeContainer::Iterator node = nodes.Begin(); node != nodes.End(); node++) {
+ Ptr<AppDelayTracer> trace = Install(*node, outputStream);
+ tracers.push_back(trace);
+ }
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
void
-AppDelayTracer::Install (Ptr<Node> node, const std::string &file)
+AppDelayTracer::Install(Ptr<Node> node, const std::string& file)
{
using namespace boost;
using namespace std;
- std::list<Ptr<AppDelayTracer> > tracers;
+ std::list<Ptr<AppDelayTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- Ptr<AppDelayTracer> trace = Install (node, outputStream);
- tracers.push_back (trace);
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ Ptr<AppDelayTracer> trace = Install(node, outputStream);
+ tracers.push_back(trace);
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
-
Ptr<AppDelayTracer>
-AppDelayTracer::Install (Ptr<Node> node,
- boost::shared_ptr<std::ostream> outputStream)
+AppDelayTracer::Install(Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream)
{
- NS_LOG_DEBUG ("Node: " << node->GetId ());
+ NS_LOG_DEBUG("Node: " << node->GetId());
- Ptr<AppDelayTracer> trace = Create<AppDelayTracer> (outputStream, node);
+ Ptr<AppDelayTracer> trace = Create<AppDelayTracer>(outputStream, node);
return trace;
}
@@ -201,86 +182,86 @@
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
-AppDelayTracer::AppDelayTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node)
-: m_nodePtr (node)
-, m_os (os)
+AppDelayTracer::AppDelayTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node)
+ : m_nodePtr(node)
+ , m_os(os)
{
- m_node = boost::lexical_cast<string> (m_nodePtr->GetId ());
+ m_node = boost::lexical_cast<string>(m_nodePtr->GetId());
- Connect ();
+ Connect();
- string name = Names::FindName (node);
- if (!name.empty ())
- {
- m_node = name;
- }
+ string name = Names::FindName(node);
+ if (!name.empty()) {
+ m_node = name;
+ }
}
-AppDelayTracer::AppDelayTracer (boost::shared_ptr<std::ostream> os, const std::string &node)
-: m_node (node)
-, m_os (os)
+AppDelayTracer::AppDelayTracer(boost::shared_ptr<std::ostream> os, const std::string& node)
+ : m_node(node)
+ , m_os(os)
{
- Connect ();
+ Connect();
}
-AppDelayTracer::~AppDelayTracer ()
-{
-};
-
+AppDelayTracer::~AppDelayTracer(){};
void
-AppDelayTracer::Connect ()
+AppDelayTracer::Connect()
{
- Config::ConnectWithoutContext ("/NodeList/"+m_node+"/ApplicationList/*/LastRetransmittedInterestDataDelay",
- MakeCallback (&AppDelayTracer::LastRetransmittedInterestDataDelay, this));
+ Config::ConnectWithoutContext("/NodeList/" + m_node
+ + "/ApplicationList/*/LastRetransmittedInterestDataDelay",
+ MakeCallback(&AppDelayTracer::LastRetransmittedInterestDataDelay,
+ this));
- Config::ConnectWithoutContext ("/NodeList/"+m_node+"/ApplicationList/*/FirstInterestDataDelay",
- MakeCallback (&AppDelayTracer::FirstInterestDataDelay, this));
+ Config::ConnectWithoutContext("/NodeList/" + m_node + "/ApplicationList/*/FirstInterestDataDelay",
+ MakeCallback(&AppDelayTracer::FirstInterestDataDelay, this));
}
void
-AppDelayTracer::PrintHeader (std::ostream &os) const
+AppDelayTracer::PrintHeader(std::ostream& os) const
{
- os << "Time" << "\t"
- << "Node" << "\t"
- << "AppId" << "\t"
- << "SeqNo" << "\t"
+ os << "Time"
+ << "\t"
+ << "Node"
+ << "\t"
+ << "AppId"
+ << "\t"
+ << "SeqNo"
+ << "\t"
- << "Type" << "\t"
- << "DelayS" << "\t"
- << "DelayUS" << "\t"
- << "RetxCount" << "\t"
- << "HopCount" << "";
+ << "Type"
+ << "\t"
+ << "DelayS"
+ << "\t"
+ << "DelayUS"
+ << "\t"
+ << "RetxCount"
+ << "\t"
+ << "HopCount"
+ << "";
}
void
-AppDelayTracer::LastRetransmittedInterestDataDelay (Ptr<App> app, uint32_t seqno, Time delay, int32_t hopCount)
+AppDelayTracer::LastRetransmittedInterestDataDelay(Ptr<App> app, uint32_t seqno, Time delay,
+ int32_t hopCount)
{
- *m_os << Simulator::Now ().ToDouble (Time::S) << "\t"
- << m_node << "\t"
- << app->GetId () << "\t"
+ *m_os << Simulator::Now().ToDouble(Time::S) << "\t" << m_node << "\t" << app->GetId() << "\t"
<< seqno << "\t"
- << "LastDelay" << "\t"
- << delay.ToDouble (Time::S) << "\t"
- << delay.ToDouble (Time::US) << "\t"
- << 1 << "\t"
+ << "LastDelay"
+ << "\t" << delay.ToDouble(Time::S) << "\t" << delay.ToDouble(Time::US) << "\t" << 1 << "\t"
<< hopCount << "\n";
}
void
-AppDelayTracer::FirstInterestDataDelay (Ptr<App> app, uint32_t seqno, Time delay, uint32_t retxCount, int32_t hopCount)
+AppDelayTracer::FirstInterestDataDelay(Ptr<App> app, uint32_t seqno, Time delay, uint32_t retxCount,
+ int32_t hopCount)
{
- *m_os << Simulator::Now ().ToDouble (Time::S) << "\t"
- << m_node << "\t"
- << app->GetId () << "\t"
+ *m_os << Simulator::Now().ToDouble(Time::S) << "\t" << m_node << "\t" << app->GetId() << "\t"
<< seqno << "\t"
- << "FullDelay" << "\t"
- << delay.ToDouble (Time::S) << "\t"
- << delay.ToDouble (Time::US) << "\t"
- << retxCount << "\t"
- << hopCount << "\n";
+ << "FullDelay"
+ << "\t" << delay.ToDouble(Time::S) << "\t" << delay.ToDouble(Time::US) << "\t" << retxCount
+ << "\t" << hopCount << "\n";
}
-
} // namespace ndn
} // namespace ns3
diff --git a/utils/tracers/ndn-app-delay-tracer.hpp b/utils/tracers/ndn-app-delay-tracer.hpp
index d911fc9..64b695a 100644
--- a/utils/tracers/ndn-app-delay-tracer.hpp
+++ b/utils/tracers/ndn-app-delay-tracer.hpp
@@ -44,20 +44,20 @@
* @ingroup ndn-tracers
* @brief Tracer to obtain application-level delays
*/
-class AppDelayTracer : public SimpleRefCount<AppDelayTracer>
-{
+class AppDelayTracer : public SimpleRefCount<AppDelayTracer> {
public:
/**
* @brief Helper method to install tracers on all simulation nodes
*
* @param file File to which traces will be written. If filename is -, then std::out is used
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
- *
+ *
*/
static void
- InstallAll (const std::string &file);
+ InstallAll(const std::string& file);
/**
* @brief Helper method to install tracers on the selected simulation nodes
@@ -65,39 +65,44 @@
* @param nodes Nodes on which to install tracer
* @param file File to which traces will be written. If filename is -, then std::out is used
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*
*/
static void
- Install (const NodeContainer &nodes, const std::string &file);
+ Install(const NodeContainer& nodes, const std::string& file);
/**
* @brief Helper method to install tracers on a specific simulation node
*
* @param nodes Nodes on which to install tracer
* @param file File to which traces will be written. If filename is -, then std::out is used
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*
*/
static void
- Install (Ptr<Node> node, const std::string &file);
+ Install(Ptr<Node> node, const std::string& file);
/**
* @brief Helper method to install tracers on a specific simulation node
*
* @param nodes Nodes on which to install tracer
* @param outputStream Smart pointer to a stream
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*/
static Ptr<AppDelayTracer>
- Install (Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream);
+ Install(Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream);
/**
* @brief Explicit request to remove all statically created tracers
@@ -106,26 +111,26 @@
* or if it is desired to do a postprocessing of the resulting data
*/
static void
- Destroy ();
-
+ Destroy();
+
/**
* @brief Trace constructor that attaches to all applications on the node using node's pointer
* @param os reference to the output stream
* @param node pointer to the node
*/
- AppDelayTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node);
+ AppDelayTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node);
/**
* @brief Trace constructor that attaches to all applications on the node using node's name
* @param os reference to the output stream
* @param nodeName name of the node registered using Names::Add
*/
- AppDelayTracer (boost::shared_ptr<std::ostream> os, const std::string &node);
+ AppDelayTracer(boost::shared_ptr<std::ostream> os, const std::string& node);
/**
* @brief Destructor
*/
- ~AppDelayTracer ();
+ ~AppDelayTracer();
/**
* @brief Print head of the trace (e.g., for post-processing)
@@ -133,18 +138,19 @@
* @param os reference to output stream
*/
void
- PrintHeader (std::ostream &os) const;
-
+ PrintHeader(std::ostream& os) const;
+
private:
void
- Connect ();
+ Connect();
- void
- LastRetransmittedInterestDataDelay (Ptr<App> app, uint32_t seqno, Time delay, int32_t hopCount);
-
- void
- FirstInterestDataDelay (Ptr<App> app, uint32_t seqno, Time delay, uint32_t rextCount, int32_t hopCount);
-
+ void
+ LastRetransmittedInterestDataDelay(Ptr<App> app, uint32_t seqno, Time delay, int32_t hopCount);
+
+ void
+ FirstInterestDataDelay(Ptr<App> app, uint32_t seqno, Time delay, uint32_t rextCount,
+ int32_t hopCount);
+
private:
std::string m_node;
Ptr<Node> m_nodePtr;
diff --git a/utils/tracers/ndn-cs-tracer.cpp b/utils/tracers/ndn-cs-tracer.cpp
index 74fa3dd..bc5d8de 100644
--- a/utils/tracers/ndn-cs-tracer.cpp
+++ b/utils/tracers/ndn-cs-tracer.cpp
@@ -38,164 +38,146 @@
#include <fstream>
-NS_LOG_COMPONENT_DEFINE ("ndn.CsTracer");
+NS_LOG_COMPONENT_DEFINE("ndn.CsTracer");
using namespace std;
namespace ns3 {
namespace ndn {
-static std::list< boost::tuple< boost::shared_ptr<std::ostream>, std::list<Ptr<CsTracer> > > > g_tracers;
+static std::list<boost::tuple<boost::shared_ptr<std::ostream>, std::list<Ptr<CsTracer>>>> g_tracers;
template<class T>
static inline void
-NullDeleter (T *ptr)
+NullDeleter(T* ptr)
{
}
void
-CsTracer::Destroy ()
+CsTracer::Destroy()
{
- g_tracers.clear ();
+ g_tracers.clear();
}
void
-CsTracer::InstallAll (const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
-{
- using namespace boost;
- using namespace std;
-
- std::list<Ptr<CsTracer> > tracers;
- boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
-
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
- }
-
- for (NodeList::Iterator node = NodeList::Begin ();
- node != NodeList::End ();
- node++)
- {
- Ptr<CsTracer> trace = Install (*node, outputStream, averagingPeriod);
- tracers.push_back (trace);
- }
-
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
-
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
-}
-
-void
-CsTracer::Install (const NodeContainer &nodes, const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
+CsTracer::InstallAll(const std::string& file, Time averagingPeriod /* = Seconds (0.5)*/)
{
using namespace boost;
using namespace std;
- std::list<Ptr<CsTracer> > tracers;
+ std::list<Ptr<CsTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- for (NodeContainer::Iterator node = nodes.Begin ();
- node != nodes.End ();
- node++)
- {
- Ptr<CsTracer> trace = Install (*node, outputStream, averagingPeriod);
- tracers.push_back (trace);
- }
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ for (NodeList::Iterator node = NodeList::Begin(); node != NodeList::End(); node++) {
+ Ptr<CsTracer> trace = Install(*node, outputStream, averagingPeriod);
+ tracers.push_back(trace);
+ }
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
void
-CsTracer::Install (Ptr<Node> node, const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
+CsTracer::Install(const NodeContainer& nodes, const std::string& file,
+ Time averagingPeriod /* = Seconds (0.5)*/)
{
using namespace boost;
using namespace std;
- std::list<Ptr<CsTracer> > tracers;
+ std::list<Ptr<CsTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- Ptr<CsTracer> trace = Install (node, outputStream, averagingPeriod);
- tracers.push_back (trace);
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ for (NodeContainer::Iterator node = nodes.Begin(); node != nodes.End(); node++) {
+ Ptr<CsTracer> trace = Install(*node, outputStream, averagingPeriod);
+ tracers.push_back(trace);
+ }
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
+void
+CsTracer::Install(Ptr<Node> node, const std::string& file,
+ Time averagingPeriod /* = Seconds (0.5)*/)
+{
+ using namespace boost;
+ using namespace std;
+
+ std::list<Ptr<CsTracer>> tracers;
+ boost::shared_ptr<std::ostream> outputStream;
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
+
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
+ }
+
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
+
+ Ptr<CsTracer> trace = Install(node, outputStream, averagingPeriod);
+ tracers.push_back(trace);
+
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
+}
Ptr<CsTracer>
-CsTracer::Install (Ptr<Node> node,
- boost::shared_ptr<std::ostream> outputStream,
- Time averagingPeriod/* = Seconds (0.5)*/)
+CsTracer::Install(Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream,
+ Time averagingPeriod /* = Seconds (0.5)*/)
{
- NS_LOG_DEBUG ("Node: " << node->GetId ());
+ NS_LOG_DEBUG("Node: " << node->GetId());
- Ptr<CsTracer> trace = Create<CsTracer> (outputStream, node);
- trace->SetAveragingPeriod (averagingPeriod);
+ Ptr<CsTracer> trace = Create<CsTracer>(outputStream, node);
+ trace->SetAveragingPeriod(averagingPeriod);
return trace;
}
@@ -204,106 +186,101 @@
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
-CsTracer::CsTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node)
-: m_nodePtr (node)
-, m_os (os)
+CsTracer::CsTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node)
+ : m_nodePtr(node)
+ , m_os(os)
{
- m_node = boost::lexical_cast<string> (m_nodePtr->GetId ());
+ m_node = boost::lexical_cast<string>(m_nodePtr->GetId());
- Connect ();
+ Connect();
- string name = Names::FindName (node);
- if (!name.empty ())
- {
- m_node = name;
- }
+ string name = Names::FindName(node);
+ if (!name.empty()) {
+ m_node = name;
+ }
}
-CsTracer::CsTracer (boost::shared_ptr<std::ostream> os, const std::string &node)
-: m_node (node)
-, m_os (os)
+CsTracer::CsTracer(boost::shared_ptr<std::ostream> os, const std::string& node)
+ : m_node(node)
+ , m_os(os)
{
- Connect ();
+ Connect();
}
-CsTracer::~CsTracer ()
-{
-};
-
+CsTracer::~CsTracer(){};
void
-CsTracer::Connect ()
+CsTracer::Connect()
{
- Ptr<ContentStore> cs = m_nodePtr->GetObject<ContentStore> ();
- cs->TraceConnectWithoutContext ("CacheHits", MakeCallback (&CsTracer::CacheHits, this));
- cs->TraceConnectWithoutContext ("CacheMisses", MakeCallback (&CsTracer::CacheMisses, this));
+ Ptr<ContentStore> cs = m_nodePtr->GetObject<ContentStore>();
+ cs->TraceConnectWithoutContext("CacheHits", MakeCallback(&CsTracer::CacheHits, this));
+ cs->TraceConnectWithoutContext("CacheMisses", MakeCallback(&CsTracer::CacheMisses, this));
- Reset ();
+ Reset();
}
-
void
-CsTracer::SetAveragingPeriod (const Time &period)
+CsTracer::SetAveragingPeriod(const Time& period)
{
m_period = period;
- m_printEvent.Cancel ();
- m_printEvent = Simulator::Schedule (m_period, &CsTracer::PeriodicPrinter, this);
+ m_printEvent.Cancel();
+ m_printEvent = Simulator::Schedule(m_period, &CsTracer::PeriodicPrinter, this);
}
void
-CsTracer::PeriodicPrinter ()
+CsTracer::PeriodicPrinter()
{
- Print (*m_os);
- Reset ();
-
- m_printEvent = Simulator::Schedule (m_period, &CsTracer::PeriodicPrinter, this);
+ Print(*m_os);
+ Reset();
+
+ m_printEvent = Simulator::Schedule(m_period, &CsTracer::PeriodicPrinter, this);
}
void
-CsTracer::PrintHeader (std::ostream &os) const
+CsTracer::PrintHeader(std::ostream& os) const
{
- os << "Time" << "\t"
+ os << "Time"
+ << "\t"
- << "Node" << "\t"
+ << "Node"
+ << "\t"
- << "Type" << "\t"
- << "Packets" << "\t";
+ << "Type"
+ << "\t"
+ << "Packets"
+ << "\t";
}
void
-CsTracer::Reset ()
+CsTracer::Reset()
{
m_stats.Reset();
}
-#define PRINTER(printName, fieldName) \
- os << time.ToDouble (Time::S) << "\t" \
- << m_node << "\t" \
- << printName << "\t" \
- << m_stats.fieldName << "\n";
-
+#define PRINTER(printName, fieldName) \
+ os << time.ToDouble(Time::S) << "\t" << m_node << "\t" << printName << "\t" << m_stats.fieldName \
+ << "\n";
void
-CsTracer::Print (std::ostream &os) const
+CsTracer::Print(std::ostream& os) const
{
- Time time = Simulator::Now ();
+ Time time = Simulator::Now();
- PRINTER ("CacheHits", m_cacheHits);
- PRINTER ("CacheMisses", m_cacheMisses);
+ PRINTER("CacheHits", m_cacheHits);
+ PRINTER("CacheMisses", m_cacheMisses);
}
-void
-CsTracer::CacheHits (Ptr<const Interest>, Ptr<const Data>)
+void
+CsTracer::CacheHits(Ptr<const Interest>, Ptr<const Data>)
{
- m_stats.m_cacheHits ++;
+ m_stats.m_cacheHits++;
}
-void
-CsTracer::CacheMisses (Ptr<const Interest>)
+void
+CsTracer::CacheMisses(Ptr<const Interest>)
{
- m_stats.m_cacheMisses ++;
+ m_stats.m_cacheMisses++;
}
-
} // namespace ndn
} // namespace ns3
diff --git a/utils/tracers/ndn-cs-tracer.hpp b/utils/tracers/ndn-cs-tracer.hpp
index eb07585..939df9b 100644
--- a/utils/tracers/ndn-cs-tracer.hpp
+++ b/utils/tracers/ndn-cs-tracer.hpp
@@ -49,80 +49,87 @@
namespace cs {
/// @cond include_hidden
-struct Stats
-{
- inline void Reset ()
+struct Stats {
+ inline void
+ Reset()
{
- m_cacheHits = 0;
+ m_cacheHits = 0;
m_cacheMisses = 0;
}
double m_cacheHits;
double m_cacheMisses;
};
/// @endcond
-
-}
+}
/**
* @ingroup ndn-tracers
* @brief NDN tracer for cache performance (hits and misses)
*/
-class CsTracer : public SimpleRefCount<CsTracer>
-{
+class CsTracer : public SimpleRefCount<CsTracer> {
public:
/**
* @brief Helper method to install tracers on all simulation nodes
*
* @param file File to which traces will be written. If filename is -, then std::out is used
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
- *
+ *
*/
static void
- InstallAll (const std::string &file, Time averagingPeriod = Seconds (0.5));
+ InstallAll(const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Helper method to install tracers on the selected simulation nodes
*
* @param nodes Nodes on which to install tracer
* @param file File to which traces will be written. If filename is -, then std::out is used
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*
*/
static void
- Install (const NodeContainer &nodes, const std::string &file, Time averagingPeriod = Seconds (0.5));
+ Install(const NodeContainer& nodes, const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Helper method to install tracers on a specific simulation node
*
* @param nodes Nodes on which to install tracer
* @param file File to which traces will be written. If filename is -, then std::out is used
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*
*/
static void
- Install (Ptr<Node> node, const std::string &file, Time averagingPeriod = Seconds (0.5));
+ Install(Ptr<Node> node, const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Helper method to install tracers on a specific simulation node
*
* @param nodes Nodes on which to install tracer
* @param outputStream Smart pointer to a stream
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*/
static Ptr<CsTracer>
- Install (Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream, Time averagingPeriod = Seconds (0.5));
+ Install(Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream,
+ Time averagingPeriod = Seconds(0.5));
/**
* @brief Explicit request to remove all statically created tracers
@@ -131,26 +138,26 @@
* or if it is desired to do a postprocessing of the resulting data
*/
static void
- Destroy ();
-
+ Destroy();
+
/**
* @brief Trace constructor that attaches to the node using node pointer
* @param os reference to the output stream
* @param node pointer to the node
*/
- CsTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node);
+ CsTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node);
/**
* @brief Trace constructor that attaches to the node using node name
* @param os reference to the output stream
* @param nodeName name of the node registered using Names::Add
*/
- CsTracer (boost::shared_ptr<std::ostream> os, const std::string &node);
+ CsTracer(boost::shared_ptr<std::ostream> os, const std::string& node);
/**
* @brief Destructor
*/
- ~CsTracer ();
+ ~CsTracer();
/**
* @brief Print head of the trace (e.g., for post-processing)
@@ -158,7 +165,7 @@
* @param os reference to output stream
*/
void
- PrintHeader (std::ostream &os) const;
+ PrintHeader(std::ostream& os) const;
/**
* @brief Print current trace data
@@ -166,28 +173,28 @@
* @param os reference to output stream
*/
void
- Print (std::ostream &os) const;
-
-private:
- void
- Connect ();
-
- void
- CacheHits (Ptr<const Interest>, Ptr<const Data>);
-
- void
- CacheMisses (Ptr<const Interest>);
+ Print(std::ostream& os) const;
private:
void
- SetAveragingPeriod (const Time &period);
+ Connect();
void
- Reset ();
+ CacheHits(Ptr<const Interest>, Ptr<const Data>);
void
- PeriodicPrinter ();
-
+ CacheMisses(Ptr<const Interest>);
+
+private:
+ void
+ SetAveragingPeriod(const Time& period);
+
+ void
+ Reset();
+
+ void
+ PeriodicPrinter();
+
private:
std::string m_node;
Ptr<Node> m_nodePtr;
@@ -196,19 +203,19 @@
Time m_period;
EventId m_printEvent;
- cs::Stats m_stats;
+ cs::Stats m_stats;
};
/**
* @brief Helper to dump the trace to an output stream
*/
inline std::ostream&
-operator << (std::ostream &os, const CsTracer &tracer)
+operator<<(std::ostream& os, const CsTracer& tracer)
{
os << "# ";
- tracer.PrintHeader (os);
+ tracer.PrintHeader(os);
os << "\n";
- tracer.Print (os);
+ tracer.Print(os);
return os;
}
diff --git a/utils/tracers/ndn-l3-aggregate-tracer.cpp b/utils/tracers/ndn-l3-aggregate-tracer.cpp
index 556a792..d9fc671 100644
--- a/utils/tracers/ndn-l3-aggregate-tracer.cpp
+++ b/utils/tracers/ndn-l3-aggregate-tracer.cpp
@@ -36,388 +36,349 @@
#include <fstream>
-NS_LOG_COMPONENT_DEFINE ("ndn.L3AggregateTracer");
+NS_LOG_COMPONENT_DEFINE("ndn.L3AggregateTracer");
namespace ns3 {
namespace ndn {
-static std::list< boost::tuple< boost::shared_ptr<std::ostream>, std::list<Ptr<L3AggregateTracer> > > > g_tracers;
+static std::list<boost::tuple<boost::shared_ptr<std::ostream>, std::list<Ptr<L3AggregateTracer>>>>
+ g_tracers;
template<class T>
static inline void
-NullDeleter (T *ptr)
+NullDeleter(T* ptr)
{
}
void
-L3AggregateTracer::Destroy ()
+L3AggregateTracer::Destroy()
{
- g_tracers.clear ();
+ g_tracers.clear();
}
void
-L3AggregateTracer::InstallAll (const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
+L3AggregateTracer::InstallAll(const std::string& file, Time averagingPeriod /* = Seconds (0.5)*/)
{
using namespace boost;
using namespace std;
- std::list<Ptr<L3AggregateTracer> > tracers;
+ std::list<Ptr<L3AggregateTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- for (NodeList::Iterator node = NodeList::Begin ();
- node != NodeList::End ();
- node++)
- {
- Ptr<L3AggregateTracer> trace = Install (*node, outputStream, averagingPeriod);
- tracers.push_back (trace);
- }
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ for (NodeList::Iterator node = NodeList::Begin(); node != NodeList::End(); node++) {
+ Ptr<L3AggregateTracer> trace = Install(*node, outputStream, averagingPeriod);
+ tracers.push_back(trace);
+ }
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
void
-L3AggregateTracer::Install (const NodeContainer &nodes, const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
+L3AggregateTracer::Install(const NodeContainer& nodes, const std::string& file,
+ Time averagingPeriod /* = Seconds (0.5)*/)
{
using namespace boost;
using namespace std;
- std::list<Ptr<L3AggregateTracer> > tracers;
+ std::list<Ptr<L3AggregateTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- for (NodeContainer::Iterator node = nodes.Begin ();
- node != nodes.End ();
- node++)
- {
- Ptr<L3AggregateTracer> trace = Install (*node, outputStream, averagingPeriod);
- tracers.push_back (trace);
- }
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ for (NodeContainer::Iterator node = nodes.Begin(); node != nodes.End(); node++) {
+ Ptr<L3AggregateTracer> trace = Install(*node, outputStream, averagingPeriod);
+ tracers.push_back(trace);
+ }
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
void
-L3AggregateTracer::Install (Ptr<Node> node, const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
+L3AggregateTracer::Install(Ptr<Node> node, const std::string& file,
+ Time averagingPeriod /* = Seconds (0.5)*/)
{
using namespace boost;
using namespace std;
- std::list<Ptr<L3AggregateTracer> > tracers;
+ std::list<Ptr<L3AggregateTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- Ptr<L3AggregateTracer> trace = Install (node, outputStream, averagingPeriod);
- tracers.push_back (trace);
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ Ptr<L3AggregateTracer> trace = Install(node, outputStream, averagingPeriod);
+ tracers.push_back(trace);
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
-
Ptr<L3AggregateTracer>
-L3AggregateTracer::Install (Ptr<Node> node,
- boost::shared_ptr<std::ostream> outputStream,
- Time averagingPeriod/* = Seconds (0.5)*/)
+L3AggregateTracer::Install(Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream,
+ Time averagingPeriod /* = Seconds (0.5)*/)
{
- NS_LOG_DEBUG ("Node: " << node->GetId ());
+ NS_LOG_DEBUG("Node: " << node->GetId());
- Ptr<L3AggregateTracer> trace = Create<L3AggregateTracer> (outputStream, node);
- trace->SetAveragingPeriod (averagingPeriod);
+ Ptr<L3AggregateTracer> trace = Create<L3AggregateTracer>(outputStream, node);
+ trace->SetAveragingPeriod(averagingPeriod);
return trace;
}
-L3AggregateTracer::L3AggregateTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node)
- : L3Tracer (node)
- , m_os (os)
+L3AggregateTracer::L3AggregateTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node)
+ : L3Tracer(node)
+ , m_os(os)
{
- Reset ();
+ Reset();
}
-L3AggregateTracer::L3AggregateTracer (boost::shared_ptr<std::ostream> os, const std::string &node)
- : L3Tracer (node)
- , m_os (os)
+L3AggregateTracer::L3AggregateTracer(boost::shared_ptr<std::ostream> os, const std::string& node)
+ : L3Tracer(node)
+ , m_os(os)
{
- Reset ();
+ Reset();
}
-L3AggregateTracer::~L3AggregateTracer ()
-{
-};
+L3AggregateTracer::~L3AggregateTracer(){};
void
-L3AggregateTracer::SetAveragingPeriod (const Time &period)
+L3AggregateTracer::SetAveragingPeriod(const Time& period)
{
m_period = period;
- m_printEvent.Cancel ();
- m_printEvent = Simulator::Schedule (m_period, &L3AggregateTracer::PeriodicPrinter, this);
+ m_printEvent.Cancel();
+ m_printEvent = Simulator::Schedule(m_period, &L3AggregateTracer::PeriodicPrinter, this);
}
void
-L3AggregateTracer::PeriodicPrinter ()
+L3AggregateTracer::PeriodicPrinter()
{
- Print (*m_os);
- Reset ();
+ Print(*m_os);
+ Reset();
- m_printEvent = Simulator::Schedule (m_period, &L3AggregateTracer::PeriodicPrinter, this);
+ m_printEvent = Simulator::Schedule(m_period, &L3AggregateTracer::PeriodicPrinter, this);
}
void
-L3AggregateTracer::PrintHeader (std::ostream &os) const
+L3AggregateTracer::PrintHeader(std::ostream& os) const
{
- os << "Time" << "\t"
+ os << "Time"
+ << "\t"
- << "Node" << "\t"
- << "FaceId" << "\t"
- << "FaceDescr" << "\t"
+ << "Node"
+ << "\t"
+ << "FaceId"
+ << "\t"
+ << "FaceDescr"
+ << "\t"
- << "Type" << "\t"
- << "Packets" << "\t"
+ << "Type"
+ << "\t"
+ << "Packets"
+ << "\t"
<< "Kilobytes";
}
void
-L3AggregateTracer::Reset ()
+L3AggregateTracer::Reset()
{
- for (std::map<Ptr<const Face>, boost::tuple<Stats, Stats> >::iterator stats = m_stats.begin ();
- stats != m_stats.end ();
- stats++)
- {
- stats->second.get<0> ().Reset ();
- stats->second.get<1> ().Reset ();
- }
+ for (std::map<Ptr<const Face>, boost::tuple<Stats, Stats>>::iterator stats = m_stats.begin();
+ stats != m_stats.end(); stats++) {
+ stats->second.get<0>().Reset();
+ stats->second.get<1>().Reset();
+ }
}
+#define STATS(INDEX) stats->second.get<INDEX>()
-#define STATS(INDEX) stats->second.get<INDEX> ()
-
-#define PRINTER(printName, fieldName) \
- os << time.ToDouble (Time::S) << "\t" \
- << m_node << "\t"; \
- if (stats->first) \
- { \
- os \
- << stats->first->GetId () << "\t" \
- << *stats->first << "\t"; \
- } \
- else \
- { \
- os << "-1\tall\t"; \
- } \
- os \
- << printName << "\t" \
- << STATS(0).fieldName << "\t" \
- << STATS(1).fieldName / 1024.0 << "\n";
-
+#define PRINTER(printName, fieldName) \
+ os << time.ToDouble(Time::S) << "\t" << m_node << "\t"; \
+ if (stats->first) { \
+ os << stats->first->GetId() << "\t" << *stats->first << "\t"; \
+ } \
+ else { \
+ os << "-1\tall\t"; \
+ } \
+ os << printName << "\t" << STATS(0).fieldName << "\t" << STATS(1).fieldName / 1024.0 << "\n";
void
-L3AggregateTracer::Print (std::ostream &os) const
+L3AggregateTracer::Print(std::ostream& os) const
{
- Time time = Simulator::Now ();
+ Time time = Simulator::Now();
- for (std::map<Ptr<const Face>, boost::tuple<Stats, Stats> >::iterator stats = m_stats.begin ();
- stats != m_stats.end ();
- stats++)
- {
- if (!stats->first)
- continue;
+ for (std::map<Ptr<const Face>, boost::tuple<Stats, Stats>>::iterator stats = m_stats.begin();
+ stats != m_stats.end(); stats++) {
+ if (!stats->first)
+ continue;
- PRINTER ("InInterests", m_inInterests);
- PRINTER ("OutInterests", m_outInterests);
- PRINTER ("DropInterests", m_dropInterests);
+ PRINTER("InInterests", m_inInterests);
+ PRINTER("OutInterests", m_outInterests);
+ PRINTER("DropInterests", m_dropInterests);
- PRINTER ("InNacks", m_inNacks);
- PRINTER ("OutNacks", m_outNacks);
- PRINTER ("DropNacks", m_dropNacks);
+ PRINTER("InNacks", m_inNacks);
+ PRINTER("OutNacks", m_outNacks);
+ PRINTER("DropNacks", m_dropNacks);
- PRINTER ("InData", m_inData);
- PRINTER ("OutData", m_outData);
- PRINTER ("DropData", m_dropData);
- }
+ PRINTER("InData", m_inData);
+ PRINTER("OutData", m_outData);
+ PRINTER("DropData", m_dropData);
+ }
{
- std::map<Ptr<const Face>, boost::tuple<Stats, Stats> >::iterator stats = m_stats.find (Ptr<const Face> (0));
- if (stats != m_stats.end ())
- {
- PRINTER ("SatisfiedInterests", m_satisfiedInterests);
- PRINTER ("TimedOutInterests", m_timedOutInterests);
- }
+ std::map<Ptr<const Face>, boost::tuple<Stats, Stats>>::iterator stats =
+ m_stats.find(Ptr<const Face>(0));
+ if (stats != m_stats.end()) {
+ PRINTER("SatisfiedInterests", m_satisfiedInterests);
+ PRINTER("TimedOutInterests", m_timedOutInterests);
+ }
}
}
void
-L3AggregateTracer::OutInterests (Ptr<const Interest> interest, Ptr<const Face> face)
+L3AggregateTracer::OutInterests(Ptr<const Interest> interest, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_outInterests ++;
- if (interest->GetWire ())
- {
- m_stats[face].get<1> ().m_outInterests += interest->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_outInterests++;
+ if (interest->GetWire()) {
+ m_stats[face].get<1>().m_outInterests += interest->GetWire()->GetSize();
+ }
}
void
-L3AggregateTracer::InInterests (Ptr<const Interest> interest, Ptr<const Face> face)
+L3AggregateTracer::InInterests(Ptr<const Interest> interest, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_inInterests ++;
- if (interest->GetWire ())
- {
- m_stats[face].get<1> ().m_inInterests += interest->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_inInterests++;
+ if (interest->GetWire()) {
+ m_stats[face].get<1>().m_inInterests += interest->GetWire()->GetSize();
+ }
}
void
-L3AggregateTracer::DropInterests (Ptr<const Interest> interest, Ptr<const Face> face)
+L3AggregateTracer::DropInterests(Ptr<const Interest> interest, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_dropInterests ++;
- if (interest->GetWire ())
- {
- m_stats[face].get<1> ().m_dropInterests += interest->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_dropInterests++;
+ if (interest->GetWire()) {
+ m_stats[face].get<1>().m_dropInterests += interest->GetWire()->GetSize();
+ }
}
void
-L3AggregateTracer::OutNacks (Ptr<const Interest> nack, Ptr<const Face> face)
+L3AggregateTracer::OutNacks(Ptr<const Interest> nack, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_outNacks ++;
- if (nack->GetWire ())
- {
- m_stats[face].get<1> ().m_outNacks += nack->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_outNacks++;
+ if (nack->GetWire()) {
+ m_stats[face].get<1>().m_outNacks += nack->GetWire()->GetSize();
+ }
}
void
-L3AggregateTracer::InNacks (Ptr<const Interest> nack, Ptr<const Face> face)
+L3AggregateTracer::InNacks(Ptr<const Interest> nack, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_inNacks ++;
- if (nack->GetWire ())
- {
- m_stats[face].get<1> ().m_inNacks += nack->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_inNacks++;
+ if (nack->GetWire()) {
+ m_stats[face].get<1>().m_inNacks += nack->GetWire()->GetSize();
+ }
}
void
-L3AggregateTracer::DropNacks (Ptr<const Interest> nack, Ptr<const Face> face)
+L3AggregateTracer::DropNacks(Ptr<const Interest> nack, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_dropNacks ++;
- if (nack->GetWire ())
- {
- m_stats[face].get<1> ().m_dropNacks += nack->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_dropNacks++;
+ if (nack->GetWire()) {
+ m_stats[face].get<1>().m_dropNacks += nack->GetWire()->GetSize();
+ }
}
void
-L3AggregateTracer::OutData (Ptr<const Data> data,
- bool fromCache, Ptr<const Face> face)
+L3AggregateTracer::OutData(Ptr<const Data> data, bool fromCache, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_outData ++;
- if (data->GetWire ())
- {
- m_stats[face].get<1> ().m_outData += data->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_outData++;
+ if (data->GetWire()) {
+ m_stats[face].get<1>().m_outData += data->GetWire()->GetSize();
+ }
}
void
-L3AggregateTracer::InData (Ptr<const Data> data,
- Ptr<const Face> face)
+L3AggregateTracer::InData(Ptr<const Data> data, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_inData ++;
- if (data->GetWire ())
- {
- m_stats[face].get<1> ().m_inData += data->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_inData++;
+ if (data->GetWire()) {
+ m_stats[face].get<1>().m_inData += data->GetWire()->GetSize();
+ }
}
void
-L3AggregateTracer::DropData (Ptr<const Data> data,
- Ptr<const Face> face)
+L3AggregateTracer::DropData(Ptr<const Data> data, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_dropData ++;
- if (data->GetWire ())
- {
- m_stats[face].get<1> ().m_dropData += data->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_dropData++;
+ if (data->GetWire()) {
+ m_stats[face].get<1>().m_dropData += data->GetWire()->GetSize();
+ }
}
void
-L3AggregateTracer::SatisfiedInterests (Ptr<const pit::Entry>)
+L3AggregateTracer::SatisfiedInterests(Ptr<const pit::Entry>)
{
- m_stats[0].get<0> ().m_satisfiedInterests ++;
+ m_stats[0].get<0>().m_satisfiedInterests++;
// no "size" stats
}
void
-L3AggregateTracer::TimedOutInterests (Ptr<const pit::Entry>)
+L3AggregateTracer::TimedOutInterests(Ptr<const pit::Entry>)
{
- m_stats[0].get<0> ().m_timedOutInterests ++;
+ m_stats[0].get<0>().m_timedOutInterests++;
// no "size" stats
}
diff --git a/utils/tracers/ndn-l3-aggregate-tracer.hpp b/utils/tracers/ndn-l3-aggregate-tracer.hpp
index a94d2f5..bedfccc 100644
--- a/utils/tracers/ndn-l3-aggregate-tracer.hpp
+++ b/utils/tracers/ndn-l3-aggregate-tracer.hpp
@@ -39,49 +39,54 @@
* @ingroup ndn-tracers
* @brief NDN network-layer tracer for aggregate packet counts
*/
-class L3AggregateTracer : public L3Tracer
-{
+class L3AggregateTracer : public L3Tracer {
public:
/**
* @brief Helper method to install tracers on all simulation nodes
*
* @param file File to which traces will be written. If filename is -, then std::out is used
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*
*/
static void
- InstallAll (const std::string &file, Time averagingPeriod = Seconds (0.5));
+ InstallAll(const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Helper method to install tracers on the selected simulation nodes
*
* @param nodes Nodes on which to install tracer
* @param file File to which traces will be written. If filename is -, then std::out is used
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*
*/
static void
- Install (const NodeContainer &nodes, const std::string &file, Time averagingPeriod = Seconds (0.5));
+ Install(const NodeContainer& nodes, const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Helper method to install tracers on a specific simulation node
*
* @param nodes Nodes on which to install tracer
* @param file File to which traces will be written. If filename is -, then std::out is used
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*
*/
static void
- Install (Ptr<Node> node, const std::string &file, Time averagingPeriod = Seconds (0.5));
+ Install(Ptr<Node> node, const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Explicit request to remove all statically created tracers
@@ -90,91 +95,93 @@
* or if it is desired to do a postprocessing of the resulting data
*/
static void
- Destroy ();
+ Destroy();
/**
* @brief Trace constructor that attaches to the node using node pointer
* @param os reference to the output stream
* @param node pointer to the node
*/
- L3AggregateTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node);
+ L3AggregateTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node);
/**
* @brief Trace constructor that attaches to the node using node name
* @param os reference to the output stream
* @param nodeName name of the node registered using Names::Add
*/
- L3AggregateTracer (boost::shared_ptr<std::ostream> os, const std::string &nodeName);
+ L3AggregateTracer(boost::shared_ptr<std::ostream> os, const std::string& nodeName);
/**
* @brief Destructor
*/
- virtual ~L3AggregateTracer ();
+ virtual ~L3AggregateTracer();
/**
* @brief Helper method to install tracers on a specific simulation node
*
* @param nodes Nodes on which to install tracer
* @param outputStream Smart pointer to a stream
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*/
static Ptr<L3AggregateTracer>
- Install (Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream, Time averagingPeriod = Seconds (0.5));
+ Install(Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream,
+ Time averagingPeriod = Seconds(0.5));
protected:
// from L3Tracer
virtual void
- PrintHeader (std::ostream &os) const;
+ PrintHeader(std::ostream& os) const;
virtual void
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
virtual void
- OutInterests (Ptr<const Interest>, Ptr<const Face>);
+ OutInterests(Ptr<const Interest>, Ptr<const Face>);
virtual void
- InInterests (Ptr<const Interest>, Ptr<const Face>);
+ InInterests(Ptr<const Interest>, Ptr<const Face>);
virtual void
- DropInterests (Ptr<const Interest>, Ptr<const Face>);
+ DropInterests(Ptr<const Interest>, Ptr<const Face>);
virtual void
- OutNacks (Ptr<const Interest>, Ptr<const Face>);
+ OutNacks(Ptr<const Interest>, Ptr<const Face>);
virtual void
- InNacks (Ptr<const Interest>, Ptr<const Face>);
+ InNacks(Ptr<const Interest>, Ptr<const Face>);
virtual void
- DropNacks (Ptr<const Interest>, Ptr<const Face>);
+ DropNacks(Ptr<const Interest>, Ptr<const Face>);
virtual void
- OutData (Ptr<const Data>, bool fromCache, Ptr<const Face>);
+ OutData(Ptr<const Data>, bool fromCache, Ptr<const Face>);
virtual void
- InData (Ptr<const Data>, Ptr<const Face>);
+ InData(Ptr<const Data>, Ptr<const Face>);
virtual void
- DropData (Ptr<const Data>, Ptr<const Face>);
-
+ DropData(Ptr<const Data>, Ptr<const Face>);
virtual void
- SatisfiedInterests (Ptr<const pit::Entry>);
+ SatisfiedInterests(Ptr<const pit::Entry>);
virtual void
- TimedOutInterests (Ptr<const pit::Entry>);
+ TimedOutInterests(Ptr<const pit::Entry>);
protected:
void
- SetAveragingPeriod (const Time &period);
+ SetAveragingPeriod(const Time& period);
void
- Reset ();
+ Reset();
void
- PeriodicPrinter ();
+ PeriodicPrinter();
protected:
boost::shared_ptr<std::ostream> m_os;
@@ -182,7 +189,7 @@
Time m_period;
EventId m_printEvent;
- mutable std::map<Ptr<const Face>, boost::tuple<Stats, Stats> > m_stats;
+ mutable std::map<Ptr<const Face>, boost::tuple<Stats, Stats>> m_stats;
};
} // namespace ndn
diff --git a/utils/tracers/ndn-l3-rate-tracer.cpp b/utils/tracers/ndn-l3-rate-tracer.cpp
index ca80bef..38170bc 100644
--- a/utils/tracers/ndn-l3-rate-tracer.cpp
+++ b/utils/tracers/ndn-l3-rate-tracer.cpp
@@ -39,433 +39,392 @@
using namespace boost;
using namespace std;
-NS_LOG_COMPONENT_DEFINE ("ndn.L3RateTracer");
+NS_LOG_COMPONENT_DEFINE("ndn.L3RateTracer");
namespace ns3 {
namespace ndn {
-static std::list< boost::tuple< boost::shared_ptr<std::ostream>, std::list<Ptr<L3RateTracer> > > > g_tracers;
+static std::list<boost::tuple<boost::shared_ptr<std::ostream>, std::list<Ptr<L3RateTracer>>>>
+ g_tracers;
template<class T>
static inline void
-NullDeleter (T *ptr)
+NullDeleter(T* ptr)
{
}
void
-L3RateTracer::Destroy ()
+L3RateTracer::Destroy()
{
- g_tracers.clear ();
+ g_tracers.clear();
}
void
-L3RateTracer::InstallAll (const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
+L3RateTracer::InstallAll(const std::string& file, Time averagingPeriod /* = Seconds (0.5)*/)
{
- std::list<Ptr<L3RateTracer> > tracers;
+ std::list<Ptr<L3RateTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- for (NodeList::Iterator node = NodeList::Begin ();
- node != NodeList::End ();
- node++)
- {
- Ptr<L3RateTracer> trace = Install (*node, outputStream, averagingPeriod);
- tracers.push_back (trace);
- }
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ for (NodeList::Iterator node = NodeList::Begin(); node != NodeList::End(); node++) {
+ Ptr<L3RateTracer> trace = Install(*node, outputStream, averagingPeriod);
+ tracers.push_back(trace);
+ }
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
void
-L3RateTracer::Install (const NodeContainer &nodes, const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
+L3RateTracer::Install(const NodeContainer& nodes, const std::string& file,
+ Time averagingPeriod /* = Seconds (0.5)*/)
{
using namespace boost;
using namespace std;
- std::list<Ptr<L3RateTracer> > tracers;
+ std::list<Ptr<L3RateTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- for (NodeContainer::Iterator node = nodes.Begin ();
- node != nodes.End ();
- node++)
- {
- Ptr<L3RateTracer> trace = Install (*node, outputStream, averagingPeriod);
- tracers.push_back (trace);
- }
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ for (NodeContainer::Iterator node = nodes.Begin(); node != nodes.End(); node++) {
+ Ptr<L3RateTracer> trace = Install(*node, outputStream, averagingPeriod);
+ tracers.push_back(trace);
+ }
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
void
-L3RateTracer::Install (Ptr<Node> node, const std::string &file, Time averagingPeriod/* = Seconds (0.5)*/)
+L3RateTracer::Install(Ptr<Node> node, const std::string& file,
+ Time averagingPeriod /* = Seconds (0.5)*/)
{
using namespace boost;
using namespace std;
- std::list<Ptr<L3RateTracer> > tracers;
+ std::list<Ptr<L3RateTracer>> tracers;
boost::shared_ptr<std::ostream> outputStream;
- if (file != "-")
- {
- boost::shared_ptr<std::ofstream> os (new std::ofstream ());
- os->open (file.c_str (), std::ios_base::out | std::ios_base::trunc);
+ if (file != "-") {
+ boost::shared_ptr<std::ofstream> os(new std::ofstream());
+ os->open(file.c_str(), std::ios_base::out | std::ios_base::trunc);
- if (!os->is_open ())
- {
- NS_LOG_ERROR ("File " << file << " cannot be opened for writing. Tracing disabled");
- return;
- }
-
- outputStream = os;
- }
- else
- {
- outputStream = boost::shared_ptr<std::ostream> (&std::cout, NullDeleter<std::ostream>);
+ if (!os->is_open()) {
+ NS_LOG_ERROR("File " << file << " cannot be opened for writing. Tracing disabled");
+ return;
}
- Ptr<L3RateTracer> trace = Install (node, outputStream, averagingPeriod);
- tracers.push_back (trace);
+ outputStream = os;
+ }
+ else {
+ outputStream = boost::shared_ptr<std::ostream>(&std::cout, NullDeleter<std::ostream>);
+ }
- if (tracers.size () > 0)
- {
- // *m_l3RateTrace << "# "; // not necessary for R's read.table
- tracers.front ()->PrintHeader (*outputStream);
- *outputStream << "\n";
- }
+ Ptr<L3RateTracer> trace = Install(node, outputStream, averagingPeriod);
+ tracers.push_back(trace);
- g_tracers.push_back (boost::make_tuple (outputStream, tracers));
+ if (tracers.size() > 0) {
+ // *m_l3RateTrace << "# "; // not necessary for R's read.table
+ tracers.front()->PrintHeader(*outputStream);
+ *outputStream << "\n";
+ }
+
+ g_tracers.push_back(boost::make_tuple(outputStream, tracers));
}
-
Ptr<L3RateTracer>
-L3RateTracer::Install (Ptr<Node> node,
- boost::shared_ptr<std::ostream> outputStream,
- Time averagingPeriod/* = Seconds (0.5)*/)
+L3RateTracer::Install(Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream,
+ Time averagingPeriod /* = Seconds (0.5)*/)
{
- NS_LOG_DEBUG ("Node: " << node->GetId ());
+ NS_LOG_DEBUG("Node: " << node->GetId());
- Ptr<L3RateTracer> trace = Create<L3RateTracer> (outputStream, node);
- trace->SetAveragingPeriod (averagingPeriod);
+ Ptr<L3RateTracer> trace = Create<L3RateTracer>(outputStream, node);
+ trace->SetAveragingPeriod(averagingPeriod);
return trace;
}
-
-L3RateTracer::L3RateTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node)
- : L3Tracer (node)
- , m_os (os)
+L3RateTracer::L3RateTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node)
+ : L3Tracer(node)
+ , m_os(os)
{
- SetAveragingPeriod (Seconds (1.0));
+ SetAveragingPeriod(Seconds(1.0));
}
-L3RateTracer::L3RateTracer (boost::shared_ptr<std::ostream> os, const std::string &node)
- : L3Tracer (node)
- , m_os (os)
+L3RateTracer::L3RateTracer(boost::shared_ptr<std::ostream> os, const std::string& node)
+ : L3Tracer(node)
+ , m_os(os)
{
- SetAveragingPeriod (Seconds (1.0));
+ SetAveragingPeriod(Seconds(1.0));
}
-L3RateTracer::~L3RateTracer ()
+L3RateTracer::~L3RateTracer()
{
- m_printEvent.Cancel ();
+ m_printEvent.Cancel();
}
void
-L3RateTracer::SetAveragingPeriod (const Time &period)
+L3RateTracer::SetAveragingPeriod(const Time& period)
{
m_period = period;
- m_printEvent.Cancel ();
- m_printEvent = Simulator::Schedule (m_period, &L3RateTracer::PeriodicPrinter, this);
+ m_printEvent.Cancel();
+ m_printEvent = Simulator::Schedule(m_period, &L3RateTracer::PeriodicPrinter, this);
}
void
-L3RateTracer::PeriodicPrinter ()
+L3RateTracer::PeriodicPrinter()
{
- Print (*m_os);
- Reset ();
+ Print(*m_os);
+ Reset();
- m_printEvent = Simulator::Schedule (m_period, &L3RateTracer::PeriodicPrinter, this);
+ m_printEvent = Simulator::Schedule(m_period, &L3RateTracer::PeriodicPrinter, this);
}
void
-L3RateTracer::PrintHeader (std::ostream &os) const
+L3RateTracer::PrintHeader(std::ostream& os) const
{
- os << "Time" << "\t"
+ os << "Time"
+ << "\t"
- << "Node" << "\t"
- << "FaceId" << "\t"
- << "FaceDescr" << "\t"
+ << "Node"
+ << "\t"
+ << "FaceId"
+ << "\t"
+ << "FaceDescr"
+ << "\t"
- << "Type" << "\t"
- << "Packets" << "\t"
- << "Kilobytes" << "\t"
- << "PacketRaw" << "\t"
+ << "Type"
+ << "\t"
+ << "Packets"
+ << "\t"
+ << "Kilobytes"
+ << "\t"
+ << "PacketRaw"
+ << "\t"
<< "KilobytesRaw";
}
void
-L3RateTracer::Reset ()
+L3RateTracer::Reset()
{
- for (std::map<Ptr<const Face>, boost::tuple<Stats, Stats, Stats, Stats> >::iterator stats = m_stats.begin ();
- stats != m_stats.end ();
- stats++)
- {
- stats->second.get<0> ().Reset ();
- stats->second.get<1> ().Reset ();
- }
+ for (std::map<Ptr<const Face>, boost::tuple<Stats, Stats, Stats, Stats>>::iterator stats =
+ m_stats.begin();
+ stats != m_stats.end(); stats++) {
+ stats->second.get<0>().Reset();
+ stats->second.get<1>().Reset();
+ }
}
const double alpha = 0.8;
-#define STATS(INDEX) stats->second.get<INDEX> ()
-#define RATE(INDEX, fieldName) STATS(INDEX).fieldName / m_period.ToDouble (Time::S)
+#define STATS(INDEX) stats->second.get<INDEX>()
+#define RATE(INDEX, fieldName) STATS(INDEX).fieldName / m_period.ToDouble(Time::S)
-#define PRINTER(printName, fieldName) \
- STATS(2).fieldName = /*new value*/alpha * RATE(0, fieldName) + /*old value*/(1-alpha) * STATS(2).fieldName; \
- STATS(3).fieldName = /*new value*/alpha * RATE(1, fieldName) / 1024.0 + /*old value*/(1-alpha) * STATS(3).fieldName; \
- \
- os << time.ToDouble (Time::S) << "\t" \
- << m_node << "\t"; \
- if (stats->first) \
- { \
- os \
- << stats->first->GetId () << "\t" \
- << *stats->first << "\t"; \
- } \
- else \
- { \
- os << "-1\tall\t"; \
- } \
- os \
- << printName << "\t" \
- << STATS(2).fieldName << "\t" \
- << STATS(3).fieldName << "\t" \
- << STATS(0).fieldName << "\t" \
- << STATS(1).fieldName / 1024.0 << "\n";
+#define PRINTER(printName, fieldName) \
+ STATS(2).fieldName = \
+ /*new value*/ alpha * RATE(0, fieldName) + /*old value*/ (1 - alpha) * STATS(2).fieldName; \
+ STATS(3).fieldName = /*new value*/ alpha * RATE(1, fieldName) / 1024.0 \
+ + /*old value*/ (1 - alpha) * STATS(3).fieldName; \
+ \
+ os << time.ToDouble(Time::S) << "\t" << m_node << "\t"; \
+ if (stats->first) { \
+ os << stats->first->GetId() << "\t" << *stats->first << "\t"; \
+ } \
+ else { \
+ os << "-1\tall\t"; \
+ } \
+ os << printName << "\t" << STATS(2).fieldName << "\t" << STATS(3).fieldName << "\t" \
+ << STATS(0).fieldName << "\t" << STATS(1).fieldName / 1024.0 << "\n";
void
-L3RateTracer::Print (std::ostream &os) const
+L3RateTracer::Print(std::ostream& os) const
{
- Time time = Simulator::Now ();
+ Time time = Simulator::Now();
- for (std::map<Ptr<const Face>, boost::tuple<Stats, Stats, Stats, Stats> >::iterator stats = m_stats.begin ();
- stats != m_stats.end ();
- stats++)
- {
- if (!stats->first)
- continue;
+ for (std::map<Ptr<const Face>, boost::tuple<Stats, Stats, Stats, Stats>>::iterator stats =
+ m_stats.begin();
+ stats != m_stats.end(); stats++) {
+ if (!stats->first)
+ continue;
- PRINTER ("InInterests", m_inInterests);
- PRINTER ("OutInterests", m_outInterests);
- PRINTER ("DropInterests", m_dropInterests);
+ PRINTER("InInterests", m_inInterests);
+ PRINTER("OutInterests", m_outInterests);
+ PRINTER("DropInterests", m_dropInterests);
- PRINTER ("InNacks", m_inNacks);
- PRINTER ("OutNacks", m_outNacks);
- PRINTER ("DropNacks", m_dropNacks);
+ PRINTER("InNacks", m_inNacks);
+ PRINTER("OutNacks", m_outNacks);
+ PRINTER("DropNacks", m_dropNacks);
- PRINTER ("InData", m_inData);
- PRINTER ("OutData", m_outData);
- PRINTER ("DropData", m_dropData);
+ PRINTER("InData", m_inData);
+ PRINTER("OutData", m_outData);
+ PRINTER("DropData", m_dropData);
- PRINTER ("InSatisfiedInterests", m_satisfiedInterests);
- PRINTER ("InTimedOutInterests", m_timedOutInterests);
+ PRINTER("InSatisfiedInterests", m_satisfiedInterests);
+ PRINTER("InTimedOutInterests", m_timedOutInterests);
- PRINTER ("OutSatisfiedInterests", m_outSatisfiedInterests);
- PRINTER ("OutTimedOutInterests", m_outTimedOutInterests);
- }
+ PRINTER("OutSatisfiedInterests", m_outSatisfiedInterests);
+ PRINTER("OutTimedOutInterests", m_outTimedOutInterests);
+ }
{
- std::map<Ptr<const Face>, boost::tuple<Stats, Stats, Stats, Stats> >::iterator stats = m_stats.find (Ptr<const Face> (0));
- if (stats != m_stats.end ())
- {
- PRINTER ("SatisfiedInterests", m_satisfiedInterests);
- PRINTER ("TimedOutInterests", m_timedOutInterests);
- }
+ std::map<Ptr<const Face>, boost::tuple<Stats, Stats, Stats, Stats>>::iterator stats =
+ m_stats.find(Ptr<const Face>(0));
+ if (stats != m_stats.end()) {
+ PRINTER("SatisfiedInterests", m_satisfiedInterests);
+ PRINTER("TimedOutInterests", m_timedOutInterests);
+ }
}
}
-
void
-L3RateTracer::OutInterests (Ptr<const Interest> interest, Ptr<const Face> face)
+L3RateTracer::OutInterests(Ptr<const Interest> interest, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_outInterests ++;
- if (interest->GetWire ())
- {
- m_stats[face].get<1> ().m_outInterests += interest->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_outInterests++;
+ if (interest->GetWire()) {
+ m_stats[face].get<1>().m_outInterests += interest->GetWire()->GetSize();
+ }
}
void
-L3RateTracer::InInterests (Ptr<const Interest> interest, Ptr<const Face> face)
+L3RateTracer::InInterests(Ptr<const Interest> interest, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_inInterests ++;
- if (interest->GetWire ())
- {
- m_stats[face].get<1> ().m_inInterests += interest->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_inInterests++;
+ if (interest->GetWire()) {
+ m_stats[face].get<1>().m_inInterests += interest->GetWire()->GetSize();
+ }
}
void
-L3RateTracer::DropInterests (Ptr<const Interest> interest, Ptr<const Face> face)
+L3RateTracer::DropInterests(Ptr<const Interest> interest, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_dropInterests ++;
- if (interest->GetWire ())
- {
- m_stats[face].get<1> ().m_dropInterests += interest->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_dropInterests++;
+ if (interest->GetWire()) {
+ m_stats[face].get<1>().m_dropInterests += interest->GetWire()->GetSize();
+ }
}
void
-L3RateTracer::OutNacks (Ptr<const Interest> interest, Ptr<const Face> face)
+L3RateTracer::OutNacks(Ptr<const Interest> interest, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_outNacks ++;
- if (interest->GetWire ())
- {
- m_stats[face].get<1> ().m_outNacks += interest->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_outNacks++;
+ if (interest->GetWire()) {
+ m_stats[face].get<1>().m_outNacks += interest->GetWire()->GetSize();
+ }
}
void
-L3RateTracer::InNacks (Ptr<const Interest> interest, Ptr<const Face> face)
+L3RateTracer::InNacks(Ptr<const Interest> interest, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_inNacks ++;
- if (interest->GetWire ())
- {
- m_stats[face].get<1> ().m_inNacks += interest->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_inNacks++;
+ if (interest->GetWire()) {
+ m_stats[face].get<1>().m_inNacks += interest->GetWire()->GetSize();
+ }
}
void
-L3RateTracer::DropNacks (Ptr<const Interest> interest, Ptr<const Face> face)
+L3RateTracer::DropNacks(Ptr<const Interest> interest, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_dropNacks ++;
- if (interest->GetWire ())
- {
- m_stats[face].get<1> ().m_dropNacks += interest->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_dropNacks++;
+ if (interest->GetWire()) {
+ m_stats[face].get<1>().m_dropNacks += interest->GetWire()->GetSize();
+ }
}
void
-L3RateTracer::OutData (Ptr<const Data> data,
- bool fromCache, Ptr<const Face> face)
+L3RateTracer::OutData(Ptr<const Data> data, bool fromCache, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_outData ++;
- if (data->GetWire ())
- {
- m_stats[face].get<1> ().m_outData += data->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_outData++;
+ if (data->GetWire()) {
+ m_stats[face].get<1>().m_outData += data->GetWire()->GetSize();
+ }
}
void
-L3RateTracer::InData (Ptr<const Data> data,
- Ptr<const Face> face)
+L3RateTracer::InData(Ptr<const Data> data, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_inData ++;
- if (data->GetWire ())
- {
- m_stats[face].get<1> ().m_inData += data->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_inData++;
+ if (data->GetWire()) {
+ m_stats[face].get<1>().m_inData += data->GetWire()->GetSize();
+ }
}
void
-L3RateTracer::DropData (Ptr<const Data> data,
- Ptr<const Face> face)
+L3RateTracer::DropData(Ptr<const Data> data, Ptr<const Face> face)
{
- m_stats[face].get<0> ().m_dropData ++;
- if (data->GetWire ())
- {
- m_stats[face].get<1> ().m_dropData += data->GetWire ()->GetSize ();
- }
+ m_stats[face].get<0>().m_dropData++;
+ if (data->GetWire()) {
+ m_stats[face].get<1>().m_dropData += data->GetWire()->GetSize();
+ }
}
void
-L3RateTracer::SatisfiedInterests (Ptr<const pit::Entry> entry)
+L3RateTracer::SatisfiedInterests(Ptr<const pit::Entry> entry)
{
- m_stats[0].get<0> ().m_satisfiedInterests ++;
+ m_stats[0].get<0>().m_satisfiedInterests++;
// no "size" stats
- for (pit::Entry::in_container::const_iterator i = entry->GetIncoming ().begin ();
- i != entry->GetIncoming ().end ();
- i++)
- {
- m_stats[i->m_face].get<0> ().m_satisfiedInterests ++;
-}
+ for (pit::Entry::in_container::const_iterator i = entry->GetIncoming().begin();
+ i != entry->GetIncoming().end(); i++) {
+ m_stats[i->m_face].get<0>().m_satisfiedInterests++;
+ }
- for (pit::Entry::out_container::const_iterator i = entry->GetOutgoing ().begin ();
- i != entry->GetOutgoing ().end ();
- i++)
- {
- m_stats[i->m_face].get<0> ().m_outSatisfiedInterests ++;
- }
+ for (pit::Entry::out_container::const_iterator i = entry->GetOutgoing().begin();
+ i != entry->GetOutgoing().end(); i++) {
+ m_stats[i->m_face].get<0>().m_outSatisfiedInterests++;
+ }
}
void
-L3RateTracer::TimedOutInterests (Ptr<const pit::Entry> entry)
+L3RateTracer::TimedOutInterests(Ptr<const pit::Entry> entry)
{
- m_stats[0].get<0> ().m_timedOutInterests ++;
+ m_stats[0].get<0>().m_timedOutInterests++;
// no "size" stats
-
- for (pit::Entry::in_container::const_iterator i = entry->GetIncoming ().begin ();
- i != entry->GetIncoming ().end ();
- i++)
- {
- m_stats[i->m_face].get<0> ().m_timedOutInterests ++;
-}
- for (pit::Entry::out_container::const_iterator i = entry->GetOutgoing ().begin ();
- i != entry->GetOutgoing ().end ();
- i++)
- {
- m_stats[i->m_face].get<0> ().m_outTimedOutInterests ++;
- }
-}
+ for (pit::Entry::in_container::const_iterator i = entry->GetIncoming().begin();
+ i != entry->GetIncoming().end(); i++) {
+ m_stats[i->m_face].get<0>().m_timedOutInterests++;
+ }
+ for (pit::Entry::out_container::const_iterator i = entry->GetOutgoing().begin();
+ i != entry->GetOutgoing().end(); i++) {
+ m_stats[i->m_face].get<0>().m_outTimedOutInterests++;
+ }
+}
} // namespace ndn
} // namespace ns3
diff --git a/utils/tracers/ndn-l3-rate-tracer.hpp b/utils/tracers/ndn-l3-rate-tracer.hpp
index 1a6a401..21bb06c 100644
--- a/utils/tracers/ndn-l3-rate-tracer.hpp
+++ b/utils/tracers/ndn-l3-rate-tracer.hpp
@@ -39,38 +39,40 @@
* @ingroup ndn-tracers
* @brief NDN network-layer rate tracer
*/
-class L3RateTracer : public L3Tracer
-{
+class L3RateTracer : public L3Tracer {
public:
/**
* @brief Helper method to install tracers on all simulation nodes
*
* @param file File to which traces will be written. If filename is -, then std::out is used
* @param averagingPeriod Defines averaging period for the rate calculation,
- * as well as how often data will be written into the trace file (default, every half second)
+ * as well as how often data will be written into the trace file (default, every half
+ *second)
*/
static void
- InstallAll (const std::string &file, Time averagingPeriod = Seconds (0.5));
+ InstallAll(const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Helper method to install tracers on the selected simulation nodes
*
* @param nodes Nodes on which to install tracer
* @param file File to which traces will be written. If filename is -, then std::out is used
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*/
static void
- Install (const NodeContainer &nodes, const std::string &file, Time averagingPeriod = Seconds (0.5));
+ Install(const NodeContainer& nodes, const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Helper method to install tracers on a specific simulation node
*
* @param nodes Nodes on which to install tracer
* @param file File to which traces will be written. If filename is -, then std::out is used
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*/
static void
- Install (Ptr<Node> node, const std::string &file, Time averagingPeriod = Seconds (0.5));
+ Install(Ptr<Node> node, const std::string& file, Time averagingPeriod = Seconds(0.5));
/**
* @brief Explicit request to remove all statically created tracers
@@ -79,98 +81,101 @@
* or if it is desired to do a postprocessing of the resulting data
*/
static void
- Destroy ();
-
+ Destroy();
+
/**
* @brief Trace constructor that attaches to the node using node pointer
* @param os reference to the output stream
* @param node pointer to the node
*/
- L3RateTracer (boost::shared_ptr<std::ostream> os, Ptr<Node> node);
+ L3RateTracer(boost::shared_ptr<std::ostream> os, Ptr<Node> node);
/**
* @brief Trace constructor that attaches to the node using node name
* @param os reference to the output stream
* @param nodeName name of the node registered using Names::Add
*/
- L3RateTracer (boost::shared_ptr<std::ostream> os, const std::string &node);
+ L3RateTracer(boost::shared_ptr<std::ostream> os, const std::string& node);
/**
* @brief Destructor
*/
- virtual ~L3RateTracer ();
+ virtual ~L3RateTracer();
/**
* @brief Helper method to install tracers on a specific simulation node
*
* @param nodes Nodes on which to install tracer
* @param outputStream Smart pointer to a stream
- * @param averagingPeriod How often data will be written into the trace file (default, every half second)
+ * @param averagingPeriod How often data will be written into the trace file (default, every half
+ *second)
*
- * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This tuple needs to be preserved
+ * @returns a tuple of reference to output stream and list of tracers. !!! Attention !!! This
+ *tuple needs to be preserved
* for the lifetime of simulation, otherwise SEGFAULTs are inevitable
*/
static Ptr<L3RateTracer>
- Install (Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream, Time averagingPeriod = Seconds (0.5));
-
+ Install(Ptr<Node> node, boost::shared_ptr<std::ostream> outputStream,
+ Time averagingPeriod = Seconds(0.5));
+
// from L3Tracer
virtual void
- PrintHeader (std::ostream &os) const;
+ PrintHeader(std::ostream& os) const;
virtual void
- Print (std::ostream &os) const;
+ Print(std::ostream& os) const;
protected:
// from L3Tracer
virtual void
- OutInterests (Ptr<const Interest>, Ptr<const Face>);
+ OutInterests(Ptr<const Interest>, Ptr<const Face>);
virtual void
- InInterests (Ptr<const Interest>, Ptr<const Face>);
+ InInterests(Ptr<const Interest>, Ptr<const Face>);
virtual void
- DropInterests (Ptr<const Interest>, Ptr<const Face>);
+ DropInterests(Ptr<const Interest>, Ptr<const Face>);
virtual void
- OutNacks (Ptr<const Interest>, Ptr<const Face>);
+ OutNacks(Ptr<const Interest>, Ptr<const Face>);
virtual void
- InNacks (Ptr<const Interest>, Ptr<const Face>);
+ InNacks(Ptr<const Interest>, Ptr<const Face>);
virtual void
- DropNacks (Ptr<const Interest>, Ptr<const Face>);
+ DropNacks(Ptr<const Interest>, Ptr<const Face>);
virtual void
- OutData (Ptr<const Data>, bool fromCache, Ptr<const Face>);
+ OutData(Ptr<const Data>, bool fromCache, Ptr<const Face>);
virtual void
- InData (Ptr<const Data>, Ptr<const Face>);
+ InData(Ptr<const Data>, Ptr<const Face>);
virtual void
- DropData (Ptr<const Data>, Ptr<const Face>);
+ DropData(Ptr<const Data>, Ptr<const Face>);
virtual void
- SatisfiedInterests (Ptr<const pit::Entry>);
+ SatisfiedInterests(Ptr<const pit::Entry>);
virtual void
- TimedOutInterests (Ptr<const pit::Entry>);
+ TimedOutInterests(Ptr<const pit::Entry>);
private:
void
- SetAveragingPeriod (const Time &period);
+ SetAveragingPeriod(const Time& period);
void
- PeriodicPrinter ();
+ PeriodicPrinter();
void
- Reset ();
+ Reset();
private:
boost::shared_ptr<std::ostream> m_os;
Time m_period;
EventId m_printEvent;
- mutable std::map<Ptr<const Face>, boost::tuple<Stats, Stats, Stats, Stats> > m_stats;
+ mutable std::map<Ptr<const Face>, boost::tuple<Stats, Stats, Stats, Stats>> m_stats;
};
} // namespace ndn
diff --git a/utils/tracers/ndn-l3-tracer.cpp b/utils/tracers/ndn-l3-tracer.cpp
index c69a4d3..8d59eb0 100644
--- a/utils/tracers/ndn-l3-tracer.cpp
+++ b/utils/tracers/ndn-l3-tracer.cpp
@@ -38,52 +38,50 @@
namespace ns3 {
namespace ndn {
-L3Tracer::L3Tracer (Ptr<Node> node)
-: m_nodePtr (node)
+L3Tracer::L3Tracer(Ptr<Node> node)
+ : m_nodePtr(node)
{
- m_node = boost::lexical_cast<string> (m_nodePtr->GetId ());
+ m_node = boost::lexical_cast<string>(m_nodePtr->GetId());
- Connect ();
+ Connect();
- string name = Names::FindName (node);
- if (!name.empty ())
- {
- m_node = name;
- }
+ string name = Names::FindName(node);
+ if (!name.empty()) {
+ m_node = name;
+ }
}
-L3Tracer::L3Tracer (const std::string &node)
-: m_node (node)
+L3Tracer::L3Tracer(const std::string& node)
+ : m_node(node)
{
- Connect ();
+ Connect();
}
-L3Tracer::~L3Tracer ()
-{
-};
-
+L3Tracer::~L3Tracer(){};
void
-L3Tracer::Connect ()
+L3Tracer::Connect()
{
- Ptr<ForwardingStrategy> fw = m_nodePtr->GetObject<ForwardingStrategy> ();
-
- fw->TraceConnectWithoutContext ("OutInterests", MakeCallback (&L3Tracer::OutInterests, this));
- fw->TraceConnectWithoutContext ("InInterests", MakeCallback (&L3Tracer::InInterests, this));
- fw->TraceConnectWithoutContext ("DropInterests", MakeCallback (&L3Tracer::DropInterests, this));
-
- fw->TraceConnectWithoutContext ("OutData", MakeCallback (&L3Tracer::OutData, this));
- fw->TraceConnectWithoutContext ("InData", MakeCallback (&L3Tracer::InData, this));
- fw->TraceConnectWithoutContext ("DropData", MakeCallback (&L3Tracer::DropData, this));
+ Ptr<ForwardingStrategy> fw = m_nodePtr->GetObject<ForwardingStrategy>();
+
+ fw->TraceConnectWithoutContext("OutInterests", MakeCallback(&L3Tracer::OutInterests, this));
+ fw->TraceConnectWithoutContext("InInterests", MakeCallback(&L3Tracer::InInterests, this));
+ fw->TraceConnectWithoutContext("DropInterests", MakeCallback(&L3Tracer::DropInterests, this));
+
+ fw->TraceConnectWithoutContext("OutData", MakeCallback(&L3Tracer::OutData, this));
+ fw->TraceConnectWithoutContext("InData", MakeCallback(&L3Tracer::InData, this));
+ fw->TraceConnectWithoutContext("DropData", MakeCallback(&L3Tracer::DropData, this));
// only for some strategies
- fw->TraceConnectWithoutContext ("OutNacks", MakeCallback (&L3Tracer::OutNacks, this));
- fw->TraceConnectWithoutContext ("InNacks", MakeCallback (&L3Tracer::InNacks, this));
- fw->TraceConnectWithoutContext ("DropNacks", MakeCallback (&L3Tracer::DropNacks, this));
-
+ fw->TraceConnectWithoutContext("OutNacks", MakeCallback(&L3Tracer::OutNacks, this));
+ fw->TraceConnectWithoutContext("InNacks", MakeCallback(&L3Tracer::InNacks, this));
+ fw->TraceConnectWithoutContext("DropNacks", MakeCallback(&L3Tracer::DropNacks, this));
+
// satisfied/timed out PIs
- fw->TraceConnectWithoutContext ("SatisfiedInterests", MakeCallback (&L3Tracer::SatisfiedInterests, this));
- fw->TraceConnectWithoutContext ("TimedOutInterests", MakeCallback (&L3Tracer::TimedOutInterests, this));
+ fw->TraceConnectWithoutContext("SatisfiedInterests",
+ MakeCallback(&L3Tracer::SatisfiedInterests, this));
+ fw->TraceConnectWithoutContext("TimedOutInterests",
+ MakeCallback(&L3Tracer::TimedOutInterests, this));
}
} // namespace ndn
diff --git a/utils/tracers/ndn-l3-tracer.hpp b/utils/tracers/ndn-l3-tracer.hpp
index 2f132bd..d3534fa 100644
--- a/utils/tracers/ndn-l3-tracer.hpp
+++ b/utils/tracers/ndn-l3-tracer.hpp
@@ -49,25 +49,24 @@
* @ingroup ndn-tracers
* @brief Base class for network-layer (incoming/outgoing Interests and Data) tracing of NDN stack
*/
-class L3Tracer : public SimpleRefCount<L3Tracer>
-{
+class L3Tracer : public SimpleRefCount<L3Tracer> {
public:
/**
* @brief Trace constructor that attaches to the node using node pointer
* @param node pointer to the node
*/
- L3Tracer (Ptr<Node> node);
+ L3Tracer(Ptr<Node> node);
/**
* @brief Trace constructor that attaches to the node using node name
* @param nodeName name of the node registered using Names::Add
*/
- L3Tracer (const std::string &node);
+ L3Tracer(const std::string& node);
/**
* @brief Destructor
*/
- virtual ~L3Tracer ();
+ virtual ~L3Tracer();
/**
* @brief Print head of the trace (e.g., for post-processing)
@@ -75,7 +74,7 @@
* @param os reference to output stream
*/
virtual void
- PrintHeader (std::ostream &os) const = 0;
+ PrintHeader(std::ostream& os) const = 0;
/**
* @brief Print current trace data
@@ -83,63 +82,62 @@
* @param os reference to output stream
*/
virtual void
- Print (std::ostream &os) const = 0;
+ Print(std::ostream& os) const = 0;
protected:
void
- Connect ();
+ Connect();
virtual void
- OutInterests (Ptr<const Interest>, Ptr<const Face>) = 0;
+ OutInterests(Ptr<const Interest>, Ptr<const Face>) = 0;
virtual void
- InInterests (Ptr<const Interest>, Ptr<const Face>) = 0;
+ InInterests(Ptr<const Interest>, Ptr<const Face>) = 0;
virtual void
- DropInterests (Ptr<const Interest>, Ptr<const Face>) = 0;
+ DropInterests(Ptr<const Interest>, Ptr<const Face>) = 0;
virtual void
- OutNacks (Ptr<const Interest>, Ptr<const Face>) = 0;
+ OutNacks(Ptr<const Interest>, Ptr<const Face>) = 0;
virtual void
- InNacks (Ptr<const Interest>, Ptr<const Face>) = 0;
+ InNacks(Ptr<const Interest>, Ptr<const Face>) = 0;
virtual void
- DropNacks (Ptr<const Interest>, Ptr<const Face>) = 0;
-
+ DropNacks(Ptr<const Interest>, Ptr<const Face>) = 0;
virtual void
- OutData (Ptr<const Data>, bool fromCache, Ptr<const Face>) = 0;
+ OutData(Ptr<const Data>, bool fromCache, Ptr<const Face>) = 0;
virtual void
- InData (Ptr<const Data>, Ptr<const Face>) = 0;
+ InData(Ptr<const Data>, Ptr<const Face>) = 0;
virtual void
- DropData (Ptr<const Data>, Ptr<const Face>) = 0;
+ DropData(Ptr<const Data>, Ptr<const Face>) = 0;
virtual void
- SatisfiedInterests (Ptr<const pit::Entry>) = 0;
+ SatisfiedInterests(Ptr<const pit::Entry>) = 0;
virtual void
- TimedOutInterests (Ptr<const pit::Entry>) = 0;
+ TimedOutInterests(Ptr<const pit::Entry>) = 0;
protected:
std::string m_node;
Ptr<Node> m_nodePtr;
- struct Stats
- {
- inline void Reset ()
+ struct Stats {
+ inline void
+ Reset()
{
- m_inInterests = 0;
- m_outInterests = 0;
+ m_inInterests = 0;
+ m_outInterests = 0;
m_dropInterests = 0;
- m_inNacks = 0;
- m_outNacks = 0;
- m_dropNacks = 0;
- m_inData = 0;
- m_outData = 0;
- m_dropData = 0;
+ m_inNacks = 0;
+ m_outNacks = 0;
+ m_dropNacks = 0;
+ m_inData = 0;
+ m_outData = 0;
+ m_dropData = 0;
m_satisfiedInterests = 0;
m_timedOutInterests = 0;
@@ -167,12 +165,12 @@
* @brief Helper to dump the trace to an output stream
*/
inline std::ostream&
-operator << (std::ostream &os, const L3Tracer &tracer)
+operator<<(std::ostream& os, const L3Tracer& tracer)
{
os << "# ";
- tracer.PrintHeader (os);
+ tracer.PrintHeader(os);
os << "\n";
- tracer.Print (os);
+ tracer.Print(os);
return os;
}
diff --git a/utils/trie/aggregate-stats-policy.hpp b/utils/trie/aggregate-stats-policy.hpp
index ce466dd..b2cb0bd 100644
--- a/utils/trie/aggregate-stats-policy.hpp
+++ b/utils/trie/aggregate-stats-policy.hpp
@@ -32,80 +32,84 @@
* @brief Traits for policy that just keeps track of number of elements
* It's doing a rather expensive job, but just in case it needs to be extended later
*/
-struct aggregate_stats_policy_traits
-{
+struct aggregate_stats_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return "AggregateStats"; }
- struct policy_hook_type { };
-
- template<class Container>
- struct container_hook
+ static std::string
+ GetName()
{
- struct type { };
+ return "AggregateStats";
+ }
+ struct policy_hook_type {
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
+ template<class Container>
+ struct container_hook {
+ struct type {
+ };
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
// typedef typename boost::intrusive::list< Container, Hook > policy_container;
// could be just typedef
- class type
- {
+ class type {
public:
typedef Container parent_trie;
- type (Base &base)
- : base_ (base)
- , m_updates (0)
- , m_inserts (0)
- , m_lookups (0)
- , m_erases (0)
+ type(Base& base)
+ : base_(base)
+ , m_updates(0)
+ , m_inserts(0)
+ , m_lookups(0)
+ , m_erases(0)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
- m_updates ++;
+ m_updates++;
// do nothing
}
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- m_inserts ++;
+ m_inserts++;
return true;
}
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
- m_lookups ++;
+ m_lookups++;
}
inline void
- erase (typename parent_trie::iterator item)
+ erase(typename parent_trie::iterator item)
{
- m_erases ++;
+ m_erases++;
}
- inline void
- set_max_size (uint32_t) {}
+ inline void set_max_size(uint32_t)
+ {
+ }
inline uint32_t
- get_max_size () const { return 0; }
+ get_max_size() const
+ {
+ return 0;
+ }
inline void
- clear ()
+ clear()
{
// is called only at the end of simulation
}
inline void
- ResetStats ()
+ ResetStats()
{
m_updates = 0;
m_inserts = 0;
@@ -114,23 +118,36 @@
}
inline uint64_t
- GetUpdates () const { return m_updates; }
+ GetUpdates() const
+ {
+ return m_updates;
+ }
inline uint64_t
- GetInserts () const { return m_inserts; }
+ GetInserts() const
+ {
+ return m_inserts;
+ }
inline uint64_t
- GetLookups () const { return m_lookups; }
+ GetLookups() const
+ {
+ return m_lookups;
+ }
inline uint64_t
- GetErases () const { return m_erases; }
+ GetErases() const
+ {
+ return m_erases;
+ }
private:
- type () : base_(*((Base*)0)) { };
+ type()
+ : base_(*((Base*)0)){};
private:
- Base &base_;
-
+ Base& base_;
+
uint64_t m_updates;
uint64_t m_inserts;
uint64_t m_lookups;
diff --git a/utils/trie/counting-policy.hpp b/utils/trie/counting-policy.hpp
index 2c8656c..a44c290 100644
--- a/utils/trie/counting-policy.hpp
+++ b/utils/trie/counting-policy.hpp
@@ -32,76 +32,75 @@
* @brief Traits for policy that just keeps track of number of elements
* It's doing a rather expensive job, but just in case it needs to be extended later
*/
-struct counting_policy_traits
-{
+struct counting_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return "Counting"; }
-
- struct policy_hook_type : public boost::intrusive::list_member_hook<> {};
-
- template<class Container>
- struct container_hook
+ static std::string
+ GetName()
{
- // could be class/struct implementation
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+ return "Counting";
+ }
+
+ struct policy_hook_type : public boost::intrusive::list_member_hook<> {
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- typedef typename boost::intrusive::list< Container, Hook > policy_container;
-
+ template<class Container>
+ struct container_hook {
+ // could be class/struct implementation
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ typedef typename boost::intrusive::list<Container, Hook> policy_container;
+
// could be just typedef
- class type : public policy_container
- {
+ class type : public policy_container {
public:
typedef Container parent_trie;
- type (Base &base)
- : base_ (base)
+ type(Base& base)
+ : base_(base)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
// do nothing
}
-
+
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- policy_container::push_back (*item);
+ policy_container::push_back(*item);
return true;
}
-
+
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
// do nothing
}
-
+
inline void
- erase (typename parent_trie::iterator item)
+ erase(typename parent_trie::iterator item)
{
- policy_container::erase (policy_container::s_iterator_to (*item));
+ policy_container::erase(policy_container::s_iterator_to(*item));
}
inline void
- clear ()
+ clear()
{
- policy_container::clear ();
+ policy_container::clear();
}
private:
- type () : base_(*((Base*)0)) { };
+ type()
+ : base_(*((Base*)0)){};
private:
- Base &base_;
+ Base& base_;
};
};
};
diff --git a/utils/trie/detail/functor-hook.hpp b/utils/trie/detail/functor-hook.hpp
index f34969c..b0daadd 100644
--- a/utils/trie/detail/functor-hook.hpp
+++ b/utils/trie/detail/functor-hook.hpp
@@ -29,36 +29,43 @@
namespace detail {
template<class BaseHook, class ValueType, int N>
-struct FunctorHook
-{
+struct FunctorHook {
typedef typename BaseHook::template index<N>::type hook_type;
- typedef hook_type* hook_ptr;
- typedef const hook_type* const_hook_ptr;
-
- typedef ValueType value_type;
- typedef value_type* pointer;
- typedef const value_type* const_pointer;
-
- //Required static functions
- static hook_ptr to_hook_ptr (value_type &value)
- { return &value.policy_hook_.template get<N> (); }
-
- static const_hook_ptr to_hook_ptr(const value_type &value)
- { return &value.policy_hook_.template get<N> (); }
-
- static pointer to_value_ptr(hook_ptr n)
+ typedef hook_type* hook_ptr;
+ typedef const hook_type* const_hook_ptr;
+
+ typedef ValueType value_type;
+ typedef value_type* pointer;
+ typedef const value_type* const_pointer;
+
+ // Required static functions
+ static hook_ptr
+ to_hook_ptr(value_type& value)
{
- return
- boost::intrusive::get_parent_from_member<value_type>
- (static_cast<BaseHook*> (boost::intrusive::get_parent_from_member< wrap<hook_type> >(n, &wrap<hook_type>::value_)),
- &value_type::policy_hook_);
+ return &value.policy_hook_.template get<N>();
}
- static const_pointer to_value_ptr(const_hook_ptr n)
+
+ static const_hook_ptr
+ to_hook_ptr(const value_type& value)
{
- return
- boost::intrusive::get_parent_from_member<value_type>
- (static_cast<const BaseHook*> (boost::intrusive::get_parent_from_member< wrap<hook_type> >(n, &wrap<hook_type>::value_)),
- &value_type::policy_hook_);
+ return &value.policy_hook_.template get<N>();
+ }
+
+ static pointer
+ to_value_ptr(hook_ptr n)
+ {
+ return boost::intrusive::get_parent_from_member<value_type>(
+ static_cast<BaseHook*>(
+ boost::intrusive::get_parent_from_member<wrap<hook_type>>(n, &wrap<hook_type>::value_)),
+ &value_type::policy_hook_);
+ }
+ static const_pointer
+ to_value_ptr(const_hook_ptr n)
+ {
+ return boost::intrusive::get_parent_from_member<value_type>(
+ static_cast<const BaseHook*>(
+ boost::intrusive::get_parent_from_member<wrap<hook_type>>(n, &wrap<hook_type>::value_)),
+ &value_type::policy_hook_);
}
};
diff --git a/utils/trie/detail/multi-policy-container.hpp b/utils/trie/detail/multi-policy-container.hpp
index c1251e9..00bfbf1 100644
--- a/utils/trie/detail/multi-policy-container.hpp
+++ b/utils/trie/detail/multi-policy-container.hpp
@@ -29,144 +29,180 @@
namespace ndnSIM {
namespace detail {
-template< class Base, class Value >
-struct policy_wrap
-{
- policy_wrap (Base &base) : value_ (base) { }
+template<class Base, class Value>
+struct policy_wrap {
+ policy_wrap(Base& base)
+ : value_(base)
+ {
+ }
Value value_;
};
-template< class Base, class Super/*empy_wrap/previous level*/, class Value/*policy_wrap< element in vector >*/ >
-struct inherit_with_base : Super, Value
-{
- inherit_with_base (Base &base) : Super (base), Value (base) { }
+template<class Base, class Super /*empy_wrap/previous level*/,
+ class Value /*policy_wrap< element in vector >*/>
+struct inherit_with_base : Super, Value {
+ inherit_with_base(Base& base)
+ : Super(base)
+ , Value(base)
+ {
+ }
void
- update (typename Base::iterator item)
+ update(typename Base::iterator item)
{
- Value::value_.update (item);
- Super::update (item);
+ Value::value_.update(item);
+ Super::update(item);
}
bool
- insert (typename Base::iterator item)
+ insert(typename Base::iterator item)
{
- bool ok = Value::value_.insert (item);
+ bool ok = Value::value_.insert(item);
if (!ok)
return false;
- ok = Super::insert (item);
- if (!ok)
- {
- Value::value_.erase (item);
- return false;
- }
+ ok = Super::insert(item);
+ if (!ok) {
+ Value::value_.erase(item);
+ return false;
+ }
return true;
}
void
- lookup (typename Base::iterator item)
+ lookup(typename Base::iterator item)
{
- Value::value_.lookup (item);
- Super::lookup (item);
+ Value::value_.lookup(item);
+ Super::lookup(item);
}
void
- erase (typename Base::iterator item)
+ erase(typename Base::iterator item)
{
- Value::value_.erase (item);
- Super::erase (item);
- }
+ Value::value_.erase(item);
+ Super::erase(item);
+ }
void
- clear ()
+ clear()
{
- Value::value_.clear ();
- Super::clear ();
+ Value::value_.clear();
+ Super::clear();
}
};
-template< class Base >
-struct empty_policy_wrap
-{
- empty_policy_wrap (Base &base) { }
+template<class Base>
+struct empty_policy_wrap {
+ empty_policy_wrap(Base& base)
+ {
+ }
- void update (typename Base::iterator item) {}
- bool insert (typename Base::iterator item) { return true; }
- void lookup (typename Base::iterator item) {}
- void erase (typename Base::iterator item) {}
- void clear () {}
+ void
+ update(typename Base::iterator item)
+ {
+ }
+ bool
+ insert(typename Base::iterator item)
+ {
+ return true;
+ }
+ void
+ lookup(typename Base::iterator item)
+ {
+ }
+ void
+ erase(typename Base::iterator item)
+ {
+ }
+ void
+ clear()
+ {
+ }
};
-template< class Base, class Vector >
+template<class Base, class Vector>
struct multi_policy_container
- : public boost::mpl::fold< Vector,
- empty_policy_wrap<Base>,
- inherit_with_base<Base,
- boost::mpl::_1/*empty/previous*/,
- policy_wrap<Base, boost::mpl::_2>/*element in vector*/>
- >::type
-{
- typedef typename boost::mpl::fold< Vector,
- empty_policy_wrap<Base>,
- inherit_with_base<Base,
- boost::mpl::_1/*empty/previous*/,
- policy_wrap<Base, boost::mpl::_2>/*element in vector*/>
- >::type super;
+ : public boost::mpl::
+ fold<Vector, empty_policy_wrap<Base>,
+ inherit_with_base<Base, boost::mpl::_1 /*empty/previous*/,
+ policy_wrap<Base, boost::mpl::_2> /*element in vector*/>>::type {
+ typedef typename boost::mpl::
+ fold<Vector, empty_policy_wrap<Base>,
+ inherit_with_base<Base, boost::mpl::_1 /*empty/previous*/,
+ policy_wrap<Base, boost::mpl::_2> /*element in vector*/>>::type super;
typedef typename boost::mpl::at_c<Vector, 0>::type::iterator iterator;
typedef typename boost::mpl::at_c<Vector, 0>::type::const_iterator const_iterator;
- iterator begin () { return this->get<0> ().begin (); }
- const_iterator begin () const { return this->get<0> ().begin (); }
+ iterator
+ begin()
+ {
+ return this->get<0>().begin();
+ }
+ const_iterator
+ begin() const
+ {
+ return this->get<0>().begin();
+ }
- iterator end () { return this->get<0> ().end (); }
- const_iterator end () const { return this->get<0> ().end (); }
+ iterator
+ end()
+ {
+ return this->get<0>().end();
+ }
+ const_iterator
+ end() const
+ {
+ return this->get<0>().end();
+ }
- size_t size () const { return this->get<0> ().size (); }
-
- multi_policy_container (Base &base)
- : super (base)
- { }
+ size_t
+ size() const
+ {
+ return this->get<0>().size();
+ }
+
+ multi_policy_container(Base& base)
+ : super(base)
+ {
+ }
template<int N>
- struct index
- {
+ struct index {
typedef typename boost::mpl::at_c<Vector, N>::type type;
};
-
+
template<class T>
- T &
- get ()
+ T&
+ get()
{
- return static_cast< policy_wrap<Base, T> &> (*this).value_;
+ return static_cast<policy_wrap<Base, T>&>(*this).value_;
}
template<class T>
- const T &
- get () const
+ const T&
+ get() const
{
- return static_cast< const policy_wrap<Base, T> &> (*this).value_;
+ return static_cast<const policy_wrap<Base, T>&>(*this).value_;
}
template<int N>
- typename boost::mpl::at_c<Vector, N>::type &
- get ()
+ typename boost::mpl::at_c<Vector, N>::type&
+ get()
{
typedef typename boost::mpl::at_c<Vector, N>::type T;
- return static_cast< policy_wrap<Base, T> &> (*this).value_;
+ return static_cast<policy_wrap<Base, T>&>(*this).value_;
}
template<int N>
- const typename boost::mpl::at_c<Vector, N>::type &
- get () const
+ const typename boost::mpl::at_c<Vector, N>::type&
+ get() const
{
typedef typename boost::mpl::at_c<Vector, N>::type T;
- return static_cast< const policy_wrap<Base, T> &> (*this).value_;
+ return static_cast<const policy_wrap<Base, T>&>(*this).value_;
}
};
-
} // detail
} // ndnSIM
} // ndn
diff --git a/utils/trie/detail/multi-type-container.hpp b/utils/trie/detail/multi-type-container.hpp
index d4971c4..56dc89e 100644
--- a/utils/trie/detail/multi-type-container.hpp
+++ b/utils/trie/detail/multi-type-container.hpp
@@ -30,54 +30,51 @@
namespace ndnSIM {
namespace detail {
-template <class T>
-struct wrap
-{
+template<class T>
+struct wrap {
T value_;
};
-template< class Vector >
+template<class Vector>
struct multi_type_container
- : public boost::mpl::inherit_linearly< Vector, boost::mpl::inherit<wrap<boost::mpl::_2>, boost::mpl::_1 >
- >::type
-{
+ : public boost::mpl::inherit_linearly<Vector, boost::mpl::inherit<wrap<boost::mpl::_2>,
+ boost::mpl::_1>>::type {
template<int N>
- struct index
- {
+ struct index {
typedef typename boost::mpl::at_c<Vector, N>::type type;
};
-
+
template<class T>
- T &
- get ()
+ T&
+ get()
{
- return static_cast< wrap<T> &> (*this).value_;
+ return static_cast<wrap<T>&>(*this).value_;
}
template<class T>
- const T &
- get () const
+ const T&
+ get() const
{
- return static_cast< const wrap<T> &> (*this).value_;
- }
-
- template<int N>
- typename boost::mpl::at_c<Vector, N>::type &
- get ()
- {
- typedef typename boost::mpl::at_c<Vector, N>::type T;
- return static_cast< wrap<T> &> (*this).value_;
+ return static_cast<const wrap<T>&>(*this).value_;
}
template<int N>
- const typename boost::mpl::at_c<Vector, N>::type &
- get () const
+ typename boost::mpl::at_c<Vector, N>::type&
+ get()
{
typedef typename boost::mpl::at_c<Vector, N>::type T;
- return static_cast< const wrap<T> &> (*this).value_;
+ return static_cast<wrap<T>&>(*this).value_;
+ }
+
+ template<int N>
+ const typename boost::mpl::at_c<Vector, N>::type&
+ get() const
+ {
+ typedef typename boost::mpl::at_c<Vector, N>::type T;
+ return static_cast<const wrap<T>&>(*this).value_;
}
};
-
+
} // detail
} // ndnSIM
} // ndn
diff --git a/utils/trie/empty-policy.hpp b/utils/trie/empty-policy.hpp
index c610717..7d077b6 100644
--- a/utils/trie/empty-policy.hpp
+++ b/utils/trie/empty-policy.hpp
@@ -28,29 +28,47 @@
/**
* @brief Traits for empty (bogus) replacement policy
*/
-struct empty_policy_traits
-{
+struct empty_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return ""; }
+ static std::string
+ GetName()
+ {
+ return "";
+ }
typedef void* policy_hook_type;
- template<class Container> struct container_hook { typedef void* type; };
+ template<class Container>
+ struct container_hook {
+ typedef void* type;
+ };
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- struct type
- {
- inline type (Base &base) {}
-
- inline void update (typename Container::iterator) { }
- inline bool insert (typename Container::iterator) { return true; }
- inline void lookup (typename Container::iterator item) { }
- inline void erase (typename Container::iterator item) { }
- inline void clear () { }
+ template<class Base, class Container, class Hook>
+ struct policy {
+ struct type {
+ inline type(Base& base)
+ {
+ }
+
+ inline void update(typename Container::iterator)
+ {
+ }
+ inline bool insert(typename Container::iterator)
+ {
+ return true;
+ }
+ inline void
+ lookup(typename Container::iterator item)
+ {
+ }
+ inline void
+ erase(typename Container::iterator item)
+ {
+ }
+ inline void
+ clear()
+ {
+ }
};
};
};
diff --git a/utils/trie/fifo-policy.hpp b/utils/trie/fifo-policy.hpp
index 7ab4ec7..2527c16 100644
--- a/utils/trie/fifo-policy.hpp
+++ b/utils/trie/fifo-policy.hpp
@@ -31,94 +31,92 @@
/**
* @brief Traits for First In First Out replacement policy
*/
-struct fifo_policy_traits
-{
+struct fifo_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return "Fifo"; }
-
- struct policy_hook_type : public boost::intrusive::list_member_hook<> {};
-
- template<class Container>
- struct container_hook
+ static std::string
+ GetName()
{
- // could be class/struct implementation
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+ return "Fifo";
+ }
+
+ struct policy_hook_type : public boost::intrusive::list_member_hook<> {
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- typedef typename boost::intrusive::list< Container, Hook > policy_container;
-
+ template<class Container>
+ struct container_hook {
+ // could be class/struct implementation
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ typedef typename boost::intrusive::list<Container, Hook> policy_container;
+
// could be just typedef
- class type : public policy_container
- {
+ class type : public policy_container {
public:
typedef Container parent_trie;
- type (Base &base)
- : base_ (base)
- , max_size_ (100)
+ type(Base& base)
+ : base_(base)
+ , max_size_(100)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
// do nothing
}
-
+
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- if (max_size_ != 0 && policy_container::size () >= max_size_)
- {
- base_.erase (&(*policy_container::begin ()));
- }
-
- policy_container::push_back (*item);
+ if (max_size_ != 0 && policy_container::size() >= max_size_) {
+ base_.erase(&(*policy_container::begin()));
+ }
+
+ policy_container::push_back(*item);
return true;
}
-
+
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
// do nothing
}
-
+
inline void
- erase (typename parent_trie::iterator item)
+ erase(typename parent_trie::iterator item)
{
- policy_container::erase (policy_container::s_iterator_to (*item));
+ policy_container::erase(policy_container::s_iterator_to(*item));
}
inline void
- clear ()
+ clear()
{
- policy_container::clear ();
+ policy_container::clear();
}
inline void
- set_max_size (size_t max_size)
+ set_max_size(size_t max_size)
{
max_size_ = max_size;
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
return max_size_;
}
private:
- type () : base_(*((Base*)0)) { };
+ type()
+ : base_(*((Base*)0)){};
private:
- Base &base_;
+ Base& base_;
size_t max_size_;
};
};
diff --git a/utils/trie/lfu-policy.hpp b/utils/trie/lfu-policy.hpp
index c6d6108..897dc49 100644
--- a/utils/trie/lfu-policy.hpp
+++ b/utils/trie/lfu-policy.hpp
@@ -31,124 +31,125 @@
/**
* @brief Traits for LFU replacement policy
*/
-struct lfu_policy_traits
-{
+struct lfu_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return "Lfu"; }
-
- struct policy_hook_type : public boost::intrusive::set_member_hook<> { double frequency; };
-
- template<class Container>
- struct container_hook
+ static std::string
+ GetName()
{
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+ return "Lfu";
+ }
+
+ struct policy_hook_type : public boost::intrusive::set_member_hook<> {
+ double frequency;
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- static double& get_order (typename Container::iterator item)
+ template<class Container>
+ struct container_hook {
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ static double&
+ get_order(typename Container::iterator item)
{
- return static_cast<policy_hook_type*>
- (policy_container::value_traits::to_node_ptr(*item))->frequency;
+ return static_cast<policy_hook_type*>(policy_container::value_traits::to_node_ptr(*item))
+ ->frequency;
}
- static const double& get_order (typename Container::const_iterator item)
+ static const double&
+ get_order(typename Container::const_iterator item)
{
- return static_cast<const policy_hook_type*>
- (policy_container::value_traits::to_node_ptr(*item))->frequency;
+ return static_cast<const policy_hook_type*>(
+ policy_container::value_traits::to_node_ptr(*item))->frequency;
}
template<class Key>
- struct MemberHookLess
- {
- bool operator () (const Key &a, const Key &b) const
+ struct MemberHookLess {
+ bool
+ operator()(const Key& a, const Key& b) const
{
- return get_order (&a) < get_order (&b);
+ return get_order(&a) < get_order(&b);
}
};
- typedef boost::intrusive::multiset< Container,
- boost::intrusive::compare< MemberHookLess< Container > >,
- Hook > policy_container;
+ typedef boost::intrusive::multiset<Container,
+ boost::intrusive::compare<MemberHookLess<Container>>,
+ Hook> policy_container;
// could be just typedef
- class type : public policy_container
- {
+ class type : public policy_container {
public:
typedef policy policy_base; // to get access to get_order methods from outside
typedef Container parent_trie;
- type (Base &base)
- : base_ (base)
- , max_size_ (100)
+ type(Base& base)
+ : base_(base)
+ , max_size_(100)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
- policy_container::erase (policy_container::s_iterator_to (*item));
- get_order (item) += 1;
- policy_container::insert (*item);
+ policy_container::erase(policy_container::s_iterator_to(*item));
+ get_order(item) += 1;
+ policy_container::insert(*item);
}
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- get_order (item) = 0;
+ get_order(item) = 0;
- if (max_size_ != 0 && policy_container::size () >= max_size_)
- {
- // this erases the "least frequently used item" from cache
- base_.erase (&(*policy_container::begin ()));
- }
+ if (max_size_ != 0 && policy_container::size() >= max_size_) {
+ // this erases the "least frequently used item" from cache
+ base_.erase(&(*policy_container::begin()));
+ }
- policy_container::insert (*item);
+ policy_container::insert(*item);
return true;
}
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
- policy_container::erase (policy_container::s_iterator_to (*item));
- get_order (item) += 1;
- policy_container::insert (*item);
+ policy_container::erase(policy_container::s_iterator_to(*item));
+ get_order(item) += 1;
+ policy_container::insert(*item);
}
inline void
- erase (typename parent_trie::iterator item)
+ erase(typename parent_trie::iterator item)
{
- policy_container::erase (policy_container::s_iterator_to (*item));
+ policy_container::erase(policy_container::s_iterator_to(*item));
}
inline void
- clear ()
+ clear()
{
- policy_container::clear ();
+ policy_container::clear();
}
inline void
- set_max_size (size_t max_size)
+ set_max_size(size_t max_size)
{
max_size_ = max_size;
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
return max_size_;
}
private:
- type () : base_(*((Base*)0)) { };
+ type()
+ : base_(*((Base*)0)){};
private:
- Base &base_;
+ Base& base_;
size_t max_size_;
};
};
diff --git a/utils/trie/lru-policy.hpp b/utils/trie/lru-policy.hpp
index a248117..77a65ca 100644
--- a/utils/trie/lru-policy.hpp
+++ b/utils/trie/lru-policy.hpp
@@ -31,99 +31,95 @@
/**
* @brief Traits for Least Recently Used replacement policy
*/
-struct lru_policy_traits
-{
+struct lru_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return "Lru"; }
-
- struct policy_hook_type : public boost::intrusive::list_member_hook<> {};
-
- template<class Container>
- struct container_hook
+ static std::string
+ GetName()
{
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+ return "Lru";
+ }
+
+ struct policy_hook_type : public boost::intrusive::list_member_hook<> {
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- typedef typename boost::intrusive::list< Container, Hook > policy_container;
-
+ template<class Container>
+ struct container_hook {
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ typedef typename boost::intrusive::list<Container, Hook> policy_container;
+
// could be just typedef
- class type : public policy_container
- {
+ class type : public policy_container {
public:
typedef Container parent_trie;
-
- type (Base &base)
- : base_ (base)
- , max_size_ (100)
+
+ type(Base& base)
+ : base_(base)
+ , max_size_(100)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
// do relocation
- policy_container::splice (policy_container::end (),
- *this,
- policy_container::s_iterator_to (*item));
+ policy_container::splice(policy_container::end(), *this,
+ policy_container::s_iterator_to(*item));
}
-
+
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- if (max_size_ != 0 && policy_container::size () >= max_size_)
- {
- base_.erase (&(*policy_container::begin ()));
- }
-
- policy_container::push_back (*item);
+ if (max_size_ != 0 && policy_container::size() >= max_size_) {
+ base_.erase(&(*policy_container::begin()));
+ }
+
+ policy_container::push_back(*item);
return true;
}
-
+
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
// do relocation
- policy_container::splice (policy_container::end (),
- *this,
- policy_container::s_iterator_to (*item));
- }
-
- inline void
- erase (typename parent_trie::iterator item)
- {
- policy_container::erase (policy_container::s_iterator_to (*item));
+ policy_container::splice(policy_container::end(), *this,
+ policy_container::s_iterator_to(*item));
}
inline void
- clear ()
+ erase(typename parent_trie::iterator item)
{
- policy_container::clear ();
+ policy_container::erase(policy_container::s_iterator_to(*item));
}
inline void
- set_max_size (size_t max_size)
+ clear()
+ {
+ policy_container::clear();
+ }
+
+ inline void
+ set_max_size(size_t max_size)
{
max_size_ = max_size;
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
return max_size_;
}
private:
- type () : base_(*((Base*)0)) { };
+ type()
+ : base_(*((Base*)0)){};
private:
- Base &base_;
+ Base& base_;
size_t max_size_;
};
};
diff --git a/utils/trie/multi-policy.hpp b/utils/trie/multi-policy.hpp
index 125df02..170f691 100644
--- a/utils/trie/multi-policy.hpp
+++ b/utils/trie/multi-policy.hpp
@@ -40,144 +40,148 @@
namespace ndnSIM {
template<typename Policies> // e.g., mpl::vector1< lru_policy_traits >
-struct multi_policy_traits
-{
+struct multi_policy_traits {
typedef Policies policy_traits;
- struct getHook { template<class Item> struct apply { typedef typename Item::policy_hook_type type; }; };
- typedef detail::multi_type_container< typename boost::mpl::transform1<policy_traits, getHook>::type > policy_hook_type;
-
+ struct getHook {
+ template<class Item>
+ struct apply {
+ typedef typename Item::policy_hook_type type;
+ };
+ };
+ typedef detail::multi_type_container<
+ typename boost::mpl::transform1<policy_traits, getHook>::type> policy_hook_type;
+
template<class Container>
- struct container_hook
- {
+ struct container_hook {
typedef policy_hook_type type;
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- typedef boost::mpl::range_c<int, 0, boost::mpl::size<policy_traits>::type::value> policies_range;
+ template<class Base, class Container, class Hook>
+ struct policy {
+ typedef boost::mpl::range_c<int, 0, boost::mpl::size<policy_traits>::type::value>
+ policies_range;
- struct getPolicy
- {
+ struct getPolicy {
template<class Number>
- struct apply
- {
- typedef
- typename boost::mpl::at_c<policy_traits, Number::value>::type::
- template policy<Base,
- Container,
- boost::intrusive::function_hook< detail::FunctorHook <Hook,
- Container,
- Number::value> > >::type
- type;
+ struct apply {
+ typedef typename boost::mpl::at_c<policy_traits, Number::value>::type::
+ template policy<Base, Container,
+ boost::intrusive::function_hook<detail::FunctorHook<Hook, Container,
+ Number::value>>>::type
+ type;
};
};
-
- typedef
- typename boost::mpl::transform1<policies_range,
- getPolicy,
- boost::mpl::back_inserter< boost::mpl::vector0<> > >::type policies;
-
-
- typedef detail::multi_policy_container< Base, policies > policy_container;
-
- class type : public policy_container
- {
+
+ typedef typename boost::mpl::transform1<policies_range, getPolicy,
+ boost::mpl::back_inserter<boost::mpl::vector0<>>>::type
+ policies;
+
+ typedef detail::multi_policy_container<Base, policies> policy_container;
+
+ class type : public policy_container {
public:
typedef policy policy_base; // to get access to get_time methods from outside
typedef Container parent_trie;
- type (Base &base)
- : policy_container (base)
+ type(Base& base)
+ : policy_container(base)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
- policy_container::update (item);
+ policy_container::update(item);
}
-
+
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- return policy_container::insert (item);
- }
-
- inline void
- lookup (typename parent_trie::iterator item)
- {
- policy_container::lookup (item);
- }
-
- inline void
- erase (typename parent_trie::iterator item)
- {
- policy_container::erase (item);
- }
-
- inline void
- clear ()
- {
- policy_container::clear ();
+ return policy_container::insert(item);
}
- struct max_size_setter
+ inline void
+ lookup(typename parent_trie::iterator item)
{
- max_size_setter (policy_container &container, size_t size) : m_container (container), m_size (size) { }
-
- template< typename U > void operator() (U index)
+ policy_container::lookup(item);
+ }
+
+ inline void
+ erase(typename parent_trie::iterator item)
+ {
+ policy_container::erase(item);
+ }
+
+ inline void
+ clear()
+ {
+ policy_container::clear();
+ }
+
+ struct max_size_setter {
+ max_size_setter(policy_container& container, size_t size)
+ : m_container(container)
+ , m_size(size)
{
- m_container.template get<U::value> ().set_max_size (m_size);
+ }
+
+ template<typename U>
+ void
+ operator()(U index)
+ {
+ m_container.template get<U::value>().set_max_size(m_size);
}
private:
- policy_container &m_container;
+ policy_container& m_container;
size_t m_size;
};
-
+
inline void
- set_max_size (size_t max_size)
+ set_max_size(size_t max_size)
{
- boost::mpl::for_each< boost::mpl::range_c<int, 0, boost::mpl::size<policy_traits>::type::value> >
- (max_size_setter (*this, max_size));
+ boost::mpl::for_each<boost::mpl::range_c<int, 0,
+ boost::mpl::size<policy_traits>::type::value>>(
+ max_size_setter(*this, max_size));
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
// as max size should be the same everywhere, get the value from the first available policy
- return policy_container::template get<0> ().get_max_size ();
+ return policy_container::template get<0>().get_max_size();
}
-
};
};
-
- struct name_getter
- {
- name_getter (std::string &name) : m_name (name) { }
-
- template< typename U > void operator() (U index)
+ struct name_getter {
+ name_getter(std::string& name)
+ : m_name(name)
{
- if (!m_name.empty ())
- m_name += "::";
- m_name += boost::mpl::at_c< policy_traits, U::value >::type::GetName ();
}
- std::string &m_name;
+ template<typename U>
+ void
+ operator()(U index)
+ {
+ if (!m_name.empty())
+ m_name += "::";
+ m_name += boost::mpl::at_c<policy_traits, U::value>::type::GetName();
+ }
+
+ std::string& m_name;
};
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName ()
+ static std::string
+ GetName()
{
// combine names of all internal policies
std::string name;
- boost::mpl::for_each< boost::mpl::range_c<int, 0, boost::mpl::size<policy_traits>::type::value> > (name_getter (name));
-
+ boost::mpl::for_each<boost::mpl::range_c<int, 0, boost::mpl::size<policy_traits>::type::value>>(
+ name_getter(name));
+
return name;
}
};
diff --git a/utils/trie/payload-policy.hpp b/utils/trie/payload-policy.hpp
index a474afd..9193442 100644
--- a/utils/trie/payload-policy.hpp
+++ b/utils/trie/payload-policy.hpp
@@ -32,96 +32,88 @@
* @brief Traits for policy that keeps items in a sorted order using payload member
*/
template<class Member>
-struct payload_policy_traits
-{
- struct policy_hook_type : public boost::intrusive::set_member_hook<> {};
-
- template<class Container>
- struct container_hook
- {
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+struct payload_policy_traits {
+ struct policy_hook_type : public boost::intrusive::set_member_hook<> {
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- typedef typename boost::intrusive::list< Container, Hook > policy_container;
-
+ template<class Container>
+ struct container_hook {
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ typedef typename boost::intrusive::list<Container, Hook> policy_container;
+
// could be just typedef
- class type : public policy_container
- {
+ class type : public policy_container {
public:
typedef Container parent_trie;
-
- type (Base &base)
- : base_ (base)
- , max_size_ (100)
+
+ type(Base& base)
+ : base_(base)
+ , max_size_(100)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
// do relocation
- policy_container::splice (policy_container::end (),
- *this,
- policy_container::s_iterator_to (*item));
+ policy_container::splice(policy_container::end(), *this,
+ policy_container::s_iterator_to(*item));
}
-
+
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- if (policy_container::size () >= max_size_)
- {
- base_.erase (&(*policy_container::begin ()));
- }
-
- policy_container::push_back (*item);
+ if (policy_container::size() >= max_size_) {
+ base_.erase(&(*policy_container::begin()));
+ }
+
+ policy_container::push_back(*item);
return true;
}
-
+
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
// do relocation
- policy_container::splice (policy_container::end (),
- *this,
- policy_container::s_iterator_to (*item));
- }
-
- inline void
- erase (typename parent_trie::iterator item)
- {
- policy_container::erase (policy_container::s_iterator_to (*item));
+ policy_container::splice(policy_container::end(), *this,
+ policy_container::s_iterator_to(*item));
}
inline void
- clear ()
+ erase(typename parent_trie::iterator item)
{
- policy_container::clear ();
+ policy_container::erase(policy_container::s_iterator_to(*item));
}
inline void
- set_max_size (size_t max_size)
+ clear()
+ {
+ policy_container::clear();
+ }
+
+ inline void
+ set_max_size(size_t max_size)
{
max_size_ = max_size;
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
return max_size_;
}
private:
- type () : base_(*((Base*)0)) { };
+ type()
+ : base_(*((Base*)0)){};
private:
- Base &base_;
+ Base& base_;
size_t max_size_;
};
};
diff --git a/utils/trie/payload-with-policy.hpp b/utils/trie/payload-with-policy.hpp
index 7db278b..4010511 100644
--- a/utils/trie/payload-with-policy.hpp
+++ b/utils/trie/payload-with-policy.hpp
@@ -25,32 +25,29 @@
namespace ndn {
namespace ndnSIM {
-template<typename PayloadTraits,
- typename IndexTraits>
-class payload_with_index
-{
+template<typename PayloadTraits, typename IndexTraits>
+class payload_with_index {
public:
typedef PayloadTraits::pointer_type iterator;
-
- typedef typename IndexTraits::template index<
- PayloadTraits,
- typename IndexTraits::template container_hook<parent_trie>::type >::type index_container;
- inline
- payload_with_index ()
- : index_ (*this)
+ typedef typename IndexTraits::
+ template index<PayloadTraits,
+ typename IndexTraits::template container_hook<parent_trie>::type>::type
+ index_container;
+
+ inline payload_with_index()
+ : index_(*this)
{
}
- inline std::pair< iterator, bool >
- insert (typename iterator payload)
+ inline std::pair<iterator, bool>
+ insert(typename iterator payload)
{
- bool ok = policy_.insert (s_iterator_to (item.first));
- if (!ok)
- {
- item.first->erase (); // cannot insert
- return std::make_pair (end (), false);
- }
+ bool ok = policy_.insert(s_iterator_to(item.first));
+ if (!ok) {
+ item.first->erase(); // cannot insert
+ return std::make_pair(end(), false);
+ }
return item;
}
@@ -61,7 +58,7 @@
// iterator foundItem, lastItem;
// bool reachLast;
// boost::tie (foundItem, reachLast, lastItem) = trie_.find (key);
-
+
// if (!reachLast || lastItem->payload () == PayloadTraits::empty_payload)
// return; // nothing to invalidate
diff --git a/utils/trie/persistent-policy.hpp b/utils/trie/persistent-policy.hpp
index 9b706b0..c8f116c 100644
--- a/utils/trie/persistent-policy.hpp
+++ b/utils/trie/persistent-policy.hpp
@@ -32,84 +32,83 @@
* @brief Traits for persistent replacement policy
*
* In this policy entries are added until there is a space (controlled by set_max_size call).
- * If maximum is reached, new entries will not be added and nothing will be removed from the container
+ * If maximum is reached, new entries will not be added and nothing will be removed from the
+ *container
*/
-struct persistent_policy_traits
-{
+struct persistent_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return "Persistent"; }
-
- struct policy_hook_type : public boost::intrusive::list_member_hook<> {};
-
- template<class Container>
- struct container_hook
+ static std::string
+ GetName()
{
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+ return "Persistent";
+ }
+
+ struct policy_hook_type : public boost::intrusive::list_member_hook<> {
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- typedef typename boost::intrusive::list< Container, Hook > policy_container;
-
+ template<class Container>
+ struct container_hook {
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ typedef typename boost::intrusive::list<Container, Hook> policy_container;
+
// could be just typedef
- class type : public policy_container
- {
+ class type : public policy_container {
public:
typedef Container parent_trie;
-
- type (Base &base)
- : base_ (base)
- , max_size_ (100) // when 0, policy is not enforced
+
+ type(Base& base)
+ : base_(base)
+ , max_size_(100) // when 0, policy is not enforced
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
// do nothing
}
-
+
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- if (max_size_ != 0 && policy_container::size () >= max_size_)
+ if (max_size_ != 0 && policy_container::size() >= max_size_)
return false;
-
- policy_container::push_back (*item);
+
+ policy_container::push_back(*item);
return true;
}
-
+
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
// do nothing
}
-
+
inline void
- erase (typename parent_trie::iterator item)
+ erase(typename parent_trie::iterator item)
{
- policy_container::erase (policy_container::s_iterator_to (*item));
+ policy_container::erase(policy_container::s_iterator_to(*item));
}
inline void
- clear ()
+ clear()
{
- policy_container::clear ();
+ policy_container::clear();
}
inline void
- set_max_size (size_t max_size)
+ set_max_size(size_t max_size)
{
max_size_ = max_size;
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
return max_size_;
}
@@ -118,7 +117,7 @@
// type () : base_(*((Base*)0)) { };
private:
- Base &base_;
+ Base& base_;
size_t max_size_;
};
};
diff --git a/utils/trie/random-policy.hpp b/utils/trie/random-policy.hpp
index 1a7308c..7264bed 100644
--- a/utils/trie/random-policy.hpp
+++ b/utils/trie/random-policy.hpp
@@ -33,130 +33,129 @@
/**
* @brief Traits for random replacement policy
*/
-struct random_policy_traits
-{
+struct random_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
- static std::string GetName () { return "Random"; }
-
- struct policy_hook_type : public boost::intrusive::set_member_hook<> { uint32_t randomOrder; };
-
- template<class Container>
- struct container_hook
+ static std::string
+ GetName()
{
- typedef boost::intrusive::member_hook< Container,
- policy_hook_type,
- &Container::policy_hook_ > type;
+ return "Random";
+ }
+
+ struct policy_hook_type : public boost::intrusive::set_member_hook<> {
+ uint32_t randomOrder;
};
- template<class Base,
- class Container,
- class Hook>
- struct policy
- {
- static uint32_t& get_order (typename Container::iterator item)
+ template<class Container>
+ struct container_hook {
+ typedef boost::intrusive::member_hook<Container, policy_hook_type, &Container::policy_hook_>
+ type;
+ };
+
+ template<class Base, class Container, class Hook>
+ struct policy {
+ static uint32_t&
+ get_order(typename Container::iterator item)
{
- return static_cast<typename policy_container::value_traits::hook_type*>
- (policy_container::value_traits::to_node_ptr(*item))->randomOrder;
+ return static_cast<typename policy_container::value_traits::hook_type*>(
+ policy_container::value_traits::to_node_ptr(*item))->randomOrder;
}
-
- static const uint32_t& get_order (typename Container::const_iterator item)
+
+ static const uint32_t&
+ get_order(typename Container::const_iterator item)
{
- return static_cast<const typename policy_container::value_traits::hook_type*>
- (policy_container::value_traits::to_node_ptr(*item))->randomOrder;
+ return static_cast<const typename policy_container::value_traits::hook_type*>(
+ policy_container::value_traits::to_node_ptr(*item))->randomOrder;
}
-
+
template<class Key>
- struct MemberHookLess
- {
- bool operator () (const Key &a, const Key &b) const
+ struct MemberHookLess {
+ bool
+ operator()(const Key& a, const Key& b) const
{
- return get_order (&a) < get_order (&b);
+ return get_order(&a) < get_order(&b);
}
};
- typedef boost::intrusive::multiset< Container,
- boost::intrusive::compare< MemberHookLess< Container > >,
- Hook > policy_container;
-
+ typedef boost::intrusive::multiset<Container,
+ boost::intrusive::compare<MemberHookLess<Container>>,
+ Hook> policy_container;
+
// could be just typedef
- class type : public policy_container
- {
+ class type : public policy_container {
public:
typedef policy policy_base; // to get access to get_order methods from outside
typedef Container parent_trie;
- type (Base &base)
- : base_ (base)
- , u_rand (0, std::numeric_limits<uint32_t>::max ())
- , max_size_ (100)
+ type(Base& base)
+ : base_(base)
+ , u_rand(0, std::numeric_limits<uint32_t>::max())
+ , max_size_(100)
{
}
inline void
- update (typename parent_trie::iterator item)
+ update(typename parent_trie::iterator item)
{
// do nothing. it's random policy
}
-
+
inline bool
- insert (typename parent_trie::iterator item)
+ insert(typename parent_trie::iterator item)
{
- get_order (item) = u_rand.GetValue ();
+ get_order(item) = u_rand.GetValue();
- if (max_size_ != 0 && policy_container::size () >= max_size_)
- {
- if (MemberHookLess<Container>() (*item, *policy_container::begin ()))
- {
- // std::cout << "Cannot add. Signaling fail\n";
- // just return false. Indicating that insert "failed"
- return false;
- }
- else
- {
- // removing some random element
- base_.erase (&(*policy_container::begin ()));
- }
+ if (max_size_ != 0 && policy_container::size() >= max_size_) {
+ if (MemberHookLess<Container>()(*item, *policy_container::begin())) {
+ // std::cout << "Cannot add. Signaling fail\n";
+ // just return false. Indicating that insert "failed"
+ return false;
}
+ else {
+ // removing some random element
+ base_.erase(&(*policy_container::begin()));
+ }
+ }
- policy_container::insert (*item);
+ policy_container::insert(*item);
return true;
}
-
+
inline void
- lookup (typename parent_trie::iterator item)
+ lookup(typename parent_trie::iterator item)
{
// do nothing. it's random policy
}
-
+
inline void
- erase (typename parent_trie::iterator item)
+ erase(typename parent_trie::iterator item)
{
- policy_container::erase (policy_container::s_iterator_to (*item));
+ policy_container::erase(policy_container::s_iterator_to(*item));
}
inline void
- clear ()
+ clear()
{
- policy_container::clear ();
+ policy_container::clear();
}
inline void
- set_max_size (size_t max_size)
+ set_max_size(size_t max_size)
{
max_size_ = max_size;
}
inline size_t
- get_max_size () const
+ get_max_size() const
{
return max_size_;
}
private:
- type () : base_(*((Base*)0)) { };
-
+ type()
+ : base_(*((Base*)0)){};
+
private:
- Base &base_;
+ Base& base_;
ns3::UniformVariable u_rand;
size_t max_size_;
};
diff --git a/utils/trie/trie-with-policy.hpp b/utils/trie/trie-with-policy.hpp
index f09f13b..790dd0f 100644
--- a/utils/trie/trie-with-policy.hpp
+++ b/utils/trie/trie-with-policy.hpp
@@ -27,93 +27,86 @@
namespace ndn {
namespace ndnSIM {
-template<typename FullKey,
- typename PayloadTraits,
- typename PolicyTraits
- >
-class trie_with_policy
-{
+template<typename FullKey, typename PayloadTraits, typename PolicyTraits>
+class trie_with_policy {
public:
- typedef trie< FullKey,
- PayloadTraits,
- typename PolicyTraits::policy_hook_type > parent_trie;
+ typedef trie<FullKey, PayloadTraits, typename PolicyTraits::policy_hook_type> parent_trie;
typedef typename parent_trie::iterator iterator;
typedef typename parent_trie::const_iterator const_iterator;
- typedef typename PolicyTraits::template policy<
- trie_with_policy<FullKey, PayloadTraits, PolicyTraits>,
- parent_trie,
- typename PolicyTraits::template container_hook<parent_trie>::type >::type policy_container;
+ typedef typename PolicyTraits::
+ template policy<trie_with_policy<FullKey, PayloadTraits, PolicyTraits>, parent_trie,
+ typename PolicyTraits::template container_hook<parent_trie>::type>::type
+ policy_container;
- inline
- trie_with_policy (size_t bucketSize = 1, size_t bucketIncrement = 1)
- : trie_ (name::Component (), bucketSize, bucketIncrement)
- , policy_ (*this)
+ inline trie_with_policy(size_t bucketSize = 1, size_t bucketIncrement = 1)
+ : trie_(name::Component(), bucketSize, bucketIncrement)
+ , policy_(*this)
{
}
- inline std::pair< iterator, bool >
- insert (const FullKey &key, typename PayloadTraits::insert_type payload)
+ inline std::pair<iterator, bool>
+ insert(const FullKey& key, typename PayloadTraits::insert_type payload)
{
- std::pair<iterator, bool> item =
- trie_.insert (key, payload);
+ std::pair<iterator, bool> item = trie_.insert(key, payload);
if (item.second) // real insert
- {
- bool ok = policy_.insert (s_iterator_to (item.first));
- if (!ok)
- {
- item.first->erase (); // cannot insert
- return std::make_pair (end (), false);
- }
+ {
+ bool ok = policy_.insert(s_iterator_to(item.first));
+ if (!ok) {
+ item.first->erase(); // cannot insert
+ return std::make_pair(end(), false);
}
- else
- {
- return std::make_pair (s_iterator_to (item.first), false);
- }
+ }
+ else {
+ return std::make_pair(s_iterator_to(item.first), false);
+ }
return item;
}
inline void
- erase (const FullKey &key)
+ erase(const FullKey& key)
{
iterator foundItem, lastItem;
bool reachLast;
- boost::tie (foundItem, reachLast, lastItem) = trie_.find (key);
+ boost::tie(foundItem, reachLast, lastItem) = trie_.find(key);
- if (!reachLast || lastItem->payload () == PayloadTraits::empty_payload)
+ if (!reachLast || lastItem->payload() == PayloadTraits::empty_payload)
return; // nothing to invalidate
- erase (lastItem);
+ erase(lastItem);
}
inline void
- erase (iterator node)
+ erase(iterator node)
{
- if (node == end ()) return;
+ if (node == end())
+ return;
- policy_.erase (s_iterator_to (node));
- node->erase (); // will do cleanup here
+ policy_.erase(s_iterator_to(node));
+ node->erase(); // will do cleanup here
}
inline void
- clear ()
+ clear()
{
- policy_.clear ();
- trie_.clear ();
+ policy_.clear();
+ trie_.clear();
}
template<typename Modifier>
bool
- modify (iterator position, Modifier mod)
+ modify(iterator position, Modifier mod)
{
- if (position == end ()) return false;
- if (position->payload () == PayloadTraits::empty_payload) return false;
+ if (position == end())
+ return false;
+ if (position->payload() == PayloadTraits::empty_payload)
+ return false;
- mod (*position->payload ());
- policy_.update (position);
+ mod(*position->payload());
+ policy_.update(position);
return true;
}
@@ -121,14 +114,14 @@
* @brief Find a node that has the exact match with the key
*/
inline iterator
- find_exact (const FullKey &key)
+ find_exact(const FullKey& key)
{
iterator foundItem, lastItem;
bool reachLast;
- boost::tie (foundItem, reachLast, lastItem) = trie_.find (key);
+ boost::tie(foundItem, reachLast, lastItem) = trie_.find(key);
- if (!reachLast || lastItem->payload () == PayloadTraits::empty_payload)
- return end ();
+ if (!reachLast || lastItem->payload() == PayloadTraits::empty_payload)
+ return end();
return lastItem;
}
@@ -137,15 +130,14 @@
* @brief Find a node that has the longest common prefix with key (FIB/PIT lookup)
*/
inline iterator
- longest_prefix_match (const FullKey &key)
+ longest_prefix_match(const FullKey& key)
{
iterator foundItem, lastItem;
bool reachLast;
- boost::tie (foundItem, reachLast, lastItem) = trie_.find (key);
- if (foundItem != trie_.end ())
- {
- policy_.lookup (s_iterator_to (foundItem));
- }
+ boost::tie(foundItem, reachLast, lastItem) = trie_.find(key);
+ if (foundItem != trie_.end()) {
+ policy_.lookup(s_iterator_to(foundItem));
+ }
return foundItem;
}
@@ -154,15 +146,14 @@
*/
template<class Predicate>
inline iterator
- longest_prefix_match_if (const FullKey &key, Predicate pred)
+ longest_prefix_match_if(const FullKey& key, Predicate pred)
{
iterator foundItem, lastItem;
bool reachLast;
- boost::tie (foundItem, reachLast, lastItem) = trie_.find_if (key, pred);
- if (foundItem != trie_.end ())
- {
- policy_.lookup (s_iterator_to (foundItem));
- }
+ boost::tie(foundItem, reachLast, lastItem) = trie_.find_if(key, pred);
+ if (foundItem != trie_.end()) {
+ policy_.lookup(s_iterator_to(foundItem));
+ }
return foundItem;
}
@@ -180,29 +171,26 @@
* @brief Find a node that has prefix at least as the key (cache lookup)
*/
inline iterator
- deepest_prefix_match (const FullKey &key)
+ deepest_prefix_match(const FullKey& key)
{
iterator foundItem, lastItem;
bool reachLast;
- boost::tie (foundItem, reachLast, lastItem) = trie_.find (key);
+ boost::tie(foundItem, reachLast, lastItem) = trie_.find(key);
// guard in case we don't have anything in the trie
- if (lastItem == trie_.end ())
- return trie_.end ();
+ if (lastItem == trie_.end())
+ return trie_.end();
- if (reachLast)
- {
- if (foundItem == trie_.end ())
- {
- foundItem = lastItem->find (); // should be something
- }
- policy_.lookup (s_iterator_to (foundItem));
- return foundItem;
+ if (reachLast) {
+ if (foundItem == trie_.end()) {
+ foundItem = lastItem->find(); // should be something
}
- else
- { // couldn't find a node that has prefix at least as key
- return trie_.end ();
- }
+ policy_.lookup(s_iterator_to(foundItem));
+ return foundItem;
+ }
+ else { // couldn't find a node that has prefix at least as key
+ return trie_.end();
+ }
}
/**
@@ -210,30 +198,27 @@
*/
template<class Predicate>
inline iterator
- deepest_prefix_match_if (const FullKey &key, Predicate pred)
+ deepest_prefix_match_if(const FullKey& key, Predicate pred)
{
iterator foundItem, lastItem;
bool reachLast;
- boost::tie (foundItem, reachLast, lastItem) = trie_.find (key);
+ boost::tie(foundItem, reachLast, lastItem) = trie_.find(key);
// guard in case we don't have anything in the trie
- if (lastItem == trie_.end ())
- return trie_.end ();
+ if (lastItem == trie_.end())
+ return trie_.end();
- if (reachLast)
- {
- foundItem = lastItem->find_if (pred); // may or may not find something
- if (foundItem == trie_.end ())
- {
- return trie_.end ();
- }
- policy_.lookup (s_iterator_to (foundItem));
- return foundItem;
+ if (reachLast) {
+ foundItem = lastItem->find_if(pred); // may or may not find something
+ if (foundItem == trie_.end()) {
+ return trie_.end();
}
- else
- { // couldn't find a node that has prefix at least as key
- return trie_.end ();
- }
+ policy_.lookup(s_iterator_to(foundItem));
+ return foundItem;
+ }
+ else { // couldn't find a node that has prefix at least as key
+ return trie_.end();
+ }
}
/**
@@ -244,51 +229,61 @@
*/
template<class Predicate>
inline iterator
- deepest_prefix_match_if_next_level (const FullKey &key, Predicate pred)
+ deepest_prefix_match_if_next_level(const FullKey& key, Predicate pred)
{
iterator foundItem, lastItem;
bool reachLast;
- boost::tie (foundItem, reachLast, lastItem) = trie_.find (key);
+ boost::tie(foundItem, reachLast, lastItem) = trie_.find(key);
// guard in case we don't have anything in the trie
- if (lastItem == trie_.end ())
- return trie_.end ();
+ if (lastItem == trie_.end())
+ return trie_.end();
- if (reachLast)
- {
- foundItem = lastItem->find_if_next_level (pred); // may or may not find something
- if (foundItem == trie_.end ())
- {
- return trie_.end ();
- }
- policy_.lookup (s_iterator_to (foundItem));
- return foundItem;
+ if (reachLast) {
+ foundItem = lastItem->find_if_next_level(pred); // may or may not find something
+ if (foundItem == trie_.end()) {
+ return trie_.end();
}
- else
- { // couldn't find a node that has prefix at least as key
- return trie_.end ();
- }
+ policy_.lookup(s_iterator_to(foundItem));
+ return foundItem;
+ }
+ else { // couldn't find a node that has prefix at least as key
+ return trie_.end();
+ }
}
-
- iterator end () const
+
+ iterator
+ end() const
{
return 0;
}
- const parent_trie &
- getTrie () const { return trie_; }
+ const parent_trie&
+ getTrie() const
+ {
+ return trie_;
+ }
- parent_trie &
- getTrie () { return trie_; }
+ parent_trie&
+ getTrie()
+ {
+ return trie_;
+ }
- const policy_container &
- getPolicy () const { return policy_; }
+ const policy_container&
+ getPolicy() const
+ {
+ return policy_;
+ }
- policy_container &
- getPolicy () { return policy_; }
+ policy_container&
+ getPolicy()
+ {
+ return policy_;
+ }
static inline iterator
- s_iterator_to (typename parent_trie::iterator item)
+ s_iterator_to(typename parent_trie::iterator item)
{
if (item == 0)
return 0;
@@ -297,7 +292,7 @@
}
private:
- parent_trie trie_;
+ parent_trie trie_;
mutable policy_container policy_;
};
diff --git a/utils/trie/trie.hpp b/utils/trie/trie.hpp
index 1e37cbd..9afc8d1 100644
--- a/utils/trie/trie.hpp
+++ b/utils/trie/trie.hpp
@@ -40,33 +40,32 @@
// Allow customization for payload
//
template<typename Payload, typename BasePayload = Payload>
-struct pointer_payload_traits
-{
- typedef Payload payload_type; // general type of the payload
- typedef Payload* storage_type; // how the payload is actually stored
- typedef Payload* insert_type; // what parameter is inserted
+struct pointer_payload_traits {
+ typedef Payload payload_type; // general type of the payload
+ typedef Payload* storage_type; // how the payload is actually stored
+ typedef Payload* insert_type; // what parameter is inserted
- typedef Payload* return_type; // what is returned on access
- typedef const Payload* const_return_type; // what is returned on const access
+ typedef Payload* return_type; // what is returned on access
+ typedef const Payload* const_return_type; // what is returned on const access
- typedef BasePayload* base_type; // base type of the entry (when implementation details need to be hidden)
- typedef const BasePayload* const_base_type; // const base type of the entry (when implementation details need to be hidden)
+ typedef BasePayload*
+ base_type; // base type of the entry (when implementation details need to be hidden)
+ typedef const BasePayload*
+ const_base_type; // const base type of the entry (when implementation details need to be hidden)
static Payload* empty_payload;
};
template<typename Payload, typename BasePayload>
-Payload*
-pointer_payload_traits<Payload, BasePayload>::empty_payload = 0;
+Payload* pointer_payload_traits<Payload, BasePayload>::empty_payload = 0;
template<typename Payload, typename BasePayload = Payload>
-struct smart_pointer_payload_traits
-{
- typedef Payload payload_type;
- typedef ns3::Ptr<Payload> storage_type;
- typedef ns3::Ptr<Payload> insert_type;
+struct smart_pointer_payload_traits {
+ typedef Payload payload_type;
+ typedef ns3::Ptr<Payload> storage_type;
+ typedef ns3::Ptr<Payload> insert_type;
- typedef ns3::Ptr<Payload> return_type;
+ typedef ns3::Ptr<Payload> return_type;
typedef ns3::Ptr<const Payload> const_return_type;
typedef ns3::Ptr<BasePayload> base_type;
@@ -76,51 +75,44 @@
};
template<typename Payload, typename BasePayload>
-ns3::Ptr<Payload>
-smart_pointer_payload_traits<Payload, BasePayload>::empty_payload = 0;
+ns3::Ptr<Payload> smart_pointer_payload_traits<Payload, BasePayload>::empty_payload = 0;
template<typename Payload, typename BasePayload = Payload>
-struct non_pointer_traits
-{
- typedef Payload payload_type;
- typedef Payload storage_type;
- typedef const Payload & insert_type; // nothing to insert
+struct non_pointer_traits {
+ typedef Payload payload_type;
+ typedef Payload storage_type;
+ typedef const Payload& insert_type; // nothing to insert
- typedef Payload& return_type;
- typedef const Payload & const_return_type;
+ typedef Payload& return_type;
+ typedef const Payload& const_return_type;
- typedef BasePayload& base_type;
+ typedef BasePayload& base_type;
typedef const BasePayload& const_base_type;
static Payload empty_payload;
};
template<typename Payload, typename BasePayload>
-Payload
-non_pointer_traits<Payload, BasePayload>::empty_payload = Payload ();
-
+Payload non_pointer_traits<Payload, BasePayload>::empty_payload = Payload();
////////////////////////////////////////////////////
// forward declarations
//
-template<typename FullKey,
- typename PayloadTraits,
- typename PolicyHook >
+template<typename FullKey, typename PayloadTraits, typename PolicyHook>
class trie;
template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline std::ostream&
-operator << (std::ostream &os,
- const trie<FullKey, PayloadTraits, PolicyHook> &trie_node);
+operator<<(std::ostream& os, const trie<FullKey, PayloadTraits, PolicyHook>& trie_node);
template<typename FullKey, typename PayloadTraits, typename PolicyHook>
bool
-operator== (const trie<FullKey, PayloadTraits, PolicyHook> &a,
- const trie<FullKey, PayloadTraits, PolicyHook> &b);
+operator==(const trie<FullKey, PayloadTraits, PolicyHook>& a,
+ const trie<FullKey, PayloadTraits, PolicyHook>& b);
-template<typename FullKey, typename PayloadTraits, typename PolicyHook >
+template<typename FullKey, typename PayloadTraits, typename PolicyHook>
std::size_t
-hash_value (const trie<FullKey, PayloadTraits, PolicyHook> &trie_node);
+hash_value(const trie<FullKey, PayloadTraits, PolicyHook>& trie_node);
///////////////////////////////////////////////////
// actual definition
@@ -131,15 +123,12 @@
template<class T>
class trie_point_iterator;
-template<typename FullKey,
- typename PayloadTraits,
- typename PolicyHook >
-class trie
-{
+template<typename FullKey, typename PayloadTraits, typename PolicyHook>
+class trie {
public:
typedef typename FullKey::partial_type Key;
- typedef trie* iterator;
+ typedef trie* iterator;
typedef const trie* const_iterator;
typedef trie_iterator<trie, trie> recursive_iterator;
@@ -150,126 +139,119 @@
typedef PayloadTraits payload_traits;
- inline
- trie (const Key &key, size_t bucketSize = 1, size_t bucketIncrement = 1)
- : key_ (key)
- , initialBucketSize_ (bucketSize)
- , bucketIncrement_ (bucketIncrement)
- , bucketSize_ (initialBucketSize_)
- , buckets_ (new bucket_type [bucketSize_]) //cannot use normal pointer, because lifetime of buckets should be larger than lifetime of the container
- , children_ (bucket_traits (buckets_.get (), bucketSize_))
- , payload_ (PayloadTraits::empty_payload)
- , parent_ (0)
+ inline trie(const Key& key, size_t bucketSize = 1, size_t bucketIncrement = 1)
+ : key_(key)
+ , initialBucketSize_(bucketSize)
+ , bucketIncrement_(bucketIncrement)
+ , bucketSize_(initialBucketSize_)
+ , buckets_(new bucket_type[bucketSize_]) // cannot use normal pointer, because lifetime of
+ // buckets should be larger than lifetime of the
+ // container
+ , children_(bucket_traits(buckets_.get(), bucketSize_))
+ , payload_(PayloadTraits::empty_payload)
+ , parent_(0)
{
}
- inline
- ~trie ()
+ inline ~trie()
{
payload_ = PayloadTraits::empty_payload; // necessary for smart pointers...
- children_.clear_and_dispose (trie_delete_disposer ());
+ children_.clear_and_dispose(trie_delete_disposer());
}
void
- clear ()
+ clear()
{
- children_.clear_and_dispose (trie_delete_disposer ());
+ children_.clear_and_dispose(trie_delete_disposer());
}
template<class Predicate>
void
- clear_if (Predicate cond)
+ clear_if(Predicate cond)
{
- recursive_iterator trieNode (this);
- recursive_iterator end (0);
+ recursive_iterator trieNode(this);
+ recursive_iterator end(0);
- while (trieNode != end)
- {
- if (cond (*trieNode))
- {
- trieNode = recursive_iterator (trieNode->erase ());
- }
- trieNode ++;
+ while (trieNode != end) {
+ if (cond(*trieNode)) {
+ trieNode = recursive_iterator(trieNode->erase());
}
+ trieNode++;
+ }
}
// actual entry
- friend bool
- operator== <> (const trie<FullKey, PayloadTraits, PolicyHook> &a,
- const trie<FullKey, PayloadTraits, PolicyHook> &b);
+ friend bool operator==<>(const trie<FullKey, PayloadTraits, PolicyHook>& a,
+ const trie<FullKey, PayloadTraits, PolicyHook>& b);
friend std::size_t
- hash_value <> (const trie<FullKey, PayloadTraits, PolicyHook> &trie_node);
+ hash_value<>(const trie<FullKey, PayloadTraits, PolicyHook>& trie_node);
inline std::pair<iterator, bool>
- insert (const FullKey &key,
- typename PayloadTraits::insert_type payload)
+ insert(const FullKey& key, typename PayloadTraits::insert_type payload)
{
- trie *trieNode = this;
+ trie* trieNode = this;
- BOOST_FOREACH (const Key &subkey, key)
- {
- typename unordered_set::iterator item = trieNode->children_.find (subkey);
- if (item == trieNode->children_.end ())
- {
- trie *newNode = new trie (subkey, initialBucketSize_, bucketIncrement_);
- // std::cout << "new " << newNode << "\n";
- newNode->parent_ = trieNode;
+ BOOST_FOREACH (const Key& subkey, key) {
+ typename unordered_set::iterator item = trieNode->children_.find(subkey);
+ if (item == trieNode->children_.end()) {
+ trie* newNode = new trie(subkey, initialBucketSize_, bucketIncrement_);
+ // std::cout << "new " << newNode << "\n";
+ newNode->parent_ = trieNode;
- if (trieNode->children_.size () >= trieNode->bucketSize_)
- {
- trieNode->bucketSize_ += trieNode->bucketIncrement_;
- trieNode->bucketIncrement_ *= 2; // increase bucketIncrement exponentially
+ if (trieNode->children_.size() >= trieNode->bucketSize_) {
+ trieNode->bucketSize_ += trieNode->bucketIncrement_;
+ trieNode->bucketIncrement_ *= 2; // increase bucketIncrement exponentially
- buckets_array newBuckets (new bucket_type [trieNode->bucketSize_]);
- trieNode->children_.rehash (bucket_traits (newBuckets.get (), trieNode->bucketSize_));
- trieNode->buckets_.swap (newBuckets);
- }
+ buckets_array newBuckets(new bucket_type[trieNode->bucketSize_]);
+ trieNode->children_.rehash(bucket_traits(newBuckets.get(), trieNode->bucketSize_));
+ trieNode->buckets_.swap(newBuckets);
+ }
- std::pair< typename unordered_set::iterator, bool > ret =
- trieNode->children_.insert (*newNode);
+ std::pair<typename unordered_set::iterator, bool> ret =
+ trieNode->children_.insert(*newNode);
- trieNode = &(*ret.first);
- }
- else
- trieNode = &(*item);
+ trieNode = &(*ret.first);
}
+ else
+ trieNode = &(*item);
+ }
- if (trieNode->payload_ == PayloadTraits::empty_payload)
- {
- trieNode->payload_ = payload;
- return std::make_pair (trieNode, true);
- }
+ if (trieNode->payload_ == PayloadTraits::empty_payload) {
+ trieNode->payload_ = payload;
+ return std::make_pair(trieNode, true);
+ }
else
- return std::make_pair (trieNode, false);
+ return std::make_pair(trieNode, false);
}
/**
* @brief Removes payload (if it exists) and if there are no children, prunes parents trie
*/
inline iterator
- erase ()
+ erase()
{
payload_ = PayloadTraits::empty_payload;
- return prune ();
+ return prune();
}
/**
* @brief Do exactly as erase, but without erasing the payload
*/
inline iterator
- prune ()
+ prune()
{
- if (payload_ == PayloadTraits::empty_payload &&
- children_.size () == 0)
- {
- if (parent_ == 0) return this;
+ if (payload_ == PayloadTraits::empty_payload && children_.size() == 0) {
+ if (parent_ == 0)
+ return this;
- trie *parent = parent_;
- parent->children_.erase_and_dispose (*this, trie_delete_disposer ()); // delete this; basically, committing a suicide
+ trie* parent = parent_;
+ parent->children_
+ .erase_and_dispose(*this,
+ trie_delete_disposer()); // delete this; basically, committing a suicide
- return parent->prune ();
- }
+ return parent->prune();
+ }
return this;
}
@@ -277,16 +259,17 @@
* @brief Perform prune of the node, but without attempting to parent of the node
*/
inline void
- prune_node ()
+ prune_node()
{
- if (payload_ == PayloadTraits::empty_payload &&
- children_.size () == 0)
- {
- if (parent_ == 0) return;
+ if (payload_ == PayloadTraits::empty_payload && children_.size() == 0) {
+ if (parent_ == 0)
+ return;
- trie *parent = parent_;
- parent->children_.erase_and_dispose (*this, trie_delete_disposer ()); // delete this; basically, committing a suicide
- }
+ trie* parent = parent_;
+ parent->children_
+ .erase_and_dispose(*this,
+ trie_delete_disposer()); // delete this; basically, committing a suicide
+ }
}
// inline boost::tuple<const iterator, bool, const iterator>
@@ -302,30 +285,27 @@
* @return ->second is true if prefix in ->first is longer than key
*/
inline boost::tuple<iterator, bool, iterator>
- find (const FullKey &key)
+ find(const FullKey& key)
{
- trie *trieNode = this;
+ trie* trieNode = this;
iterator foundNode = (payload_ != PayloadTraits::empty_payload) ? this : 0;
bool reachLast = true;
- BOOST_FOREACH (const Key &subkey, key)
- {
- typename unordered_set::iterator item = trieNode->children_.find (subkey);
- if (item == trieNode->children_.end ())
- {
- reachLast = false;
- break;
- }
- else
- {
- trieNode = &(*item);
-
- if (trieNode->payload_ != PayloadTraits::empty_payload)
- foundNode = trieNode;
- }
+ BOOST_FOREACH (const Key& subkey, key) {
+ typename unordered_set::iterator item = trieNode->children_.find(subkey);
+ if (item == trieNode->children_.end()) {
+ reachLast = false;
+ break;
}
+ else {
+ trieNode = &(*item);
- return boost::make_tuple (foundNode, reachLast, trieNode);
+ if (trieNode->payload_ != PayloadTraits::empty_payload)
+ foundNode = trieNode;
+ }
+ }
+
+ return boost::make_tuple(foundNode, reachLast, trieNode);
}
/**
@@ -336,55 +316,50 @@
*/
template<class Predicate>
inline boost::tuple<iterator, bool, iterator>
- find_if (const FullKey &key, Predicate pred)
+ find_if(const FullKey& key, Predicate pred)
{
- trie *trieNode = this;
+ trie* trieNode = this;
iterator foundNode = (payload_ != PayloadTraits::empty_payload) ? this : 0;
bool reachLast = true;
- BOOST_FOREACH (const Key &subkey, key)
- {
- typename unordered_set::iterator item = trieNode->children_.find (subkey);
- if (item == trieNode->children_.end ())
- {
- reachLast = false;
- break;
- }
- else
- {
- trieNode = &(*item);
-
- if (trieNode->payload_ != PayloadTraits::empty_payload &&
- pred (trieNode->payload_))
- {
- foundNode = trieNode;
- }
- }
+ BOOST_FOREACH (const Key& subkey, key) {
+ typename unordered_set::iterator item = trieNode->children_.find(subkey);
+ if (item == trieNode->children_.end()) {
+ reachLast = false;
+ break;
}
+ else {
+ trieNode = &(*item);
- return boost::make_tuple (foundNode, reachLast, trieNode);
+ if (trieNode->payload_ != PayloadTraits::empty_payload && pred(trieNode->payload_)) {
+ foundNode = trieNode;
+ }
+ }
+ }
+
+ return boost::make_tuple(foundNode, reachLast, trieNode);
}
/**
* @brief Find next payload of the sub-trie
- * @returns end() or a valid iterator pointing to the trie leaf (order is not defined, enumeration )
+ * @returns end() or a valid iterator pointing to the trie leaf (order is not defined, enumeration
+ * )
*/
inline iterator
- find ()
+ find()
{
if (payload_ != PayloadTraits::empty_payload)
return this;
typedef trie<FullKey, PayloadTraits, PolicyHook> trie;
- for (typename trie::unordered_set::iterator subnode = children_.begin ();
- subnode != children_.end ();
- subnode++ )
- // BOOST_FOREACH (trie &subnode, children_)
- {
- iterator value = subnode->find ();
- if (value != 0)
- return value;
- }
+ for (typename trie::unordered_set::iterator subnode = children_.begin();
+ subnode != children_.end(); subnode++)
+ // BOOST_FOREACH (trie &subnode, children_)
+ {
+ iterator value = subnode->find();
+ if (value != 0)
+ return value;
+ }
return 0;
}
@@ -392,25 +367,25 @@
/**
* @brief Find next payload of the sub-trie satisfying the predicate
* @param pred predicate
- * @returns end() or a valid iterator pointing to the trie leaf (order is not defined, enumeration )
+ * @returns end() or a valid iterator pointing to the trie leaf (order is not defined, enumeration
+ * )
*/
template<class Predicate>
inline const iterator
- find_if (Predicate pred)
+ find_if(Predicate pred)
{
- if (payload_ != PayloadTraits::empty_payload && pred (payload_))
+ if (payload_ != PayloadTraits::empty_payload && pred(payload_))
return this;
typedef trie<FullKey, PayloadTraits, PolicyHook> trie;
- for (typename trie::unordered_set::iterator subnode = children_.begin ();
- subnode != children_.end ();
- subnode++ )
- // BOOST_FOREACH (const trie &subnode, children_)
- {
- iterator value = subnode->find_if (pred);
- if (value != 0)
- return value;
- }
+ for (typename trie::unordered_set::iterator subnode = children_.begin();
+ subnode != children_.end(); subnode++)
+ // BOOST_FOREACH (const trie &subnode, children_)
+ {
+ iterator value = subnode->find_if(pred);
+ if (value != 0)
+ return value;
+ }
return 0;
}
@@ -421,84 +396,83 @@
*
* This version check predicate only for the next level children
*
- * @returns end() or a valid iterator pointing to the trie leaf (order is not defined, enumeration )
+ * @returns end() or a valid iterator pointing to the trie leaf (order is not defined, enumeration
+ *)
*/
template<class Predicate>
inline const iterator
- find_if_next_level (Predicate pred)
+ find_if_next_level(Predicate pred)
{
typedef trie<FullKey, PayloadTraits, PolicyHook> trie;
- for (typename trie::unordered_set::iterator subnode = children_.begin ();
- subnode != children_.end ();
- subnode++ )
- {
- if (pred (subnode->key ()))
- {
- return subnode->find ();
- }
+ for (typename trie::unordered_set::iterator subnode = children_.begin();
+ subnode != children_.end(); subnode++) {
+ if (pred(subnode->key())) {
+ return subnode->find();
}
+ }
return 0;
}
- iterator end ()
+ iterator
+ end()
{
return 0;
}
- const_iterator end () const
+ const_iterator
+ end() const
{
return 0;
}
typename PayloadTraits::const_return_type
- payload () const
+ payload() const
{
return payload_;
}
typename PayloadTraits::return_type
- payload ()
+ payload()
{
return payload_;
}
void
- set_payload (typename PayloadTraits::insert_type payload)
+ set_payload(typename PayloadTraits::insert_type payload)
{
payload_ = payload;
}
- Key key () const
+ Key
+ key() const
{
return key_;
}
inline void
- PrintStat (std::ostream &os) const;
+ PrintStat(std::ostream& os) const;
private:
- //The disposer object function
- struct trie_delete_disposer
- {
- void operator() (trie *delete_this)
+ // The disposer object function
+ struct trie_delete_disposer {
+ void
+ operator()(trie* delete_this)
{
delete delete_this;
}
};
template<class D>
- struct array_disposer
- {
- void operator() (D *array)
+ struct array_disposer {
+ void
+ operator()(D* array)
{
- delete [] array;
+ delete[] array;
}
};
- friend
- std::ostream&
- operator<< < > (std::ostream &os, const trie &trie_node);
+ friend std::ostream& operator<<<>(std::ostream& os, const trie& trie_node);
public:
PolicyHook policy_hook_;
@@ -508,12 +482,11 @@
// necessary typedefs
typedef trie self_type;
- typedef boost::intrusive::member_hook< trie,
- boost::intrusive::unordered_set_member_hook< >,
- &trie::unordered_set_member_hook_ > member_hook;
+ typedef boost::intrusive::member_hook<trie, boost::intrusive::unordered_set_member_hook<>,
+ &trie::unordered_set_member_hook_> member_hook;
- typedef boost::intrusive::unordered_set< trie, member_hook > unordered_set;
- typedef typename unordered_set::bucket_type bucket_type;
+ typedef boost::intrusive::unordered_set<trie, member_hook> unordered_set;
+ typedef typename unordered_set::bucket_type bucket_type;
typedef typename unordered_set::bucket_traits bucket_traits;
template<class T, class NonConstT>
@@ -532,204 +505,267 @@
size_t bucketIncrement_;
size_t bucketSize_;
- typedef boost::interprocess::unique_ptr< bucket_type, array_disposer<bucket_type> > buckets_array;
+ typedef boost::interprocess::unique_ptr<bucket_type, array_disposer<bucket_type>> buckets_array;
buckets_array buckets_;
unordered_set children_;
typename PayloadTraits::storage_type payload_;
- trie *parent_; // to make cleaning effective
+ trie* parent_; // to make cleaning effective
};
-
-
-
template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline std::ostream&
-operator << (std::ostream &os, const trie<FullKey, PayloadTraits, PolicyHook> &trie_node)
+operator<<(std::ostream& os, const trie<FullKey, PayloadTraits, PolicyHook>& trie_node)
{
- os << "# " << trie_node.key_ << ((trie_node.payload_ != PayloadTraits::empty_payload)?"*":"") << std::endl;
+ os << "# " << trie_node.key_ << ((trie_node.payload_ != PayloadTraits::empty_payload) ? "*" : "")
+ << std::endl;
typedef trie<FullKey, PayloadTraits, PolicyHook> trie;
- for (typename trie::unordered_set::const_iterator subnode = trie_node.children_.begin ();
- subnode != trie_node.children_.end ();
- subnode++ )
+ for (typename trie::unordered_set::const_iterator subnode = trie_node.children_.begin();
+ subnode != trie_node.children_.end(); subnode++)
// BOOST_FOREACH (const trie &subnode, trie_node.children_)
- {
- os << "\"" << &trie_node << "\"" << " [label=\"" << trie_node.key_ << ((trie_node.payload_ != PayloadTraits::empty_payload)?"*":"") << "\"]\n";
- os << "\"" << &(*subnode) << "\"" << " [label=\"" << subnode->key_ << ((subnode->payload_ != PayloadTraits::empty_payload)?"*":"") << "\"]""\n";
+ {
+ os << "\"" << &trie_node << "\""
+ << " [label=\"" << trie_node.key_
+ << ((trie_node.payload_ != PayloadTraits::empty_payload) ? "*" : "") << "\"]\n";
+ os << "\"" << &(*subnode) << "\""
+ << " [label=\"" << subnode->key_
+ << ((subnode->payload_ != PayloadTraits::empty_payload) ? "*" : "") << "\"]"
+ "\n";
- os << "\"" << &trie_node << "\"" << " -> " << "\"" << &(*subnode) << "\"" << "\n";
- os << *subnode;
- }
+ os << "\"" << &trie_node << "\""
+ << " -> "
+ << "\"" << &(*subnode) << "\""
+ << "\n";
+ os << *subnode;
+ }
return os;
}
template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline void
-trie<FullKey, PayloadTraits, PolicyHook>
-::PrintStat (std::ostream &os) const
+trie<FullKey, PayloadTraits, PolicyHook>::PrintStat(std::ostream& os) const
{
- os << "# " << key_ << ((payload_ != PayloadTraits::empty_payload)?"*":"") << ": " << children_.size() << " children" << std::endl;
- for (size_t bucket = 0, maxbucket = children_.bucket_count ();
- bucket < maxbucket;
- bucket++)
- {
- os << " " << children_.bucket_size (bucket);
- }
+ os << "# " << key_ << ((payload_ != PayloadTraits::empty_payload) ? "*" : "") << ": "
+ << children_.size() << " children" << std::endl;
+ for (size_t bucket = 0, maxbucket = children_.bucket_count(); bucket < maxbucket; bucket++) {
+ os << " " << children_.bucket_size(bucket);
+ }
os << "\n";
typedef trie<FullKey, PayloadTraits, PolicyHook> trie;
- for (typename trie::unordered_set::const_iterator subnode = children_.begin ();
- subnode != children_.end ();
- subnode++ )
+ for (typename trie::unordered_set::const_iterator subnode = children_.begin();
+ subnode != children_.end(); subnode++)
// BOOST_FOREACH (const trie &subnode, children_)
- {
- subnode->PrintStat (os);
- }
+ {
+ subnode->PrintStat(os);
+ }
}
-
template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline bool
-operator == (const trie<FullKey, PayloadTraits, PolicyHook> &a,
- const trie<FullKey, PayloadTraits, PolicyHook> &b)
+operator==(const trie<FullKey, PayloadTraits, PolicyHook>& a,
+ const trie<FullKey, PayloadTraits, PolicyHook>& b)
{
return a.key_ == b.key_;
}
template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline std::size_t
-hash_value (const trie<FullKey, PayloadTraits, PolicyHook> &trie_node)
+hash_value(const trie<FullKey, PayloadTraits, PolicyHook>& trie_node)
{
- return boost::hash_value (trie_node.key_);
+ return boost::hash_value(trie_node.key_);
}
-
-
template<class Trie, class NonConstTrie> // hack for boost < 1.47
-class trie_iterator
-{
+class trie_iterator {
public:
- trie_iterator () : trie_ (0) {}
- trie_iterator (typename Trie::iterator item) : trie_ (item) {}
- trie_iterator (Trie &item) : trie_ (&item) {}
-
- Trie & operator* () { return *trie_; }
- const Trie & operator* () const { return *trie_; }
- Trie * operator-> () { return trie_; }
- const Trie * operator-> () const { return trie_; }
- bool operator== (trie_iterator<const Trie, NonConstTrie> &other) const { return (trie_ == other.trie_); }
- bool operator== (trie_iterator<Trie, NonConstTrie> &other) { return (trie_ == other.trie_); }
- bool operator!= (trie_iterator<const Trie, NonConstTrie> &other) const { return !(*this == other); }
- bool operator!= (trie_iterator<Trie, NonConstTrie> &other) { return !(*this == other); }
-
- trie_iterator<Trie,NonConstTrie> &
- operator++ (int)
+ trie_iterator()
+ : trie_(0)
{
- if (trie_->children_.size () > 0)
- trie_ = &(*trie_->children_.begin ());
+ }
+ trie_iterator(typename Trie::iterator item)
+ : trie_(item)
+ {
+ }
+ trie_iterator(Trie& item)
+ : trie_(&item)
+ {
+ }
+
+ Trie& operator*()
+ {
+ return *trie_;
+ }
+ const Trie& operator*() const
+ {
+ return *trie_;
+ }
+ Trie* operator->()
+ {
+ return trie_;
+ }
+ const Trie* operator->() const
+ {
+ return trie_;
+ }
+ bool
+ operator==(trie_iterator<const Trie, NonConstTrie>& other) const
+ {
+ return (trie_ == other.trie_);
+ }
+ bool
+ operator==(trie_iterator<Trie, NonConstTrie>& other)
+ {
+ return (trie_ == other.trie_);
+ }
+ bool
+ operator!=(trie_iterator<const Trie, NonConstTrie>& other) const
+ {
+ return !(*this == other);
+ }
+ bool
+ operator!=(trie_iterator<Trie, NonConstTrie>& other)
+ {
+ return !(*this == other);
+ }
+
+ trie_iterator<Trie, NonConstTrie>&
+ operator++(int)
+ {
+ if (trie_->children_.size() > 0)
+ trie_ = &(*trie_->children_.begin());
else
- trie_ = goUp ();
+ trie_ = goUp();
return *this;
}
- trie_iterator<Trie,NonConstTrie> &
- operator++ ()
+ trie_iterator<Trie, NonConstTrie>&
+ operator++()
{
(*this)++;
return *this;
}
private:
- typedef typename boost::mpl::if_< boost::is_same<Trie, NonConstTrie>,
- typename Trie::unordered_set::iterator,
- typename Trie::unordered_set::const_iterator>::type set_iterator;
+ typedef typename boost::mpl::if_<boost::is_same<Trie, NonConstTrie>,
+ typename Trie::unordered_set::iterator,
+ typename Trie::unordered_set::const_iterator>::type set_iterator;
- Trie* goUp ()
+ Trie*
+ goUp()
{
- if (trie_->parent_ != 0)
- {
- // typename Trie::unordered_set::iterator item =
- set_iterator item = const_cast<NonConstTrie*>(trie_)->parent_->children_.iterator_to (const_cast<NonConstTrie&> (*trie_));
- item++;
- if (item != trie_->parent_->children_.end ())
- {
- return &(*item);
- }
- else
- {
- trie_ = trie_->parent_;
- return goUp ();
- }
+ if (trie_->parent_ != 0) {
+ // typename Trie::unordered_set::iterator item =
+ set_iterator item = const_cast<NonConstTrie*>(trie_)
+ ->parent_->children_.iterator_to(const_cast<NonConstTrie&>(*trie_));
+ item++;
+ if (item != trie_->parent_->children_.end()) {
+ return &(*item);
}
+ else {
+ trie_ = trie_->parent_;
+ return goUp();
+ }
+ }
else
return 0;
}
+
private:
- Trie *trie_;
+ Trie* trie_;
};
-
template<class Trie>
-class trie_point_iterator
-{
+class trie_point_iterator {
private:
- typedef typename boost::mpl::if_< boost::is_same<Trie, const Trie>,
- typename Trie::unordered_set::const_iterator,
- typename Trie::unordered_set::iterator>::type set_iterator;
+ typedef typename boost::mpl::if_<boost::is_same<Trie, const Trie>,
+ typename Trie::unordered_set::const_iterator,
+ typename Trie::unordered_set::iterator>::type set_iterator;
public:
- trie_point_iterator () : trie_ (0) {}
- trie_point_iterator (typename Trie::iterator item) : trie_ (item) {}
- trie_point_iterator (Trie &item)
+ trie_point_iterator()
+ : trie_(0)
{
- if (item.children_.size () != 0)
- trie_ = &*item.children_.begin ();
+ }
+ trie_point_iterator(typename Trie::iterator item)
+ : trie_(item)
+ {
+ }
+ trie_point_iterator(Trie& item)
+ {
+ if (item.children_.size() != 0)
+ trie_ = &*item.children_.begin();
else
trie_ = 0;
}
- Trie & operator* () { return *trie_; }
- const Trie & operator* () const { return *trie_; }
- Trie * operator-> () { return trie_; }
- const Trie * operator-> () const { return trie_; }
- bool operator== (trie_point_iterator<const Trie> &other) const { return (trie_ == other.trie_); }
- bool operator== (trie_point_iterator<Trie> &other) { return (trie_ == other.trie_); }
- bool operator!= (trie_point_iterator<const Trie> &other) const { return !(*this == other); }
- bool operator!= (trie_point_iterator<Trie> &other) { return !(*this == other); }
-
- trie_point_iterator<Trie> &
- operator++ (int)
+ Trie& operator*()
{
- if (trie_->parent_ != 0)
- {
- set_iterator item = trie_->parent_->children_.iterator_to (*trie_);
- item ++;
- if (item == trie_->parent_->children_.end ())
- trie_ = 0;
- else
- trie_ = &*item;
- }
- else
- {
+ return *trie_;
+ }
+ const Trie& operator*() const
+ {
+ return *trie_;
+ }
+ Trie* operator->()
+ {
+ return trie_;
+ }
+ const Trie* operator->() const
+ {
+ return trie_;
+ }
+ bool
+ operator==(trie_point_iterator<const Trie>& other) const
+ {
+ return (trie_ == other.trie_);
+ }
+ bool
+ operator==(trie_point_iterator<Trie>& other)
+ {
+ return (trie_ == other.trie_);
+ }
+ bool
+ operator!=(trie_point_iterator<const Trie>& other) const
+ {
+ return !(*this == other);
+ }
+ bool
+ operator!=(trie_point_iterator<Trie>& other)
+ {
+ return !(*this == other);
+ }
+
+ trie_point_iterator<Trie>&
+ operator++(int)
+ {
+ if (trie_->parent_ != 0) {
+ set_iterator item = trie_->parent_->children_.iterator_to(*trie_);
+ item++;
+ if (item == trie_->parent_->children_.end())
trie_ = 0;
- }
+ else
+ trie_ = &*item;
+ }
+ else {
+ trie_ = 0;
+ }
return *this;
}
- trie_point_iterator<Trie> &
- operator++ ()
+ trie_point_iterator<Trie>&
+ operator++()
{
(*this)++;
return *this;
}
private:
- Trie *trie_;
+ Trie* trie_;
};
-
} // ndnSIM
} // ndn
} // ns3