hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
778122422bce87c04baa208e6888ee0fbeeb696a | 148 | cpp | C++ | Programacion Competitiva/Practicas/11_18/minimal_falling_path_sum.cpp | Angel1612/Computer_Science_UNSA | e1696fd2cb7c66f6af9aa14dbd96b4f67c787425 | [
"MIT"
] | null | null | null | Programacion Competitiva/Practicas/11_18/minimal_falling_path_sum.cpp | Angel1612/Computer_Science_UNSA | e1696fd2cb7c66f6af9aa14dbd96b4f67c787425 | [
"MIT"
] | null | null | null | Programacion Competitiva/Practicas/11_18/minimal_falling_path_sum.cpp | Angel1612/Computer_Science_UNSA | e1696fd2cb7c66f6af9aa14dbd96b4f67c787425 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
//solution Minimum Falling Path Sum II
| 16.444444 | 39 | 0.77027 | [
"vector"
] |
778a33d36d2880e507458f8575c221c0301eeaee | 4,521 | ipp | C++ | include/External/stlib/packages/geom/mesh/simplicial/file_io.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/geom/mesh/simplicial/file_io.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/geom/mesh/simplicial/file_io.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | // -*- C++ -*-
#if !defined(__geom_mesh_simplicial_file_io_ipp__)
#error This file is an implementation detail.
#endif
namespace geom {
//! Write a mesh as an indexed simplex set in ascii format.
template < std::size_t N, std::size_t M, typename T,
template<class> class Node,
template<class> class Cell,
template<class, class> class Cont >
inline
void
writeAscii(std::ostream& out, const SimpMeshRed<N, M, T, Node, Cell, Cont>& x) {
// Set the vertex identifiers.
x.setNodeIdentifiers();
writeIssAscii<N, M>(out, x.getVerticesBeginning(), x.getVerticesEnd(),
x.getIndexedSimplicesBeginning(),
x.getIndexedSimplicesEnd());
}
//! Print detailed information about the mesh.
template < std::size_t N, std::size_t M, typename T,
template<class> class Node,
template<class> class Cell,
template<class, class> class Cont >
inline
void
print(std::ostream& out, const SimpMeshRed<N, M, T, Node, Cell, Cont>& x) {
typedef SimpMeshRed<N, M, T, Node, Cell, Cont> SMR;
typedef typename SMR::NodeConstIterator NodeConstIterator;
typedef typename SMR::CellConstIterator CellConstIterator;
// Set the vertex identifiers and cell identifiers.
x.setNodeIdentifiers();
x.setCellIdentifiers();
// Write the nodes.
out << "Nodes:\n";
for (NodeConstIterator i = x.getNodesBeginning(); i != x.getNodesEnd();
++i) {
i->put(out);
}
// Write the indexed cells.
out << "Cells:\n";
for (CellConstIterator i = x.getCellsBeginning(); i != x.getCellsEnd();
++i) {
i->put(out);
}
}
//! Write a mesh as an indexed simplex set in binary format.
template < std::size_t N, std::size_t M, typename T,
template<class> class Node,
template<class> class Cell,
template<class, class> class Cont >
void
writeBinary(std::ostream& out, const SimpMeshRed<N, M, T, Node, Cell, Cont>& x) {
// Set the vertex identifiers.
x.setNodeIdentifiers();
writeIssBinary<N, M>(out, x.getVerticesBeginning(), x.getVerticesEnd(),
x.getIndexedSimplicesBeginning(),
x.getIndexedSimplicesEnd());
}
//! Read a mesh as an indexed simplex set in ascii format.
template < std::size_t N, std::size_t M, typename T,
template<class> class Node,
template<class> class Cell,
template<class, class> class Cont >
inline
void
readAscii(std::istream& in, SimpMeshRed<N, M, T, Node, Cell, Cont>* x) {
// Read an indexed simplex set.
IndSimpSet<N, M, T> iss;
readAscii(in, &iss);
// Build the mesh from the indexed simplex set.
x->build(iss);
}
//! Read an indexed simplex set in binary format.
template < std::size_t N, std::size_t M, typename T,
template<class> class Node,
template<class> class Cell,
template<class, class> class Cont >
inline
void
readBinary(std::istream& in, SimpMeshRed<N, M, T, Node, Cell, Cont>* x) {
// Read an indexed simplex set.
IndSimpSet<N, M, T> iss;
readBinary(in, &iss);
// Build the mesh from the indexed simplex set.
x->build(iss);
}
//! Write in VTK XML unstructured grid format.
template < std::size_t N, std::size_t M, typename T,
template<class> class Node,
template<class> class Cell,
template<class, class> class Cont >
inline
void
writeVtkXml(std::ostream& out, const SimpMeshRed<N, M, T, Node, Cell, Cont>& x) {
// Set the vertex identifiers.
x.setNodeIdentifiers();
writeIssVtkXml<N, M>(out, x.getVerticesBeginning(), x.getVerticesEnd(),
x.getIndexedSimplicesBeginning(),
x.getIndexedSimplicesEnd());
}
//! Write in legacy VTK unstructured grid format.
template < std::size_t N, std::size_t M, typename T,
template<class> class Node,
template<class> class Cell,
template<class, class> class Cont >
inline
void
writeVtkLegacy(std::ostream& out,
const SimpMeshRed<N, M, T, Node, Cell, Cont>& x,
std::string title) {
// Set the vertex identifiers.
x.setNodeIdentifiers();
writeIssVtkLegacy<N, M>(out, x.getVerticesBeginning(), x.getVerticesEnd(),
x.getIndexedSimplicesBeginning(),
x.getIndexedSimplicesEnd(), title);
}
} // namespace geom
| 31.838028 | 82 | 0.616899 | [
"mesh"
] |
778b33c5efb30fe88b297e03f59fa1c634d5d6fd | 1,233 | cpp | C++ | android-31/android/text/method/ReplacementTransformationMethod.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/text/method/ReplacementTransformationMethod.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/text/method/ReplacementTransformationMethod.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JCharArray.hpp"
#include "../../graphics/Rect.hpp"
#include "../../view/View.hpp"
#include "../../../JString.hpp"
#include "./ReplacementTransformationMethod.hpp"
namespace android::text::method
{
// Fields
// QJniObject forward
ReplacementTransformationMethod::ReplacementTransformationMethod(QJniObject obj) : JObject(obj) {}
// Constructors
ReplacementTransformationMethod::ReplacementTransformationMethod()
: JObject(
"android.text.method.ReplacementTransformationMethod",
"()V"
) {}
// Methods
JString ReplacementTransformationMethod::getTransformation(JString arg0, android::view::View arg1) const
{
return callObjectMethod(
"getTransformation",
"(Ljava/lang/CharSequence;Landroid/view/View;)Ljava/lang/CharSequence;",
arg0.object<jstring>(),
arg1.object()
);
}
void ReplacementTransformationMethod::onFocusChanged(android::view::View arg0, JString arg1, jboolean arg2, jint arg3, android::graphics::Rect arg4) const
{
callMethod<void>(
"onFocusChanged",
"(Landroid/view/View;Ljava/lang/CharSequence;ZILandroid/graphics/Rect;)V",
arg0.object(),
arg1.object<jstring>(),
arg2,
arg3,
arg4.object()
);
}
} // namespace android::text::method
| 27.4 | 155 | 0.721006 | [
"object"
] |
778d18763fe7168bb3c7b0ff15a3e778ce30b49e | 7,895 | cpp | C++ | codeforces/543d.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | 1 | 2020-04-04T14:56:12.000Z | 2020-04-04T14:56:12.000Z | codeforces/543d.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | codeforces/543d.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007; // 998244353; // 998244853;
template <typename T>
struct modular {
constexpr modular() : val(0){}
constexpr modular(const modular<T>& _m) : val(_m.val) {}
template <typename U> constexpr modular(const U& _r = U()) {
val = -MOD <= _r && _r < MOD ? _r: _r % MOD;
if (val < 0) { val += MOD; } }
const T operator()() { return val; }
template <typename U> explicit operator U() const { return static_cast<U>(val); }
modular<T>& operator+=(const modular<T>& _m) { if ((val += _m.val) >= MOD) { val -= MOD; } return *this; }
modular<T>& operator-=(const modular<T>& _m) { if ((val -= _m.val) < 0) { val += MOD; } return *this; }
modular<T>& operator*=(const modular<T>& _m) { val = modular<T>(static_cast<int64_t>(val) * static_cast<int64_t>(_m.val)).val; return *this; }
modular<T>& operator/=(const modular<T>& _m) {
T a = _m.val, b = MOD, u = 0, v = 1;
while (a != 0) {
T q = b / a;
b -= q * a; swap(a, b);
u -= q * v; swap(u, v);
} return *this *= u; }
modular<T>& operator =(const modular<T>& _m) { val = _m.val; return *this; }
template <typename U> modular<T>& operator+=(const U& _r) { return *this += modular<T>(_r); }
template <typename U> modular<T>& operator-=(const U& _r) { return *this -= modular<T>(_r); }
template <typename U> modular<T>& operator*=(const U& _r) { return *this *= modular<T>(_r); }
template <typename U> modular<T>& operator/=(const U& _r) { return *this /= modular<T>(_r); }
template <typename U> modular<T>& operator =(const U& _r) { val = modular<T>(_r).val; return *this; }
modular<T> operator-() { return modular<T>(-val); }
template <typename U> friend bool operator==(const modular<U>&, const modular<U>&);
friend std::istream& operator>>(std::istream& os, modular<T>& _m) { os >> _m.val; _m *= 1; return os; }
friend std::ostream& operator<<(std::ostream& os, const modular<T>& _m) { return os << _m.val; }
template <typename U>
modular<T> exp(U e) {
modular<T> res = 1;
modular<T> b = val;
if (e < 0) { b = 1/b; e *= -1; }
for (; e; e >>= 1) {
if (e & 1) { res *= b; }
b *= b;
} return res; }
private:
T val;
};
template <typename T> inline modular<T> operator+(const modular<T>& _lhs, const modular<T>& _rhs) { return modular<T>(_lhs) += _rhs; }
template <typename T, typename U> inline modular<T> operator+(const modular<T>& _lhs, const U& _rhs) { return modular<T>(_lhs) += _rhs; }
template <typename T, typename U> inline modular<T> operator+(const U& _lhs, const modular<T>& _rhs) { return modular<T>(_lhs) += _rhs; }
template <typename T> inline modular<T> operator-(const modular<T>& _lhs, const modular<T>& _rhs) { return modular<T>(_lhs) -= _rhs; }
template <typename T, typename U> inline modular<T> operator-(const modular<T>& _lhs, const U& _rhs) { return modular<T>(_lhs) -= _rhs; }
template <typename T, typename U> inline modular<T> operator-(const U& _lhs, const modular<T>& _rhs) { return modular<T>(_lhs) -= _rhs; }
template <typename T> inline modular<T> operator*(const modular<T>& _lhs, const modular<T>& _rhs) { return modular<T>(_lhs) *= _rhs; }
template <typename T, typename U> inline modular<T> operator*(const modular<T>& _lhs, const U& _rhs) { return modular<T>(_lhs) *= _rhs; }
template <typename T, typename U> inline modular<T> operator*(const U& _lhs, const modular<T>& _rhs) { return modular<T>(_lhs) *= _rhs; }
template <typename T> inline modular<T> operator/(const modular<T>& _lhs, const modular<T>& _rhs) { return modular<T>(_lhs) /= _rhs; }
template <typename T, typename U> inline modular<T> operator/(const modular<T>& _lhs, const U& _rhs) { return modular<T>(_lhs) /= _rhs; }
template <typename T, typename U> inline modular<T> operator/(const U& _lhs, const modular<T>& _rhs) { return modular<T>(_lhs) /= _rhs; }
template <typename T> inline bool operator==(const modular<T>& _lhs, const modular<T>& _rhs) { return _lhs.val == _rhs.val; }
template <typename T, typename U> inline bool operator==(const modular<T>& _lhs, const U& _rhs) { return _lhs == modular<T>(_rhs); }
template <typename T, typename U> inline bool operator==(const U& _lhs, const modular<T>& _rhs) { return modular<T>(_lhs) == _rhs; }
template <typename T> inline bool operator!=(const modular<T>& _lhs, const modular<T>& _rhs) { return !(_lhs == _rhs); }
template <typename T, typename U> inline bool operator!=(const modular<T>& _lhs, const U& _rhs) { return !(_lhs == _rhs); }
template <typename T, typename U> inline bool operator!=(const U& _lhs, const modular<T>& _rhs) { return !(_lhs == _rhs); }
typedef modular<int> mint;
void __solve() {
int n; cin >> n;
vector<int> pa(n); pa[0]=-1;
vector<vector<int>> g(n);
for (int i = 1; i < n; i++) {
int x; cin >> x; x--;
pa[i] = x;
g[x].push_back(i);
}
vector<array<mint,2>> dn(n); // [k] any sub path, #bad<=k
for (int u = n-1; u >= 0; u--) {
mint x = 1, z = 1;
for (int v: g[u]){
x *= dn[v][0] + dn[v][1];
z *= dn[v][0];
}
dn[u][0] = z;
dn[u][1] = x;
}
vector<array<mint,2>> up(n);
up[0][0] = up[0][1] = 1;
for (int u = 0; u < n; u++) {
int m = g[u].size();
// no divide, might /P=0
{
vector<mint> pref(m + 1), suff(m + 1);
pref[0] = suff[m] = 1;
for (int i = 0; i < m; i++) {
pref[i+1] = pref[i] * dn[g[u][i]][0];
}
for (int i = m-1; i >= 0; i--) {
suff[i] = suff[i+1] * dn[g[u][i]][0];
}
for (int i = 0; i < m; i++) {
int v = g[u][i];
up[v][0] = up[u][0] * pref[i] * suff[i+1];
}
}
{
vector<mint> pref(m + 1), suff(m + 1);
pref[0] = suff[m] = 1;
for (int i = 0; i < m; i++) {
pref[i+1] = pref[i] * (dn[g[u][i]][0] + dn[g[u][i]][1]);
}
for (int i = m-1; i >= 0; i--) {
suff[i] = suff[i+1] * (dn[g[u][i]][0] + dn[g[u][i]][1]);
}
for (int i = 0; i < m; i++) {
int v = g[u][i];
up[v][1] = up[v][0] + up[u][1] * pref[i] * suff[i+1];
}
}
}
for (int i = 0; i < n; i++) {
mint res = dn[i][1] * up[i][1];
cout << res << ' ';
}
}
// above dn[.][0] = 1. actually, i.e. all sub be good
void solve() {
int n; cin >> n;
vector<int> pa(n); pa[0]=-1;
vector<vector<int>> g(n);
for (int i = 1; i < n; i++) {
int x; cin >> x; x--;
pa[i] = x;
g[x].push_back(i);
}
vector<mint> dn(n); // #bad <= 1
for (int u = n-1; u >= 0; u--) {
dn[u] = 1;
for (int v: g[u]) {
// 1 means if all sub of v good, then u-v can be bad
dn[u] *= dn[v] + 1;
}
}
vector<mint> up(n); // #bad <= 1 on uptree
up[0] = 1;
for (int u = 0; u < n; u++) {
int m = g[u].size();
vector<mint> pref(m + 1), suff(m + 1);
pref[0] = suff[m] = 1;
for (int i = 0; i < m; i++) {
int v = g[u][i];
pref[i+1] = pref[i] * (dn[v] + 1); // don't forget +1
}
for (int i = m-1; i >= 0; i--) {
int v = g[u][i];
suff[i] = suff[i+1] * (dn[v] + 1);
}
for (int i = 0; i < m; i++) {
int v = g[u][i];
// 1 same idea as above
up[v] = 1 + up[u] * pref[i] * suff[i+1];
}
}
for (int i = 0; i < n; i++) {
cout << dn[i]*up[i] << ' ';
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
}
| 44.60452 | 146 | 0.511843 | [
"vector"
] |
7791250b2f4f742b2cf0ba1f79ee5241c5bc6899 | 1,533 | hpp | C++ | src/Geometry/Scene.hpp | prise-3d/vpbrt | d0aca0fe6dc76f0079efcec049b0be04c9cd174b | [
"MIT"
] | 6 | 2021-09-23T03:10:31.000Z | 2021-12-16T11:35:44.000Z | src/Geometry/Scene.hpp | prise-3d/vpbrt | d0aca0fe6dc76f0079efcec049b0be04c9cd174b | [
"MIT"
] | null | null | null | src/Geometry/Scene.hpp | prise-3d/vpbrt | d0aca0fe6dc76f0079efcec049b0be04c9cd174b | [
"MIT"
] | 2 | 2021-09-23T03:10:34.000Z | 2021-12-01T22:34:51.000Z | #ifndef _VPBRT_SCENE_HPP
#define _VPBRT_SCENE_HPP
#include <vector>
#include <iostream>
using namespace std;
#include "Mesh.hpp"
#include "Cylindre.hpp"
#include "Objet.hpp"
#include "../rply-1.1.4/rply.h"
#include "transform.h"
#include "../Materials/Material.hpp"
class Scene {
private:
// objets nommés - non visibles
vector <Objet *> objets;
// les meshes visibles et leur ltm
vector <Transform *> ltm; // local transformation matrices
vector <Mesh *> meshes;
vector <Cylindre *> cylindres;
// statistiques sur la scène
unsigned int nbFaces;
unsigned int nbSommets;
// bounding box de la scène
BoundingBox bb;
public:
Scene();
~Scene();
void add(Mesh *m);
void add(Mesh *m, Transform *t);
void add(Cylindre *c);
void add(Cylindre *c, Transform *t);
void add(Objet *o);
void add(Scene *sc);
void addInstance(const string &oname, const Transform &t);
void draw();
void draw(bool vc);
friend ostream& operator<<(ostream &out, const Scene &sc);
bool load_ply(const char *filename, const Transform &ctm, Objet *cur, Material *mat);
// int vertex_cb(p_ply_argument argument);
// int face_cb(p_ply_argument argument);
inline int getNbFaces(){ return nbFaces; }
inline int getNbSommets(){ return nbSommets; }
inline int getNBCylindre(){ return cylindres.size(); }
void printStats();
void printCylinders();
BoundingBox getBB(){ return bb; }
bool isInsideBB(const Point3f &p);
private:
void updateBB(const BoundingBox &bbp);
};
#endif
| 21.291667 | 87 | 0.688193 | [
"mesh",
"vector",
"transform"
] |
77954ffa261a04b8782dc839a4d8ba17c1f7960c | 1,586 | cpp | C++ | ProjectTemplate/src/AppBase.cpp | alexk95/uiCore | fdc1e927710db431d4dcfa13aaeffaef3b36a9b1 | [
"MIT"
] | 2 | 2020-09-26T18:24:15.000Z | 2021-07-09T01:57:29.000Z | ProjectTemplate/src/AppBase.cpp | alexk95/uiCore | fdc1e927710db431d4dcfa13aaeffaef3b36a9b1 | [
"MIT"
] | null | null | null | ProjectTemplate/src/AppBase.cpp | alexk95/uiCore | fdc1e927710db431d4dcfa13aaeffaef3b36a9b1 | [
"MIT"
] | null | null | null | // Application header
#include "AppBase.h" // Corresponding header
#include "TabToolbar.h" // TabToolbar
// AK header
#include <akAPI/uiAPI.h> // The uiAPI
#include <akGui/aColorStyle.h> // ColorStyle if needed for custom widgets
using namespace ak;
// We create some constant values for the icons
const QString c_dialogErrorIcon = "DialogError";
const QString c_dialogIconPath = "Dialog";
const std::string c_appVersion = "1.0";
const QString c_settingsWindowState = "WindowState";
const QString c_settingsColorStyle = "ColorStyle";
AppBase::AppBase(int _argc, char ** _argv)
: m_ttb(nullptr)
{
// Create own UID
m_uid = ak::uiAPI::createUid();
// Create the main window
m_mainWindow = uiAPI::createWindow(m_uid);
// Create the tabToolbar
m_ttb = new TabToolbar(this);
// Create your elements
// ...
// Add this object as an window event listener to the main window
uiAPI::window::addEventHandler(m_mainWindow, this);
// Show window
uiAPI::window::showMaximized(m_mainWindow);
// Restore the window settings
uiAPI::restoreStateColorStyle(uiAPI::settings::getString(c_settingsColorStyle, "").toStdString(), c_appVersion);
uiAPI::window::restoreState(m_mainWindow, uiAPI::settings::getString(c_settingsWindowState, "").toStdString());
}
AppBase::~AppBase() {
if (m_ttb != nullptr) { delete m_ttb; }
}
bool AppBase::closeEvent(void) {
uiAPI::settings::setString(c_settingsWindowState, uiAPI::window::saveState(m_mainWindow).c_str());
uiAPI::settings::setString(c_settingsColorStyle, uiAPI::saveStateColorStyle(c_appVersion).c_str());
return true;
} | 28.836364 | 113 | 0.744641 | [
"object"
] |
7797d2132f184407980605c37187a113345f2a7d | 2,403 | cc | C++ | Source.cc | EmanueleGallone/OmnetProject | e907a46ab28ea9bf03b01a6dc5adac5b752deb04 | [
"MIT"
] | 1 | 2020-05-03T19:54:23.000Z | 2020-05-03T19:54:23.000Z | Source.cc | davidetestoni/OmnetProject | 3c1d37405af554c26bc9079d0cdaf71b17b4ff0d | [
"MIT"
] | 1 | 2019-02-14T11:14:10.000Z | 2021-03-23T06:54:40.000Z | Source.cc | EmanueleGallone/OmnetProject | e907a46ab28ea9bf03b01a6dc5adac5b752deb04 | [
"MIT"
] | 1 | 2020-05-03T19:55:36.000Z | 2020-05-03T19:55:36.000Z | #include <omnetpp.h>
#include <cstdlib>
#include <PriorityMessage_m.h>
using namespace omnetpp;
class Source : public cSimpleModule
{
private:
PriorityMessage *priorityMessage;
int numPrio;
cMersenneTwister* rng; // random number generator
std::vector<double> interArrivalTimes; // we default to exponential times
//Needed for taking track of id generation of messages for each priority
int generatedMsgCounter[100] = {0}; //obviously need to limit the max number of priority queues
public:
Source();
virtual ~Source();
protected:
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
virtual double getPriorityTime(int priority);
};
Define_Module(Source);
Source::Source()
{
priorityMessage = nullptr;
}
Source::~Source()
{
cancelAndDelete(priorityMessage);
}
void Source::initialize()
{
numPrio = par("numPrio").intValue(); //getting the numbers of n priorities from parameter
rng = new cMersenneTwister();
interArrivalTimes = cStringTokenizer(par("interArrivalTimes")).asDoubleVector();
priorityMessage = new PriorityMessage("dataPriorityMessage");
scheduleAt(simTime(), priorityMessage);
}
void Source::handleMessage(cMessage *msg)
{
ASSERT(msg == priorityMessage);
char msgname[60];
int priority = (rand() % numPrio); //generating priority number from parameter
sprintf(msgname, "message-%d-priority-%d", ++generatedMsgCounter[priority], priority);
PriorityMessage *message = new PriorityMessage(msgname);
message->setPriority(priority);
message->setWorkLeft(SIMTIME_ZERO);
message->setQueueingTime(SIMTIME_ZERO);
message->setTimestamp(SIMTIME_ZERO);
message->setWorkStart(SIMTIME_ZERO);
send(message, "out");
auto prio = getPriorityTime(priority);
scheduleAt(simTime() + prio, priorityMessage);
}
double Source::getPriorityTime(int priority){
if(priority >= 0 && priority < numPrio && interArrivalTimes.size() > 0){
if (priority <= (interArrivalTimes.size() - 1)) return omnetpp::exponential(rng, interArrivalTimes.at(priority)); // if the interArrivalTimes array has enough values, return the correct one
else return omnetpp::exponential(rng, interArrivalTimes.at(rand() % interArrivalTimes.size())); // otherwise just return a random time out of all the available ones
}
return 0;
}
| 29.304878 | 197 | 0.719933 | [
"vector"
] |
7799254da3b97262899ab65f4b596dbb19fdcc09 | 6,765 | cc | C++ | examples/physics/FullCMS/Geant4/src/G4ScalarRZMagFieldFromMap.cc | amadio/geant | a46790aa9eb3663f8324320a71e993d73ca443da | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-10-16T14:37:42.000Z | 2018-04-05T15:49:09.000Z | examples/physics/FullCMS/Geant4/src/G4ScalarRZMagFieldFromMap.cc | amadio/geant | a46790aa9eb3663f8324320a71e993d73ca443da | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | examples/physics/FullCMS/Geant4/src/G4ScalarRZMagFieldFromMap.cc | amadio/geant | a46790aa9eb3663f8324320a71e993d73ca443da | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Created by J. Apostolakis, 18 May 2018
//
// based on ScalarRZMagFieldFromMap
// which was based on the work of Ananya Fall 2015
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <stdlib.h>
#include <cassert>
#include "G4Types.hh"
#include "G4ScalarRZMagFieldFromMap.hh"
using namespace std;
G4ScalarRZMagFieldFromMap::G4ScalarRZMagFieldFromMap()
: G4MagneticField()
{
}
G4ScalarRZMagFieldFromMap::G4ScalarRZMagFieldFromMap(std::string inputMap)
: G4ScalarRZMagFieldFromMap()
{
ReadVectorData(inputMap);
}
G4ScalarRZMagFieldFromMap::~G4ScalarRZMagFieldFromMap()
{
}
void G4ScalarRZMagFieldFromMap::ReadVectorData(string inputMap)
{
string line;
string s1, s2, s3, s4, s5, s0;
double d1, d2, d3, d4, d5, d0;
ifstream pFile(inputMap);
if (pFile.is_open()) {
// getline() returns the stream. testing the stream with while returns error such as EOF
while (getline(pFile, line)) {
// so here we know that the read was a success and that line has valid data
stringstream ss(line);
// parsing all the parts. s0's store the string names which are of no use to us.
ss >> s0 >> d1 >> s1 >> d0 >> s2 >> d2 >> s3 >> d3 >> s4 >> d4 >> s5 >> d5;
fRadius.push_back(d1);
fPhi.push_back(d0);
fZ.push_back(d2);
fBz.push_back(d3);
fBr.push_back(d4);
fBphi.push_back(d5);
}
pFile.close();
G4cout << "ReadVectorData> Data read - closing file " << inputMap << G4endl;
} else {
G4cerr << "G4ScalarRZMagFieldFromMap::ReadVectorData> Unable to open file"
<< inputMap << G4endl;
exit(1);
}
}
void G4ScalarRZMagFieldFromMap::
GetFieldValueRZ(double r, double Zin, G4ThreeVector &rzField) const
{
// Take care that radius and z for out of limit values take values at end points
double radius = min(r, kRMax);
double z = max(min(Zin, kZMax), -kZMax); // max(min(Z,Zmax), Zmin )
// to make sense of the indices, consider any particular instance e.g. (25,-200)
int rFloor = std::min( (int) floor(radius * kRDiffInv), kNoRValues - 2 );
int rIndLow = rFloor * kNoZValues;
int rIndHigh = rIndLow + kNoZValues;
// int rIndHigh = (radius < kRMax) ? rIndLow + kNoZValues ? rIndLow;
// if we use z-z0 in place of two loops for Z<0 and Z>0
// z-z0 = [0,32000]
// so indices 0 to 160 : total 161 indices for (z-z0)/200
int zInd = std::min( (int) std::floor(z * kZDiffInv) + kHalfZValues, kNoZValues - 2);
// cout << " r: floor = " << rFloor << " Index = " << rIndLow << " hi= " << rIndHigh << endl;
// cout << " z-Index = " << zInd << endl;
// need i1,i2,i3,i4 for 4 required indices
int i1 = rIndLow + zInd;
int i2 = i1 + 1;
int i3 = rIndHigh + zInd;
int i4 = i3 + 1;
double zLow = (zInd - kHalfZValues) * kZDiff; // 80 because it's the middle index in 0 to 160
double zHigh = zLow + kZDiff;
double radiusLow = rFloor * kRDiff;
double radiusHigh = radiusLow + kRDiff;
// cout<<i1<<" "<<i2<<" "<<i3<<" "<<i4<<endl;
// now write function
double a1 = (radiusHigh - radius) * (zHigh - z); // area to be multiplied with i1
double a2 = (radiusHigh - radius) * (z - zLow);
double a3 = (radius - radiusLow) * (zHigh - z);
double a4 = (radius - radiusLow) * (z - zLow);
unsigned long minSzUL= std::min( std::min( fBr.size(), fBphi.size()) , fBz.size() );
assert( 0 <= i1 );
assert( i4 <= (int) minSzUL ) ;
assert( 0. <= a1 && a1 * kAInverse <= 1.0 );
assert( 0. <= a2 && a2 * kAInverse <= 1.0 );
assert( 0. <= a3 && a3 * kAInverse <= 1.0 );
assert( 0. <= a4 && a4 * kAInverse <= 1.0 );
double BR = (fBr[i1] * a1 + fBr[i2] * a2 + fBr[i3] * a3 + fBr[i4] * a4) * kAInverse;
double BZ = (fBz[i1] * a1 + fBz[i2] * a2 + fBz[i3] * a3 + fBz[i4] * a4) * kAInverse;
double BPhi = (fBphi[i1] * a1 + fBphi[i2] * a2 + fBphi[i3] * a3 + fBphi[i4] * a4) * kAInverse;
rzField = G4ThreeVector( BR, BPhi, BZ );
}
// Sidenote: For theta =0; xyzField = rzField.
// theta =0 corresponds to y=0
void G4ScalarRZMagFieldFromMap::GetFieldValueXYZ(const G4ThreeVector &pos, G4ThreeVector &xyzField) const
{
double cyl[2];
CartesianToCylindrical(pos, cyl);
G4ThreeVector rzField;
GetFieldValueRZ(cyl[0], cyl[1], rzField); // cyl[2] =[r,z]
double sinTheta = 0.0, cosTheta = 1.0; // initialize as theta=0
// To take care of r =0 case
if (cyl[0] != 0.0) {
double rInv = 1 / cyl[0];
sinTheta = pos.y() * rInv;
cosTheta = pos.x() * rInv;
}
CylindricalToCartesian(rzField, sinTheta, cosTheta, xyzField);
}
void G4ScalarRZMagFieldFromMap::GetFieldValueTest(const G4ThreeVector &pos, G4ThreeVector &rzField)
{
double cyl[2];
CartesianToCylindrical(pos, cyl);
GetFieldValueRZ(cyl[0], cyl[1], rzField); // cyl[] =[r,z]
}
/*******
void G4ScalarRZMagFieldFromMap::GetFieldValues(const vecgeom::SOA3D<double> &posVec,
vecgeom::SOA3D<double> &fieldVec)
{
int len= posVec.size();
for (int i = 0; i < len; ++i) {
// fill a vector3D with ith triplet for input to getFieldValue
G4ThreeVector pos(posVec.x(i), posVec.y(i), posVec.z(i));
G4ThreeVector xyzField;
GetFieldValueXYZ(pos, xyzField); // runs for 1 triplet
// Fill SOA3D field with single field values
fieldVec.x(i) = xyzField.x();
fieldVec.y(i) = xyzField.y();
fieldVec.z(i) = xyzField.z();
}
}
************/
/** @brief Vector interface for field retrieval */
/************
void G4ScalarRZMagFieldFromMap::
ObtainFieldValueSIMD(const Vector3D<Double_v> &positionVec, Vector3D<Double_v> &fieldValueVec)
{
Vector3D<double> position, fieldValue;
int vecsz = vecCore::VectorSize<Double_v>(); // Deprecated !?
// Double_v dv;
// int vecsz = VectorSize<decltype(dv)>();
Double_v fieldValueArr[3];
for( int i= 0; i < vecsz ; ++i)
{
position= G4ThreeVector( vecCore::Get(positionVec[0], i),
vecCore::Get(positionVec[1], i),
vecCore::Get(positionVec[2], i) ) ;
ObtainFieldValue( position, fieldValue);
for( int j= 0; j < 3; j++)
vecCore::Set( fieldValueArr[j], i, fieldValue[j] );
vecCore::Set( fieldValueVec[0], i, fieldValue.x() );
vecCore::Set( fieldValueVec[0], i, fieldValue.x() );
vecCore::Set( fieldValueVec[0], i, fieldValue.x() );
}
}
************/
G4ScalarRZMagFieldFromMap::
G4ScalarRZMagFieldFromMap(const G4ScalarRZMagFieldFromMap &right)
: G4ScalarRZMagFieldFromMap()
{
fRadius = right.fRadius;
fPhi = right.fPhi;
fZ = right.fZ;
fBr = right.fBr;
fBz = right.fBz;
fBphi = right.fBphi;
}
| 33.325123 | 105 | 0.615817 | [
"vector"
] |
779df917084730acc04569b52c9916d6d8fafdfa | 3,337 | cpp | C++ | src/fmi4cpp/fmi2/cs_library.cpp | feelpp/FMI4cpp | 3e78df0835e026137e943b626f604e718b6b1e99 | [
"MIT"
] | 1 | 2019-11-02T15:45:07.000Z | 2019-11-02T15:45:07.000Z | src/fmi4cpp/fmi2/cs_library.cpp | fmi-tools/FMI4cpp | 31cd95965da94652597e340c4b1b78c93fb830ec | [
"MIT"
] | null | null | null | src/fmi4cpp/fmi2/cs_library.cpp | fmi-tools/FMI4cpp | 31cd95965da94652597e340c4b1b78c93fb830ec | [
"MIT"
] | null | null | null |
#include <fmi4cpp/fmi2/cs_library.hpp>
#include <fmi4cpp/library_helper.hpp>
using namespace fmi4cpp;
using namespace fmi4cpp::fmi2;
cs_library::cs_library(const std::string& modelIdentifier,
const std::shared_ptr<fmu_resource>& resource)
: fmi2_library(modelIdentifier, resource)
{
fmi2SetRealInputDerivatives_ = load_function<fmi2SetRealInputDerivativesTYPE*>(handle_,
"fmi2SetRealInputDerivatives");
fmi2GetRealOutputDerivatives_ = load_function<fmi2GetRealOutputDerivativesTYPE*>(handle_,
"fmi2GetRealOutputDerivatives");
fmi2DoStep_ = load_function<fmi2DoStepTYPE*>(handle_, "fmi2DoStep");
fmi2CancelStep_ = load_function<fmi2CancelStepTYPE*>(handle_, "fmi2CancelStep");
fmi2GetStatus_ = load_function<fmi2GetStatusTYPE*>(handle_, "fmi2GetStatusTYPE");
fmi2GetRealStatus_ = load_function<fmi2GetRealStatusTYPE*>(handle_, "fmi2GetRealStatusTYPE");
fmi2GetIntegerStatus_ = load_function<fmi2GetIntegerStatusTYPE*>(handle_, "fmi2GetIntegerStatusTYPE");
fmi2GetBooleanStatus_ = load_function<fmi2GetBooleanStatusTYPE*>(handle_, "fmi2GetBooleanStatusTYPE");
fmi2GetStringStatus_ = load_function<fmi2GetStringStatusTYPE*>(handle_, "fmi2GetStringStatusTYPE");
}
bool cs_library::step(
fmi2Component c,
const fmi2Real currentCommunicationPoint,
const fmi2Real communicationStepSize,
const bool noSetFMUStatePriorToCurrentPoint)
{
return update_status_and_return_true_if_ok(
fmi2DoStep_(c, currentCommunicationPoint, communicationStepSize, noSetFMUStatePriorToCurrentPoint));
}
bool cs_library::cancel_step(fmi2Component c)
{
return update_status_and_return_true_if_ok(fmi2CancelStep_(c));
}
bool cs_library::set_real_input_derivatives(
fmi2Component c,
const std::vector<fmi2ValueReference>& vr,
const std::vector<fmi2Integer>& order,
const std::vector<fmi2Real>& value)
{
return fmi2SetRealInputDerivatives_(c, vr.data(), vr.size(), order.data(), value.data());
}
bool cs_library::get_real_output_derivatives(
fmi2Component c,
const std::vector<fmi2ValueReference>& vr,
const std::vector<fmi2Integer>& order,
std::vector<fmi2Real>& value)
{
return update_status_and_return_true_if_ok(
fmi2GetRealOutputDerivatives_(c, vr.data(), vr.size(), order.data(), value.data()));
}
bool cs_library::get_status(
fmi2Component c,
const fmi2StatusKind s,
fmi2Status& value)
{
return update_status_and_return_true_if_ok(
fmi2GetStatus_(c, s, &value));
}
bool cs_library::get_real_status(
fmi2Component c,
const fmi2StatusKind s,
fmi2Real& value)
{
return update_status_and_return_true_if_ok(
fmi2GetRealStatus_(c, s, &value));
}
bool cs_library::get_integer_status(
fmi2Component c,
const fmi2StatusKind s,
fmi2Integer& value)
{
return update_status_and_return_true_if_ok(
fmi2GetIntegerStatus_(c, s, &value));
}
bool cs_library::get_boolean_status(
fmi2Component c,
const fmi2StatusKind s,
fmi2Boolean& value)
{
return update_status_and_return_true_if_ok(
fmi2GetBooleanStatus_(c, s, &value));
}
bool cs_library::get_string_status(
fmi2Component c,
const fmi2StatusKind s,
fmi2String& value)
{
return update_status_and_return_true_if_ok(
fmi2GetStringStatus_(c, s, &value));
}
| 31.481132 | 108 | 0.758166 | [
"vector"
] |
77a9c8230a918f4de40e46a07e9584395675adbd | 5,983 | cc | C++ | third_party/harfbuzz-ng/src/hb-ot-shape-complex-arabic.cc | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | 1 | 2015-10-12T09:14:22.000Z | 2015-10-12T09:14:22.000Z | third_party/harfbuzz-ng/src/hb-ot-shape-complex-arabic.cc | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | null | null | null | third_party/harfbuzz-ng/src/hb-ot-shape-complex-arabic.cc | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T07:22:28.000Z | 2020-11-04T07:22:28.000Z | /*
* Copyright (C) 2010 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod
*/
#include "hb-ot-shape-complex-private.hh"
HB_BEGIN_DECLS
/* buffer var allocations */
#define arabic_shaping_action() var2.u32 /* arabic shaping action */
/*
* Bits used in the joining tables
*/
enum {
JOINING_TYPE_U = 0,
JOINING_TYPE_R = 1,
JOINING_TYPE_D = 2,
JOINING_TYPE_C = JOINING_TYPE_D,
JOINING_GROUP_ALAPH = 3,
JOINING_GROUP_DALATH_RISH = 4,
NUM_STATE_MACHINE_COLS = 5,
/* We deliberately don't have a JOINING_TYPE_L since that's unused in Unicode. */
JOINING_TYPE_T = 6,
JOINING_TYPE_X = 7 /* means: use general-category to choose between U or T. */
};
/*
* Joining types:
*/
#include "hb-ot-shape-complex-arabic-table.h"
static unsigned int get_joining_type (hb_codepoint_t u, hb_category_t gen_cat)
{
/* TODO Macroize the magic bit operations */
if (likely (JOINING_TABLE_FIRST <= u && u <= JOINING_TABLE_LAST)) {
unsigned int j_type = joining_table[u - JOINING_TABLE_FIRST];
if (likely (j_type != JOINING_TYPE_X))
return j_type;
}
/* Mongolian joining data is not in ArabicJoining.txt yet */
if (unlikely (0x1800 <= u && u <= 0x18AF))
{
/* All letters, SIBE SYLLABLE BOUNDARY MARKER, and NIRUGU are D */
if (gen_cat == HB_CATEGORY_OTHER_LETTER || u == 0x1807 || u == 0x180A)
return JOINING_TYPE_D;
}
if (unlikely ((u & ~(0x200C^0x200D)) == 0x200C)) {
return u == 0x200C ? JOINING_TYPE_U : JOINING_TYPE_C;
}
return ((1<<gen_cat) & ((1<<HB_CATEGORY_NON_SPACING_MARK)|(1<<HB_CATEGORY_ENCLOSING_MARK)|(1<<HB_CATEGORY_FORMAT))) ?
JOINING_TYPE_T : JOINING_TYPE_U;
}
static const hb_tag_t arabic_syriac_features[] =
{
HB_TAG('i','n','i','t'),
HB_TAG('m','e','d','i'),
HB_TAG('f','i','n','a'),
HB_TAG('i','s','o','l'),
/* Syriac */
HB_TAG('m','e','d','2'),
HB_TAG('f','i','n','2'),
HB_TAG('f','i','n','3'),
HB_TAG_NONE
};
/* Same order as the feature array */
enum {
INIT,
MEDI,
FINA,
ISOL,
/* Syriac */
MED2,
FIN2,
FIN3,
NONE,
COMMON_NUM_FEATURES = 4,
SYRIAC_NUM_FEATURES = 7,
TOTAL_NUM_FEATURES = NONE
};
static const struct arabic_state_table_entry {
uint8_t prev_action;
uint8_t curr_action;
uint8_t next_state;
uint8_t padding;
} arabic_state_table[][NUM_STATE_MACHINE_COLS] =
{
/* jt_U, jt_R, jt_D, jg_ALAPH, jg_DALATH_RISH */
/* State 0: prev was U, not willing to join. */
{ {NONE,NONE,0}, {NONE,ISOL,1}, {NONE,ISOL,2}, {NONE,ISOL,1}, {NONE,ISOL,6}, },
/* State 1: prev was R or ISOL/ALAPH, not willing to join. */
{ {NONE,NONE,0}, {NONE,ISOL,1}, {NONE,ISOL,2}, {NONE,FIN2,5}, {NONE,ISOL,6}, },
/* State 2: prev was D/ISOL, willing to join. */
{ {NONE,NONE,0}, {INIT,FINA,1}, {INIT,FINA,3}, {INIT,FINA,4}, {INIT,FINA,6}, },
/* State 3: prev was D/FINA, willing to join. */
{ {NONE,NONE,0}, {MEDI,FINA,1}, {MEDI,FINA,3}, {MEDI,FINA,4}, {MEDI,FINA,6}, },
/* State 4: prev was FINA ALAPH, not willing to join. */
{ {NONE,NONE,0}, {MED2,ISOL,1}, {MED2,ISOL,2}, {MED2,FIN2,5}, {MED2,ISOL,6}, },
/* State 5: prev was FIN2/FIN3 ALAPH, not willing to join. */
{ {NONE,NONE,0}, {ISOL,ISOL,1}, {ISOL,ISOL,2}, {ISOL,FIN2,5}, {ISOL,ISOL,6}, },
/* State 6: prev was DALATH/RISH, not willing to join. */
{ {NONE,NONE,0}, {NONE,ISOL,1}, {NONE,ISOL,2}, {NONE,FIN3,5}, {NONE,ISOL,6}, }
};
void
_hb_ot_shape_complex_collect_features_arabic (hb_ot_shape_plan_t *plan, const hb_segment_properties_t *props)
{
unsigned int num_features = props->script == HB_SCRIPT_SYRIAC ? SYRIAC_NUM_FEATURES : COMMON_NUM_FEATURES;
for (unsigned int i = 0; i < num_features; i++)
plan->map.add_bool_feature (arabic_syriac_features[i], false);
}
void
_hb_ot_shape_complex_setup_masks_arabic (hb_ot_shape_context_t *c)
{
unsigned int count = c->buffer->len;
unsigned int prev = 0, state = 0;
for (unsigned int i = 0; i < count; i++)
{
unsigned int this_type = get_joining_type (c->buffer->info[i].codepoint, (hb_category_t) c->buffer->info[i].general_category());
if (unlikely (this_type == JOINING_TYPE_T)) {
c->buffer->info[i].arabic_shaping_action() = NONE;
continue;
}
const arabic_state_table_entry *entry = &arabic_state_table[state][this_type];
if (entry->prev_action != NONE)
c->buffer->info[prev].arabic_shaping_action() = entry->prev_action;
c->buffer->info[i].arabic_shaping_action() = entry->curr_action;
prev = i;
state = entry->next_state;
}
hb_mask_t mask_array[TOTAL_NUM_FEATURES + 1] = {0};
unsigned int num_masks = c->buffer->props.script == HB_SCRIPT_SYRIAC ? SYRIAC_NUM_FEATURES : COMMON_NUM_FEATURES;
for (unsigned int i = 0; i < num_masks; i++)
mask_array[i] = c->plan->map.get_1_mask (arabic_syriac_features[i]);
for (unsigned int i = 0; i < count; i++)
c->buffer->info[i].mask |= mask_array[c->buffer->info[i].arabic_shaping_action()];
}
HB_END_DECLS
| 30.065327 | 132 | 0.673909 | [
"shape"
] |
77ad9694f67da36c055ae289ff38e5c22ca6da05 | 12,096 | cpp | C++ | src/ukf.cpp | ShriefSalama/UncentedKalmanFilter | a5af8c97832818d24771b1f4aed23cb4595f8fc9 | [
"MIT"
] | null | null | null | src/ukf.cpp | ShriefSalama/UncentedKalmanFilter | a5af8c97832818d24771b1f4aed23cb4595f8fc9 | [
"MIT"
] | null | null | null | src/ukf.cpp | ShriefSalama/UncentedKalmanFilter | a5af8c97832818d24771b1f4aed23cb4595f8fc9 | [
"MIT"
] | 1 | 2021-07-02T17:27:35.000Z | 2021-07-02T17:27:35.000Z | #include "ukf.h"
#include "Eigen/Dense"
#include <iostream>
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::vector;
/**
* Initializes Unscented Kalman filter
* This is scaffolding, do not modify
*/
UKF::UKF() {
// if this is false, laser measurements will be ignored (except during init)
use_laser_ = true;
// if this is false, radar measurements will be ignored (except during init)
use_radar_ = true;
// initial state vector
x_ = VectorXd(5);
// initial covariance matrix
P_ = MatrixXd(5, 5);
// Process noise standard deviation longitudinal acceleration in m/s^2
std_a_ = 0.2;
// Process noise standard deviation yaw acceleration in rad/s^2
std_yawdd_ = 0.2;
//DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer.
// Laser measurement noise standard deviation position1 in m
std_laspx_ = 0.15;
// Laser measurement noise standard deviation position2 in m
std_laspy_ = 0.15;
// Radar measurement noise standard deviation radius in m
std_radr_ = 0.3;
// Radar measurement noise standard deviation angle in rad
std_radphi_ = 0.0175;
// Radar measurement noise standard deviation radius change in m/s
std_radrd_ = 0.1;
//DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer.
/**
TODO:
Complete the initialization. See ukf.h for other member properties.
Hint: one or more values initialized above might be wildly off...
*/
//set state dimension
n_x_ = 5;
//set augmented dimension
n_aug_ = 7;
//define spreading parameter
lambda_ = 3 - n_aug_;
//create sigma point matrix
Xsig_pred_ = MatrixXd(n_x_, 2 * n_aug_ + 1);
weights_ = VectorXd(2*n_aug_+1);
}
UKF::~UKF() {}
/**
* @param {MeasurementPackage} meas_package The latest measurement data of
* either radar or laser.
*/
void UKF::ProcessMeasurement(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Make sure you switch between lidar and radar
measurements.
*/
static float previous_timestamp_ = 0.0;
/*****************************************************************************
* Initialization
****************************************************************************/
if (!is_initialized_) {
/**
TODO:
* Initialize the state ekf_.x_ with the first measurement.
* Create the covariance matrix.
* Remember: you'll need to convert radar from polar to cartesian coordinates.
*/
// first measurement
if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
/**
Convert radar from polar to cartesian coordinates and initialize state.
*/
}
else if (meas_package.sensor_type_ == MeasurementPackage::LASER) {
/**
Initialize state.
*/
x_ << meas_package.raw_measurements_[0], meas_package.raw_measurements_[1], 0, 0, 0;
is_initialized_ = true;
}
// done initializing, no need to predict or update
previous_timestamp_ = meas_package.timestamp_ ;
return;
}
/*****************************************************************************
* Prediction
****************************************************************************/
float dt = (meas_package.timestamp_ - previous_timestamp_)/1000000.0;
previous_timestamp_ = meas_package.timestamp_ ;
Prediction(dt);
/*****************************************************************************
* Update
****************************************************************************/
if (meas_package.sensor_type_ == MeasurementPackage::RADAR &&
use_radar_ == true)
{
// Radar updates
UpdateRadar(meas_package);
}
else if (meas_package.sensor_type_ == MeasurementPackage::LASER &&
use_laser_ == true)
{
// Laser updates
UpdateLidar(meas_package);
}
else{
//do nothing
}
}
/**
* Predicts sigma points, the state, and the state covariance matrix.
* @param {double} delta_t the change in time (in seconds) between the last
* measurement and this one.
*/
void UKF::Prediction(double delta_t) {
/**
TODO:
Complete this function! Estimate the object's location. Modify the state
vector, x_. Predict sigma points, the state, and the state covariance matrix.
*/
//create augmented mean vector
VectorXd x_aug = VectorXd(n_aug_);
//create augmented state covariance
MatrixXd P_aug = MatrixXd(n_aug_, n_aug_);
//create sigma point matrix
MatrixXd Xsig_aug = MatrixXd(n_aug_, 2 * n_aug_ + 1);
//create augmented mean state
x_aug.head(5) = x_;
x_aug(5) = 0;
x_aug(6) = 0;
//create augmented covariance matrix
P_aug.fill(0.0);
P_aug.topLeftCorner(5,5) = P_;
P_aug(5,5) = std_a_*std_a_;
P_aug(6,6) = std_yawdd_*std_yawdd_;
//create square root matrix
MatrixXd L = P_aug.llt().matrixL();
//create augmented sigma points
Xsig_aug.col(0) = x_aug;
for (int i = 0; i< n_aug_; i++)
{
Xsig_aug.col(i+1) = x_aug + sqrt(lambda+n_aug_) * L.col(i);
Xsig_aug.col(i+1+n_aug) = x_aug - sqrt(lambda+n_aug_) * L.col(i);
}
/////////////////////////////////////////////////////////////////////////
///////////// END of Generating Sigma Points ////////////////
//////////////////////////////////////////////////////////////////////////
for(unsigned i = 0; i<2*n_aug_+1 ; i++)
{
double px = Xsig_aug.col(i)(0);
double py = Xsig_aug.col(i)(1);
double speed = Xsig_aug.col(i)(2);
double angle = Xsig_aug.col(i)(3);
double angle_rate = Xsig_aug.col(i)(4);
double noise_a = Xsig_aug.col(i)(5);
double noise_yaw = Xsig_aug.col(i)(6);
if(angle_rate <= 0.001)
{
Xsig_pred_.col(i)(0) = px + (delta_t * speed * cos(angle)) + (0.5 * delta_t * delta_t * cos(angle) *noise_a);
Xsig_pred_.col(i)(1) = py + (delta_t * speed * sin(angle)) + (0.5 * delta_t * delta_t * sin(angle) *noise_a);
}
else
{
Xsig_pred_.col(i)(0) = px + ((speed / angle_rate) * (sin(angle+angle_rate*delta_t) - sin(angle))) + (0.5 * delta_t * delta_t * cos(angle) *noise_a);
Xsig_pred_.col(i)(1) = py + ((speed / angle_rate) * (cos(angle) - cos(angle+angle_rate*delta_t))) + (0.5 * delta_t * delta_t * sin(angle) *noise_a);
}
Xsig_pred_.col(i)(2) = speed + delta_t * noise_a;
Xsig_pred_.col(i)(3) = angle + delta_t * angle_rate + (0.5 * delta_t * delta_t * noise_yaw);
Xsig_pred_.col(i)(4) = angle_rate +delta_t * noise_yaw;
}
/////////////////////////////////////////////////////////////////////////
///////////// END of Predicting Sigma Points ////////////////
/////////////////////////////////////////////////////////////////////////
//set weights
weights_(0) = lambda_/(lambda_+n_aug_);
for (unsigned int i = 1; i<2*n_aug_ +1; i++)
{
weights_(i) = 1/(2*(lambda_+n_aug_));
}
//predict state mean
for (unsigned int i = 0; i<2*n_aug_+1; i++)
{
x_ += weights_(i)*Xsig_pred_.col(i);
}
//predict state covariance matrix
for (unsigned int i = 0; i<2*n_aug_+1; i++)
{
VectorXd C = Xsig_pred_.col(i) - x;
while (C(3) > M_PI || C(3) < -M_PI )
{
if (C(3) > M_PI) C(3) -= 2*M_PI;
else if (C(3) < -M_PI) C(3) += 2*M_PI;
}
P_ += weights_(i)*C*C.transpose();
}
}
/**
* Updates the state and the state covariance matrix using a laser measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateLidar(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Use lidar data to update the belief about the object's
position. Modify the state vector, x_, and covariance, P_.
You'll also need to calculate the lidar NIS.
*/
VectorXd z = meas_package.raw_measurements_;
long x_size = x_.size();
MatrixXd I = MatrixXd::Identity(x_size, x_size);
MatrixXd H_input(2,5);
H_input << 1,0,0,0,0,
0,1,0,0,0;
//add measurement noise covariance matrix
MatrixXd R_laser = MatrixXd(2,2);
R_laser << std_laspx_*std_laspx_, 0,
0, std_laspy_*std_laspy_;
MatrixXd z_pred = H_input * x_;
VectorXd s = H_input * P_ * H_input.transpose() + R_laser ;
VectorXd k = P_ * H_input.transpose() * s.inverse();
VectorXd y = z - z_pred ;
//new state
x_ = x_ + (k*y);
P_ = (I - k* H_input) * P_;
}
/**
* Updates the state and the state covariance matrix using a radar measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateRadar(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Use radar data to update the belief about the object's
position. Modify the state vector, x_, and covariance, P_.
You'll also need to calculate the radar NIS.
*/
//set measurement dimension, radar can measure r, phi, and r_dot
int n_z = 3;
MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1);
VectorXd z = meas_package.raw_measurements_;
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
// extract values for better readibility
double p_x = Xsig_pred_(0,i);
double p_y = Xsig_pred_(1,i);
double v = Xsig_pred_(2,i);
double yaw = Xsig_pred_(3,i);
double v1 = cos(yaw)*v;
double v2 = sin(yaw)*v;
// measurement model
Zsig(0,i) = sqrt(p_x*p_x + p_y*p_y); //r
Zsig(1,i) = atan2(p_y,p_x); //phi
Zsig(2,i) = (p_x*v1 + p_y*v2 ) / sqrt(p_x*p_x + p_y*p_y); //r_dot
}
/////////////////////////////////////////////////////////////////////////
/// END of Predicting Sigma points to Measurement space ///
/////////////////////////////////////////////////////////////////////////
//mean predicted measurement
VectorXd z_pred = VectorXd(n_z);
z_pred.fill(0.0);
for (int i=0; i < 2*n_aug_+1; i++) {
z_pred = z_pred + weights_(i) * Zsig.col(i);
}
//innovation covariance matrix S
MatrixXd S = MatrixXd(n_z,n_z);
S.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++)
{ //2n+1 simga points
//residual
VectorXd z_diff = Zsig.col(i) - z_pred;
//angle normalization
while (z_diff(1) > M_PI || z_diff(1) < -M_PI )
{
if (z_diff(1) > M_PI) z_diff(1) -= 2*M_PI;
else if (z_diff(1) < -M_PI) z_diff(1) += 2*M_PI;
}
S = S + weights_(i) * z_diff * z_diff.transpose();
}
//add measurement noise covariance matrix
MatrixXd R_rader = MatrixXd(n_z,n_z);
R_rader << std_radr_*std_radr_, 0, 0,
0, std_radphi_*std_radphi_, 0,
0, 0,std_radrd_*std_radrd_;
S = S + R_rader;
/////////////////////////////////////////////////////////////////////////
/// END of Calculating S, Z_pred ///
/////////////////////////////////////////////////////////////////////////
//create matrix for cross correlation Tc
MatrixXd Tc = MatrixXd(n_x_, n_z);
//calculate cross correlation matrix
Tc.fill(0.0);
for (unsigned int i = 0; i < 2*n_aug_+1; i++)
{
VectorXd C = Zsig.col(i) - z_pred;
while (C(1) > M_PI || C(1) < -M_PI )
{
if (C(1) > M_PI) C(1) -= 2*M_PI;
else if (C(1) < -M_PI) C(1) += 2*M_PI;
}
VectorXd L = Xsig_pred.col(i) - x;
while (L(3) > M_PI || L(3) < -M_PI )
{
if (L(3) > M_PI) L(3) -= 2*M_PI;
else if (L(3) < -M_PI) L(3) += 2*M_PI;
}
Tc += weights_(i) * L * C.transpose();
}
//calculate Kalman gain K;
MatrixXd K = Tc*S.inverse();
VectorXd z_diff = z - z_pred;
while (z_diff(1) > M_PI || z_diff(1) < -M_PI )
{
if (z_diff(1) > M_PI) z_diff(1) -= 2*M_PI;
else if (z_diff(1) < -M_PI) z_diff(1) += 2*M_PI;
}
//update state mean and covariance matrix
x_ = x_ + K*z_diff;
P_ = P_ - K*S*K.transpose();
}
| 30.39196 | 159 | 0.550595 | [
"object",
"vector",
"model"
] |
77b3857ca2ff0934b64bd31c224378ce291fe46d | 176 | hh | C++ | src/Types.hh | michaeljones/alembic-fs | 765b51774e40b0a5656e9f59338539f5b11f3e4b | [
"BSD-3-Clause"
] | 6 | 2015-03-20T07:58:22.000Z | 2020-01-08T21:57:06.000Z | src/Types.hh | michaeljones/alembic-fs | 765b51774e40b0a5656e9f59338539f5b11f3e4b | [
"BSD-3-Clause"
] | null | null | null | src/Types.hh | michaeljones/alembic-fs | 765b51774e40b0a5656e9f59338539f5b11f3e4b | [
"BSD-3-Clause"
] | null | null | null | #ifndef ALBEMBICFS_TYPES_HH
#define ALBEMBICFS_TYPES_HH
#include <vector>
#include <string>
typedef std::vector< std::string > PathSegments;
#endif // ALBEMBICFS_TYPES_HH
| 14.666667 | 48 | 0.778409 | [
"vector"
] |
77b7f91432bcf009a49dabad76825924fee7eb26 | 5,365 | cpp | C++ | liquidfun/liquidfun/Box2D/Unittests/Multi/MultipleParticleSystemsTests.cpp | subatomicglue/fluid | c85376f86828a1c234bcd9535b9030cfb1a1e8bd | [
"MIT"
] | 17 | 2017-04-02T00:17:47.000Z | 2021-11-23T21:42:48.000Z | liquidfun/liquidfun/Box2D/Unittests/Multi/MultipleParticleSystemsTests.cpp | subatomicglue/fluid | c85376f86828a1c234bcd9535b9030cfb1a1e8bd | [
"MIT"
] | 1 | 2022-01-09T17:14:54.000Z | 2022-01-16T12:35:06.000Z | liquidfun/liquidfun/Box2D/Unittests/Multi/MultipleParticleSystemsTests.cpp | subatomicglue/fluid | c85376f86828a1c234bcd9535b9030cfb1a1e8bd | [
"MIT"
] | 5 | 2017-08-06T12:47:18.000Z | 2020-08-14T14:16:22.000Z | /*
* Copyright (c) 2014 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "gtest/gtest.h"
#include "Box2D/Box2D.h"
#include "AndroidUtil/AndroidMainWrapper.h"
static const int kNumParticleSystems = 3;
static const int kNumParticlesPerSystem = 3;
class MultipleParticleSystemsTests : public ::testing::Test {
protected:
virtual void SetUp();
virtual void TearDown();
void drop();
b2World *m_world;
b2Body *m_body;
b2ParticleSystem *m_particleSystems[kNumParticleSystems];
};
void
MultipleParticleSystemsTests::SetUp()
{
// Define the gravity vector.
b2Vec2 gravity(0.0f, -10.0f);
// Construct a world object, which will simulate the contacts.
m_world = new b2World(gravity);
// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0.0f, 0.0f);
// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
m_body = m_world->CreateBody(&groundBodyDef);
// Construct a valley and add to ground body.
b2PolygonShape shape;
const b2Vec2 vertices[3] = {
b2Vec2(-10.0, 34.0),
b2Vec2(-10.0, 35.0),
b2Vec2(0.0, 15.0)};
shape.Set(vertices, 3);
m_body->CreateFixture(&shape, 0.0f);
const b2Vec2 vertices2[3] = {
b2Vec2(10.0, 34.0),
b2Vec2(10.0, 35.0),
b2Vec2(0.0, 15.0)};
shape.Set(vertices2, 3);
m_body->CreateFixture(&shape, 0.0f);
// Construct several particle systems, all with the same definition.
const b2ParticleSystemDef particleSystemDef;
for (int i = 0; i < kNumParticleSystems; ++i) {
m_particleSystems[i] =
m_world->CreateParticleSystem(&particleSystemDef);
}
// Add particles to the particle systems.
const float kParticlePositionsXStart = -10.0f;
const float kParticlePositionsYStart = 32.0f;
const float kParticlePositionsXEnd = 10.0f;
const float kParticlePositionsYEnd = 33.0f;
const float kParticlePositionsXStep =
(kParticlePositionsXEnd - kParticlePositionsXStart)
/ (kNumParticlesPerSystem - 1);
const float kParticlePositionsYStep =
(kParticlePositionsYEnd - kParticlePositionsYStart)
/ (kNumParticlesPerSystem - 1);
b2ParticleDef pd;
pd.velocity.Set(0.0, -1.0);
// Particles are spaced evenly between (X_START, Y_START) and
// (X_END, Y_END).
float x = kParticlePositionsXStart;
float y = kParticlePositionsYStart;
for (int j = 0; j < kNumParticlesPerSystem; ++j) {
pd.position.Set(x, y);
for (int i = 0; i < kNumParticleSystems; ++i) {
m_particleSystems[i]->CreateParticle(pd);
}
x += kParticlePositionsXStep;
y += kParticlePositionsYStep;
}
}
void
MultipleParticleSystemsTests::TearDown()
{
// Intentionally blank.
}
// Ensure that all particle systems give the same result, when they are
// initialized the same.
TEST_F(MultipleParticleSystemsTests, IdenticalSimulations) {
// Count the number of contacts for each particle system
int32 contacts[kNumParticleSystems];
for (int j = 0; j < kNumParticleSystems; ++j) {
contacts[j] = 0;
}
// Simulate the world for 10 seconds.
// All of the particle systems should run the same.
const float32 timeStep = 1.0f / 60.0f;
const int32 timeout = (int32) (1.0f / timeStep) * 10; // 10 "seconds"
const int32 velocityIterations = 6;
const int32 positionIterations = 2;
for (int i = 0; i < timeout; ++i) {
m_world->Step(timeStep, velocityIterations, positionIterations);
for (int j = 0; j < kNumParticleSystems; ++j) {
contacts[j] += m_particleSystems[j]->GetBodyContactCount();
}
}
// Verify that all the particle systems are in the same state.
const b2Vec2* positions0 =
m_particleSystems[0]->GetPositionBuffer();
const b2Vec2* velocities0 =
m_particleSystems[0]->GetVelocityBuffer();
for (int j = 1; j < kNumParticleSystems; ++j) {
// Check that the particle count matches.
const int32 particleCount = m_particleSystems[0]->GetParticleCount();
ASSERT_EQ(particleCount, m_particleSystems[j]->GetParticleCount());
// Check that the particle positions and velocities match.
const b2Vec2* positionsJ =
m_particleSystems[j]->GetPositionBuffer();
const b2Vec2* velocitiesJ =
m_particleSystems[j]->GetVelocityBuffer();
for (int k = 0; k < particleCount; ++k ) {
EXPECT_EQ(positions0[k], positionsJ[k]) << "Positions differ";
EXPECT_EQ(velocities0[k], velocitiesJ[k]) << "Velocities differ";
}
// Check that the contact reporting matches.
EXPECT_EQ(contacts[0], contacts[j]) << "Contacts differ";
}
}
int
main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 31.745562 | 76 | 0.731594 | [
"object",
"shape",
"vector"
] |
77c8b6833559585c1b1a45141eff963479e7ac4f | 21,884 | cpp | C++ | src/soundengine/redbooksound.cpp | AllegianceZone/Allegiance | ef69a16638fb35e34cbb51f6aee891080f71d38b | [
"MIT"
] | 11 | 2015-01-11T08:45:18.000Z | 2022-01-28T09:20:54.000Z | src/soundengine/redbooksound.cpp | AllegianceZone/Allegiance | ef69a16638fb35e34cbb51f6aee891080f71d38b | [
"MIT"
] | 15 | 2015-05-25T20:22:41.000Z | 2017-08-14T17:10:57.000Z | src/soundengine/redbooksound.cpp | FreeAllegiance/Allegiance-AZ | 1d8678ddff9e2efc79ed449de6d47544989bc091 | [
"MIT"
] | 3 | 2015-07-12T05:50:54.000Z | 2017-08-13T06:42:50.000Z | //
// redbooksound.cpp
//
// SoundEngine support for redbook audio.
//
#include "pch.h"
#include "soundbase.h"
#include "redbooksound.h"
#include "ds3dutil.h"
using std::list;
namespace SoundEngine {
//
// A class dedicated to controling the volume of the CD player(s) on a system
//
class CDVolume
{
public:
enum { c_nMaxChannels = 8 };
private:
struct MixerLineData
{
HMIXEROBJ hmixer;
DWORD cChannels;
MIXERCONTROL mixercontrol;
MIXERCONTROLDETAILS_UNSIGNED vmixercontrolsOld[c_nMaxChannels];
};
public:
list<MixerLineData> m_listMixerLines;
CDVolume()
{
UINT uMaxDevices = mixerGetNumDevs(); //Fix memory leak -Imago 8/2/09
// find all of the CD line controls and store their ID and starting volume
for (UINT uDeviceID = 0; uDeviceID < uMaxDevices; ++uDeviceID)
{
HMIXEROBJ hmixer;
//
// open the mixer in question
//
if (MMSYSERR_NOERROR != mixerOpen((LPHMIXER)&hmixer, uDeviceID, NULL, NULL, MIXER_OBJECTF_MIXER))
{
debugf("Failed to open mixer %d\n", uDeviceID);
continue;
}
//
// look for a mixer line attached to a CD
//
MIXERLINE mixerline;
mixerline.cbStruct = sizeof(mixerline);
mixerline.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC;
if (MMSYSERR_NOERROR != mixerGetLineInfo(hmixer, &mixerline, MIXER_GETLINEINFOF_COMPONENTTYPE)
|| mixerline.cControls == 0)
{
debugf("Failed to find CD line on mixer %d\n", uDeviceID);
mixerClose((HMIXER)hmixer);
continue;
}
//
// look for a volume control for that mixer line
//
MIXERLINECONTROLS mixerlinecontrols;
MixerLineData mixerlinedata;
mixerlinecontrols.cbStruct = sizeof(mixerlinecontrols);
mixerlinecontrols.dwLineID = mixerline.dwLineID;
mixerlinecontrols.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
mixerlinecontrols.cControls = 1;
mixerlinecontrols.cbmxctrl = sizeof(MIXERCONTROL);
mixerlinecontrols.pamxctrl = &(mixerlinedata.mixercontrol);
mixerlinedata.hmixer = hmixer;
mixerlinedata.cChannels = mixerline.cChannels;
if (MMSYSERR_NOERROR !=
mixerGetLineControls(hmixer, &mixerlinecontrols, MIXER_GETLINECONTROLSF_ONEBYTYPE))
{
debugf("Failed to find CD volume fader on mixer %d\n", uDeviceID);
mixerClose((HMIXER)hmixer);
continue;
}
// don't try to use more than 8 channels (not likely to be a problem)
if (mixerlinedata.cChannels > c_nMaxChannels)
mixerlinedata.cChannels = 1;
//
// Get the initial volume settings (so we can restore them when we are done)
//
MIXERCONTROLDETAILS mixercontroldetails;
mixercontroldetails.cbStruct = sizeof(MIXERCONTROLDETAILS);
mixercontroldetails.dwControlID = mixerlinedata.mixercontrol.dwControlID;
mixercontroldetails.cChannels = mixerlinedata.cChannels;
mixercontroldetails.cMultipleItems = 0;
mixercontroldetails.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
mixercontroldetails.paDetails = &(mixerlinedata.vmixercontrolsOld);
if (MMSYSERR_NOERROR !=
mixerGetControlDetails(hmixer, &mixercontroldetails, MIXER_GETCONTROLDETAILSF_VALUE))
{
debugf("Failed to get previous volume levels for mixer %d\n", uDeviceID);
mixerClose((HMIXER)hmixer);
continue;
}
// add this to the list of volume controls
m_listMixerLines.push_back(mixerlinedata);
}
}
~CDVolume()
{
// restore the volume settings for all of the CD players
while (!m_listMixerLines.empty())
{
MixerLineData& mixerlinedata = m_listMixerLines.back();
MIXERCONTROLDETAILS mixercontroldetails;
mixercontroldetails.cbStruct = sizeof(MIXERCONTROLDETAILS);
mixercontroldetails.dwControlID = mixerlinedata.mixercontrol.dwControlID;
mixercontroldetails.cChannels = mixerlinedata.cChannels;
mixercontroldetails.cMultipleItems = 0;
mixercontroldetails.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
mixercontroldetails.paDetails = &(mixerlinedata.vmixercontrolsOld);
ZVerify(mixerSetControlDetails(mixerlinedata.hmixer, &mixercontroldetails, MIXER_SETCONTROLDETAILSF_VALUE)
== MMSYSERR_NOERROR);
ZVerify(mixerClose((HMIXER)mixerlinedata.hmixer) == MMSYSERR_NOERROR);
m_listMixerLines.pop_back();
}
}
HRESULT SetGain(float fGain)
{
if (fGain > 0.0f)
{
return E_INVALIDARG;
}
const float fMinGain = -40;
float fClippedGain = max(fMinGain, fGain);
// set the volume on every CD player (since we can't map to the right one)
// restore the volume settings for all of the CD players
std::list<MixerLineData>::iterator mixerline;
for (mixerline = m_listMixerLines.begin(); mixerline != m_listMixerLines.end(); ++mixerline)
{
MixerLineData& mixerlinedata = *mixerline;
// translate the gain to a linear volume setting.
MIXERCONTROLDETAILS_UNSIGNED volume;
volume.dwValue = (DWORD)(mixerlinedata.mixercontrol.Bounds.dwMinimum
+ (mixerlinedata.mixercontrol.Bounds.dwMaximum - mixerlinedata.mixercontrol.Bounds.dwMinimum)
* (1 - fClippedGain/fMinGain));
// set the volume for this control
MIXERCONTROLDETAILS mixercontroldetails;
mixercontroldetails.cbStruct = sizeof(MIXERCONTROLDETAILS);
mixercontroldetails.dwControlID = mixerlinedata.mixercontrol.dwControlID;
mixercontroldetails.cChannels = 1;
mixercontroldetails.cMultipleItems = 0;
mixercontroldetails.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
mixercontroldetails.paDetails = &volume;
ZVerify(mixerSetControlDetails(mixerlinedata.hmixer, &mixercontroldetails, MIXER_SETCONTROLDETAILSF_VALUE)
== MMSYSERR_NOERROR);
}
return S_OK;
}
};
//
// An implementation of a generic disk player wrapper that wraps a CD player
//
class DiskPlayerImpl : public IDiskPlayer, private WorkerThread
{
UINT m_idDevice;
// the device name
ZString m_strElementName;
// a critical section controling access to the queued track and current track
CriticalSection m_csTrack;
enum { trackEmpty = -1, trackStop = 0 };
// the next track to play (trackEmpty if the queue is empty, or trackStop
// if a stop is queued).
volatile int m_nQueuedTrack;
// the current track of the CD player (or trackStop if the cd player is stopped).
volatile int m_nCurrentTrack;
CDVolume m_cdvolume;
public:
DiskPlayerImpl() :
m_nQueuedTrack(trackEmpty),
m_nCurrentTrack(trackStop)
{
};
~DiskPlayerImpl()
{
StopThread();
}
HRESULT Init(const ZString& strDevice)
{
DWORD dwError;
// try to open the device
MCI_OPEN_PARMSA mciOpenParms;
DWORD dwFlags;
mciOpenParms.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO;
dwFlags = MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID;
// translate the device name into an element name, if appropriate
if (!strDevice.IsEmpty())
{
m_strElementName = TranslateElementName(strDevice);
mciOpenParms.lpstrElementName = m_strElementName;
dwFlags |= MCI_OPEN_ELEMENT;
}
// try opening it to make sure it exists
dwError = mciSendCommand(NULL, MCI_OPEN, dwFlags, (UINT_PTR)&mciOpenParms); //Fix memory leak -Imago 8/2/09
if (dwError)
{
char cbError[256];
mciGetErrorStringA(dwError, cbError, 256);
debugf("Open failed for CD Audio device '%c': %s\n", (const char*)strDevice, cbError);
return E_FAIL;
}
mciSendCommand(mciOpenParms.wDeviceID, MCI_CLOSE, 0, NULL);
// start the background (io) thread
StartThread(THREAD_PRIORITY_NORMAL, 200);
return S_OK;
}
void ThreadInit()
{
DWORD dwError;
// try to open the device
MCI_OPEN_PARMSA mciOpenParms;
DWORD dwFlags;
ZString strElementName;
mciOpenParms.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO;
dwFlags = MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID;
if (!m_strElementName.IsEmpty())
{
mciOpenParms.lpstrElementName = m_strElementName;
dwFlags |= MCI_OPEN_ELEMENT;
}
dwError = mciSendCommand(NULL, MCI_OPEN, dwFlags, (UINT_PTR)&mciOpenParms);
if (dwError)
{
char cbError[256];
mciGetErrorStringA(dwError, cbError, 256);
debugf("Open failed for CD Audio device '%': %s\n", (const char*)m_strElementName, cbError);
}
m_idDevice = mciOpenParms.wDeviceID;
// Set the time format to track/minute/second/frame (TMSF).
MCI_SET_PARMS mciSetParms;
mciSetParms.dwTimeFormat = MCI_FORMAT_TMSF;
dwError = mciSendCommand(m_idDevice, MCI_SET, MCI_SET_TIME_FORMAT, (UINT_PTR)&mciSetParms);
if (dwError)
{
char cbError[256];
mciGetErrorStringA(dwError, cbError, 256);
debugf("Set format failed for CD Audio device: %s\n", cbError);
}
}
// called for background thread; changes state (since that can involve
// slow blocking calls) and updates the state (since the state is read
// frequently and querying the device is a bit slow)
bool ThreadIteration()
{
// fetch the current requested state and copy it to the current state
int nRequestedTrack;
int nOldTrack;
{
CriticalSectionLock lock(m_csTrack);
nOldTrack = m_nCurrentTrack;
nRequestedTrack = m_nQueuedTrack;
if (nRequestedTrack != trackEmpty)
m_nCurrentTrack = nRequestedTrack;
m_nQueuedTrack = trackEmpty;
}
// if there is a new state requested, make that change
if (nRequestedTrack != trackEmpty)
{
if (nRequestedTrack == trackStop)
StopImpl();
else
PlayImpl(nRequestedTrack);
}
// otherwise, just update the current state
else
{
if ((nOldTrack != trackStop) && (IsPlayingImpl() != S_OK))
{
CriticalSectionLock lock(m_csTrack);
m_nCurrentTrack = trackStop;
}
}
return true;
}
void ThreadCleanup()
{
StopImpl();
mciSendCommand(m_idDevice, MCI_CLOSE, 0, NULL);
}
ZString TranslateElementName(const ZString& strDevice)
{
if (strDevice.Find(':') != -1)
{
return strDevice;
}
else
{
// get a list of all of the drives on the system
char cTemp;
int nDrivesStringLength = GetLogicalDriveStringsA(1, &cTemp);
if (nDrivesStringLength == 0)
{
ZError("Error getting drives list\n");
return strDevice;
}
char* cbDrives = (char*)_alloca(nDrivesStringLength);
nDrivesStringLength = GetLogicalDriveStringsA(nDrivesStringLength, cbDrives);
if (nDrivesStringLength == 0)
{
ZError("Error getting drives list\n");
return strDevice;
}
// search through the list of drives looking for a CD-ROM who's volume
// label matches strDevice
while (cbDrives[0] != '\0')
{
const int c_nVolumeNameLength = 1024;
char cbVolumeName[c_nVolumeNameLength];
if (GetDriveTypeA(cbDrives) == DRIVE_CDROM
&& GetVolumeInformationA(cbDrives, cbVolumeName,
c_nVolumeNameLength, NULL, NULL, NULL, NULL, 0))
{
if (_stricmp(strDevice, cbVolumeName) == 0)
{
return cbDrives;
}
}
cbDrives += strlen(cbDrives) + 1;
}
return strDevice;
}
}
// plays one track
virtual HRESULT Play(int nTrack)
{
CriticalSectionLock lock(m_csTrack);
if (nTrack <= 0)
{
return E_INVALIDARG;
}
m_nQueuedTrack = nTrack;
return S_OK;
}
// stops the CD player
virtual HRESULT Stop()
{
CriticalSectionLock lock(m_csTrack);
m_nQueuedTrack = trackStop;
return S_OK;
}
// returns S_OK if the CD player is playing, S_FALSE otherwise
virtual HRESULT IsPlaying()
{
CriticalSectionLock lock(m_csTrack);
int nTrack;
if (m_nQueuedTrack != trackEmpty)
{
nTrack = m_nQueuedTrack;
}
else
{
nTrack = m_nCurrentTrack;
}
return (nTrack == trackStop) ? S_FALSE : S_OK;
}
// returns the current track of the CD player
virtual HRESULT GetCurrentTrack(int& nTrack)
{
CriticalSectionLock lock(m_csTrack);
if (m_nQueuedTrack != trackEmpty)
{
nTrack = m_nQueuedTrack;
}
else
{
nTrack = m_nCurrentTrack;
}
return (nTrack != trackStop) ? S_OK : E_FAIL;
}
// sets the gain on the CD player, from 0 to -100 dB
virtual HRESULT SetGain(float fGain)
{
return m_cdvolume.SetGain(fGain);
};
// plays one track (blocking)
HRESULT PlayImpl(int nTrack)
{
MCI_PLAY_PARMS mciPlayParms;
mciPlayParms.dwFrom = MCI_MAKE_TMSF(nTrack, 0, 0, 0);
mciPlayParms.dwTo = MCI_MAKE_TMSF(nTrack + 1, 0, 0, 0);
DWORD dwError = mciSendCommand(m_idDevice, MCI_PLAY, MCI_FROM | MCI_TO, (UINT_PTR)&mciPlayParms);
// if the track is out of range, retry without the stop point in case
// this is the last track on the CD. (review: we could store it, but
// this case handles switching the CD)
if (dwError == MCIERR_OUTOFRANGE)
dwError = mciSendCommand(m_idDevice, MCI_PLAY, MCI_FROM, (UINT_PTR)&mciPlayParms);
// this is the highest track on the CD
if (dwError)
{
char cbError[256];
mciGetErrorStringA(dwError, cbError, 256);
debugf("Play track %d failed for CD Audio device: %s\n", nTrack, cbError);
return E_FAIL;
}
return S_OK;
};
// stops the CD player (blocking)
HRESULT StopImpl()
{
DWORD dwError = mciSendCommand(m_idDevice, MCI_STOP, 0, NULL);
if (dwError)
{
char cbError[256];
mciGetErrorStringA(dwError, cbError, 256);
debugf("Stop failed for CD Audio device: %s\n", cbError);
return E_FAIL;
}
return S_OK;
};
// returns S_OK if the CD player is playing, S_FALSE otherwise (blocking)
HRESULT IsPlayingImpl()
{
MCI_STATUS_PARMS mciStatusParams;
mciStatusParams.dwItem = MCI_STATUS_MODE;
DWORD dwError = mciSendCommandA(m_idDevice, MCI_STATUS, MCI_STATUS_ITEM, (UINT_PTR)&mciStatusParams);
if (dwError)
{
char cbError[256];
mciGetErrorStringA(dwError, cbError, 256);
debugf("Status:Mode failed for CD Audio device: %s\n", cbError);
return E_FAIL;
}
return (mciStatusParams.dwReturn == MCI_MODE_PLAY) ? S_OK : S_FALSE;
};
// returns the current track of the CD player (blocking)
HRESULT GetCurrentTrackImpl(int& nTrack)
{
MCI_STATUS_PARMS mciStatusParams;
mciStatusParams.dwItem = MCI_STATUS_CURRENT_TRACK;
DWORD dwError = mciSendCommand(m_idDevice, MCI_STATUS, MCI_STATUS_ITEM, (UINT_PTR)&mciStatusParams);
if (dwError)
{
char cbError[256];
mciGetErrorStringA(dwError, cbError, 256);
debugf("Status:Track failed for CD Audio device: %s\n", cbError);
return E_FAIL;
}
nTrack = mciStatusParams.dwReturn;
return S_OK;
};
};
// Creates a new disk player object (CD, minidisk, etc.). strDevice can be
// empty (choose any device), a path ("E:\"), or a volume label.
HRESULT CreateDiskPlayer(TRef<IDiskPlayer>& pdiskplayer, const ZString& strDevice)
{
TRef<DiskPlayerImpl> pdiskplayerimpl = new DiskPlayerImpl();
HRESULT hr = pdiskplayerimpl->Init(strDevice);
if (SUCCEEDED(hr))
pdiskplayer = pdiskplayerimpl;
return hr;
};
class DummyDiskPlayer : public IDiskPlayer
{
public:
// plays one track
virtual HRESULT Play(int nTrack)
{
return S_OK;
};
// stops the CD player
virtual HRESULT Stop()
{
return S_OK;
};
// returns S_OK if the CD player is playing
virtual HRESULT IsPlaying()
{
return S_FALSE;
};
// returns the current track of the CD player
virtual HRESULT GetCurrentTrack(int& nTrack)
{
nTrack = 1;
return S_OK;
};
// sets the gain on the CD player, from 0 to -100 dB
virtual HRESULT SetGain(float fGain)
{
return S_OK;
};
};
// Creates a new disk player object that only has stubs for each of the calls
HRESULT CreateDummyDiskPlayer(TRef<IDiskPlayer>& pdiskplayer)
{
pdiskplayer = new DummyDiskPlayer();
return S_OK;
}
// a template for redbook audio
class RedbookSoundTemplate : public ISoundTemplate
{
private:
TRef<IDiskPlayer> m_pdiskplayer;
int m_nTrack;
//
// Playback controls
//
class RedbookSoundInstance : public ISoundInstance
{
TRef<IDiskPlayer> m_pdiskplayer;
int m_nTrack;
public:
RedbookSoundInstance(TRef<IDiskPlayer> pdiskplayer, int nTrack) :
m_pdiskplayer(pdiskplayer),
m_nTrack(nTrack)
{
pdiskplayer->Play(nTrack);
}
// Stops the sound. If bForceNow is true the sound will stop ASAP,
// possibly popping. If it is false some sounds may play a trail-off
// sound or fade away.
virtual HRESULT Stop(bool bForceNow = false)
{
HRESULT hr = IsPlaying();
if (hr == S_OK)
{
return m_pdiskplayer->Stop();
}
else if (SUCCEEDED(hr))
return S_OK;
else
return hr;
}
// returns S_OK if the sound is currently playing, S_FALSE otherwise.
virtual HRESULT IsPlaying()
{
HRESULT hr = m_pdiskplayer->IsPlaying();
if (hr == S_OK)
{
// it's playing, but is it playing our track or something else?
int nTrack;
hr = m_pdiskplayer->GetCurrentTrack(nTrack);
if (FAILED(hr))
return hr;
return (nTrack == m_nTrack) ? S_OK : S_FALSE;
}
else
return hr;
}
// Gets an event which fires when the sound finishes playing (for any
// reason)
virtual IEventSource* GetFinishEventSource()
{
ZError("NYI");
return NULL;
}
// Gets an interface for tweaking the sound, if supported, NULL otherwise.
virtual TRef<ISoundTweakable> GetISoundTweakable()
{
return NULL;
}
virtual TRef<ISoundTweakable3D> GetISoundTweakable3D()
{
return NULL;
}
};
public:
// tries to initialize the object with the given file.
HRESULT Init(TRef<IDiskPlayer> pdiskplayer, int nTrack)
{
if (!pdiskplayer)
{
ZAssert(false);
return E_POINTER;
}
if (nTrack <= 0)
{
ZAssert(false);
return E_INVALIDARG;
}
m_pdiskplayer = pdiskplayer;
m_nTrack = nTrack;
return S_OK;
};
// Creates a new instance of the given sound
virtual HRESULT CreateSound(TRef<ISoundInstance>& psoundNew,
ISoundBufferSource* pbufferSource, ISoundPositionSource* psource = NULL)
{
if (!pbufferSource)
{
ZAssert(false);
return E_POINTER;
}
if (psource)
{
ZAssert(false);
return E_NOTIMPL;
}
psoundNew = new RedbookSoundInstance(m_pdiskplayer, m_nTrack);
return S_OK;
}
};
// creates a sound template representing a redbook audio track
HRESULT CreateRedbookSoundTemplate(TRef<ISoundTemplate>& pstDest, TRef<IDiskPlayer> pdiskplayer, int nTrack)
{
TRef<RedbookSoundTemplate> ptemplate = new RedbookSoundTemplate();
HRESULT hr = ptemplate->Init(pdiskplayer, nTrack);
if (ZSucceeded(hr))
pstDest = ptemplate;
return hr;
}
}; | 29.612991 | 119 | 0.588512 | [
"object"
] |
77df0ef132cb99f499fae386be29d42c70b2db87 | 980 | cpp | C++ | 661/P661/P661/main.cpp | swy20190/Leetcode-Cracker | 3b80eacfa63983d5fcc50442f0813296d5c1af94 | [
"MIT"
] | null | null | null | 661/P661/P661/main.cpp | swy20190/Leetcode-Cracker | 3b80eacfa63983d5fcc50442f0813296d5c1af94 | [
"MIT"
] | null | null | null | 661/P661/P661/main.cpp | swy20190/Leetcode-Cracker | 3b80eacfa63983d5fcc50442f0813296d5c1af94 | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
vector<vector<int>> num = M;
int row = M.size();
int col = M[0].size();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int m = 1;
int n;
if (M[i][j] != 0) {
n = M[i][j];
}
else {
n = 0;
}
if (i > 0) {
m++;
n += M[i - 1][j];
}
if (i < row - 1) {
m++;
n += M[i + 1][j];
}
if (j > 0) {
m += 1;
n += M[i][j - 1];
}
if (j < col - 1) {
m += 1;
n += M[i][j + 1];
}
if (i > 0 && j > 0) {
m += 1;
n += M[i - 1][j - 1];
}
if (i > 0 && j < col - 1) {
m += 1;
n += M[i - 1][j + 1];
}
if (i < row - 1 && j>0) {
m += 1;
n += M[i + 1][j - 1];
}
if (i < row - 1 && j < col - 1) {
m += 1;
n += M[i + 1][j + 1];
}
num[i][j] = n / m;
}
}
return num;
}
}; | 16.896552 | 60 | 0.32449 | [
"vector"
] |
77e0ddd8f497454d7e1bea8564def2bc3709b045 | 8,582 | cpp | C++ | scripts/workload.cpp | Renz7/gStore | 99b01a8951342f28abb985089278f8f81434f875 | [
"BSD-3-Clause"
] | 408 | 2018-08-30T14:07:16.000Z | 2022-03-30T05:19:20.000Z | scripts/workload.cpp | Renz7/gStore | 99b01a8951342f28abb985089278f8f81434f875 | [
"BSD-3-Clause"
] | 55 | 2018-09-29T10:47:05.000Z | 2022-03-28T02:23:48.000Z | scripts/workload.cpp | Renz7/gStore | 99b01a8951342f28abb985089278f8f81434f875 | [
"BSD-3-Clause"
] | 149 | 2018-09-06T08:04:11.000Z | 2022-03-30T08:43:21.000Z | #include <iostream>
#include <set>
#include <vector>
#include <deque>
#include <algorithm>
#include <fstream>
#include <mutex>
#include <thread>
#include "../Database/Txn_manager.h"
using namespace std;
struct task
{
string op1;
string op2;
string op3;
task() {op1 = op2 = op3 = "";}
};
class task_manager
{
private:
ifstream insert_if;
ifstream delete_if;
mutex l;
const string insert_filename = "./scripts/insert.nt";
const string delete_filename = "./scripts/delete.nt";
public:
task get_task();
task_manager();
~task_manager();
};
task_manager::task_manager()
{
insert_if.open(insert_filename, ios::in);
delete_if.open(delete_filename, ios::in);
}
task_manager::~task_manager()
{
insert_if.close();
delete_if.close();
}
task task_manager::get_task()
{
task t;
l.lock();
string sparql;
getline(insert_if, sparql);
if(insert_if.eof()) {
l.unlock();
return t;
}
t.op1 = sparql;
getline(insert_if, sparql);
t.op2 = sparql;
getline(delete_if, sparql);
t.op3 = sparql;
l.unlock();
return t;
}
class writer
{
private:
ofstream of;
mutex lock;
atomic<int> n;
const string out_filename = "./scripts/statics.txt";
public:
writer();
~writer();
void write_task(task &t, int code);
void write_num(int num);
void write_dataset(vector<IDSet>& readset, vector<IDSet>& writeset, txn_id_t TID);
};
writer::writer()
{
of.open(out_filename, ios::out);
n.store(1);
}
writer::~writer()
{
of.close();
}
void writer::write_task(task &t, int code)
{
lock.lock();
of << "#" << code << endl << t.op1 << endl << t.op2 << endl << t.op3 << endl;
n++;
lock.unlock();
}
void writer::write_num(int num)
{
lock.lock();
of << "###" << n.load() << ": " << num << endl;
n++;
lock.unlock();
}
void writer::write_dataset(vector<IDSet>& readset, vector<IDSet>& writeset, txn_id_t TID)
{
lock.lock();
of << TID << endl;
of << "read set: " << endl;
for(int i = 0; i < 3; i++){
for(auto id: readset[i])
{
of << id << " ";
}
of << endl;
}
of << "write set: " << endl;
for(int i = 0; i < 3; i++){
for(auto id: writeset[i])
{
of << id << " ";
}
of << endl;
}
of << endl;
lock.unlock();
}
task_manager t_m;
writer w;
void func()
{
task t;
int cnt = 0;
while(1){
t = t_m.get_task();
if(t.op1 == "") break;
//start transaction
w.write_task(t, 1);
cnt++;
}
cout << this_thread::get_id() << " " << cnt << endl;
}
void run_transaction(int isolevel, Txn_manager& txn_m)
{
task t;
while(true){
t = t_m.get_task();
if(t.op1 == "") return;
string res, sparql;
int cnt = 0;
int base_time = 1000;
txn_id_t TID;
int num = 0;
while(true){
TID = txn_m.Begin(static_cast<IsolationLevelType>(isolevel));
//cerr << "transaction #" << TID << endl;
int ret;
cnt++;
sparql = "insert data {" + t.op1 + "}";
ret = txn_m.Query(TID, sparql, res);
if(ret < 0) {
//cerr << "insert 1 failed ! " << ret << endl;
usleep(base_time);
base_time = min(base_time*2, 1000000);
continue;
}
sparql = "insert data {" + t.op2 + "}";
ret = txn_m.Query(TID, sparql, res);
if(ret < 0) {
//cerr << "insert 2 failed ! " << ret << endl;
usleep(base_time);
base_time = min(base_time*2, 1000000);
continue;
}
sparql = "delete data {" + t.op3 + "}";
ret = txn_m.Query(TID, sparql, res);
if(ret < 0) {
//cerr << "delete 1 failed ! " << ret << endl;
usleep(base_time);
base_time = min(base_time*2, 1000000);
continue;
}
if(txn_m.Commit(TID) == 0) break;
}
w.write_num(cnt);
}
}
void create_versions(Txn_manager& txn_m)
{
string query = "select ?v {<V1> <R1> ?v.}";
string insert1 = "insert data { <V1> <R1> \"5\"^^<http://www.w3.org/2001/XMLSchema#integer> }";
string insert2 = "insert data { <V1> <R1> \"15\"^^<http://www.w3.org/2001/XMLSchema#integer> }";
string delete1 = "delete data { <V1> <R1> \"5\"^^<http://www.w3.org/2001/XMLSchema#integer> }";
string delete2 = "delete data { <V1> <R1> \"15\"^^<http://www.w3.org/2001/XMLSchema#integer> }";
string res;
txn_id_t id = txn_m.Begin();
txn_m.Query(id, query, res);
txn_m.print_txn_dataset(id);
txn_m.Commit(id);
id = txn_m.Begin();
txn_m.Query(id, insert1, res);
txn_m.print_txn_dataset(id);
txn_m.Commit(id);
id = txn_m.Begin();
txn_m.Query(id, insert2, res);
txn_m.print_txn_dataset(id);
txn_m.Commit(id);
id = txn_m.Begin();
txn_m.Query(id, delete1, res);
txn_m.print_txn_dataset(id);
txn_m.Commit(id);
id = txn_m.Begin();
txn_m.Query(id, delete2, res);
txn_m.print_txn_dataset(id);
txn_m.Commit(id);
}
void no_txn_update(Database &db)
{
const string insert_filename = "./scripts/insert.nt";
const string delete_filename = "./scripts/delete.nt";
fstream in;
string line, sparql, res;
ResultSet rs;
in.open(insert_filename, ios::in);
while(getline(in, line))
{
sparql = "insert data {" + line + "}";
FILE *fp = stdout;
db.query(sparql, rs, fp);
}
in.close();
in.open(delete_filename, ios::in);
while(getline(in, line))
{
sparql = "delete data {" + line + "}";
FILE *fp = stdout;
db.query(sparql, rs, fp);
}
in.close();
}
bool single_txn(int threads_num, Txn_manager& txn_m)
{
txn_id_t TID = txn_m.Begin(static_cast<IsolationLevelType>(3));
ifstream in;
string line, sparql, res;
in.open("./scripts/insert.nt", ios::in);
int num = 0;
while(getline(in, line))
{
sparql = "insert data {" + line + "}";
int ret = txn_m.Query(TID, sparql, res);
num += ret;
//txn_m.Get_Transaction(TID)->print_all();
//if(ret != 0) cerr << "wrong answer!" << endl;
// getline(in, line);
// sparql = "insert data {" + line + "}";
// ret = txn_m.Query(TID, sparql, res);
//txn_m.Get_Transaction(TID)->print_all();
//if(ret != 0) cerr << "wrong answer!" << endl;
}
in.close();
in.open("./scripts/delete.nt", ios::in);
while(getline(in, line))
{
sparql = "delete data{" + line + "}";
int ret = txn_m.Query(TID, sparql, res);
//if(ret == 0) cerr << "wrong answer!wrong answer!wrong answer!wrong answer!" << endl;
num += ret;
}
//txn_m.Get_Transaction(TID)->print_all();
in.close();
txn_m.Commit(TID);
cout << "update num: " << num << endl;
return true;
}
void check_results(int threads_num, Txn_manager& txn_m)
{
txn_id_t TID = txn_m.Begin();
ifstream in;
in.open("./scripts/insert.nt", ios::in);
for(int i = 0; i < threads_num; i++)
{
string line, sparql, res;
getline(in, line);
sparql = "ask where {" + line + "}";
int ret = txn_m.Query(TID, sparql, res);
cout << res << endl;
getline(in, line);
sparql = "ask where {" + line + "}";
ret = txn_m.Query(TID, sparql, res);
cout << res << endl;
}
in.close();
in.open("./scripts/delete.nt", ios::in);
for(int i = 0; i < threads_num; i++)
{
string line, sparql, query, res;
getline(in, line);
sparql = "ask where{" + line + "}";
int ret = txn_m.Query(TID, sparql, res);
cout << res << endl;
}
txn_m.Commit(TID);
}
int main(int argc, char* argv[])
{
Util util;
string db_folder = "lubm";
Database _db(db_folder);
_db.load();
cout << "finish loading" << endl;
Txn_manager txn_m(&_db, string("lubm"));
int threads_num;
//threads_num = thread::hardware_concurrency()-1;
threads_num = 17;
vector<thread> pool(threads_num);
int n = pool.size();
cout << n;
for(int i = 0; i < n; i++)
{
pool[i] = thread(run_transaction, 1 , ref(txn_m));
//pool[i] = thread(create_versions, ref(txn_m));
//pool[i] = thread(func);
}
for(int i = 0; i < n; i++)
{
pool[i].join();
}
// single_txn(61, txn_m);
// check_results(61, txn_m);
// no_txn_update(_db);
// single_txn(61, txn_m);
cout << "workload finished!" << endl;
return 0;
} | 23.972067 | 97 | 0.544978 | [
"vector"
] |
77e2ba10cd616db964b9293b54198520dd7a543d | 6,954 | cpp | C++ | src/stsort.cpp | jeewhanchoi/row-sparse-cpstream | 29525f45d2e8344f07c99efd614f0b3934bf9cfb | [
"MIT"
] | null | null | null | src/stsort.cpp | jeewhanchoi/row-sparse-cpstream | 29525f45d2e8344f07c99efd614f0b3934bf9cfb | [
"MIT"
] | null | null | null | src/stsort.cpp | jeewhanchoi/row-sparse-cpstream | 29525f45d2e8344f07c99efd614f0b3934bf9cfb | [
"MIT"
] | null | null | null | #include "stsort.hpp"
#include <algorithm>
#include <omp.h>
// intel parallel stl includes:
#if __INTEL_COMPILER
#include "pstl/algorithm"
#include "pstl/execution"
#endif
inline int ceil_log2(unsigned long long x)
{
static const unsigned long long t[6] = {
0xFFFFFFFF00000000ull,
0x00000000FFFF0000ull,
0x000000000000FF00ull,
0x00000000000000F0ull,
0x000000000000000Cull,
0x0000000000000002ull
};
int y = (((x & (x - 1)) == 0) ? 0 : 1);
int j = 32;
int i;
for (i = 0; i < 6; i++) {
int k = (((x & t[i]) == 0) ? 0 : j);
y += k;
x >>= k;
j >>= 1;
}
return y;
}
// most naive histogram prefix sum (columnwise with wrap around)
void colwise_prefix(idx_t* hist, idx_t n, idx_t nrows) {
// expects a matrix of p*n
//int nthreads = splatt_omp_get_num_threads();
//int tid = splatt_omp_get_thread_num();
idx_t* sums;
#pragma omp parallel
{
int tid = omp_get_thread_num();
int p = omp_get_num_threads();
#pragma omp single
{
//sums = (idx_t*)malloc(nthreads*64);
sums = (idx_t*)malloc(p*sizeof(idx_t));
}
idx_t local_sum = 0;
// TODO: block by cachelines
// TODO: figure out if we can use horizontal adds for this
// TODO; use 32 bit impl. if total nnz (or # buckets) is < 2^31
// TODO: or even 16 bit impl if small enough ...
idx_t np = (n+p-1) / p;
idx_t tbegin = tid*np;
idx_t tend = std::min<idx_t>((tid+1)*np, n);
for (idx_t j = tbegin; j < tend; ++j) {
for (idx_t i = 0; i < nrows; ++i) {
const idx_t idx = i*n + j;
idx_t h = hist[idx];
hist[idx] = local_sum;
local_sum += h;
}
}
// TODO: use cachelines per thread (false sharing!)
//*(idx_t*)(((char*)sums) + 64*tid) = local_sum;
sums[tid] = local_sum;
#pragma omp barrier
idx_t local_offset = 0;
for (int i = 0; i < tid; ++i) {
local_offset += sums[i];
}
for (idx_t j = tbegin; j < tend; ++j) {
for (idx_t i = 0; i < nrows; ++i) {
const idx_t idx = i*n + j;
hist[idx] += local_offset;
}
}
}
}
idx_t* tt_bucket_sort(sptensor_t * const tt, const idx_t mode, bool coarsen, idx_t& num_bins) {
// TODO: chunking/coarsening of histogram bins
#if 0
const idx_t I = tt->dims[mode];
// TODO: case if < 16*p*64 elements
const idx_t approx_num_chunks = 16*omp_get_num_threads();
const idx_t chunk_size_log = max(ceil_log2(I / approx_num_chunks), 4);
const idx_t chunk_size = 1 << chunk_size_log;
const idx_t num_chunks = (I + (chunk_size - 1)) / chunk_size;
#endif
const idx_t I = tt->dims[mode];
idx_t num_chunks = I;
idx_t chunk_size_log = 0;
// set max number of chunks depending on number of threads
// TODO: do this dynamically based on load balance and sparseness etc
int nthreads = omp_get_max_threads();
if (coarsen) {
while (num_chunks > 128*nthreads) {
// pre-coarsening
chunk_size_log++;
num_chunks >>= 1;
}
const idx_t chunk_size = 1 << chunk_size_log;
num_chunks = (I + (chunk_size - 1)) / chunk_size;
}
num_bins = num_chunks;
// parallel bucketing into the num_chunks buckets
idx_t* hists;
{
timed_section ts("par_hist");
hists = my_par_hist(tt->ind[mode], tt->nnz, num_chunks, chunk_size_log);
}
// check if last row of `hists` is same as total prefix hist
// apply permutation (ie, sort the tensor data)
idx_t ** new_ind = (idx_t**) splatt_malloc(tt->nmodes*sizeof(idx_t*));
for (int m = 0; m < tt->nmodes; ++m) {
new_ind[m] = (idx_t*) splatt_malloc(tt->nnz*sizeof(idx_t));
}
val_t* new_vals = (val_t*) splatt_malloc(tt->nnz*sizeof(val_t));
{
timed_section ts("par-rearrange tt");
#pragma omp parallel
{
int tid = omp_get_thread_num();
int p = omp_get_num_threads();
idx_t* my_hist = hists + num_chunks*tid;
idx_t np = (tt->nnz + p - 1) / p;
idx_t tstart = tid*np;
idx_t tend = std::min<idx_t>((tid+1)*np, tt->nnz);
for (idx_t i = tstart; i < tend; ++i) {
const idx_t hidx = (tt->ind[mode][i] >> chunk_size_log);
const idx_t oidx = my_hist[hidx];
new_vals[oidx] = tt->vals[i];
for (int m = 0; m < tt->nmodes; ++m) {
new_ind[m][oidx] = tt->ind[m][i];
}
++my_hist[hidx];
}
}
}
// replace tensor data with sorted data
for (int m = 0; m < tt->nmodes; ++m) {
splatt_free(tt->ind[m]);
tt->ind[m] = new_ind[m];
}
splatt_free(new_ind);
splatt_free(tt->vals);
tt->vals = new_vals;
return hists;
}
// tensor std::sort
void tensor_stdsort_inplace(sptensor_t* const tt, idx_t mode) {
timed_section ts("tensor_stdsort");
{
timed_section t("create idx");
std::vector<size_t> idx(tt->nnz);
for (size_t i = 0; i < tt->nnz; ++i) {
idx[i] = i;
}
t.new_section("sort idx");
#if __INTEL_COMPILER
std::sort(std::execution::par, idx.begin(), idx.end(), [&](size_t x, size_t y) {
return (tt->ind[mode][x] < tt->ind[mode][y]);});
#else
// TODO: non intel parallel sort
std::sort(idx.begin(), idx.end(), [&](size_t x, size_t y) {
return (tt->ind[mode][x] < tt->ind[mode][y]);});
#endif
t.new_section("permuted tt.ind");
{
std::vector<idx_t> tmp(tt->nnz);
for (int m = 0; m < tt->nmodes; ++m) {
std::copy(tt->ind[m],tt->ind[m] + tt->nnz, tmp.begin());
for (idx_t i = 0; i < tt->nnz; ++i) {
tt->ind[m][i] = tmp[idx[i]];
}
}
}
t.new_section("permuted tt.vals");
{
std::vector<val_t> tmp(tt->nnz);
std::copy(tt->vals,tt->vals + tt->nnz, tmp.begin());
for (idx_t i = 0; i < tt->nnz; ++i) {
tt->vals[i] = tmp[idx[i]];
}
}
}
}
// tensor std::sort
void tensor_stdsort(const sptensor_t* const tt, idx_t mode, sptensor_t** out_tt) {
timed_section ts("tensor_stdsort");
{
timed_section t("create idx");
std::vector<size_t> idx(tt->nnz);
for (size_t i = 0; i < tt->nnz; ++i) {
idx[i] = i;
}
t.new_section("sort idx");
#if __INTEL_COMPILER
std::sort(std::execution::par, idx.begin(), idx.end(), [&](size_t x, size_t y) {
return (tt->ind[mode][x] < tt->ind[mode][y]);});
#else
// TODO: non-intel parallel sort
std::sort(idx.begin(), idx.end(), [&](size_t x, size_t y) {
return (tt->ind[mode][x] < tt->ind[mode][y]);});
#endif
t.new_section("alloc new tensor");
sptensor_t* stt = tt_alloc(tt->nnz, tt->nmodes);
t.new_section("permuted tt.ind");
for (int m = 0; m < tt->nmodes; ++m) {
for (idx_t i = 0; i < tt->nnz; ++i) {
stt->ind[m][i] = tt->ind[m][idx[i]];
}
}
t.new_section("permuted tt.vals");
for (idx_t i = 0; i < tt->nnz; ++i) {
stt->vals[i] = tt->vals[idx[i]];
}
*out_tt = stt;
}
}
| 25.851301 | 95 | 0.566005 | [
"vector"
] |
77e2f3bee5b39e9b424515910af6fe5e4bbaf734 | 8,891 | cpp | C++ | gl_7/main.cpp | leefige/OpenGL-Exercises | 16aecc159a9e658367de1cf7cbd4f268c5d3dc90 | [
"MIT"
] | null | null | null | gl_7/main.cpp | leefige/OpenGL-Exercises | 16aecc159a9e658367de1cf7cbd4f268c5d3dc90 | [
"MIT"
] | null | null | null | gl_7/main.cpp | leefige/OpenGL-Exercises | 16aecc159a9e658367de1cf7cbd4f268c5d3dc90 | [
"MIT"
] | null | null | null | /*
* OpenGL version 3.3 project.
*/
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <SOIL2/SOIL2.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include "shader.hpp"
#include "particalsys.hpp"
using namespace cg;
// window settings
int screenWidth = 800;
int screenHeight = 600;
FireWork** fireWorks;
const int fireWorkNum = 3;
GLfloat deltaTime = 0.0f; // Time between current frame and last frame
GLfloat lastFrame = 0.0f; // Time of last frame
// normalized coordinates
constexpr GLfloat vertices[] = {
// Positions // Colors
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Right
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // Bottom Left
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // Top
};
// callbacks
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mode);
void framebufferSizeCallback(GLFWwindow* window, int width, int height);
int main()
{
// Setup a GLFW window
// init GLFW, set GL version & pipeline info
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// create a window
GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "My OpenGL project", nullptr, nullptr);
if (window == nullptr) {
std::cerr << "Error creating window" << std::endl;
glfwTerminate();
return -1;
}
// use newly created window as context
glfwMakeContextCurrent(window);
// register callbacks
glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);
glfwSetKeyCallback(window, keyCallback);
// ---------------------------------------------------------------
// Connect GLAD to GLFW by registerring glfwGetProcAddress() as GLAD loader function,
// this must be done after setting current context
if (gladLoadGLLoader((GLADloadproc)glfwGetProcAddress) == 0) {
std::cerr << "Error registerring gladLoadGLLoader" << std::endl;
glfwTerminate();
return -2;
}
// ---------------------------------------------------------------
// Setup OpenGL options
glEnable(GL_DEPTH_TEST);
// Install GLSL Shader programs
auto shaderProgram = Shader::Create("VertexShader.vert", "FragmentShader.frag");
if (shaderProgram == nullptr) {
std::cerr << "Error creating Shader Program" << std::endl;
glfwTerminate();
return -3;
}
// ---------------------------------------------------------------
fireWorks = new FireWork * [fireWorkNum];
for (int i = 0; i < fireWorkNum; ++i) {
fireWorks[i] = new FireWork(500, 0.5, glm::vec3(rand() % (screenWidth / 3) + screenWidth / 3 * i, screenHeight / 4, 0),
glm::vec3(0.0, 70, 0.0), glm::vec3(0.0, -9.8, 0.0), (double)rand() / (double)RAND_MAX * 2 + 12);
// massNum: 500, each firework consists of 500 particle
// mass: 5, each particle's mass is 5
// position: start position
// speed: initial speed is (0, 70, 0)
// gravity: gravity is (0, -9.8, 0)
// lifeValue: existing time in seconds
}
GLfloat particle_quad[] = {
0.0f, 1.0f, 0.0f, 1.0f,
1.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 0.0f, 1.0f, 0.0f
};
// ---------------------------------------------------------------
// Set up vertex data (and buffer(s)) and attribute pointers
// bind VAO
GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// bind VBO, buffer data to it
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(particle_quad), particle_quad, GL_STATIC_DRAW);
// set vertex attribute pointers
// position attribute
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
// unbind VBO & VAO
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// ---------------------------------------------------------------
// Load and create a texture
GLuint texture;
// ====================
// Texture
// ====================
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object
// Set our texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set texture filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Load, create texture and generate mipmaps
int width, height;
unsigned char* image = SOIL_load_image("Particle.bmp", &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture.
// ---------------------------------------------------------------
// Define the viewport dimensions
glViewport(0, 0, screenWidth, screenHeight);
// Update loop
while (glfwWindowShouldClose(window) == 0) {
// Calculate deltatime of current frame
GLfloat currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// check event queue
glfwPollEvents();
/* your update code here */
// draw background
GLfloat red = 0.1f;
GLfloat green = 0.1f;
GLfloat blue = 0.1f;
glClearColor(red, green, blue, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
for (int i = 0; i < fireWorkNum; ++i) {
fireWorks[i]->Process(deltaTime * 3, glm::vec3(rand() % (screenWidth / 3) + screenWidth / 3 * i, screenHeight / 4, 0)); // apply gravity and update speed, position
}
// Draw
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glm::mat4 projection = glm::ortho(0.0f, GLfloat(screenWidth), 0.0f, GLfloat(screenHeight), -1.0f, 100.0f);
shaderProgram->Use();
GLint projLoc = glGetUniformLocation(shaderProgram->Program(), "projection");
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
for (int i = 0; i < fireWorkNum; ++i) {
if (fireWorks[i]->hasExploded) {
for (int j = 0; j < fireWorks[i]->GetMassNum(); ++j) {
GLint offsetLoc = glGetUniformLocation(shaderProgram->Program(), "offset");
glUniform2f(offsetLoc, fireWorks[i]->GetMass(j)->position[0], fireWorks[i]->GetMass(j)->position[1]);
GLint colorLoc = glGetUniformLocation(shaderProgram->Program(), "color");
glUniform4f(colorLoc, fireWorks[i]->GetMass(j)->color.r, fireWorks[i]->GetMass(j)->color.g, fireWorks[i]->GetMass(j)->color.b,
fireWorks[i]->GetMass(j)->color.a);
glBindTexture(GL_TEXTURE_2D, texture);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
}
} else {// before explosion, only one point
int j = 0;
GLint offsetLoc = glGetUniformLocation(shaderProgram->Program(), "offset");
glUniform2f(offsetLoc, fireWorks[i]->GetMass(j)->position[0], fireWorks[i]->GetMass(j)->position[1]);
GLint colorLoc = glGetUniformLocation(shaderProgram->Program(), "color");
glUniform4f(colorLoc, fireWorks[i]->GetMass(j)->color.r, fireWorks[i]->GetMass(j)->color.g, fireWorks[i]->GetMass(j)->color.b,
fireWorks[i]->GetMass(j)->color.a);
glBindTexture(GL_TEXTURE_2D, texture);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
}
}
// swap buffer
glfwSwapBuffers(window);
}
// properly de-allocate all resources
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}
/* ======================== helper functions ======================== */
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
// exit when pressing ESC
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
void framebufferSizeCallback(GLFWwindow* window, int width, int height)
{
screenWidth = width;
screenHeight = height;
// resize window
glViewport(0, 0, width, height);
}
| 34.196154 | 175 | 0.612192 | [
"object"
] |
77e9161aeea9a0d2a7451299f6251539e117af90 | 29,098 | cpp | C++ | javaStructures/jdk-master/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp | IThawk/learnCode | 0ac843d28b193eaab33fb33692f18361d71c7331 | [
"MIT"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | javaStructures/jdk-master/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp | IThawk/learnCode | 0ac843d28b193eaab33fb33692f18361d71c7331 | [
"MIT"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | javaStructures/jdk-master/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp | IThawk/learnCode | 0ac843d28b193eaab33fb33692f18361d71c7331 | [
"MIT"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | /*
* Copyright (c) 2018, 2021, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "gc/shenandoah/shenandoahBarrierSet.hpp"
#include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
#include "gc/shenandoah/shenandoahForwarding.hpp"
#include "gc/shenandoah/shenandoahHeap.inline.hpp"
#include "gc/shenandoah/shenandoahHeapRegion.hpp"
#include "gc/shenandoah/shenandoahRuntime.hpp"
#include "gc/shenandoah/shenandoahThreadLocalData.hpp"
#include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/interp_masm.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/thread.hpp"
#ifdef COMPILER1
#include "c1/c1_LIRAssembler.hpp"
#include "c1/c1_MacroAssembler.hpp"
#include "gc/shenandoah/c1/shenandoahBarrierSetC1.hpp"
#endif
#define __ masm->
void ShenandoahBarrierSetAssembler::arraycopy_prologue(MacroAssembler* masm, DecoratorSet decorators, bool is_oop,
Register src, Register dst, Register count, RegSet saved_regs) {
if (is_oop) {
bool dest_uninitialized = (decorators & IS_DEST_UNINITIALIZED) != 0;
if ((ShenandoahSATBBarrier && !dest_uninitialized) || ShenandoahIUBarrier || ShenandoahLoadRefBarrier) {
Label done;
// Avoid calling runtime if count == 0
__ cbz(count, done);
// Is GC active?
Address gc_state(rthread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
__ ldrb(rscratch1, gc_state);
if (ShenandoahSATBBarrier && dest_uninitialized) {
__ tbz(rscratch1, ShenandoahHeap::HAS_FORWARDED_BITPOS, done);
} else {
__ mov(rscratch2, ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::MARKING);
__ tst(rscratch1, rscratch2);
__ br(Assembler::EQ, done);
}
__ push(saved_regs, sp);
if (UseCompressedOops) {
__ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_narrow_oop_entry), src, dst, count);
} else {
__ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_oop_entry), src, dst, count);
}
__ pop(saved_regs, sp);
__ bind(done);
}
}
}
void ShenandoahBarrierSetAssembler::shenandoah_write_barrier_pre(MacroAssembler* masm,
Register obj,
Register pre_val,
Register thread,
Register tmp,
bool tosca_live,
bool expand_call) {
if (ShenandoahSATBBarrier) {
satb_write_barrier_pre(masm, obj, pre_val, thread, tmp, tosca_live, expand_call);
}
}
void ShenandoahBarrierSetAssembler::satb_write_barrier_pre(MacroAssembler* masm,
Register obj,
Register pre_val,
Register thread,
Register tmp,
bool tosca_live,
bool expand_call) {
// If expand_call is true then we expand the call_VM_leaf macro
// directly to skip generating the check by
// InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
assert(thread == rthread, "must be");
Label done;
Label runtime;
assert_different_registers(obj, pre_val, tmp, rscratch1);
assert(pre_val != noreg && tmp != noreg, "expecting a register");
Address in_progress(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_active_offset()));
Address index(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
Address buffer(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
// Is marking active?
if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
__ ldrw(tmp, in_progress);
} else {
assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
__ ldrb(tmp, in_progress);
}
__ cbzw(tmp, done);
// Do we need to load the previous value?
if (obj != noreg) {
__ load_heap_oop(pre_val, Address(obj, 0), noreg, noreg, AS_RAW);
}
// Is the previous value null?
__ cbz(pre_val, done);
// Can we store original value in the thread's buffer?
// Is index == 0?
// (The index field is typed as size_t.)
__ ldr(tmp, index); // tmp := *index_adr
__ cbz(tmp, runtime); // tmp == 0?
// If yes, goto runtime
__ sub(tmp, tmp, wordSize); // tmp := tmp - wordSize
__ str(tmp, index); // *index_adr := tmp
__ ldr(rscratch1, buffer);
__ add(tmp, tmp, rscratch1); // tmp := tmp + *buffer_adr
// Record the previous value
__ str(pre_val, Address(tmp, 0));
__ b(done);
__ bind(runtime);
// save the live input values
RegSet saved = RegSet::of(pre_val);
if (tosca_live) saved += RegSet::of(r0);
if (obj != noreg) saved += RegSet::of(obj);
__ push(saved, sp);
// Calling the runtime using the regular call_VM_leaf mechanism generates
// code (generated by InterpreterMacroAssember::call_VM_leaf_base)
// that checks that the *(rfp+frame::interpreter_frame_last_sp) == NULL.
//
// If we care generating the pre-barrier without a frame (e.g. in the
// intrinsified Reference.get() routine) then ebp might be pointing to
// the caller frame and so this check will most likely fail at runtime.
//
// Expanding the call directly bypasses the generation of the check.
// So when we do not have have a full interpreter frame on the stack
// expand_call should be passed true.
if (expand_call) {
assert(pre_val != c_rarg1, "smashed arg");
__ super_call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), pre_val, thread);
} else {
__ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), pre_val, thread);
}
__ pop(saved, sp);
__ bind(done);
}
void ShenandoahBarrierSetAssembler::resolve_forward_pointer(MacroAssembler* masm, Register dst, Register tmp) {
assert(ShenandoahLoadRefBarrier || ShenandoahCASBarrier, "Should be enabled");
Label is_null;
__ cbz(dst, is_null);
resolve_forward_pointer_not_null(masm, dst, tmp);
__ bind(is_null);
}
// IMPORTANT: This must preserve all registers, even rscratch1 and rscratch2, except those explicitely
// passed in.
void ShenandoahBarrierSetAssembler::resolve_forward_pointer_not_null(MacroAssembler* masm, Register dst, Register tmp) {
assert(ShenandoahLoadRefBarrier || ShenandoahCASBarrier, "Should be enabled");
// The below loads the mark word, checks if the lowest two bits are
// set, and if so, clear the lowest two bits and copy the result
// to dst. Otherwise it leaves dst alone.
// Implementing this is surprisingly awkward. I do it here by:
// - Inverting the mark word
// - Test lowest two bits == 0
// - If so, set the lowest two bits
// - Invert the result back, and copy to dst
bool borrow_reg = (tmp == noreg);
if (borrow_reg) {
// No free registers available. Make one useful.
tmp = rscratch1;
if (tmp == dst) {
tmp = rscratch2;
}
__ push(RegSet::of(tmp), sp);
}
assert_different_registers(tmp, dst);
Label done;
__ ldr(tmp, Address(dst, oopDesc::mark_offset_in_bytes()));
__ eon(tmp, tmp, zr);
__ ands(zr, tmp, markWord::lock_mask_in_place);
__ br(Assembler::NE, done);
__ orr(tmp, tmp, markWord::marked_value);
__ eon(dst, tmp, zr);
__ bind(done);
if (borrow_reg) {
__ pop(RegSet::of(tmp), sp);
}
}
void ShenandoahBarrierSetAssembler::load_reference_barrier(MacroAssembler* masm, Register dst, Address load_addr, DecoratorSet decorators) {
assert(ShenandoahLoadRefBarrier, "Should be enabled");
assert(dst != rscratch2, "need rscratch2");
assert_different_registers(load_addr.base(), load_addr.index(), rscratch1, rscratch2);
bool is_strong = ShenandoahBarrierSet::is_strong_access(decorators);
bool is_weak = ShenandoahBarrierSet::is_weak_access(decorators);
bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
bool is_native = ShenandoahBarrierSet::is_native_access(decorators);
bool is_narrow = UseCompressedOops && !is_native;
Label heap_stable, not_cset;
__ enter();
Address gc_state(rthread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
__ ldrb(rscratch2, gc_state);
// Check for heap stability
if (is_strong) {
__ tbz(rscratch2, ShenandoahHeap::HAS_FORWARDED_BITPOS, heap_stable);
} else {
Label lrb;
__ tbnz(rscratch2, ShenandoahHeap::WEAK_ROOTS_BITPOS, lrb);
__ tbz(rscratch2, ShenandoahHeap::HAS_FORWARDED_BITPOS, heap_stable);
__ bind(lrb);
}
// use r1 for load address
Register result_dst = dst;
if (dst == r1) {
__ mov(rscratch1, dst);
dst = rscratch1;
}
// Save r0 and r1, unless it is an output register
RegSet to_save = RegSet::of(r0, r1) - result_dst;
__ push(to_save, sp);
__ lea(r1, load_addr);
__ mov(r0, dst);
// Test for in-cset
if (is_strong) {
__ mov(rscratch2, ShenandoahHeap::in_cset_fast_test_addr());
__ lsr(rscratch1, r0, ShenandoahHeapRegion::region_size_bytes_shift_jint());
__ ldrb(rscratch2, Address(rscratch2, rscratch1));
__ tbz(rscratch2, 0, not_cset);
}
__ push_call_clobbered_registers();
if (is_strong) {
if (is_narrow) {
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow));
} else {
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong));
}
} else if (is_weak) {
if (is_narrow) {
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow));
} else {
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak));
}
} else {
assert(is_phantom, "only remaining strength");
assert(!is_narrow, "phantom access cannot be narrow");
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom));
}
__ blr(lr);
__ mov(rscratch1, r0);
__ pop_call_clobbered_registers();
__ mov(r0, rscratch1);
__ bind(not_cset);
__ mov(result_dst, r0);
__ pop(to_save, sp);
__ bind(heap_stable);
__ leave();
}
void ShenandoahBarrierSetAssembler::iu_barrier(MacroAssembler* masm, Register dst, Register tmp) {
if (ShenandoahIUBarrier) {
__ push_call_clobbered_registers();
satb_write_barrier_pre(masm, noreg, dst, rthread, tmp, true, false);
__ pop_call_clobbered_registers();
}
}
//
// Arguments:
//
// Inputs:
// src: oop location to load from, might be clobbered
//
// Output:
// dst: oop loaded from src location
//
// Kill:
// rscratch1 (scratch reg)
//
// Alias:
// dst: rscratch1 (might use rscratch1 as temporary output register to avoid clobbering src)
//
void ShenandoahBarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
Register dst, Address src, Register tmp1, Register tmp_thread) {
// 1: non-reference load, no additional barrier is needed
if (!is_reference_type(type)) {
BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp_thread);
return;
}
// 2: load a reference from src location and apply LRB if needed
if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
Register result_dst = dst;
// Preserve src location for LRB
if (dst == src.base() || dst == src.index()) {
dst = rscratch1;
}
assert_different_registers(dst, src.base(), src.index());
BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp_thread);
load_reference_barrier(masm, dst, src, decorators);
if (dst != result_dst) {
__ mov(result_dst, dst);
dst = result_dst;
}
} else {
BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp_thread);
}
// 3: apply keep-alive barrier if needed
if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
__ enter();
__ push_call_clobbered_registers();
satb_write_barrier_pre(masm /* masm */,
noreg /* obj */,
dst /* pre_val */,
rthread /* thread */,
tmp1 /* tmp */,
true /* tosca_live */,
true /* expand_call */);
__ pop_call_clobbered_registers();
__ leave();
}
}
void ShenandoahBarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
Address dst, Register val, Register tmp1, Register tmp2) {
bool on_oop = is_reference_type(type);
if (!on_oop) {
BarrierSetAssembler::store_at(masm, decorators, type, dst, val, tmp1, tmp2);
return;
}
// flatten object address if needed
if (dst.index() == noreg && dst.offset() == 0) {
if (dst.base() != r3) {
__ mov(r3, dst.base());
}
} else {
__ lea(r3, dst);
}
shenandoah_write_barrier_pre(masm,
r3 /* obj */,
tmp2 /* pre_val */,
rthread /* thread */,
tmp1 /* tmp */,
val != noreg /* tosca_live */,
false /* expand_call */);
if (val == noreg) {
BarrierSetAssembler::store_at(masm, decorators, type, Address(r3, 0), noreg, noreg, noreg);
} else {
iu_barrier(masm, val, tmp1);
// G1 barrier needs uncompressed oop for region cross check.
Register new_val = val;
if (UseCompressedOops) {
new_val = rscratch2;
__ mov(new_val, val);
}
BarrierSetAssembler::store_at(masm, decorators, type, Address(r3, 0), val, noreg, noreg);
}
}
void ShenandoahBarrierSetAssembler::try_resolve_jobject_in_native(MacroAssembler* masm, Register jni_env,
Register obj, Register tmp, Label& slowpath) {
Label done;
// Resolve jobject
BarrierSetAssembler::try_resolve_jobject_in_native(masm, jni_env, obj, tmp, slowpath);
// Check for null.
__ cbz(obj, done);
assert(obj != rscratch2, "need rscratch2");
Address gc_state(jni_env, ShenandoahThreadLocalData::gc_state_offset() - JavaThread::jni_environment_offset());
__ lea(rscratch2, gc_state);
__ ldrb(rscratch2, Address(rscratch2));
// Check for heap in evacuation phase
__ tbnz(rscratch2, ShenandoahHeap::EVACUATION_BITPOS, slowpath);
__ bind(done);
}
// Special Shenandoah CAS implementation that handles false negatives due
// to concurrent evacuation. The service is more complex than a
// traditional CAS operation because the CAS operation is intended to
// succeed if the reference at addr exactly matches expected or if the
// reference at addr holds a pointer to a from-space object that has
// been relocated to the location named by expected. There are two
// races that must be addressed:
// a) A parallel thread may mutate the contents of addr so that it points
// to a different object. In this case, the CAS operation should fail.
// b) A parallel thread may heal the contents of addr, replacing a
// from-space pointer held in addr with the to-space pointer
// representing the new location of the object.
// Upon entry to cmpxchg_oop, it is assured that new_val equals NULL
// or it refers to an object that is not being evacuated out of
// from-space, or it refers to the to-space version of an object that
// is being evacuated out of from-space.
//
// By default the value held in the result register following execution
// of the generated code sequence is 0 to indicate failure of CAS,
// non-zero to indicate success. If is_cae, the result is the value most
// recently fetched from addr rather than a boolean success indicator.
//
// Clobbers rscratch1, rscratch2
void ShenandoahBarrierSetAssembler::cmpxchg_oop(MacroAssembler* masm,
Register addr,
Register expected,
Register new_val,
bool acquire, bool release,
bool is_cae,
Register result) {
Register tmp1 = rscratch1;
Register tmp2 = rscratch2;
bool is_narrow = UseCompressedOops;
Assembler::operand_size size = is_narrow ? Assembler::word : Assembler::xword;
assert_different_registers(addr, expected, tmp1, tmp2);
assert_different_registers(addr, new_val, tmp1, tmp2);
Label step4, done;
// There are two ways to reach this label. Initial entry into the
// cmpxchg_oop code expansion starts at step1 (which is equivalent
// to label step4). Additionally, in the rare case that four steps
// are required to perform the requested operation, the fourth step
// is the same as the first. On a second pass through step 1,
// control may flow through step 2 on its way to failure. It will
// not flow from step 2 to step 3 since we are assured that the
// memory at addr no longer holds a from-space pointer.
//
// The comments that immediately follow the step4 label apply only
// to the case in which control reaches this label by branch from
// step 3.
__ bind (step4);
// Step 4. CAS has failed because the value most recently fetched
// from addr is no longer the from-space pointer held in tmp2. If a
// different thread replaced the in-memory value with its equivalent
// to-space pointer, then CAS may still be able to succeed. The
// value held in the expected register has not changed.
//
// It is extremely rare we reach this point. For this reason, the
// implementation opts for smaller rather than potentially faster
// code. Ultimately, smaller code for this rare case most likely
// delivers higher overall throughput by enabling improved icache
// performance.
// Step 1. Fast-path.
//
// Try to CAS with given arguments. If successful, then we are done.
//
// No label required for step 1.
__ cmpxchg(addr, expected, new_val, size, acquire, release, false, tmp2);
// EQ flag set iff success. tmp2 holds value fetched.
// If expected equals null but tmp2 does not equal null, the
// following branches to done to report failure of CAS. If both
// expected and tmp2 equal null, the following branches to done to
// report success of CAS. There's no need for a special test of
// expected equal to null.
__ br(Assembler::EQ, done);
// if CAS failed, fall through to step 2
// Step 2. CAS has failed because the value held at addr does not
// match expected. This may be a false negative because the value fetched
// from addr (now held in tmp2) may be a from-space pointer to the
// original copy of same object referenced by to-space pointer expected.
//
// To resolve this, it suffices to find the forward pointer associated
// with fetched value. If this matches expected, retry CAS with new
// parameters. If this mismatches, then we have a legitimate
// failure, and we're done.
//
// No need for step2 label.
// overwrite tmp1 with from-space pointer fetched from memory
__ mov(tmp1, tmp2);
if (is_narrow) {
// Decode tmp1 in order to resolve its forward pointer
__ decode_heap_oop(tmp1, tmp1);
}
resolve_forward_pointer(masm, tmp1);
// Encode tmp1 to compare against expected.
__ encode_heap_oop(tmp1, tmp1);
// Does forwarded value of fetched from-space pointer match original
// value of expected? If tmp1 holds null, this comparison will fail
// because we know from step1 that expected is not null. There is
// no need for a separate test for tmp1 (the value originally held
// in memory) equal to null.
__ cmp(tmp1, expected);
// If not, then the failure was legitimate and we're done.
// Branching to done with NE condition denotes failure.
__ br(Assembler::NE, done);
// Fall through to step 3. No need for step3 label.
// Step 3. We've confirmed that the value originally held in memory
// (now held in tmp2) pointed to from-space version of original
// expected value. Try the CAS again with the from-space expected
// value. If it now succeeds, we're good.
//
// Note: tmp2 holds encoded from-space pointer that matches to-space
// object residing at expected. tmp2 is the new "expected".
// Note that macro implementation of __cmpxchg cannot use same register
// tmp2 for result and expected since it overwrites result before it
// compares result with expected.
__ cmpxchg(addr, tmp2, new_val, size, acquire, release, false, noreg);
// EQ flag set iff success. tmp2 holds value fetched, tmp1 (rscratch1) clobbered.
// If fetched value did not equal the new expected, this could
// still be a false negative because some other thread may have
// newly overwritten the memory value with its to-space equivalent.
__ br(Assembler::NE, step4);
if (is_cae) {
// We're falling through to done to indicate success. Success
// with is_cae is denoted by returning the value of expected as
// result.
__ mov(tmp2, expected);
}
__ bind(done);
// At entry to done, the Z (EQ) flag is on iff if the CAS
// operation was successful. Additionally, if is_cae, tmp2 holds
// the value most recently fetched from addr. In this case, success
// is denoted by tmp2 matching expected.
if (is_cae) {
__ mov(result, tmp2);
} else {
__ cset(result, Assembler::EQ);
}
}
#undef __
#ifdef COMPILER1
#define __ ce->masm()->
void ShenandoahBarrierSetAssembler::gen_pre_barrier_stub(LIR_Assembler* ce, ShenandoahPreBarrierStub* stub) {
ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
// At this point we know that marking is in progress.
// If do_load() is true then we have to emit the
// load of the previous value; otherwise it has already
// been loaded into _pre_val.
__ bind(*stub->entry());
assert(stub->pre_val()->is_register(), "Precondition.");
Register pre_val_reg = stub->pre_val()->as_register();
if (stub->do_load()) {
ce->mem2reg(stub->addr(), stub->pre_val(), T_OBJECT, stub->patch_code(), stub->info(), false /*wide*/, false /*unaligned*/);
}
__ cbz(pre_val_reg, *stub->continuation());
ce->store_parameter(stub->pre_val()->as_register(), 0);
__ far_call(RuntimeAddress(bs->pre_barrier_c1_runtime_code_blob()->code_begin()));
__ b(*stub->continuation());
}
void ShenandoahBarrierSetAssembler::gen_load_reference_barrier_stub(LIR_Assembler* ce, ShenandoahLoadReferenceBarrierStub* stub) {
ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
__ bind(*stub->entry());
DecoratorSet decorators = stub->decorators();
bool is_strong = ShenandoahBarrierSet::is_strong_access(decorators);
bool is_weak = ShenandoahBarrierSet::is_weak_access(decorators);
bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
bool is_native = ShenandoahBarrierSet::is_native_access(decorators);
Register obj = stub->obj()->as_register();
Register res = stub->result()->as_register();
Register addr = stub->addr()->as_pointer_register();
Register tmp1 = stub->tmp1()->as_register();
Register tmp2 = stub->tmp2()->as_register();
assert(res == r0, "result must arrive in r0");
if (res != obj) {
__ mov(res, obj);
}
if (is_strong) {
// Check for object in cset.
__ mov(tmp2, ShenandoahHeap::in_cset_fast_test_addr());
__ lsr(tmp1, res, ShenandoahHeapRegion::region_size_bytes_shift_jint());
__ ldrb(tmp2, Address(tmp2, tmp1));
__ cbz(tmp2, *stub->continuation());
}
ce->store_parameter(res, 0);
ce->store_parameter(addr, 1);
if (is_strong) {
if (is_native) {
__ far_call(RuntimeAddress(bs->load_reference_barrier_strong_native_rt_code_blob()->code_begin()));
} else {
__ far_call(RuntimeAddress(bs->load_reference_barrier_strong_rt_code_blob()->code_begin()));
}
} else if (is_weak) {
__ far_call(RuntimeAddress(bs->load_reference_barrier_weak_rt_code_blob()->code_begin()));
} else {
assert(is_phantom, "only remaining strength");
__ far_call(RuntimeAddress(bs->load_reference_barrier_phantom_rt_code_blob()->code_begin()));
}
__ b(*stub->continuation());
}
#undef __
#define __ sasm->
void ShenandoahBarrierSetAssembler::generate_c1_pre_barrier_runtime_stub(StubAssembler* sasm) {
__ prologue("shenandoah_pre_barrier", false);
// arg0 : previous value of memory
BarrierSet* bs = BarrierSet::barrier_set();
const Register pre_val = r0;
const Register thread = rthread;
const Register tmp = rscratch1;
Address queue_index(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
Address buffer(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
Label done;
Label runtime;
// Is marking still active?
Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
__ ldrb(tmp, gc_state);
__ tbz(tmp, ShenandoahHeap::MARKING_BITPOS, done);
// Can we store original value in the thread's buffer?
__ ldr(tmp, queue_index);
__ cbz(tmp, runtime);
__ sub(tmp, tmp, wordSize);
__ str(tmp, queue_index);
__ ldr(rscratch2, buffer);
__ add(tmp, tmp, rscratch2);
__ load_parameter(0, rscratch2);
__ str(rscratch2, Address(tmp, 0));
__ b(done);
__ bind(runtime);
__ push_call_clobbered_registers();
__ load_parameter(0, pre_val);
__ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), pre_val, thread);
__ pop_call_clobbered_registers();
__ bind(done);
__ epilogue();
}
void ShenandoahBarrierSetAssembler::generate_c1_load_reference_barrier_runtime_stub(StubAssembler* sasm, DecoratorSet decorators) {
__ prologue("shenandoah_load_reference_barrier", false);
// arg0 : object to be resolved
__ push_call_clobbered_registers();
__ load_parameter(0, r0);
__ load_parameter(1, r1);
bool is_strong = ShenandoahBarrierSet::is_strong_access(decorators);
bool is_weak = ShenandoahBarrierSet::is_weak_access(decorators);
bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
bool is_native = ShenandoahBarrierSet::is_native_access(decorators);
if (is_strong) {
if (is_native) {
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong));
} else {
if (UseCompressedOops) {
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow));
} else {
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong));
}
}
} else if (is_weak) {
assert(!is_native, "weak must not be called off-heap");
if (UseCompressedOops) {
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow));
} else {
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak));
}
} else {
assert(is_phantom, "only remaining strength");
assert(is_native, "phantom must only be called off-heap");
__ mov(lr, CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom));
}
__ blr(lr);
__ mov(rscratch1, r0);
__ pop_call_clobbered_registers();
__ mov(r0, rscratch1);
__ epilogue();
}
#undef __
#endif // COMPILER1
| 38.036601 | 140 | 0.678088 | [
"object"
] |
77ef46b6b9d174b765969bb65c698e118b9130a2 | 4,838 | hh | C++ | rpc/iface.hh | codesloop/codesloop | d66e51c2d898a72624306f611a90364c76deed06 | [
"BSD-2-Clause"
] | 3 | 2016-05-09T15:29:29.000Z | 2017-11-22T06:16:18.000Z | rpc/iface.hh | codesloop/codesloop | d66e51c2d898a72624306f611a90364c76deed06 | [
"BSD-2-Clause"
] | null | null | null | rpc/iface.hh | codesloop/codesloop | d66e51c2d898a72624306f611a90364c76deed06 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2008,2009,2010, CodeSLoop Team
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _csl_rpc_iface_hh_included_
#define _csl_rpc_iface_hh_included_
#include "codesloop/common/common.h"
#ifdef __cplusplus
#include <string>
#include <vector>
#include "codesloop/common/obj.hh"
#include "codesloop/rpc/csrgen.hh"
namespace csl
{
namespace rpc
{
/** @brief stores parsed interface description */
class iface : public csl::common::obj
{
CSL_OBJ(csl::rpc,iface);
public:
/** @brief structure to hold information about a parameter */
struct param {
std::string type; ///< parameter's C++ type name
std::string name; ///< parameter name
param_kind kind; ///< parameter's kind (eg. input, output, etc.)
bool is_array; ///< true when parameter is an array
size_t array_length; ///< length of an array
};
/** @brief contains a function and its parameters */
struct func {
std::string name; ///< function name
bool disposable; ///< true when invoker can omit return values
std::vector<param> params; ///< parameters in original order
typedef std::vector<param>::const_iterator
param_iterator; ///< iterator for parameters
};
/*
* setters
*/
void set_name(const token_info &); ///< sets interface name
void set_version(const token_info &); ///< sets version string
void set_namespc(const token_info &); ///< sets namespace
void set_transport(const token_info &); ///< sets namespace
void add_function(const token_info &); ///< adds one function
void set_param_type(const token_info &); ///< adds a parameter type
void set_param_name(const token_info &); ///< adds a parameter name
void set_arry_len(int); ///< sets parameter's array attribute
/** @brief adds an include statement from interface file */
void add_include(const token_info &);
/*
* getters
*/
/** @breif returns interface name */
const std::string get_name() const { return name_;}
/** @breif returns interface version */
const std::string get_version() const { return version_;}
/** @breif returns interface namespace */
const std::string get_namespc() const { return namespc_;}
/** @breif returns interface namespace */
const std::string get_transport() const
{
return transport_ == "" ? "udp" : transport_;
}
/** @brief return list of defined functions */
const std::vector<func> * get_functions() const
{
return &functions_;
}
const std::vector<std::string> * get_includes() const
{
return &includes_;
}
/** @brief dump iface content (for debug) */
std::string to_string() const;
/** @brief iterator to access includes */
typedef std::vector<std::string>::const_iterator include_iterator;
/** @brief iterator to access function */
typedef std::vector<func>::const_iterator function_iterator;
private:
std::string name_;
std::string version_;
std::string namespc_;
std::string transport_;
std::string token_to_string(const token_info & ) const;
std::string param_type_;
std::vector<func> functions_;
std::vector<std::string> includes_;
};
}
}
#endif /* __cplusplus */
#endif /* _csl_rpc_iface_hh_included_ */
| 36.651515 | 86 | 0.645515 | [
"vector"
] |
77f4f827d58926a8183e1f235785c7df9db73e09 | 1,407 | cpp | C++ | src/parameter/matrix/parameter.cpp | Ymagis/EclairLooks | c04fb1af1160305fb1dbffb2ea92cc478cd70b31 | [
"BSD-3-Clause"
] | 9 | 2019-07-03T13:11:33.000Z | 2021-10-06T13:55:31.000Z | src/parameter/matrix/parameter.cpp | Ymagis/EclairLooks | c04fb1af1160305fb1dbffb2ea92cc478cd70b31 | [
"BSD-3-Clause"
] | 1 | 2019-07-09T09:04:59.000Z | 2019-08-06T13:23:47.000Z | src/parameter/matrix/parameter.cpp | Ymagis/EclairLooks | c04fb1af1160305fb1dbffb2ea92cc478cd70b31 | [
"BSD-3-Clause"
] | 4 | 2019-07-02T15:03:43.000Z | 2019-09-28T14:33:03.000Z | #include "parameter.h"
#include "widget.h"
#include <utils/pystring.h>
MatrixParameter::MatrixParameter(const std::string &name) : Parameter(name)
{
m_value = m_default_value;
}
Matrix4x4 MatrixParameter::value() const { return m_value; }
void MatrixParameter::setValue(const Matrix4x4 &v)
{
m_value = v;
EmitEvent<UpdateValue>(*this);
}
Matrix4x4 MatrixParameter::defaultValue() const { return m_default_value; }
void MatrixParameter::setDefaultValue(const Matrix4x4 &v)
{
m_default_value = v;
EmitEvent<UpdateValue>(*this);
}
ParameterWidget *MatrixParameter::newWidget(QWidget * parent)
{
return new ParameterMatrixWidget(this, parent);
}
void MatrixParameter::load(const QSettings *setting)
{
std::string valueStr = setting->value(QString::fromStdString(name())).toString().toStdString();
Matrix4x4 m;
std::vector<std::string> numbers;
pystring::split(valueStr, numbers, " ");
if (numbers.size() != 16) {
qWarning() << "Invalid Matrix settings, expecting 16 numbers";
return;
}
for (int i = 0; i < numbers.size(); ++i)
m[i] = std::stof(numbers[i]);
setValue(m);
}
void MatrixParameter::save(QSettings *setting) const
{
std::string valueStr;
for (auto v : value())
valueStr += std::to_string(v) + " ";
setting->setValue(QString::fromStdString(name()), QString::fromStdString(valueStr));
}
| 23.45 | 99 | 0.678749 | [
"vector"
] |
af8970cf25b86f68d706374282424d338673b4b2 | 15,837 | cpp | C++ | CascadedShadowMapping/src/CascadedShadowMappingApp.cpp | Samsy/Cinder-Experiments | c81fd1f149d0a6585afd1da5507be6ca1f52e29d | [
"Unlicense"
] | 231 | 2015-03-04T04:20:55.000Z | 2022-02-09T13:40:54.000Z | CascadedShadowMapping/src/CascadedShadowMappingApp.cpp | simongeilfus/Cinder-Experiments | c81fd1f149d0a6585afd1da5507be6ca1f52e29d | [
"Unlicense"
] | null | null | null | CascadedShadowMapping/src/CascadedShadowMappingApp.cpp | simongeilfus/Cinder-Experiments | c81fd1f149d0a6585afd1da5507be6ca1f52e29d | [
"Unlicense"
] | 30 | 2015-02-10T17:32:51.000Z | 2021-07-09T02:52:55.000Z | #include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/CameraUi.h"
#include "cinder/ObjLoader.h"
#include "CinderImGui.h"
using namespace ci;
using namespace ci::app;
using namespace std;
typedef std::shared_ptr<class CascadedShadows> CascadedShadowsRef;
class CascadedShadows {
public:
//! construct a CascadedShadowsRef
static CascadedShadowsRef create();
//! creates the splits, should be called everytime the camera or the light change
void update( const CameraPersp &camera, const glm::vec3 &lightDir );
//! filters the shadowmaps with a gaussian blur
void filter();
//! sets the shadow maps resolution
void setResolution( size_t resolution ) { mResolution = resolution; createFramebuffers(); }
//! sets the over-shadowing constant
void setShadowingFactor( float factor ) { mExpC = factor; }
//! sets frustum split constant
void setSplitLambda( float lambda ) { mSplitLambda = lambda; }
//! returns the shadow maps resolution
size_t getResolution() const { return mResolution; }
//! returns the over-shadowing constant
float getShadowingFactor() const { return mExpC; }
//! returns frustum split constant
float getSplitLambda() const { return mSplitLambda; }
//! returns the shadow maps 3d texture
gl::Texture3dRef getShadowMap() const { return static_pointer_cast<gl::Texture3d>( mShadowMapArray->getTextureBase( GL_COLOR_ATTACHMENT0 ) ); }
//! returns the shadow maps framebuffer
const gl::FboRef& getShadowMapArray() const { return mShadowMapArray; }
//! returns the GlslProg used to draw the shadow maps to the screen
const gl::GlslProgRef& getDebugProg() const { return mDebugProg; }
//! returns the cascades split planes
const vector<vec2>& getSplitPlanes() const { return mSplitPlanes; }
//! returns the cascades view matrices
const vector<mat4>& getViewMatrices() const { return mViewMatrices; }
//! returns the cascades projection matrices
const vector<mat4>& getProjMatrices() const { return mProjMatrices; }
//! returns the cascades shadow matrices
const vector<mat4>& getShadowMatrices() const { return mShadowMatrices; }
//! returns the cascades near planes
const vector<float>& getNearPlanes() const { return mNearPlanes; }
//! returns the cascades far planes
const vector<float>& getFarPlanes() const { return mFarPlanes; }
CascadedShadows();
protected:
void createFramebuffers();
gl::FboRef mShadowMapArray;
gl::FboRef mBlurFbo;
gl::GlslProgRef mDebugProg;
gl::GlslProgRef mFilterProg;
size_t mResolution;
float mExpC;
float mSplitLambda;
vector<vec2> mSplitPlanes;
vector<mat4> mViewMatrices;
vector<mat4> mProjMatrices;
vector<mat4> mShadowMatrices;
vector<float> mNearPlanes;
vector<float> mFarPlanes;
};
class CascadedShadowMappingApp : public App {
public:
CascadedShadowMappingApp();
void update() override;
void draw() override;
void resize() override;
void userInterface();
// Scene Objects
using Object = std::tuple<gl::BatchRef,gl::BatchRef,AxisAlignedBox>;
CameraPersp mCamera;
CameraUi mCameraUi;
vector<Object> mScene;
vec3 mLightDir;
// Framebuffer and textures
CascadedShadowsRef mCascadedShadows;
gl::Texture2dRef mAmbientOcclusion;
// options
bool mPolygonOffset, mFiltering, mShowCascades, mShowUi, mShowShadowMaps;
int mShadowMapSize;
};
CascadedShadowMappingApp::CascadedShadowMappingApp()
{
// initialize user interface
ui::initialize();
// load shader
auto shader = gl::GlslProg::create( loadAsset( "shader.vert" ), loadAsset( "shader.frag" ) );
auto shadowShader = gl::GlslProg::create( loadAsset( "shadowmap.vert" ), loadAsset( "shadowmap.frag" ), loadAsset( "shadowmap.geom" ) );
// parse obj and split into gl::Batch
auto source = ObjLoader( loadAsset( "terrain.obj" ) );
for( size_t i = 0; i < source.getNumGroups(); ++i ) {
auto trimesh = TriMesh( source.groupIndex( i ) );
mScene.push_back( make_tuple(
gl::Batch::create( source, shader ),
gl::Batch::create( source, shadowShader ),
trimesh.calcBoundingBox()
) );
}
// load baked ao texture
mAmbientOcclusion = gl::Texture2d::create( loadImage( loadAsset( "bakedAO.jpg" ) ) );
// create the cascaded shadow map
mCascadedShadows = CascadedShadows::create();
// setup camera and camera ui
mCamera = CameraPersp( getWindowWidth(), getWindowHeight(), 50.0f, 0.1f, 18.0f ).calcFraming( Sphere( vec3( 0.0f ), 5.0f ) );
mCameraUi = CameraUi( &mCamera, getWindow(), -1 );
// initial options
mLightDir = normalize( vec3( -1.4f, -0.37f, 0.63f ) );
mShowShadowMaps = false;
mShowCascades = false;
mPolygonOffset = true;
mFiltering = true;
}
void CascadedShadowMappingApp::resize()
{
// adapt camera ratio
mCamera.setAspectRatio( getWindowAspectRatio() );
}
void CascadedShadowMappingApp::update()
{
// recreate cascades from the user point of view
mCascadedShadows->update( mCamera, mLightDir );
// render the shadowmaps
{
auto fbo = mCascadedShadows->getShadowMapArray();
gl::ScopedFramebuffer scopedFbo( fbo );
gl::ScopedViewport scopedViewport( vec2( 0.0f ), fbo->getSize() );
gl::ScopedDepth enableDepth( true );
gl::ScopedBlend disableBlending( false );
gl::ScopedFaceCulling scopedCulling( true, GL_BACK );
// polygon offset fixes some really small artifacts at grazing angles
if( mPolygonOffset ) {
gl::enable( GL_POLYGON_OFFSET_FILL );
glPolygonOffset( 2.0f, 2.0f );
}
gl::clear( Color( 1.0f, 0.0f, 0.0f ) );
for( const auto &obj : mScene ) {
auto batch = std::get<1>( obj );
auto shader = batch->getGlslProg();
shader->uniform( "uCascadesViewMatrices", mCascadedShadows->getViewMatrices().data(), mCascadedShadows->getViewMatrices().size() );
shader->uniform( "uCascadesProjMatrices", mCascadedShadows->getProjMatrices().data(), mCascadedShadows->getProjMatrices().size() );
shader->uniform( "uCascadesNear", mCascadedShadows->getNearPlanes().data(), mCascadedShadows->getNearPlanes().size() );
shader->uniform( "uCascadesFar", mCascadedShadows->getFarPlanes().data(), mCascadedShadows->getFarPlanes().size() );
batch->draw();
}
if( mPolygonOffset )
gl::disable( GL_POLYGON_OFFSET_FILL );
}
// filter if needed
if( mFiltering )
mCascadedShadows->filter();
userInterface();
}
void CascadedShadowMappingApp::draw()
{
gl::clear( Color::gray( 0.72f ) );
// render scene
gl::ScopedDepth enableDepth( true );
gl::ScopedBlend disableBlending( false );
gl::ScopedFaceCulling scopedCulling( true, GL_BACK );
gl::ScopedTextureBind scopedTexBind0( mCascadedShadows->getShadowMap(), 0 );
gl::ScopedTextureBind scopedTexBind1( mAmbientOcclusion, 1 );
gl::setMatrices( mCamera );
Frustumf frustum( mCamera );
for( const auto &obj : mScene ) {
if( frustum.intersects( std::get<2>( obj ) ) ) {
auto batch = std::get<0>( obj );
auto shader = batch->getGlslProg();
vec3 lightDir = normalize( vec3( mCamera.getViewMatrix() * vec4( mLightDir, 0.0f ) ) );
shader->uniform( "uLightDirection", lightDir );
shader->uniform( "uExpC", mCascadedShadows->getShadowingFactor() );
shader->uniform( "uShadowMap", 0 );
shader->uniform( "uAmbientOcclusion", 1 );
shader->uniform( "uCascadesNear", mCascadedShadows->getNearPlanes().data(), mCascadedShadows->getNearPlanes().size() );
shader->uniform( "uCascadesFar", mCascadedShadows->getFarPlanes().data(), mCascadedShadows->getFarPlanes().size() );
shader->uniform( "uCascadesPlanes", mCascadedShadows->getSplitPlanes().data(), mCascadedShadows->getSplitPlanes().size() );
shader->uniform( "uCascadesMatrices", mCascadedShadows->getShadowMatrices().data(), mCascadedShadows->getShadowMatrices().size() );
shader->uniform( "uShowCascades", mShowCascades ? 1.0f : 0.0f );
batch->draw();
}
}
// display array of shadow maps
if( mShowShadowMaps ) {
gl::disableDepthRead();
gl::disableDepthWrite();
gl::setMatricesWindow( getWindowSize() );
auto prog = mCascadedShadows->getDebugProg();
gl::ScopedGlslProg scopedGlsl( prog );
gl::ScopedTextureBind texBind( mCascadedShadows->getShadowMap() );
for( size_t i = 0; i < 4; i++ ) {
prog->uniform( "uSection", static_cast<int>( i ) );
gl::drawSolidRect( Rectf( vec2(64*i,0), vec2(64*i,0)+vec2(64) ) );
}
}
}
void CascadedShadowMappingApp::userInterface()
{
ui::ScopedWindow window( "Cascaded Shadow Mapping" );
// Light and Camera options
if( ui::CollapsingHeader( "Light", nullptr, true, true ) ) {
ui::DragFloat3( "Direction", &mLightDir[0], 0.01f );
}
if( ui::CollapsingHeader( "Camera", nullptr, true, true ) ) {
float near = mCamera.getNearClip();
if( ui::DragFloat( "Camera NearClip", &near, 0.1f, 0.0f, mCamera.getFarClip() ) ) mCamera.setNearClip( near );
float far = mCamera.getFarClip();
if( ui::DragFloat( "Camera FarClip", &far, 0.1f, mCamera.getNearClip() ) ) mCamera.setFarClip( far );
}
// cascade options
if( ui::CollapsingHeader( "Shadow Mapping", nullptr, true, true ) ) {
ui::Checkbox( "Filtering", &mFiltering );
ui::Checkbox( "Polygon Offset", &mPolygonOffset );
float shadowing = mCascadedShadows->getShadowingFactor();
if( ui::DragFloat( "Shadowing Factor", &shadowing, 1.0f, 0.0f, 1000.0f ) ) mCascadedShadows->setShadowingFactor( shadowing );
float splitLambda = mCascadedShadows->getSplitLambda();
if( ui::DragFloat( "SplitLambda", &splitLambda, 0.001f, 0.0f ) ) mCascadedShadows->setSplitLambda( splitLambda );
}
// debug options
if( ui::CollapsingHeader( "Debug", nullptr, true, true ) ) {
ui::Checkbox( "Show Cascades", &mShowCascades );
ui::Checkbox( "Show ShadowMaps", &mShowShadowMaps );
}
// update window title
getWindow()->setTitle( "Cascaded Shadow Mapping | " + to_string( (int) getAverageFps() ) + " fps" );
}
CascadedShadowsRef CascadedShadows::create()
{
return make_shared<CascadedShadows>();
}
CascadedShadows::CascadedShadows()
: mResolution( 1024 ), mExpC( 120.0f ), mSplitLambda( 0.5f )
{
// load shaders
auto format = gl::GlslProg::Format().vertex( loadAsset( "gaussian.vert" ) ).fragment( loadAsset( "gaussian.frag" ) ).geometry( loadAsset( "gaussian.geom" ) ).define( "KERNEL", "KERNEL_7x7_GAUSSIAN" );
mFilterProg = gl::GlslProg::create( format );
mDebugProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "debugShadowmap.vert" ) ).fragment( loadAsset( "debugShadowmap.frag" ) ) );
// create framebuffers
createFramebuffers();
}
void CascadedShadows::update( const CameraPersp &camera, const glm::vec3 &lightDir )
{
// clear vectors
mViewMatrices.clear();
mProjMatrices.clear();
mShadowMatrices.clear();
mSplitPlanes.clear();
mNearPlanes.clear();
mFarPlanes.clear();
// calculate splits
float near = camera.getNearClip();
float far = camera.getFarClip();
for( size_t i = 0; i < 4; ++i ) {
// find the split planes using GPU Gem 3. Chap 10 "Practical Split Scheme".
float splitNear = i > 0 ? glm::mix( near + ( static_cast<float>( i ) / 4.0f ) * ( far - near ), near * pow( far / near, static_cast<float>( i ) / 4.0f ), mSplitLambda ) : near;
float splitFar = i < 4 - 1 ? glm::mix( near + ( static_cast<float>( i + 1 ) / 4.0f ) * ( far - near ), near * pow( far / near, static_cast<float>( i + 1 ) / 4.0f ), mSplitLambda ) : far;
// create a camera for this split
CameraPersp splitCamera( camera );
splitCamera.setNearClip( splitNear );
splitCamera.setFarClip( splitFar );
// extract the split frutum vertices
vec3 ntl, ntr, nbl, nbr, ftl, ftr, fbl, fbr;
splitCamera.getNearClipCoordinates( &ntl, &ntr, &nbl, &nbr );
splitCamera.getFarClipCoordinates( &ftl, &ftr, &fbl, &fbr );
vec4 splitVertices[8] = { vec4( ntl, 1.0f ), vec4( ntr, 1.0f ), vec4( nbl, 1.0f ), vec4( nbr, 1.0f ), vec4( ftl, 1.0f ), vec4( ftr, 1.0f ), vec4( fbl, 1.0f ), vec4( fbr, 1.0f ) };
// find the split centroid so we can construct a view matrix
vec4 splitCentroid( 0.0f );
for( size_t i = 0; i < 8; ++i ) {
splitCentroid += splitVertices[i];
}
splitCentroid /= 8.0f;
// construct the view matrix
float dist = glm::max( splitFar - splitNear, glm::distance( ftl, ftr ) );
mat4 viewMat = glm::lookAt( vec3( splitCentroid ) - lightDir * dist, vec3( splitCentroid ), vec3( 0.0f, 1.0f, 0.0f ) );
// transform split vertices to the light view space
vec4 splitVerticesLS[8];
for( size_t i = 0; i < 8; ++i ) {
splitVerticesLS[i] = viewMat * splitVertices[i];
}
// find the frustum bounding box in viewspace
vec4 min = splitVerticesLS[0];
vec4 max = splitVerticesLS[0];
for( size_t i = 1; i < 8; ++i ) {
min = glm::min( min, splitVerticesLS[i] );
max = glm::max( max, splitVerticesLS[i] );
}
// and create an orthogonal projection matrix with the corners
float nearOffset = 10.0f;
float farOffset = 20.0f;
mat4 projMat = glm::ortho( min.x, max.x, min.y, max.y, -max.z - nearOffset, -min.z + farOffset );
static const mat4 offsetMat = mat4( vec4( 0.5f, 0.0f, 0.0f, 0.0f ), vec4( 0.0f, 0.5f, 0.0f, 0.0f ), vec4( 0.0f, 0.0f, 0.5f, 0.0f ), vec4( 0.5f, 0.5f, 0.5f, 1.0f ) );
// save matrices and near/far planes
mViewMatrices.push_back( viewMat );
mProjMatrices.push_back( projMat );
mShadowMatrices.push_back( offsetMat * projMat * viewMat );
mSplitPlanes.push_back( vec2( splitNear, splitFar ) );
mNearPlanes.push_back( -max.z - nearOffset );
mFarPlanes.push_back( -min.z + farOffset );
}
}
void CascadedShadows::filter()
{
// setup rendering for fullscreen quads
gl::ScopedMatrices scopedMatrices;
gl::ScopedViewport scopedViewport( ivec2(0), mBlurFbo->getSize() );
gl::ScopedDepth scopedDepth( false );
gl::ScopedGlslProg scopedGlsl( mFilterProg );
gl::ScopedBlend scopedBlend( false );
gl::ScopedFramebuffer scopedFbo( mBlurFbo );
gl::setMatricesWindow( mBlurFbo->getSize() );
gl::clear();
// two pass gaussian blur
mFilterProg->uniform( "uSampler", 0 );
mFilterProg->uniform( "uInvSize", vec2( 1.0f ) / vec2( mBlurFbo->getSize() ) );
// horizontal pass
mFilterProg->uniform( "uDirection", vec2( 1.0f, 0.0f ) );
gl::ScopedTextureBind scopedTexBind0( mShadowMapArray->getTextureBase( GL_COLOR_ATTACHMENT0 ), 0 );
gl::drawBuffer( GL_COLOR_ATTACHMENT0 );
gl::drawSolidRect( mBlurFbo->getBounds() );
// vertical pass
mFilterProg->uniform( "uDirection", vec2( 0.0f, 1.0f ) );
gl::ScopedTextureBind scopedTexBind1( mBlurFbo->getTextureBase( GL_COLOR_ATTACHMENT0 ), 0 );
gl::drawBuffer( GL_COLOR_ATTACHMENT1 );
gl::drawSolidRect( mBlurFbo->getBounds() );
gl::drawBuffer( GL_COLOR_ATTACHMENT0 );
}
void CascadedShadows::createFramebuffers()
{
// create a layered framebuffer for the different shadow maps
auto textureArrayFormat = gl::Texture3d::Format().target( GL_TEXTURE_2D_ARRAY ).internalFormat( GL_R16F ).magFilter( GL_LINEAR ).minFilter( GL_LINEAR ).wrap( GL_CLAMP_TO_EDGE );
auto textureArray = gl::Texture3d::create( mResolution, mResolution, 4, textureArrayFormat );
auto textureArrayDepth = gl::Texture3d::create( mResolution, mResolution, 4, gl::Texture3d::Format().target( GL_TEXTURE_2D_ARRAY ).internalFormat( GL_DEPTH_COMPONENT24 ) );
mShadowMapArray = gl::Fbo::create( mResolution, mResolution, gl::Fbo::Format().attachment( GL_COLOR_ATTACHMENT0, textureArray ).attachment( GL_DEPTH_ATTACHMENT, textureArrayDepth ) );
// create a second layered framebuffer for filtering using the same attachement has the shadowmap framebuffer
auto blurAtt0 = gl::Texture3d::create( mResolution, mResolution, 4, textureArrayFormat );
auto blurFormat = gl::Fbo::Format().attachment( GL_COLOR_ATTACHMENT0, blurAtt0 ).attachment( GL_COLOR_ATTACHMENT1, textureArray ).disableDepth();
mBlurFbo = gl::Fbo::create( mResolution, mResolution, blurFormat );
}
CINDER_APP( CascadedShadowMappingApp, RendererGl( RendererGl::Options().msaa( 4 ) ), []( App::Settings *settings ) {
settings->setWindowSize( 1280, 800 );
})
| 38.626829 | 201 | 0.707836 | [
"geometry",
"render",
"object",
"vector",
"transform",
"3d"
] |
af8d2abdb9a96d6d4fe1f53cf956bf52dcc2df32 | 2,008 | cpp | C++ | battlesnake_test.cpp | Waznop/Project-2.2---Battlesnake | b3e42998bf4cfdec06ed1ce365d31c3b692e75a6 | [
"MIT"
] | null | null | null | battlesnake_test.cpp | Waznop/Project-2.2---Battlesnake | b3e42998bf4cfdec06ed1ce365d31c3b692e75a6 | [
"MIT"
] | null | null | null | battlesnake_test.cpp | Waznop/Project-2.2---Battlesnake | b3e42998bf4cfdec06ed1ce365d31c3b692e75a6 | [
"MIT"
] | null | null | null | /** Contains tests for your code.
@file battlesnake_test.cpp
@author YOUR NAME(S) HERE
*/
// TODO: Fill in your name(s) above.
#include "battlesnake.h"
#include <gtest/gtest.h>
#include <set>
#include <vector>
#include "lib/snake.h"
#include "lib/snake_logic.h"
#include "lib/snake_presets.h"
using namespace std;
TEST(BattlesnakeTest, NewPosition) {
Pos actual;
Pos expected;
actual = new_position({.x = 2, .y = 2}, UP);
expected = {.x = 2, .y = 1};
EXPECT_EQ(actual, expected);
actual = new_position({.x = 2, .y = 2}, DOWN);
expected = {.x = 2, .y = 3};
EXPECT_EQ(actual, expected);
actual = new_position({.x = 2, .y = 2}, LEFT);
expected = {.x = 1, .y = 2};
EXPECT_EQ(actual, expected);
actual = new_position({.x = 2, .y = 2}, RIGHT);
expected = {.x = 3, .y = 2};
EXPECT_EQ(actual, expected);
actual = new_position({.x = 2, .y = 2}, NONE);
expected = {.x = 2, .y = 2};
EXPECT_EQ(actual, expected);
}
TEST(BattlesnakeTest, OutOfBounds) {
GameState gs;
gs.width = 5;
gs.height = 7;
// Out of bounds on the left
EXPECT_TRUE(out_of_bounds(gs, {.x = -1, .y = 5}));
// Touches left walls
EXPECT_TRUE(out_of_bounds(gs, {.x = 0, .y = 5}));
// Just in bounds
EXPECT_FALSE(out_of_bounds(gs, {.x = 1, .y = 5}));
EXPECT_FALSE(out_of_bounds(gs, {.x = 5, .y = 5}));
// Touches right walls
EXPECT_TRUE(out_of_bounds(gs, {.x = 6, .y = 5}));
// Out of bounds on the right
EXPECT_TRUE(out_of_bounds(gs, {.x = 7, .y = 5}));
// Out of bounds on the top
EXPECT_TRUE(out_of_bounds(gs, {.x = 2, .y = -1}));
// Touches top walls
EXPECT_TRUE(out_of_bounds(gs, {.x = 2, .y = 0}));
// Just in bounds
EXPECT_FALSE(out_of_bounds(gs, {.x = 2, .y = 1}));
EXPECT_FALSE(out_of_bounds(gs, {.x = 2, .y = 7}));
// Touches bottom walls
EXPECT_TRUE(out_of_bounds(gs, {.x = 2, .y = 8}));
// Out of bounds on the bottom
EXPECT_TRUE(out_of_bounds(gs, {.x = 2, .y = 9}));
}
// TODO (Optional): Add unit tests for your own helper functions here. | 25.417722 | 70 | 0.61255 | [
"vector"
] |
af9143663ce7e6a5bf98e9af599e3a5de1776728 | 1,451 | cpp | C++ | devtools/pfwriter/csv/pfwriter_impl.cpp | pshoben/llutils | e6eb56b0e27f9d20cf3be6291e6933ab3bebee21 | [
"MIT"
] | null | null | null | devtools/pfwriter/csv/pfwriter_impl.cpp | pshoben/llutils | e6eb56b0e27f9d20cf3be6291e6933ab3bebee21 | [
"MIT"
] | null | null | null | devtools/pfwriter/csv/pfwriter_impl.cpp | pshoben/llutils | e6eb56b0e27f9d20cf3be6291e6933ab3bebee21 | [
"MIT"
] | null | null | null | #include <pfwriter_impl.hpp>
#include <iostream>
using std::string;
//using std::string_view;
namespace llutils::devtools {
void PfWriterImpl::init(PfWriter * w) {
pwrapper = w;
}
std::vector<string> PfWriterImpl::get_supported_formats()
{
std::vector<string> v{};
return v;
}
void PfWriterImpl::set_format( string format_type )
{
this->format_type = format_type;
}
void PfWriterImpl::write( PreformattedSection & pfs ) {
ostream & out = pwrapper->output_stream;
out << quote_string(string(pfs.raw_bytes)) << ","
<< pfs.offset << ","
// ignore indent level
<< pfs.field_id << ","
<< quote_string(pfs.field_name) << ","
<< quote_string(pfs.field_value) << ","
<< quote_string(pfs.field_value_desc) << "\n";
for( auto section : pfs.sections ) {
write( section );
}
}
void PfWriterImpl::write( std::unique_ptr<Preformatted> & pf )
{
ostream & out = pwrapper->output_stream;
out << quote_string(string(pf->raw_bytes)) << ","
<< pf->type_id << ","
<< quote_string(pf->type_name) << ","
<< quote_string(pf->type_desc) << "\n";
for( auto section : pf->sections ) {
write( section );
}
}
string PfWriterImpl::quote_string( const string & s ) {
if( s.find(',') != string::npos) {
// comma found, need to quote the string
return string("\"") + s + string("\"");
} else {
return s;
}
}
void PfWriterImplDeleter::operator()(PfWriterImpl *p) { delete p ; }
}
| 23.403226 | 70 | 0.627154 | [
"vector"
] |
af9e7d338c84f5e0379c9342b2ec86107acf91aa | 985 | cpp | C++ | Data Structures/Disjoint Set Union (DSU)/dsu.cpp | vmmc2/The-Notebook-blue_book-computer- | 7c69b404e8870b5686422ed9fb143cda8623b479 | [
"MIT"
] | 2 | 2021-05-07T20:18:45.000Z | 2021-05-07T20:29:06.000Z | Data Structures/Disjoint Set Union (DSU)/dsu.cpp | vmmc2/The-Notebook | 7c69b404e8870b5686422ed9fb143cda8623b479 | [
"MIT"
] | null | null | null | Data Structures/Disjoint Set Union (DSU)/dsu.cpp | vmmc2/The-Notebook | 7c69b404e8870b5686422ed9fb143cda8623b479 | [
"MIT"
] | null | null | null | class dsu{
private:
vector<int> uf;
vector<int> size;
public:
dsu(int n){
uf.assign(n, 0);
size.assign(n, 1);
for(int i = 0; i < n; i++){
uf[i] = i;
}
}
int root(int x){
while(x != uf[x]){
uf[x] = uf[uf[x]];
x = uf[x];
}
return x;
}
void unite(int a, int b){
int rootA = root(a);
int rootB = root(b);
if(rootA != rootB){
if(size[rootA] <= size[rootB]){
uf[rootA] = rootB;
size[rootB] += size[rootA];
}else{
uf[rootB] = rootA;
size[rootA] += size[rootB];
}
}
return;
}
bool find(int a, int b){
if(root(a) == root(b)) return true;
else return false;
}
};
| 25.25641 | 47 | 0.330964 | [
"vector"
] |
afb52b37c3a4904c646d78b8ff852d7a4fc1325a | 3,348 | hpp | C++ | src/lib/any.hpp | DoumanAsh/text-ex-cpp | 7c7717291416bac65466a4791e6ccc8a194290a4 | [
"MIT"
] | null | null | null | src/lib/any.hpp | DoumanAsh/text-ex-cpp | 7c7717291416bac65466a4791e6ccc8a194290a4 | [
"MIT"
] | null | null | null | src/lib/any.hpp | DoumanAsh/text-ex-cpp | 7c7717291416bac65466a4791e6ccc8a194290a4 | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <typeinfo>
/**
* Represents Any object.
*
* It wraps arbitrary object into @ref placeholder.
* Which is abstract class that has virtual methods `.type()` and `.value()`.
* Actual type information is stored in derived @ref impl class.
* Using this information you can cast to required type correctly and safely.
*/
class Any {
public:
/**
* Default empty instance.
*/
Any() noexcept(true) : inner(nullptr) {};
/**
* Creates Any instance from value.
*/
template<typename T>
Any(const T &value) : inner(new impl<T>(value)) {};
/**
* Creates Any instance by cloning existing one.
*/
Any(const Any &other) : inner(other.inner ? other.inner->clone() : nullptr) {};
/**
* Move constructor
*/
Any(Any&& other) noexcept(true) : inner(other.inner) {
other.inner = nullptr;
};
~Any() {
if (inner) delete inner;
};
Any& operator=(const Any &rhs) = delete;
//Allow only move assignment.
//It helps to sort and it makes no sense to copy around objects implicitly.
Any& operator=(Any&& right) {
if (this->inner) delete this->inner;
this->inner = right.inner;
right.inner = nullptr;
return *this;
}
/**
* Abstract placeholder for any value.
* Just Abstract class with empty virtual methods.
*
* Idea from http://www.two-sdg.demon.co.uk/curbralan/papers/ValuedConversions.pdf
*/
class placeholder {
public:
virtual ~placeholder() {};
virtual const std::type_info& type() const noexcept(true) = 0;
virtual placeholder* clone() const = 0;
};
/**
* Implementation of @ref placeholder
*/
template<typename ValueType>
class impl: public placeholder {
public:
impl(const ValueType &value) noexcept(true) : value(value) {};
virtual const std::type_info& type() const noexcept(true) {
return typeid(ValueType);
}
virtual placeholder* clone() const {
return new impl(value);
}
ValueType value;
};
operator bool() const {
return inner != nullptr;
}
/**
* @returns type of @ref Any.
*/
inline const std::type_info& type() const noexcept(true) {
return inner ? inner->type() : typeid(void);
}
/**
* @returns pointer to value of @ref Any.
* @retval nullptr On invalid type.
*/
template<typename T>
const T* value_ptr() const noexcept(true) {
return this->type() == typeid(T) ? &static_cast<impl<T>*>(inner)->value : nullptr;
}
/**
* @returns value of @ref Any.
* @throws On invalid type.
*/
template<typename T>
T value() const {
const T* ret_val = value_ptr<T>();
return ret_val ? *ret_val : throw std::bad_cast();
}
private:
placeholder* inner;
};
| 27.9 | 94 | 0.516129 | [
"object"
] |
afb63cf713ba170c180bba76fa49c863c67e945c | 4,450 | cc | C++ | cairomm/examples/text/user-font.cc | shikanon/rtbkit-deps | c55b61b82a8f4c6ce129f6dd813cd15379207017 | [
"Apache-2.0"
] | null | null | null | cairomm/examples/text/user-font.cc | shikanon/rtbkit-deps | c55b61b82a8f4c6ce129f6dd813cd15379207017 | [
"Apache-2.0"
] | null | null | null | cairomm/examples/text/user-font.cc | shikanon/rtbkit-deps | c55b61b82a8f4c6ce129f6dd813cd15379207017 | [
"Apache-2.0"
] | 1 | 2020-09-15T05:49:43.000Z | 2020-09-15T05:49:43.000Z | #include <cairomm/cairomm.h>
#include <iostream>
#include <map>
const double HEIGHT = 200.0;
const double WIDTH = 400.0;
const double FONT_SIZE = 64.0;
const double TEXT_ORIGIN_Y = (HEIGHT / 2.0) + (FONT_SIZE / 2.0);
const double TEXT_ORIGIN_X = 50.0; // arbitrary
const double GLYPH_SPACING = 0.1;
struct GlyphBounds
{
unsigned long glyph;
double width;
double height;
};
// an array that stores the bounds of the glyphs that we're going to draw
static const GlyphBounds glyphs[] =
{
{ 'c', 0.45, 0.5 },
{ 'a', 0.45, 0.5 },
{ 'i', 0.2, 0.75 },
{ 'r', 0.4, 0.5 },
{ 'o', 0.44, 0.5 },
{ 'm', 0.75, 0.5 },
{ '!', 0.2, 0.75 }
};
// A *very* simple font that just draws a box for every glyph
class BoxFontFace : public Cairo::UserFontFace
{
public:
// Derived user font classes should have a factory method to create an object
// and return it with a RefPtr
static Cairo::RefPtr<BoxFontFace> create()
{
return Cairo::RefPtr<BoxFontFace>(new BoxFontFace());
}
Cairo::ErrorStatus
init(const Cairo::RefPtr<Cairo::ScaledFont>& /*scaled_font*/,
const Cairo::RefPtr<Cairo::Context>& /*cr*/,
Cairo::FontExtents &extents) override
{
double max = 0;
for (unsigned int i = 0; i < sizeof (glyphs) / sizeof (GlyphBounds); ++i) {
if (glyphs[i].width > max)
max = glyphs[i].width;
}
// add some spacing between characters
max += GLYPH_SPACING;
extents.max_x_advance = max;
return CAIRO_STATUS_SUCCESS;
}
Cairo::ErrorStatus
unicode_to_glyph (const Cairo::RefPtr<Cairo::ScaledFont>& /*scaled_font*/,
unsigned long unicode, unsigned long& glyph) override
{
glyph = 0;
// yes this is a stupid an ineffienct way to do this but we only have a few
// glyphs and this is just demonstration code
for (unsigned int i = 0; i < sizeof (glyphs) / sizeof (GlyphBounds); ++i) {
if (glyphs[i].glyph == unicode) {
// glyph 0 is often a special glyph-not-found value, so offset it by 1
glyph = i+1;
break;
}
}
return CAIRO_STATUS_SUCCESS;
}
Cairo::ErrorStatus
render_glyph(const Cairo::RefPtr<Cairo::ScaledFont>& /*scaled_font*/,
unsigned long glyph,
const Cairo::RefPtr<Cairo::Context>& cr,
Cairo::TextExtents& metrics) override
{
// check that the glyph is in our table
if (glyph >= 1 && glyph <= sizeof(glyphs)/sizeof(GlyphBounds)) {
cr->set_line_width(0.05);
// Need a negative Y value since the text origin is at the bottom left point
// and cairo's positive Y axis is down and we want to draw up
cr->rectangle(0.0, 0.0, glyphs[glyph-1].width, -glyphs[glyph-1].height);
cr->stroke();
metrics.x_advance = glyphs[glyph-1].width + GLYPH_SPACING;
}
return CAIRO_STATUS_SUCCESS;
}
protected:
// FontFace is a ref-counted object, so the constructor should be protected so
// it is not created without a refptr to manage it. See the create() method
BoxFontFace() : UserFontFace() { }
};
int main(int, char**)
{
auto surface =
Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, WIDTH, HEIGHT);
auto cr = Cairo::Context::create(surface);
// fill background in white
cr->set_source_rgb(1.0, 1.0, 1.0);
cr->paint();
// draw a little dot at the point where text will be drawn
cr->arc(TEXT_ORIGIN_X, TEXT_ORIGIN_Y, FONT_SIZE / 4.0, 0, 2*M_PI);
cr->set_source_rgba(0.0, 1.0, 0.0, 0.5);
cr->fill();
// draw the text
cr->move_to(TEXT_ORIGIN_X, TEXT_ORIGIN_Y);
cr->set_source_rgb(0.8, 0.2, 0.2);
auto font = BoxFontFace::create();
cr->set_font_face(font);
cr->set_font_size(FONT_SIZE);
cr->show_text("cairomm!");
// Now show it with the toy text API to demonstrate how the glyphs match up
cr->move_to(TEXT_ORIGIN_X, TEXT_ORIGIN_Y);
cr->set_source_rgba(0.2, 0.2, 0.2, 0.3);
auto toy_font =
Cairo::ToyFontFace::create("Bitstream Charter",
Cairo::FONT_SLANT_NORMAL,
Cairo::FONT_WEIGHT_BOLD);
cr->set_font_face(toy_font);
cr->set_font_size(FONT_SIZE);
cr->show_text("cairomm!");
const char* filename = "user-font.png";
try {
surface->write_to_png(filename);
std::cout << "Wrote Image " << filename << std::endl;
return 0;
} catch (const std::exception& e)
{
std::cout << "** Unable to write Image " << filename << std::endl;
return 1;
}
}
| 31.118881 | 82 | 0.63573 | [
"object"
] |
afb67741af2b054d0b3a56eafcaefb83904e1b03 | 1,191 | cpp | C++ | robotVision/Source/ListHelper.cpp | personalizedrefrigerator/2018LWHSVisionObjectDetection | 4f8c58fca73406349081f886f05c8a56cd6453bd | [
"BSD-3-Clause"
] | null | null | null | robotVision/Source/ListHelper.cpp | personalizedrefrigerator/2018LWHSVisionObjectDetection | 4f8c58fca73406349081f886f05c8a56cd6453bd | [
"BSD-3-Clause"
] | null | null | null | robotVision/Source/ListHelper.cpp | personalizedrefrigerator/2018LWHSVisionObjectDetection | 4f8c58fca73406349081f886f05c8a56cd6453bd | [
"BSD-3-Clause"
] | null | null | null | #include "ListHelper.h"
#include "Logging.h"
// Standard libraries.
#include <math.h>
#include <cstdlib>
#include <vector>
// Test the sorting function.
void ListHelper::testSort()
{
Logging::log("Starting merge sort test.");
std::vector< ObjectSortingContainer<double> > list;
for(double i = 0; i < 5; i++)
{
list.push_back(ObjectSortingContainer<double>((rand() % 10000)));
}
Logging::log("List");
for(unsigned int index = 0; index < list.size(); index++)
{
Logging::log << list.at(index).getValue() << ", ";
}
mergeSort(list, true);
Logging::log("List: ");
for(unsigned int index = 0; index < list.size(); index++)
{
Logging::log << list.at(index).getValue() << ", ";
}
Logging::log("======\nMerge two.");
list.clear();
std::vector< ObjectSortingContainer<double> > list2;
for(double i = 0; i < 5; i++)
{
list.push_back(ObjectSortingContainer<double>((rand() % 10000)));
list2.push_back(ObjectSortingContainer<double>((rand() % 10000)));
}
list = mergeTwoSorted(list, list2, true);
Logging::log("List: ");
for(unsigned int index = 0; index < list.size(); index++)
{
Logging::log << list.at(index).getValue() << ", ";
}
}
| 20.186441 | 68 | 0.625525 | [
"vector"
] |
afb9df3115a41e7939df1b3b81835010dc57ddd4 | 1,596 | cpp | C++ | aoc2/aoc2.cpp | epicyclism/aoc2021 | da29cf6523ebbba7882f5de5f2ced8b8ce48df6f | [
"MIT"
] | null | null | null | aoc2/aoc2.cpp | epicyclism/aoc2021 | da29cf6523ebbba7882f5de5f2ced8b8ce48df6f | [
"MIT"
] | null | null | null | aoc2/aoc2.cpp | epicyclism/aoc2021 | da29cf6523ebbba7882f5de5f2ced8b8ce48df6f | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <string_view>
#include <charconv>
#include <numeric>
#include "ctre_inc.h"
struct pd
{
int a_;
int h_;
int d_;
};
pd operator+(pd const& l, pd const& r)
{
return {0, l.h_ + r.h_, l.d_ + r.d_};
}
pd operator*(pd const& l, pd const& r)
{
return {l.a_ + r.d_, l.h_ + r.h_, l.d_ + ( l.a_ * r.h_)};
}
auto get_input()
{
constexpr auto rx = ctll::fixed_string{ R"((down|forward|up) (\d+))" };
std::string ln;
std::vector<pd> v;
while(std::getline(std::cin, ln))
{
if(auto[m, d, p] = ctre::match<rx>(ln); m)
{
auto pi = sv_to_t<int>(p.to_view());
switch(d.to_view()[0])
{
case 'd':
v.emplace_back(pd{0, 0, pi});
break;
case 'f':
v.emplace_back(pd{0, pi, 0});
break;
case 'u':
v.emplace_back(pd{0, 0, -pi});
break;
default: // CANNOT HAPPEN DUE REGEX
break;
}
}
else
std::cout << "Input tilt at : " << ln << "\n";
}
return v;
}
int pt1(auto const& v)
{
auto r = std::accumulate(v.begin(), v.end(), pd{});
return r.h_ * r.d_;;
}
int pt2(auto const& v)
{
auto r = std::accumulate(v.begin(), v.end(), pd{}, std::multiplies<>());
return r.h_ * r.d_;;
}
int main()
{
auto v = get_input();
std::cout << "pt1 = " << pt1(v) << "\n";
std::cout << "pt2 = " << pt2(v) << "\n";
} | 21.28 | 76 | 0.453008 | [
"vector"
] |
afc0099b89273cbeea6ba79fe89bc63de3c61a4c | 4,009 | cpp | C++ | topMetalDrone.cpp | alexanderpiers/UWTopMetalDrone | 5bb78faf2d558bb62ba65726a26d740f421d4ed3 | [
"MIT"
] | 1 | 2020-07-07T22:03:22.000Z | 2020-07-07T22:03:22.000Z | topMetalDrone.cpp | alexanderpiers/UWTopMetalDrone | 5bb78faf2d558bb62ba65726a26d740f421d4ed3 | [
"MIT"
] | null | null | null | topMetalDrone.cpp | alexanderpiers/UWTopMetalDrone | 5bb78faf2d558bb62ba65726a26d740f421d4ed3 | [
"MIT"
] | null | null | null | // Standard headers
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
// Utility headers
#include "tinyxml2.h"
#include "CLI11.hpp"
// Custom headers
#include "TopMetalDroneConfig.h"
#include "TopMetalDigitizer.h"
// Define constants
const int npx = 72;
const int npy = 72;
int main(int argc, char const *argv[])
{
CLI::App topMetalDroneParser{"UW Top Metal II- Drone Controller"};
// command line input variables
std::string infile = "topMetalConfig.xml";
std::string outfile = "";
// define command line arguments
topMetalDroneParser.add_option("-c, --config", infile, "Top Metal Drone Config file (xml)")->check(CLI::ExistingFile);
topMetalDroneParser.add_option("-o, --output", outfile, "Output file name");
// parse command line arguments
try{
topMetalDroneParser.parse(argc, argv);
}
catch (const CLI::ParseError &e) {
return topMetalDroneParser.exit(e);
}
// start controller
std::cout << "Starting UW Top Metal II- Drone Controller\n";
TopMetalDroneConfig config;
bool configSucces = config.ReadConfigFile(infile);
// Command line output file (if provided) supercedes config output filename
if(!outfile.empty()) config.SetOutputFilename(outfile);
if(configSucces) config.PrintConfigSettings();
// Create and communicate with digitizer
std::printf("Connect and configure digitizer....\n");
CaenDigitizerSettings digitizerSettings = config.GetDigitizerSettings();
TopMetalDigitizer digitizer(digitizerSettings);
digitizer.SetVerboseLevel(1);
digitizer.ConfigureDigitizer();
digitizer.StartDataAcquisition();
/*
Compute median and mad image if necessary
*/
// Define array size
double medianImage[npx][npy], madImage[npx][npy];
uint16_t * referenceImageRaw = new uint16_t[npx * npy * config.GetNumberFramesInReferenceImage()];
delete referenceImageRaw;
int eventTransferredCounter = 0;
// Open file handler
std::ofstream wf(config.GetOutputFilename(), std::ios::out | std::ios::binary);
if(!wf) {
std::cout << "Cannot open file!" << std::endl;
return 1;
}
// Get event info
CAEN_DGTZ_EventInfo_t eventInfo;
while(eventTransferredCounter < config.GetDigitizerSettings().maxNumberEventsTransferred){
// Depending on trigger type, send SW trigger or not
if(config.GetDigitizerSettings().triggerMode == SoftwareTrigger) digitizer.SendSWTrigger();
// usleep(20000);
digitizer.TransferData();
eventTransferredCounter += digitizer.GetNumberOfEventsRead();
for (int i = 0; i < digitizer.GetNumberOfEventsRead(); ++i)
{
char * evtptr = digitizer.GetEventPtr();
void * eventBuffer = digitizer.GetEventBuffer();
CAEN_DGTZ_GetEventInfo(digitizer.GetBoardAddress(), digitizer.GetBuffer(), digitizer.GetReadoutSize(), i, &eventInfo, &evtptr);
std::cout << "EventCounter: " << eventInfo.EventCounter << "\t";
CAEN_DGTZ_DecodeEvent(digitizer.GetBoardAddress(), evtptr, &eventBuffer);
CAEN_DGTZ_UINT16_EVENT_t * test = static_cast< CAEN_DGTZ_UINT16_EVENT_t * >(eventBuffer);
int waveformDownsamplingRate = config.GetWaveformDownsamplingRate();
// Write values to file
std::cout << "Mean ADU ";
for (int i = 0; i < digitizer.GetNumberOfChannels(); ++i)
{
int channelNumber = digitizerSettings.channelSettings[i].channelNumber;
wf.write((char *)test->DataChannel[channelNumber], sizeof(uint16_t)*test->ChSize[0] );
if(digitizer.GetVerboseLevel() > 0){
double mean = 0;
for(int j=0; j < test->ChSize[channelNumber]; j++){
if (j % waveformDownsamplingRate == 0)
{
mean += test->DataChannel[channelNumber][j];
}
}
mean /= (test->ChSize[channelNumber] / waveformDownsamplingRate);
std::cout << "Channel " << channelNumber << ": " << mean << "\t";
}
}
std::cout << "\n";
CAEN_DGTZ_FreeEvent(digitizer.GetBoardAddress(), &eventBuffer);
}
}
wf.close();
std::cout << "Number of Events: " << digitizer.GetNumberOfEventsRead() << std::endl;
return 0;
}
| 28.841727 | 130 | 0.705413 | [
"vector"
] |
afc28ee292dea929575257da519b3237278005f5 | 2,367 | cpp | C++ | src/CSVGFeTile.cpp | colinw7/CSVG | 049419b4114fc6ff7f5b25163398f02c21a64bf6 | [
"MIT"
] | 5 | 2015-04-11T14:56:03.000Z | 2021-12-14T10:12:36.000Z | src/CSVGFeTile.cpp | colinw7/CSVG | 049419b4114fc6ff7f5b25163398f02c21a64bf6 | [
"MIT"
] | 3 | 2015-04-20T19:23:15.000Z | 2021-09-03T20:03:30.000Z | src/CSVGFeTile.cpp | colinw7/CSVG | 049419b4114fc6ff7f5b25163398f02c21a64bf6 | [
"MIT"
] | 3 | 2015-05-21T08:33:12.000Z | 2020-05-13T15:45:11.000Z | #include <CSVGFeTile.h>
#include <CSVGFilter.h>
#include <CSVGBuffer.h>
#include <CSVG.h>
CSVGFeTile::
CSVGFeTile(CSVG &svg) :
CSVGFilterBase(svg)
{
}
CSVGFeTile::
CSVGFeTile(const CSVGFeTile &fe) :
CSVGFilterBase(fe),
filterIn_ (fe.filterIn_),
filterOut_(fe.filterOut_)
{
}
CSVGFeTile *
CSVGFeTile::
dup() const
{
return new CSVGFeTile(*this);
}
std::string
CSVGFeTile::
getFilterIn() const
{
return calcFilterIn(filterIn_);
}
std::string
CSVGFeTile::
getFilterOut() const
{
return calcFilterOut(filterOut_);
}
bool
CSVGFeTile::
processOption(const std::string &opt_name, const std::string &opt_value)
{
std::string str;
if (svg_.stringOption(opt_name, opt_value, "in", str))
filterIn_ = str;
else if (svg_.stringOption(opt_name, opt_value, "result", str))
filterOut_ = str;
else
return CSVGFilterBase::processOption(opt_name, opt_value);
return true;
}
bool
CSVGFeTile::
drawElement()
{
auto *inBuffer = svg_.getBuffer(getFilterIn ());
auto *outBuffer = svg_.getBuffer(getFilterOut());
if (svg_.getDebugFilter()) {
std::string objectBufferName = "_" + getUniqueName();
auto *buffer = svg_.getBuffer(objectBufferName + "_in");
buffer->setImageBuffer(inBuffer);
buffer->setBBox(inBuffer->bbox());
}
//---
// get filtered object coords for input
CBBox2D inBBox;
getBufferSubRegion(inBuffer, inBBox);
// get tile subregion for output
CBBox2D outBBox;
getSubRegion(outBBox);
//---
// tile
CSVGBuffer::tileBuffers(inBuffer, inBBox, outBBox, outBuffer);
outBuffer->setBBox(outBBox);
//---
if (svg_.getDebugFilter()) {
std::string objectBufferName = "_" + getUniqueName();
auto *buffer = svg_.getBuffer(objectBufferName + "_out");
buffer->setImageBuffer(outBuffer);
buffer->setBBox(outBBox);
}
return true;
}
void
CSVGFeTile::
print(std::ostream &os, bool hier) const
{
if (hier) {
os << "<feTile";
printValues(os);
os << "/>" << std::endl;
}
else
os << "feTile ";
}
void
CSVGFeTile::
printValues(std::ostream &os, bool flat) const
{
CSVGObject::printValues(os, flat);
CSVGFilterBase::printValues(os, flat);
printNameValue(os, "in" , filterIn_ );
printNameValue(os, "result", filterOut_);
}
std::ostream &
operator<<(std::ostream &os, const CSVGFeTile &fe)
{
fe.print(os, false);
return os;
}
| 16.669014 | 72 | 0.675116 | [
"object"
] |
afd0e05d6a61e83779bfac20dd554b607f5af08c | 2,022 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_intervalmap.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_intervalmap.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_intervalmap.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #ifndef INCLUDED_STDDEFX
#include "stddefx.h"
#define INCLUDED_STDDEFX
#endif
// Library headers.
// PCRaster library headers.
#ifndef INCLUDED_COM_INTERVALMAP
#include "com_intervalmap.h"
#define INCLUDED_COM_INTERVALMAP
#endif
// Module headers.
/*!
\file
This file contains the implementation of the IntervalMap class.
*/
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF STATIC INTERVALMAP MEMBERS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF INTERVALMAP MEMBERS
//------------------------------------------------------------------------------
/*
com::IntervalMap::IntervalMap()
{
}
com::IntervalMap::~IntervalMap()
{
}
*/
/* NOT IMPLEMENTED
//! Assignment operator.
com::IntervalMap& com::IntervalMap::operator=(const IntervalMap& rhs)
{
if (this != &rhs) {
}
return *this;
}
//! Copy constructor. NOT IMPLEMENTED.
com::IntervalMap::IntervalMap(const IntervalMap& rhs):
Base(rhs)
{
}
*/
//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------
template <typename R>
bool com::noOverlap(const std::vector<const Interval<R> *>& v)
{
IntervalMap<bool,R> m; // TODO actually an IntervalSet<R> suffices
for(size_t i=0; i<v.size(); ++i)
if (!m.insertInterval(*v[i]))
return false;
return true;
}
namespace com {
template bool noOverlap<float>(const std::vector<const Interval<float> *>& v);
template bool noOverlap<double>(const std::vector<const Interval<double> *>& v);
}
| 22.21978 | 80 | 0.452028 | [
"vector"
] |
afded9f40a6d1b52b2f699eae92894675ce14e8a | 4,628 | cpp | C++ | testing/testing_csv_file/main.cpp | NewYaroslav/xquotes_history | 6a72a3cf88f0d00c42aa735cc84327806257e422 | [
"MIT"
] | 4 | 2019-09-05T20:49:38.000Z | 2021-11-17T09:44:22.000Z | testing/testing_csv_file/main.cpp | NewYaroslav/xquotes_history | 6a72a3cf88f0d00c42aa735cc84327806257e422 | [
"MIT"
] | 2 | 2020-04-10T20:00:56.000Z | 2020-05-08T03:47:55.000Z | testing/testing_csv_file/main.cpp | NewYaroslav/xquotes_history | 6a72a3cf88f0d00c42aa735cc84327806257e422 | [
"MIT"
] | 3 | 2019-11-02T19:57:11.000Z | 2021-05-13T20:12:59.000Z | #include "xquotes_files.hpp"
#include "xquotes_csv.hpp"
#include "xquotes_history.hpp"
#include <vector>
#include <array>
#include <iostream>
#include <random>
#include <ctime>
#include <stdio.h>
int main(int argc, char *argv[]) {
std::string file_name_csv_mt4 = "mt4_example.csv";
std::string file_name_csv_mt5 = "mt5_example.csv";
std::string file_name_csv_dukascopy = "dukascopy_example.csv";
std::cout << file_name_csv_mt4 << std::endl;
int err_mt4 = xquotes_csv::read_file(
file_name_csv_mt4,
false,
xquotes_csv::DO_NOT_CHANGE_TIME_ZONE,
[&](const xquotes_csv::Candle candle, const bool is_end) {
std::cout
<< "candle: "
<< xtime::get_str_date_time(candle.timestamp) << " "
<< candle.open << " "
<< candle.high << " "
<< candle.low << " "
<< candle.close << " "
<< candle.volume << " is end "
<< is_end
<< std::endl;
});
std::cout << "err: " << err_mt4 << std::endl;
std::cout << file_name_csv_mt5 << std::endl;
int err_mt5 = xquotes_csv::read_file(
file_name_csv_mt5,
false,
xquotes_csv::DO_NOT_CHANGE_TIME_ZONE,
[&](const xquotes_csv::Candle candle, const bool is_end) {
std::cout
<< "candle: "
<< xtime::get_str_date_time(candle.timestamp) << " "
<< candle.open << " "
<< candle.high << " "
<< candle.low << " "
<< candle.close << " "
<< candle.volume << " is end "
<< is_end
<< std::endl;
});
std::cout << "err: " << err_mt5 << std::endl;
std::cout << file_name_csv_dukascopy << std::endl;
int err_dukascopy = xquotes_csv::read_file(
file_name_csv_dukascopy,
false,
xquotes_csv::DO_NOT_CHANGE_TIME_ZONE,
[&](const xquotes_csv::Candle candle, const bool is_end) {
std::cout
<< "candle: "
<< xtime::get_str_date_time(candle.timestamp) << " "
<< candle.open << " "
<< candle.high << " "
<< candle.low << " "
<< candle.close << " "
<< candle.volume << " is end "
<< is_end
<< std::endl;
});
std::cout << "err: " << err_dukascopy << std::endl;
std::cout << "write: test_mt4_example.csv" << std::endl;
xquotes_csv::write_file(
"test_mt4_example.csv",
"",
false,
xtime::get_timestamp(1,1,2019,0,0,0),
xtime::get_timestamp(1,1,2019,23,59,0),
xquotes_csv::MT4,
xquotes_csv::SKIPPING_BAD_CANDLES,
xquotes_csv::DO_NOT_CHANGE_TIME_ZONE,
5,
[&](xquotes_csv::Candle &candle, const xtime::timestamp_t timestamp) -> bool {
candle.open = 64.5;
candle.high = 64.5;
candle.low = 64.5;
candle.close = 64.5;
candle.volume = 10.1;
candle.timestamp = timestamp;
return true;
});
std::cout << "write: test_mt5_example.csv" << std::endl;
xquotes_csv::write_file(
"test_mt5_example.csv",
"<DATE>\t<TIME>\t<OPEN>\t<HIGH>\t<LOW>\t<CLOSE>\t<TICKVOL>\t<VOL>\t<SPREAD>",
true,
xtime::get_timestamp(1,1,2019,0,0,0),
xtime::get_timestamp(1,1,2019,23,59,0),
xquotes_csv::MT5,
xquotes_csv::SKIPPING_BAD_CANDLES,
xquotes_csv::DO_NOT_CHANGE_TIME_ZONE,
5,
[&](xquotes_csv::Candle &candle, const xtime::timestamp_t timestamp) -> bool {
candle.open = 64.5;
candle.high = 64.5;
candle.low = 64.5;
candle.close = 64.5;
candle.volume = 10.1;
candle.timestamp = timestamp;
return true;
});
std::cout << "write: test_dukascopy_example.csv" << std::endl;
xquotes_csv::write_file(
"test_dukascopy_example.csv",
"Gmt time,Open,High,Low,Close,Volume",
true,
xtime::get_timestamp(1,1,2019,0,0,0),
xtime::get_timestamp(1,1,2019,23,59,0),
xquotes_csv::DUKASCOPY,
xquotes_csv::SKIPPING_BAD_CANDLES,
xquotes_csv::DO_NOT_CHANGE_TIME_ZONE,
5,
[&](xquotes_csv::Candle &candle, const xtime::timestamp_t timestamp) -> bool {
candle.open = 64.5;
candle.high = 64.5;
candle.low = 64.5;
candle.close = 64.5;
candle.volume = 10.1;
candle.timestamp = timestamp;
return true;
});
return 0;
}
| 33.536232 | 86 | 0.533276 | [
"vector"
] |
afe0f621c7fa7866ad74ebf999edba583df616bd | 1,309 | cpp | C++ | computervision/01/cv4.cpp | pantadeusz/examples-ai | 7316191b592eeb95c5873ee6836ccb6ca5b776a5 | [
"MIT"
] | 1 | 2020-10-20T13:27:16.000Z | 2020-10-20T13:27:16.000Z | computervision/01/cv4.cpp | pantadeusz/examples-ai | 7316191b592eeb95c5873ee6836ccb6ca5b776a5 | [
"MIT"
] | null | null | null | computervision/01/cv4.cpp | pantadeusz/examples-ai | 7316191b592eeb95c5873ee6836ccb6ca5b776a5 | [
"MIT"
] | 2 | 2019-06-07T10:54:01.000Z | 2020-12-01T12:58:44.000Z | #include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <vector>
// g++ `pkg-config --cflags opencv4` cv3.cpp `pkg-config --libs opencv4`
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
int h1 = 0;
int h2 = 255;
int s1 = 0;
int s2 = 255;
int v1 = 0;
int v2 = 255;
VideoCapture cap1(0);
if (!cap1.isOpened())
return -1;
namedWindow("pierwsze", WINDOW_AUTOSIZE);
createTrackbar("h1", "pierwsze", &h1, 255);
createTrackbar("h2", "pierwsze", &h2, 255);
createTrackbar("s1", "pierwsze", &s1, 255);
createTrackbar("s2", "pierwsze", &s2, 255);
createTrackbar("v1", "pierwsze", &v1, 255);
createTrackbar("v2", "pierwsze", &v2, 255);
while (true) {
Mat f1;
// cap1 >> f1;
cap1.read(f1);
Mat dst;
Mat edges;
Mat range;
cvtColor(f1, dst, COLOR_BGR2HSV);
imshow("zrodlo", f1);
imshow("czarnobialy", dst);
inRange(dst, Scalar{h1, s1, v1}, Scalar{h2, s2, v2}, range);
Mat k = getStructuringElement(MORPH_ELLIPSE, {9, 9});
Mat diledges;
morphologyEx(range,range,MORPH_CLOSE,k);
imshow("inrange", range);
if (waitKey(1) == 27)
break;
}
return 0;
}
| 23.375 | 72 | 0.569137 | [
"vector"
] |
afe99637287188cbd4e1b6a4c14c6f38988c4183 | 1,647 | cpp | C++ | ANNWrapper.cpp | mattjr/structured | 0cb4635af7602f2a243a9b739e5ed757424ab2a7 | [
"Apache-2.0"
] | 14 | 2015-01-11T02:53:04.000Z | 2021-11-25T17:31:22.000Z | ANNWrapper.cpp | skair39/structured | 0cb4635af7602f2a243a9b739e5ed757424ab2a7 | [
"Apache-2.0"
] | null | null | null | ANNWrapper.cpp | skair39/structured | 0cb4635af7602f2a243a9b739e5ed757424ab2a7 | [
"Apache-2.0"
] | 14 | 2015-07-21T04:47:52.000Z | 2020-03-12T12:31:25.000Z | #include "ANNWrapper.h"
ANNWrapper::ANNWrapper()
{
m_anything_to_free = false;
m_eps = 0;
m_k = 1;
}
ANNWrapper::~ANNWrapper()
{
Free();
}
void ANNWrapper::Free()
{
if(!m_anything_to_free)
return;
delete [] m_nnidx; // clean things up
delete [] m_dists;
delete m_kdtree;
annDeallocPts(m_data_pts);
annClose(); // done with ANN
m_anything_to_free = false;
}
void ANNWrapper::SetPoints(const std::vector <Vertex> &P)
{
Free(); // Free, if theres anything to free
m_nnidx = new ANNidx[m_k]; // allocate near neigh indices
m_dists = new ANNdist[m_k]; // allocate near neighbor m_dists
m_query_pt = annAllocPt(dim); // allocate query point
m_npts = P.size();
m_data_pts = annAllocPts(P.size(), dim); // allocate data points
for(unsigned int i=0; i < P.size(); i++)
{
m_data_pts[i][0] = P[i].x;
m_data_pts[i][1] = P[i].y;
m_data_pts[i][2] = P[i].z;
}
m_kdtree = new ANNkd_tree( // build search structure
m_data_pts, // the data points
m_npts, // number of points
dim); // dimension of space
m_anything_to_free = true;
}
void ANNWrapper::FindClosest(const Vertex &P, double *sq_distance, int *index)
{
m_query_pt[0] = P.x;
m_query_pt[1] = P.y;
m_query_pt[2] = P.z;
m_kdtree->annkSearch( // search
m_query_pt, // query point
m_k, // number of near neighbors
m_nnidx, // nearest neighbors (returned)
m_dists, // distance (returned)
m_eps); // error bound
for(int i=0; i < m_k; i++)
{
sq_distance[i] = m_dists[i];
index[i] = m_nnidx[i];
}
}
void ANNWrapper::SetResults(int a)
{
m_k = a;
}
| 20.085366 | 78 | 0.625379 | [
"vector"
] |
afec0728fc78236aca5879f64b3f484dcad27ade | 730 | hpp | C++ | RoboNeko/robit.hpp | nspool/RoboNeko | 1f5ce273f9d38ce84dca1022d48b55d8025cec3a | [
"MIT"
] | null | null | null | RoboNeko/robit.hpp | nspool/RoboNeko | 1f5ce273f9d38ce84dca1022d48b55d8025cec3a | [
"MIT"
] | null | null | null | RoboNeko/robit.hpp | nspool/RoboNeko | 1f5ce273f9d38ce84dca1022d48b55d8025cec3a | [
"MIT"
] | null | null | null | //
// Robit.hpp
// RoboNeko
//
// Created by nsp on 16/3/17.
// Copyright 2017 nspool. All rights reserved.
//
#ifndef Robit_hpp
#define Robit_hpp
#include <vector>
#include <SDL.h>
#include <SDL_timer.h>
#include "sprite.hpp"
const int ANIMATION_FPS = 10;
const int STATE_DELAY_MS = 1000;
enum RobitState : int { Pursue, Stop, Alert, Wait, Yawn, Sleep };
class Robit : public Sprite
{
public:
Robit(SDL_Renderer* renderer, SDL_Point start_pos);
void evaluate(SDL_Point* target);
void render(SDL_Renderer* renderer);
private:
RobitState state_;
SDL_Rect position_;
SDL_Texture* texture_;
std::vector<SDL_Rect> frames_;
unsigned int transition_tm_ = 0;
void transition(RobitState newState);
};
#endif
| 18.25 | 65 | 0.720548 | [
"render",
"vector"
] |
afed03bd937c4b70fdb007de749fe1cd45fe98bf | 1,300 | cpp | C++ | DSA/Graphs/Strongly_connected_components.cpp | ShrishtiAgarwal/DSA | 8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df | [
"MIT"
] | null | null | null | DSA/Graphs/Strongly_connected_components.cpp | ShrishtiAgarwal/DSA | 8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df | [
"MIT"
] | null | null | null | DSA/Graphs/Strongly_connected_components.cpp | ShrishtiAgarwal/DSA | 8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df | [
"MIT"
] | null | null | null | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
void dfs(vector<vector<int>>&q,vector<bool>&vis,int i,stack<int>&s)
{
vis[i]=true;
for(int j=0;j<q[i].size();j++)
{
if(!vis[q[i][j]])
dfs(q,vis,q[i][j],s);
}
s.push(i);
}
void dfss(int i,vector<vector<int>>&d,vector<bool>&vis)
{
vis[i]=true;
cout<<i;
for(int j=0;j<d[i].size();j++)
{
if(vis[d[i][j]]==false)
{
dfss(d[i][j],d,vis);
}
}
}
void kosaraju(vector<vector<int>>&q,int n)
{
vector<bool>vis(n+1);
for(int i=0;i<=n;i++)
vis[i]=false;
stack<int>s;
for(int i=0;i<=n;i++)
{
if(!vis[i])
dfs(q,vis,i,s);
}
vector<vector<int>>d(n+1);
for(int i=0;i<=n;i++)
{
for(int j=0;j<q[i].size();j++)
{
d[q[i][j]].push_back(i);
}
}
for(int i=0;i<=n;i++)
vis[i]=false;
while(!s.empty())
{
int u=s.top();
s.pop();
if(u==0)
continue;
if(vis[u]==true)
continue;
else
{dfss(u,d,vis);
cout<<endl;}
}
}
int main()
{
int n,m,j=0;
int a,b;
cin>>n>>m;
vector<vector<int>>q(n+1);
while(j<m)
{
cin>>a>>b;
q[a].push_back(b);
j++;
}
kosaraju(q,n);
} | 14.130435 | 67 | 0.44 | [
"vector"
] |
afed910e74936311152eaa9d56494791d805cf15 | 912 | hpp | C++ | src/terrain.hpp | MajorArkwolf/ICT397-Lab2 | d3f1744b2a1b60d693ddbff791e5e44610a1e02b | [
"ISC"
] | null | null | null | src/terrain.hpp | MajorArkwolf/ICT397-Lab2 | d3f1744b2a1b60d693ddbff791e5e44610a1e02b | [
"ISC"
] | null | null | null | src/terrain.hpp | MajorArkwolf/ICT397-Lab2 | d3f1744b2a1b60d693ddbff791e5e44610a1e02b | [
"ISC"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <vector>
#include "shader.hpp"
#include "vertix.hpp"
namespace Red {
class Terrain {
public:
Terrain();
~Terrain();
void loadScene();
void clearScene();
void generateTerrain(int x, int z);
void generateIndicies(unsigned int xsize, unsigned int ysize);
void generateTextureCords(unsigned int xsize, unsigned int ysize);
void setupModel();
void draw(glm::mat4 projection, glm::mat4 view);
void update(double t, double dt);
void setTextures(unsigned int tex1, unsigned int tex2);
bool wireframe = false;
private:
std::vector<Verticies> vertex;
std::vector<float> vertices;
std::vector<unsigned int> indicies;
Shader* ourShader = nullptr;
unsigned int VBO = 0, VAO = 0, EBO = 0;
unsigned int textureID = 0, textureID2 = 0;
unsigned int example = 0;
};
} | 25.333333 | 68 | 0.710526 | [
"vector"
] |
affe4bb737a2706759b2cc84356d974f59c0df10 | 1,686 | cpp | C++ | fboss/agent/hw/sai/api/NeighborApi.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 834 | 2015-03-10T18:12:28.000Z | 2022-03-31T20:16:17.000Z | fboss/agent/hw/sai/api/NeighborApi.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 82 | 2015-04-07T08:48:29.000Z | 2022-03-11T21:56:58.000Z | fboss/agent/hw/sai/api/NeighborApi.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 296 | 2015-03-11T03:45:37.000Z | 2022-03-14T22:54:22.000Z | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/sai/api/NeighborApi.h"
#include "fboss/agent/Constants.h"
#include <boost/functional/hash.hpp>
#include <functional>
namespace std {
size_t hash<facebook::fboss::SaiNeighborTraits::NeighborEntry>::operator()(
const facebook::fboss::SaiNeighborTraits::NeighborEntry& n) const {
size_t seed = 0;
boost::hash_combine(seed, n.switchId());
boost::hash_combine(seed, n.routerInterfaceId());
boost::hash_combine(seed, std::hash<folly::IPAddress>()(n.ip()));
return seed;
}
} // namespace std
namespace facebook::fboss {
std::string SaiNeighborTraits::NeighborEntry::toString() const {
return folly::to<std::string>(
"NeighborEntry(switch:",
switchId(),
", rif: ",
routerInterfaceId(),
", ip: ",
ip().str(),
")");
}
folly::dynamic SaiNeighborTraits::NeighborEntry::toFollyDynamic() const {
folly::dynamic json = folly::dynamic::object;
json[kSwitchId] = switchId();
json[kIntf] = routerInterfaceId();
json[kIp] = ip().str();
return json;
}
SaiNeighborTraits::NeighborEntry
SaiNeighborTraits::NeighborEntry::fromFollyDynamic(const folly::dynamic& json) {
sai_object_id_t switchId = json[kSwitchId].asInt();
sai_object_id_t intf = json[kIntf].asInt();
folly::IPAddress ip(json[kIp].asString());
return NeighborEntry(switchId, intf, ip);
}
} // namespace facebook::fboss
| 28.576271 | 80 | 0.700474 | [
"object"
] |
9b81675734e7d879383ca337aa4c40d365e2e1e0 | 1,187 | cpp | C++ | uva/chapter_8/1252_Twenty_Questions_RIG.cpp | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | uva/chapter_8/1252_Twenty_Questions_RIG.cpp | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | uva/chapter_8/1252_Twenty_Questions_RIG.cpp | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using ii = pair<int,int>;
using ll = long long;
using llu = unsigned long long;
const int INF = numeric_limits<int>::max();
default_random_engine source(random_device{}());
int random_in_range(int a, int b) {
return uniform_int_distribution<>(a, b)(source);
}
bool random_bool() {
return random_in_range(0, 1) == 1;
}
string random_string(int length) {
string s = "";
string an = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < length; i++) {
s += an[random_in_range(0, an.size() - 1)];
}
return s;
}
int main() {
int tcc = 10;
for (int tc = 0; tc < tcc; tc++) {
int m = random_in_range(1, 11);
int n = random_in_range(1, min(128, 1 << m));
printf("%d %d\n", m, n);
bitset<(1 << 11)> used;
for (int i = 0; i < n; i++) {
int v = random_in_range(0, (1 << m) - 1);
while (used[v]) v = (v + 1) % (1 << m);
used[v] = true;
for (int j = 0; j < m; j++) {
if (v & (1 << j)) {
printf("1");
} else {
printf("0");
}
}
printf("\n");
}
}
printf("0 0\n");
}
| 22.826923 | 79 | 0.544229 | [
"vector"
] |
9b824b52f85cd5849a162d7804d6f7752f92ba76 | 2,490 | cpp | C++ | problems/sorted_twice_median.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 5 | 2021-05-17T12:32:42.000Z | 2021-12-12T21:09:55.000Z | problems/sorted_twice_median.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | null | null | null | problems/sorted_twice_median.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 1 | 2021-05-13T20:29:57.000Z | 2021-05-13T20:29:57.000Z | #include <iostream>
#include <vector>
using namespace std;
int getMedian(vector<int> &, vector<int> &, int);
int median(vector<int> &, int);
int main() {
/**
* In order to find the median of two sorted arrays, when they are
* combined, we simply find out the most suitable position for such
* a median to exist, by comparing the individual medians of the two
* arrays, the one which is lower moves up, while the higher moves
* down, till the size of vectors reduces to 2 or less
*/
cout << "\nThis program finds out the median of two sorted arrays of same size when combined.\n" << endl;
int n;
cout << "Enter the number of elements to consider: ";
cin >> n;
vector<int> arr1(n), arr2(n);
cout << "Enter space seperated sorted elements of the first array," << endl;
for (int i = 0; i < n; i += 1) cin >> arr1[i];
cout << "Enter space seperated sorted elements of the second array," << endl;
for (int i = 0; i < n; i += 1) cin >> arr2[i];
int mdn = getMedian(arr1, arr2, n);
cout << "\nThe median of the arrays when combined, turns out to be " << mdn << "." << endl;
cout << endl;
return 0;
}
int median(vector<int> &arr, int n) {
// Median lies in middle for odd number of elements, and
// average of two middle numbers for even number of elements
if (n % 2 == 0) return (arr[n / 2] + arr[n / 2 - 1]) / 2;
else return arr[n / 2];
}
int getMedian(vector<int> &arr1, vector<int> &arr2, int n) {
// Base Case for invalid input
if (n <= 0) return 0;
// When there is 1 element remaining in both, we simply return their average
if (n == 1) return (arr1[0] + arr2[0]) / 2;
// When there are 2 elements in both, we find average of max of 1st & min of 2nd indices
if (n == 2) return (max(arr1[0], arr2[0]) + min(arr1[1], arr2[1])) / 2;
int m1 = median(arr1, n);
int m2 = median(arr2, n);
// If the medians are equal, we return either
if (m1 == m2) return m1;
// Next size after determining median position
int sz = n & 1 ? n / 2 : n / 2 - 1;
if (m1 < m2) {
// If m1 < m2 then median must exist in arr1[m1....] and arr2[....m2]
arr1.erase(arr1.begin(), arr1.begin() + sz);
return getMedian(arr1, arr2, n - sz);
} else {
// If m1 > m2 then median must exist in arr1[....m1] and arr2[m2...]
arr2.erase(arr2.begin(), arr2.begin() + sz);
return getMedian(arr2, arr1, n - sz);
}
} | 36.086957 | 109 | 0.597992 | [
"vector"
] |
9b851b32ab8027cc71b00e6b74ca9e82e156b0b6 | 2,769 | cpp | C++ | systems/plants/geometricJacobianmex.cpp | andybarry/drake | 61428cff8cb523314cd87105821148519460a0b9 | [
"BSD-3-Clause"
] | null | null | null | systems/plants/geometricJacobianmex.cpp | andybarry/drake | 61428cff8cb523314cd87105821148519460a0b9 | [
"BSD-3-Clause"
] | null | null | null | systems/plants/geometricJacobianmex.cpp | andybarry/drake | 61428cff8cb523314cd87105821148519460a0b9 | [
"BSD-3-Clause"
] | 1 | 2021-07-07T18:52:51.000Z | 2021-07-07T18:52:51.000Z | #include <mex.h>
#include <iostream>
#include "drakeUtil.h"
#include "RigidBodyManipulator.h"
#include "drakeGeometryUtil.h"
#include "math.h"
using namespace Eigen;
using namespace std;
/*
* A C version of the geometricJacobian function
*
* Call with [J, vIndices] = geometricJacobianmex(model_ptr, base_body_or_frame_ind, end_effector_body_or_frame_ind, expressed_in_body_or_frame_ind);
*/
// TODO: stop copying these functions everywhere and find a good place for them
template <typename DerivedA>
mxArray* eigenToMatlab(const DerivedA &m)
{
mxArray* pm = mxCreateDoubleMatrix(static_cast<int>(m.rows()),static_cast<int>(m.cols()),mxREAL);
if (m.rows()*m.cols()>0)
memcpy(mxGetPr(pm),m.data(),sizeof(double)*m.rows()*m.cols());
return pm;
}
mxArray* stdVectorToMatlab(const std::vector<int>& vec) {
// mxArray* pm = mxCreateNumericMatrix(vec.size(), 1, mxINT32_CLASS, mxREAL);
// if (vec.size() > 0) {
// memcpy(mxGetPr(pm), vec.data(), sizeof(int) * vec.size());
// }
// return pm;
mxArray* pm = mxCreateDoubleMatrix(static_cast<int>(vec.size()), 1, mxREAL);
for (int i = 0; i < static_cast<int>(vec.size()); i++) {
mxGetPr(pm)[i] = (double) vec[i];
}
return pm;
}
void baseZeroToBaseOne(std::vector<int>& vec)
{
for (std::vector<int>::iterator iter=vec.begin(); iter!=vec.end(); iter++)
(*iter)++;
}
void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] ) {
std::string usage = "Usage [J, vIndices] = geometricJacobianmex(model_ptr, base_body_or_frame_ind, end_effector_body_or_frame_ind, expressed_in_body_or_frame_ind)";
if (nrhs != 4) {
mexErrMsgIdAndTxt("Drake:geometricJacobianmex:WrongNumberOfInputs", usage.c_str());
}
if (nlhs > 2) {
mexErrMsgIdAndTxt("Drake:geometricJacobianmex:WrongNumberOfOutputs", usage.c_str());
}
// first get the model_ptr back from matlab
RigidBodyManipulator *model= (RigidBodyManipulator*) getDrakeMexPointer(prhs[0]);
int base_body_or_frame_ind = ((int) mxGetScalar(prhs[1])) - 1; // base 1 to base 0
int end_effector_body_or_frame_ind = ((int) mxGetScalar(prhs[2])) - 1; // base 1 to base 0
int expressed_in_body_or_frame_ind = ((int) mxGetScalar(prhs[3])) - 1; // base 1 to base 0
Eigen::Matrix<double, TWIST_SIZE, Eigen::Dynamic> J(TWIST_SIZE, 1);
if (nlhs > 1) {
std::vector<int> v_indices;
model->geometricJacobian(base_body_or_frame_ind, end_effector_body_or_frame_ind, expressed_in_body_or_frame_ind, J, &v_indices);
baseZeroToBaseOne(v_indices);
plhs[1] = stdVectorToMatlab(v_indices);
}
else if (nlhs > 0){
model->geometricJacobian(base_body_or_frame_ind, end_effector_body_or_frame_ind, expressed_in_body_or_frame_ind, J, nullptr);
}
if (nlhs > 0) {
plhs[0] = eigenToMatlab(J);
}
}
| 34.185185 | 166 | 0.711448 | [
"vector",
"model"
] |
9b8ad4ad73aed36e71a6351f29c00c7dde1cc4f0 | 1,415 | cpp | C++ | src/parser.cpp | Jorengarenar/bim | 1b691201ea3a767b0169aa8aec79bf731fa42f40 | [
"MIT"
] | null | null | null | src/parser.cpp | Jorengarenar/bim | 1b691201ea3a767b0169aa8aec79bf731fa42f40 | [
"MIT"
] | 1 | 2021-11-05T20:18:39.000Z | 2021-11-05T20:18:39.000Z | src/parser.cpp | Jorengarenar/bim | 1b691201ea3a767b0169aa8aec79bf731fa42f40 | [
"MIT"
] | null | null | null | #include "parser.hpp"
#include <cstdlib>
#include <fstream>
#include <iterator>
#include <xdgdirs.h>
#include "editor.hpp"
#include "util.hpp"
#include "action.hpp"
int Parser::operator ()(const std::string& line)
{
buf = {};
buf << line;
std::string a;
while (buf >> a) {
if (a == "|") {
continue;
}
if (a[0] == '#') {
break;
}
auto r = defaults.find(a);
if (r != defaults.end()) {
r->second->exec();
}
else {
Editor::getInstance().cli.error(a + " : No such command!");
}
}
return 0;
}
void Parser::config()
{
std::string xdg_config_home = xdgConfigHome();
if (xdg_config_home.empty()) {
Editor::getInstance().cli.error("XDG_CONFIG_HOME is set to invalid (empty) location");
return;
}
std::ifstream file{ xdg_config_home + "/sXe/rc" };
if (file.is_open()) {
std::string buf;
while (getline(file, buf)) {
(*this)(buf);
}
file.close();
}
}
#define X(NS, CL, b, m, CMD, f) { CMD, std::make_shared<action::NS::CL>(this) },
Parser::Parser() :
Interpreter({
#include "action.x.hpp"
})
{
std::transform(defaults.begin(), defaults.end(),
std::inserter(commandsKeys, commandsKeys.begin()),
[](const auto& p) { return p.first; });
}
| 20.214286 | 94 | 0.513074 | [
"transform"
] |
9b8e51046a1e6b47ff6438d86b47f2955a6252d2 | 3,225 | cc | C++ | src/NeutronHPMessenger.cc | pgranhol/T1-target | d80e3607e5008cf2249d62dacc49bccd9205be27 | [
"MIT"
] | null | null | null | src/NeutronHPMessenger.cc | pgranhol/T1-target | d80e3607e5008cf2249d62dacc49bccd9205be27 | [
"MIT"
] | null | null | null | src/NeutronHPMessenger.cc | pgranhol/T1-target | d80e3607e5008cf2249d62dacc49bccd9205be27 | [
"MIT"
] | null | null | null | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file NeutronHPMessenger.cc
/// \brief Implementation of the NeutronHPMessenger class
//
// $Id: NeutronHPMessenger.cc 67268 2013-02-13 11:38:40Z ihrivnac $
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "NeutronHPMessenger.hh"
#include "HadronElasticPhysicsHP.hh"
#include "G4UIdirectory.hh"
#include "G4UIcmdWithABool.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
NeutronHPMessenger::NeutronHPMessenger(HadronElasticPhysicsHP* phys)
:G4UImessenger(),fNeutronPhysics(phys),
fPhysDir(0), fThermalCmd(0)
{
fPhysDir = new G4UIdirectory("/testhadr/phys/");
fPhysDir->SetGuidance("physics list commands");
fThermalCmd = new G4UIcmdWithABool("/testhadr/phys/thermalScattering",this);
fThermalCmd->SetGuidance("set thermal scattering model");
fThermalCmd->SetParameterName("thermal",false);
fThermalCmd->AvailableForStates(G4State_PreInit);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
NeutronHPMessenger::~NeutronHPMessenger()
{
delete fThermalCmd;
delete fPhysDir;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NeutronHPMessenger::SetNewValue(G4UIcommand* command, G4String newValue)
{
if (command == fThermalCmd)
{fNeutronPhysics->SetThermalPhysics(fThermalCmd->GetNewBoolValue(newValue));}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| 44.178082 | 80 | 0.60124 | [
"model"
] |
9b90cad08c7a3464ac42ab4b85f317517688b137 | 2,196 | cpp | C++ | examples/dest_show_landmarks.cpp | cluert/dest | 82c25f44ebe00b64e098d7e554fbc4ae1ae1c788 | [
"BSD-3-Clause"
] | 309 | 2016-01-19T23:49:41.000Z | 2022-03-14T07:16:32.000Z | examples/dest_show_landmarks.cpp | jnulzl/dest | 82c25f44ebe00b64e098d7e554fbc4ae1ae1c788 | [
"BSD-3-Clause"
] | 17 | 2016-02-16T16:36:53.000Z | 2020-05-25T05:56:02.000Z | examples/dest_show_landmarks.cpp | jnulzl/dest | 82c25f44ebe00b64e098d7e554fbc4ae1ae1c788 | [
"BSD-3-Clause"
] | 114 | 2016-02-27T13:51:21.000Z | 2022-03-01T09:00:06.000Z | /**
This file is part of Deformable Shape Tracking (DEST).
Copyright(C) 2015/2016 Christoph Heindl
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license.See the LICENSE file for details.
*/
#include <dest/dest.h>
#include <tclap/CmdLine.h>
#include <opencv2/opencv.hpp>
/**
Show landmarks on faces.
*/
int main(int argc, char **argv)
{
struct {
std::string database;
int loadMaxSize;
int loadMinSize;
} opts;
try {
TCLAP::CmdLine cmd("Evaluate regressor on test database.", ' ', "0.9");
TCLAP::ValueArg<int> maxImageSizeArg("", "load-max-size", "Maximum size of images in the database", false, 2048, "int", cmd);
TCLAP::ValueArg<int> minImageSizeArg("", "load-min-size", "Minimum size of images in the database", false, 640, "int", cmd);
TCLAP::UnlabeledValueArg<std::string> databaseArg("database", "Path to database directory to load", true, "./db", "string", cmd);
cmd.parse(argc, argv);
opts.database = databaseArg.getValue();
opts.loadMaxSize = maxImageSizeArg.getValue();
opts.loadMinSize = minImageSizeArg.getValue();
}
catch (TCLAP::ArgException &e) {
std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl;
return -1;
}
dest::io::ShapeDatabase sd;
sd.setMaxImageLoadSize(opts.loadMaxSize);
sd.setMinImageLoadSize(opts.loadMinSize);
sd.enableMirroring(true);
sd.setMaxElementsToLoad(10);
dest::core::InputData inputs;
if (!sd.load(opts.database, inputs.images, inputs.shapes, inputs.rects)) {
std::cerr << "Failed to load database." << std::endl;
return -1;
}
size_t i = 0;
bool done = false;
while (i < inputs.images.size() && !done) {
cv::Mat tmp = dest::util::drawShape(inputs.images[i], inputs.shapes[i], cv::Scalar(255, 255, 255));
dest::util::drawShapeText(tmp, inputs.shapes[i], cv::Scalar(0, 0, 255));
cv::imshow("Inputs - Press ESC to skip", tmp);
if (cv::waitKey() == 27)
done = true;
++i;
}
return 0;
}
| 30.082192 | 137 | 0.608834 | [
"shape"
] |
9b956fb069a422bb88c8a4f2c6bbb0139e8fe8bd | 2,125 | cpp | C++ | firmware/color-pickers.cpp | xntricweb/spark-lightshow | 0e2941ab79617765b3f1c3fb9c15183d53dc3b74 | [
"MIT"
] | 1 | 2020-02-02T19:44:48.000Z | 2020-02-02T19:44:48.000Z | firmware/color-pickers.cpp | xntricweb/spark-lightshow | 0e2941ab79617765b3f1c3fb9c15183d53dc3b74 | [
"MIT"
] | null | null | null | firmware/color-pickers.cpp | xntricweb/spark-lightshow | 0e2941ab79617765b3f1c3fb9c15183d53dc3b74 | [
"MIT"
] | null | null | null | // Copyright 2016 Jeremy Calloway
#include "color-pickers.h"
/* SOLID COLOR PICKER */
void SolidColorPicker::select(uint16_t index, uint16_t length, uint8_t *r, uint8_t *g, uint8_t *b) {
*r = red;
*g = green;
*b = blue;
}
void SolidColorPicker::setColor(uint8_t r, uint8_t g, uint8_t b) {
red = r;
green = g;
blue = b;
}
void SolidColorPicker::setColor(uint32_t color) {
uint8_t r, g, b;
LightShow::toRGB(color, &r, &g, &b);
setColor(r, g, b);
}
/* RAINBOW COLOR PICKER */
void RainbowColorPicker::select(uint16_t index, uint16_t length, uint8_t *r, uint8_t *g, uint8_t *b) {
uint8_t position = index * 255 / length;
if(position < 43) {
*r = 255;
*g = position * 6;
*b = 0;
} else if(position < 86) {
position -= 43;
*r = 255 - position * 6;
*g = 255;
*b = 0;
} else if(position < 128) {
position -= 86;
*r = 0;
*g = 255;
*b = position * 6;
} else if(position < 171) {
position -= 128;
*r = 0;
*g = 255 - position * 6;
*b = 255;
} else if(position < 214) {
position -= 171;
*r = position * 6;
*g = 0;
*b = 255;
} else if(position < 256) {
position -= 214;
*r = 255;
*g = 0;
*b = 255 - position * 6;
}
}
void FadeColorPicker::select(uint16_t index, uint16_t length, uint8_t *r, uint8_t *g, uint8_t *b) {
*r = fr + (index * (tr - fr) / length);
*g = fg + (index * (tg - fg) / length);
*b = fb + (index * (tb - fb) / length);
}
void FadeColorPicker::from(uint8_t r, uint8_t g,uint8_t b) {
fr = r;
fg = g;
fb = b;
}
void FadeColorPicker::to(uint8_t r, uint8_t g,uint8_t b) {
tr = r;
tg = g;
tb = b;
}
void FadeRandomColorPicker::select(uint16_t index, uint16_t length, uint8_t *r, uint8_t *g, uint8_t *b) {
if(index == length - 1) {
fr = tr;
fg = tg;
fb = tb;
tr = random(256);
tg = random(256);
tb = random(256);
}
FadeColorPicker::select(index, length, r, g, b);
}
| 22.849462 | 105 | 0.518588 | [
"solid"
] |
9b98dce70b5dbd340c548dbd63beb3d35b21062e | 1,045 | hpp | C++ | include/field.hpp | akitsu-sanae/turtle | 356834d4b17b8786704f5731f1aacaeb0cdc7bf0 | [
"BSL-1.0"
] | null | null | null | include/field.hpp | akitsu-sanae/turtle | 356834d4b17b8786704f5731f1aacaeb0cdc7bf0 | [
"BSL-1.0"
] | null | null | null | include/field.hpp | akitsu-sanae/turtle | 356834d4b17b8786704f5731f1aacaeb0cdc7bf0 | [
"BSL-1.0"
] | null | null | null | /*============================================================================
Copyright (C) 2016 akitsu sanae
https://github.com/akitsu-sanae/turtle
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
============================================================================*/
#ifndef TURTLE_FIELD_HPP
#define TIRTLE_FIELD_HPP
#include <vector>
#include <memory>
#include "operation.hpp"
#include "command_loader.hpp"
#include "track.hpp"
struct Turtle;
struct Field {
explicit Field(size_t, size_t);
~Field();
void update();
void draw() const;
bool is_quit() const { return m_is_quit; }
size_t width() const { return m_width; }
size_t height() const { return m_height; }
private:
size_t const m_width;
size_t const m_height;
bool m_is_quit = false;
bool m_is_pen_down = true;
std::unique_ptr<Turtle> m_turtle;
CommandLoader m_command_loader;
std::vector<Track> m_tracks;
};
#endif
| 25.487805 | 78 | 0.600957 | [
"vector"
] |
9b9e0f0fd248c74a790aaf5aaa8a1d0b1fa7fd5a | 3,077 | cpp | C++ | Source/Tests/Scene/AnimatedModel.cpp | ssinai1/rbfx | e69a7093d153667e3d8dd3270449d3d594c1c1a8 | [
"MIT"
] | null | null | null | Source/Tests/Scene/AnimatedModel.cpp | ssinai1/rbfx | e69a7093d153667e3d8dd3270449d3d594c1c1a8 | [
"MIT"
] | null | null | null | Source/Tests/Scene/AnimatedModel.cpp | ssinai1/rbfx | e69a7093d153667e3d8dd3270449d3d594c1c1a8 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2017-2021 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR rhs
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR rhsWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR rhs DEALINGS IN
// THE SOFTWARE.
//
#include "../CommonUtils.h"
#include "../ModelUtils.h"
#include <Urho3D/Graphics/AnimatedModel.h>
#include <Urho3D/Graphics/AnimationController.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Resource/ResourceCache.h>
TEST_CASE("Model animation played")
{
auto context = Tests::CreateCompleteTestContext();
auto cache = context->GetSubsystem<ResourceCache>();
auto model = Tests::CreateSkinnedQuad_Model(context)->ExportModel();
auto animation_2tx = Tests::CreateSkinnedQuad_Animation_2TX(context);
auto animation_2tz = Tests::CreateSkinnedQuad_Animation_2TZ(context);
auto animation_1ry = Tests::CreateSkinnedQuad_Animation_1RY(context);
cache->AddManualResource(animation_2tx);
cache->AddManualResource(animation_2tz);
cache->AddManualResource(animation_1ry);
auto scene = MakeShared<Scene>(context);
scene->CreateComponent<Octree>();
auto node = scene->CreateChild("Node");
auto animatedModel = node->CreateComponent<AnimatedModel>();
auto animationController = node->CreateComponent<AnimationController>();
animatedModel->SetModel(model);
animationController->Play(animation_2tx->GetName(), 0, true);
animationController->Play(animation_2tz->GetName(), 1, true);
animationController->SetBlendMode(animation_2tz->GetName(), ABM_ADDITIVE);
animationController->Play(animation_1ry->GetName(), 2, true);
auto quad1 = node->GetChild("Quad 1", true);
auto quad2 = node->GetChild("Quad 2", true);
Tests::RunFrame(context, 0.5f, 0.05f);
REQUIRE(quad2->GetWorldPosition().Equals({ 0.5f, 1.0f, 0.5f }, M_LARGE_EPSILON));
Tests::RunFrame(context, 1.0f, 0.05f);
REQUIRE(quad2->GetWorldPosition().Equals({ -0.5f, 1.0f, -0.5f }, M_LARGE_EPSILON));
Tests::RunFrame(context, 0.5f, 0.05f);
REQUIRE(quad2->GetWorldPosition().Equals({ 0.0f, 1.0f, 0.0f }, M_LARGE_EPSILON));
}
| 42.736111 | 87 | 0.739032 | [
"model"
] |
9ba92dc35733d562eb39f2a21ad1edba59b7d1b8 | 3,258 | cpp | C++ | text/findtextmanager.cpp | Mytherin/Panther | 1eac47074aa33ba747140950f373c9b7dd7f3d67 | [
"Apache-2.0"
] | 5 | 2018-01-25T14:43:20.000Z | 2021-02-28T11:37:55.000Z | text/findtextmanager.cpp | Mytherin/Panther | 1eac47074aa33ba747140950f373c9b7dd7f3d67 | [
"Apache-2.0"
] | null | null | null | text/findtextmanager.cpp | Mytherin/Panther | 1eac47074aa33ba747140950f373c9b7dd7f3d67 | [
"Apache-2.0"
] | 3 | 2018-01-28T13:22:49.000Z | 2020-09-23T02:55:04.000Z |
#include "findtextmanager.h"
FindTextManager::FindTextManager() :
regex(false), matchcase(false), wholeword(false), wrap(true), highlight(true),
ignore_binary_files(true), respect_gitignore(false) {
}
void FindTextManager::LoadWorkspace(nlohmann::json& j) {
if (j.count("find_text") > 0) {
nlohmann::json& settings = j["find_text"];
if (!settings.is_object()) return;
if (settings.count("toggle_regex") && settings["toggle_regex"].is_boolean())
regex = settings["toggle_regex"];
if (settings.count("toggle_matchcase") && settings["toggle_matchcase"].is_boolean())
matchcase = settings["toggle_matchcase"];
if (settings.count("toggle_wholeword") && settings["toggle_wholeword"].is_boolean())
wholeword = settings["toggle_wholeword"];
if (settings.count("toggle_wrap") && settings["toggle_wrap"].is_boolean())
wrap = settings["toggle_wrap"];
if (settings.count("toggle_highlight") && settings["toggle_highlight"].is_boolean())
highlight = settings["toggle_highlight"];
if (settings.count("toggle_ignorebinary") && settings["toggle_ignorebinary"].is_boolean())
ignore_binary_files = settings["toggle_ignorebinary"];
if (settings.count("toggle_respect_gitignore") && settings["toggle_respect_gitignore"].is_boolean())
respect_gitignore = settings["toggle_respect_gitignore"];
if (settings.count("find_history") && settings["find_history"].is_array()) {
nlohmann::json& history = settings["find_history"];;
for (auto it = history.begin(); it != history.end(); it++)
if (it->is_string())
find_history.push_back(*it);
}
if (settings.count("replace_history") && settings["replace_history"].is_array()) {
nlohmann::json& history = settings["replace_history"];;
for (auto it = history.begin(); it != history.end(); it++)
if (it->is_string())
replace_history.push_back(*it);
}
if (settings.count("filter_history") && settings["filter_history"].is_array()) {
nlohmann::json& history = settings["filter_history"];;
for (auto it = history.begin(); it != history.end(); it++)
if (it->is_string())
filter_history.push_back(*it);
}
}
}
void FindTextManager::WriteWorkspace(nlohmann::json& j) {
j["find_text"] = nlohmann::json::object();
nlohmann::json& settings = j["find_text"];
settings["toggle_regex"] = regex;
settings["toggle_matchcase"] = matchcase;
settings["toggle_wholeword"] = wholeword;
settings["toggle_wrap"] = wrap;
settings["toggle_highlight"] = highlight;
settings["toggle_ignorebinary"] = ignore_binary_files;
settings["toggle_respect_gitignore"] = respect_gitignore;
settings["find_history"] = nlohmann::json::array();
{
nlohmann::json& history = settings["find_history"];
for (auto it = find_history.begin(); it != find_history.end(); it++) {
history.push_back(*it);
}
}
settings["replace_history"] = nlohmann::json::array();
{
nlohmann::json& history = settings["replace_history"];
for (auto it = replace_history.begin(); it != replace_history.end(); it++) {
history.push_back(*it);
}
}
settings["filter_history"] = nlohmann::json::array();
{
nlohmann::json& history = settings["filter_history"];
for (auto it = filter_history.begin(); it != filter_history.end(); it++) {
history.push_back(*it);
}
}
}
| 38.785714 | 102 | 0.697974 | [
"object"
] |
9bae5e481c0bd02d4ee8d10cdacbb8b18dc01e24 | 3,162 | hpp | C++ | extension_utils/capi_manager.hpp | Segu-g/PyCppExtension | be0ada090dc983a6335f326f1dded1d267449fb7 | [
"MIT"
] | null | null | null | extension_utils/capi_manager.hpp | Segu-g/PyCppExtension | be0ada090dc983a6335f326f1dded1d267449fb7 | [
"MIT"
] | null | null | null | extension_utils/capi_manager.hpp | Segu-g/PyCppExtension | be0ada090dc983a6335f326f1dded1d267449fb7 | [
"MIT"
] | null | null | null | #pragma once
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <string>
#include <tuple>
#include "error_wrapper.hpp"
namespace utils{
template<typename APITypeTuple, typename TypeEnum>
class CAPIManager{
public:
std::string get_capsule_name();
CAPIManager(std::string name);
~CAPIManager();
void import();
template <TypeEnum api>
auto function();
private:
std::string capsule_name;
bool is_imported;
PyObject* capsule;
void** c_apis;
};
template<typename APITypeTuple, typename TypeEnum>
CAPIManager<APITypeTuple, TypeEnum>::CAPIManager(std::string name){
this->capsule_name = name;
}
template<typename APITypeTuple, typename TypeEnum>
CAPIManager<APITypeTuple, TypeEnum>::~CAPIManager(){
Py_XDECREF(this->capsule);
}
template<typename APITypeTuple, typename TypeEnum>
std::string CAPIManager<APITypeTuple, TypeEnum>::get_capsule_name(){
return this->capsule_name;
}
template<typename APITypeTuple, typename TypeEnum>
void CAPIManager<APITypeTuple, TypeEnum>::import(){
PyObject *object = nullptr;
std::string trace = "";
size_t dot_pos = 0;
size_t last_pos = 0;
while (dot_pos != std::string::npos) {
dot_pos = this->capsule_name.find_first_of(".", last_pos);
trace = this->capsule_name.substr(last_pos, dot_pos - last_pos);
if (object == nullptr) {
object = PyImport_ImportModule(trace.c_str());
if (!object) {
throw utils::ExtException(PyExc_ImportError,
"CAPIManager::import() could not import module \""
+ this->capsule_name.substr(0, last_pos)
+ "\"");
}
} else {
PyObject *object2 = PyObject_GetAttrString(object, trace.c_str());
Py_DECREF(object);
object = object2;
if (object == nullptr) {
throw utils::ExtException(PyExc_ImportError,
"CAPIManager::import() could not get attribute \""
+ this->capsule_name.substr(0, last_pos)
+ "\"");
}
}
last_pos = dot_pos + 1;
}
/* compare attribute name to module.name by hand */
if (PyCapsule_IsValid(object, this->capsule_name.c_str())) {
this->capsule = object;
this->c_apis = reinterpret_cast<void**>(PyCapsule_GetPointer(this->capsule, this->capsule_name.c_str()));
} else {
throw utils::ExtException(PyExc_AttributeError,
"PyCapsule_Import \"" + this->capsule_name +"\" is not valid");
}
}
template <typename APITypeTuple, typename TypeEnum>
template <TypeEnum api>
auto CAPIManager<APITypeTuple, TypeEnum>::function(){
return reinterpret_cast<std::tuple_element_t<static_cast<int>(api), APITypeTuple>>(
this->c_apis[static_cast<int>(api)]);
}
}
| 31.62 | 117 | 0.576218 | [
"object"
] |
9bb33c42735ae44edaed9a36cc2ecf5e17c3ee5a | 9,012 | cpp | C++ | 3_async/AsyncSerial.cpp | anton-matosov/SerialPort | b1e28d4f5d0d2422585730d11ee62f11188b6f2a | [
"ADSL"
] | 14 | 2015-02-01T09:37:16.000Z | 2021-11-24T08:40:02.000Z | 3_async/AsyncSerial.cpp | anton-matosov/SerialPort | b1e28d4f5d0d2422585730d11ee62f11188b6f2a | [
"ADSL"
] | null | null | null | 3_async/AsyncSerial.cpp | anton-matosov/SerialPort | b1e28d4f5d0d2422585730d11ee62f11188b6f2a | [
"ADSL"
] | 5 | 2016-06-15T05:35:20.000Z | 2021-07-14T08:43:53.000Z | /*
* File: AsyncSerial.cpp
* Author: Terraneo Federico
* Distributed under the Boost Software License, Version 1.0.
* Created on September 7, 2009, 10:46 AM
*
* v1.02: Fixed a bug in BufferedAsyncSerial: Using the default constructor
* the callback was not set up and reading didn't work.
*
* v1.01: Fixed a bug that did not allow to reopen a closed serial port.
*
* v1.00: First release.
*
* IMPORTANT:
* On Mac OS X boost asio's serial ports have bugs, and the usual implementation
* of this class does not work. So a workaround class was written temporarily,
* until asio (hopefully) will fix Mac compatibility for serial ports.
*
* Please note that unlike said in the documentation on OS X until asio will
* be fixed serial port *writes* are *not* asynchronous, but at least
* asynchronous *read* works.
* In addition the serial port open ignores the following options: parity,
* character size, flow, stop bits, and defaults to 8N1 format.
* I know it is bad but at least it's better than nothing.
*
*/
#include "AsyncSerial.h"
#include <string>
#include <algorithm>
#include <iostream>
#include <boost/bind.hpp>
//using namespace std;
using namespace boost;
//
//Class AsyncSerial
//
class AsyncSerialImpl: private boost::noncopyable
{
public:
AsyncSerialImpl(): io(), port(io), backgroundThread(), open(false),
error(false) {}
boost::asio::io_service io; ///< Io service object
boost::asio::serial_port port; ///< Serial port object
std::thread backgroundThread; ///< Thread that runs read/write operations
bool open; ///< True if port open
bool error; ///< Error flag
mutable std::mutex errorMutex; ///< Mutex for access to error
/// Data are queued here before they go in writeBuffer
std::vector<char> writeQueue;
boost::shared_array<char> writeBuffer; ///< Data being written
size_t writeBufferSize; ///< Size of writeBuffer
std::mutex writeQueueMutex; ///< Mutex for access to writeQueue
char readBuffer[AsyncSerial::readBufferSize]; ///< data being read
/// Read complete callback
boost::function<void (const char*, size_t)> callback;
};
AsyncSerial::AsyncSerial(): pimpl(new AsyncSerialImpl)
{
}
AsyncSerial::AsyncSerial(const std::string& devname, unsigned int baud_rate,
asio::serial_port_base::parity opt_parity,
asio::serial_port_base::character_size opt_csize,
asio::serial_port_base::flow_control opt_flow,
asio::serial_port_base::stop_bits opt_stop)
: pimpl(new AsyncSerialImpl)
{
open(devname,baud_rate,opt_parity,opt_csize,opt_flow,opt_stop);
}
void AsyncSerial::open(const std::string& devname, unsigned int baud_rate,
asio::serial_port_base::parity opt_parity,
asio::serial_port_base::character_size opt_csize,
asio::serial_port_base::flow_control opt_flow,
asio::serial_port_base::stop_bits opt_stop)
{
if(isOpen()) close();
setErrorStatus(true);//If an exception is thrown, error_ remains true
pimpl->port.open(devname);
pimpl->port.set_option(asio::serial_port_base::baud_rate(baud_rate));
pimpl->port.set_option(opt_parity);
pimpl->port.set_option(opt_csize);
pimpl->port.set_option(opt_flow);
pimpl->port.set_option(opt_stop);
//This gives some work to the io_service before it is started
pimpl->io.post(boost::bind(&AsyncSerial::doRead, this));
std::thread t(boost::bind(&asio::io_service::run, &pimpl->io));
pimpl->backgroundThread.swap(t);
setErrorStatus(false);//If we get here, no error
pimpl->open=true; //Port is now open
}
bool AsyncSerial::isOpen() const
{
return pimpl->open;
}
bool AsyncSerial::errorStatus() const
{
std::lock_guard<std::mutex> l(pimpl->errorMutex);
return pimpl->error;
}
void AsyncSerial::close()
{
if(!isOpen()) return;
pimpl->open=false;
pimpl->io.post(boost::bind(&AsyncSerial::doClose, this));
pimpl->backgroundThread.join();
pimpl->io.reset();
if(errorStatus())
{
throw(boost::system::system_error(boost::system::error_code(),
"Error while closing the device"));
}
}
void AsyncSerial::write(const char *data, size_t size)
{
{
std::lock_guard<std::mutex> l(pimpl->writeQueueMutex);
pimpl->writeQueue.insert(pimpl->writeQueue.end(),data,data+size);
}
pimpl->io.post(boost::bind(&AsyncSerial::doWrite, this));
}
void AsyncSerial::write(const std::vector<char>& data)
{
{
std::lock_guard<std::mutex> l(pimpl->writeQueueMutex);
pimpl->writeQueue.insert(pimpl->writeQueue.end(),data.begin(),
data.end());
}
pimpl->io.post(boost::bind(&AsyncSerial::doWrite, this));
}
void AsyncSerial::writeString(const std::string& s)
{
{
std::lock_guard<std::mutex> l(pimpl->writeQueueMutex);
pimpl->writeQueue.insert(pimpl->writeQueue.end(),s.begin(),s.end());
}
pimpl->io.post(boost::bind(&AsyncSerial::doWrite, this));
}
AsyncSerial::~AsyncSerial()
{
if(isOpen())
{
try {
close();
} catch(...)
{
//Don't throw from a destructor
}
}
}
void AsyncSerial::doRead()
{
pimpl->port.async_read_some(asio::buffer(pimpl->readBuffer,readBufferSize),
boost::bind(&AsyncSerial::readEnd,
this,
asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
void AsyncSerial::readEnd(const boost::system::error_code& error,
size_t bytes_transferred)
{
if(error)
{
#ifdef __APPLE__
if(error.value()==45)
{
//Bug on OS X, it might be necessary to repeat the setup
//http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
doRead();
return;
}
#endif //__APPLE__
//error can be true even because the serial port was closed.
//In this case it is not a real error, so ignore
if(isOpen())
{
doClose();
setErrorStatus(true);
}
} else {
if(pimpl->callback) pimpl->callback(pimpl->readBuffer,
bytes_transferred);
doRead();
}
}
void AsyncSerial::doWrite()
{
//If a write operation is already in progress, do nothing
if(pimpl->writeBuffer==0)
{
std::lock_guard<std::mutex> l(pimpl->writeQueueMutex);
pimpl->writeBufferSize=pimpl->writeQueue.size();
pimpl->writeBuffer.reset(new char[pimpl->writeQueue.size()]);
copy(pimpl->writeQueue.begin(),pimpl->writeQueue.end(),
pimpl->writeBuffer.get());
pimpl->writeQueue.clear();
async_write(pimpl->port,asio::buffer(pimpl->writeBuffer.get(),
pimpl->writeBufferSize),
boost::bind(&AsyncSerial::writeEnd, this, asio::placeholders::error));
}
}
void AsyncSerial::writeEnd(const boost::system::error_code& error)
{
if(!error)
{
std::lock_guard<std::mutex> l(pimpl->writeQueueMutex);
if(pimpl->writeQueue.empty())
{
pimpl->writeBuffer.reset();
pimpl->writeBufferSize=0;
return;
}
pimpl->writeBufferSize=pimpl->writeQueue.size();
pimpl->writeBuffer.reset(new char[pimpl->writeQueue.size()]);
copy(pimpl->writeQueue.begin(),pimpl->writeQueue.end(),
pimpl->writeBuffer.get());
pimpl->writeQueue.clear();
async_write(pimpl->port,asio::buffer(pimpl->writeBuffer.get(),
pimpl->writeBufferSize),
boost::bind(&AsyncSerial::writeEnd, this, asio::placeholders::error));
} else {
setErrorStatus(true);
doClose();
}
}
void AsyncSerial::doClose()
{
boost::system::error_code ec;
pimpl->port.cancel(ec);
if(ec) setErrorStatus(true);
pimpl->port.close(ec);
if(ec) setErrorStatus(true);
}
void AsyncSerial::setErrorStatus(bool e)
{
std::lock_guard<std::mutex> l(pimpl->errorMutex);
pimpl->error=e;
}
void AsyncSerial::setReadCallback(const boost::function<void (const char*, size_t)>& callback)
{
pimpl->callback=callback;
}
void AsyncSerial::clearReadCallback()
{
pimpl->callback.clear();
}
//
//Class CallbackAsyncSerial
//
CallbackAsyncSerial::CallbackAsyncSerial(): AsyncSerial()
{
}
CallbackAsyncSerial::CallbackAsyncSerial(const std::string& devname,
unsigned int baud_rate,
asio::serial_port_base::parity opt_parity,
asio::serial_port_base::character_size opt_csize,
asio::serial_port_base::flow_control opt_flow,
asio::serial_port_base::stop_bits opt_stop)
:AsyncSerial(devname,baud_rate,opt_parity,opt_csize,opt_flow,opt_stop)
{
}
void CallbackAsyncSerial::setCallback(const
boost::function<void (const char*, size_t)>& callback)
{
setReadCallback(callback);
}
void CallbackAsyncSerial::clearCallback()
{
clearReadCallback();
}
CallbackAsyncSerial::~CallbackAsyncSerial()
{
clearReadCallback();
}
| 28.700637 | 94 | 0.657235 | [
"object",
"vector"
] |
9bbd0925616b9242920779a4f71388f503f8d47b | 9,868 | cpp | C++ | platforms/common/cpp/font/BezierUtils.cpp | advancedwebdeveloper/flow9 | 26e19216495bcb948d00aaea6b5c190e30fc6e3f | [
"MIT"
] | 583 | 2019-04-26T11:52:35.000Z | 2022-02-22T17:53:19.000Z | platforms/common/cpp/font/BezierUtils.cpp | advancedwebdeveloper/flow9 | 26e19216495bcb948d00aaea6b5c190e30fc6e3f | [
"MIT"
] | 279 | 2019-04-26T11:53:17.000Z | 2022-02-21T13:35:08.000Z | platforms/common/cpp/font/BezierUtils.cpp | advancedwebdeveloper/flow9 | 26e19216495bcb948d00aaea6b5c190e30fc6e3f | [
"MIT"
] | 44 | 2019-04-29T18:09:19.000Z | 2021-12-23T16:06:05.000Z | //
// BezierUtils.as - A small collection of static utilities for use with single-segment Bezier curves, or more generally
// any curve implementing the IParametric interface
//
// copyright (c) 2006-2008, Jim Armstrong. All Rights Reserved.
//
// This software program is supplied 'as is' without any warranty, express, implied,
// or otherwise, including without limitation all warranties of merchantability or fitness
// for a particular purpose. Jim Armstrong shall not be liable for any special incidental, or
// consequential damages, including, without limitation, lost revenues, lost profits, or
// loss of prospective economic advantage, resulting from the use or misuse of this software
// program.
//
// Programmed by Jim Armstrong, Singularity (www.algorithmist.net)
//
// Version 1.0
/*
Translated to C++ and tweaked by Alexander Gavrilov.
*/
#include "BezierUtils.h"
static const unsigned MAX_DEPTH = 64; // maximum recursion depth
static const float EPSILON = 1e-4;
static vec2 bezierPoint(const std::vector<vec2> &curve, float t, int s, int e)
{
float t1 = 1.0f - t;
switch (e - s) {
case 0:
return vec2(0.0f);
case 1:
return curve[s];
case 2:
return t1*curve[s] + t*curve[s+1];
case 3:
return t1*t1*curve[s] + 2*t1*t*curve[s+1] + t*t*curve[s+2];
case 4:
return t1*t1*t1*curve[s] + 3*t1*t1*t*curve[s+1] + 3*t1*t*t*curve[s+2] + t*t*t*curve[s+3];
default:
return t1*bezierPoint(curve, t, s, e-1) + t*bezierPoint(curve, t, s+1, e);
}
}
vec2 bezierPoint(const std::vector<vec2> &curve, float t)
{
return bezierPoint(curve, t, 0, curve.size());
}
inline unsigned getLinearIndex(unsigned n, unsigned r, unsigned c) {
return n*r + c;
}
static std::vector<vec2> toBezierForm(vec2 p, const std::vector<vec2> &v)
{
/* compute control vec2s of the polynomial resulting from the inner
product of B(t)-P and B'(t), constructing the result as a Bezier
curve of order 2n-1, where n is the degree of B(t). */
unsigned n = v.size()-1;
std::vector<vec2> c(n+1);
for (unsigned i = 0; i <= n; ++i)
c[i] = v[i] - p;
std::vector<vec2> d(n);
for (unsigned i = 0; i < n; ++i)
d[i] = float(n)*(v[i+1] - v[i]);
std::vector<float> cd(n*(n+1));
for (unsigned row = 0; row < n; row++) {
vec2 dv = d[row];
for (unsigned col = 0; col <= n; col++)
cd[getLinearIndex(n+1, row, col)] = glm::dot(dv, c[col]);
}
unsigned degree = 2*n - 1;
// Bezier is uniform parameterized
std::vector<vec2> w(degree+1);
for (unsigned i = 0; i <= degree; i++)
w[i] = vec2(float(i)/degree, 0.0f);
// reference to appropriate pre-computed coefficients
static const float Z_CUBIC[] = {1.0, 0.6, 0.3, 0.1, 0.4, 0.6, 0.6, 0.4, 0.1, 0.3, 0.6, 1.0};
static const float Z_QUAD[] = {1.0, 2.0/3.0, 1.0/3.0, 1.0/3.0, 2.0/3.0, 1.0};
const float *z = (n == 3) ? Z_CUBIC : Z_QUAD;
unsigned m = n-1;
for(unsigned k=0; k <= n+m; ++k)
{
unsigned lb = std::max(0, int(k-m));
unsigned ub = std::min(k, n);
for(unsigned i=lb; i<=ub; ++i)
{
unsigned j = k - i;
unsigned index = getLinearIndex(n+1, j, i);
w[i+j].y += cd[index]*z[index];
}
}
return w;
}
static unsigned crossingCount(const std::vector<vec2> &_v, unsigned _degree)
{
/* how many times does the Bezier curve cross the horizontal
axis - the float of roots is less than or equal to this count */
unsigned nCrossings = 0;
int sign = _v[0].y < 0 ? -1 : 1;
int oldSign = sign;
for(unsigned i=1; i <= _degree; ++i)
{
sign = _v[i].y < 0 ? -1 : 1;
if( sign != oldSign )
nCrossings++;
oldSign = sign;
}
return nCrossings;
}
static bool isControlPolygonLinear(const std::vector<vec2> &_v, unsigned _degree)
{
/* is the control polygon for a Bezier curve suitably linear
for subdivision to terminate?
Given array of control vec2s, _v, find the distance from each
interior control vec2 to line connecting v[0] and v[degree] */
// implicit equation for line connecting first and last control vec2s
float a = _v[0].y - _v[_degree].y;
float b = _v[_degree].x - _v[0].x;
float c = _v[0].x * _v[_degree].y - _v[_degree].x * _v[0].y;
//float abSquared = a*a + b*b;
std::vector<float> distance(_degree); // Distances from control vec2s to line
for(unsigned i=1; i<_degree; ++i)
{
// Compute distance from each of the vec2s to that line
distance[i] = a * _v[i].x + b * _v[i].y + c;
/*if( distance[i] > 0.0 )
{
distance[i] = (distance[i] * distance[i]) / abSquared;
}
else if( distance[i] < 0.0 )
{
distance[i] = -((distance[i] * distance[i]) / abSquared);
}*/
}
// Find the largest distance
float maxDistanceAbove = 0.0;
float maxDistanceBelow = 0.0;
for(unsigned i=1; i<_degree; ++i)
{
maxDistanceBelow = std::min(maxDistanceBelow, distance[i]);
maxDistanceAbove = std::max(maxDistanceAbove, distance[i]);
}
// Implicit equation for zero line
float a1 = 0.0;
float b1 = 1.0;
float c1 = 0.0;
// Implicit equation for "above" line
float a2 = a;
float b2 = b;
float c2 = c - maxDistanceAbove;
float det = a1*b2 - a2*b1;
float dInv = 1.0/det;
float intercept1 = (b1*c2 - b2*c1)*dInv;
// Implicit equation for "below" line
a2 = a;
b2 = b;
c2 = c - maxDistanceBelow;
float intercept2 = (b1*c2 - b2*c1)*dInv;
// Compute intercepts of bounding box
float leftIntercept = std::min(intercept1, intercept2);
float rightIntercept = std::max(intercept1, intercept2);
float error = 0.5*(rightIntercept-leftIntercept);
return error < EPSILON;
}
static float computeXIntercept(const std::vector<vec2> &_v, unsigned _degree)
{
/* compute intersection of line segnet from first
to last control vec2 with horizontal axis */
float XNM = _v[_degree].x - _v[0].x;
float YNM = _v[_degree].y - _v[0].y;
float XMK = _v[0].x;
float YMK = _v[0].y;
float detInv = - 1.0/YNM;
return (XNM*YMK - YNM*XMK) * detInv;
}
static void subdivide(const std::vector<vec2> &_c, float _t, std::vector<vec2> *_left, std::vector<vec2> *_right)
{
/* subdivide( _c:Array, _t:float, _left:Array, _right:Array )
deCasteljau subdivision of an arbitrary-order Bezier curve */
unsigned degree = _c.size()-1;
unsigned n = degree+1;
float t1 = 1.0 - _t;
std::vector<vec2> p(_c.begin(), _c.end());
p.resize(n*n);
for(unsigned i=1; i<=degree; ++i)
{
for(unsigned j=0; j<=degree-i; ++j)
{
unsigned ij = getLinearIndex(n, i, j);
unsigned im1j = getLinearIndex(n, i-1, j);
unsigned im1jp1 = getLinearIndex(n, i-1, j+1);
p[ij] = t1*p[im1j] + _t*p[im1jp1];
}
}
_left->resize(degree+1);
for(unsigned j=0; j<=degree; ++j)
{
(*_left)[j] = p[getLinearIndex(n, j, 0)];
}
_right->resize(degree+1);
for(unsigned j=0; j<=degree; ++j)
{
(*_right)[j] = p[getLinearIndex(n, degree-j, j)];
}
}
static void findRoots(std::vector<float> *t, const std::vector<vec2> &_w, unsigned _degree, unsigned _depth)
{
// return roots in [0,1] of a polynomial in Bernstein-Bezier form
switch (crossingCount(_w, _degree))
{
case 0:
return;
case 1:
// Unique solution - stop recursion when the tree is deep enough (return 1 solution at midvec2)
if( _depth >= MAX_DEPTH )
{
t->push_back(0.5*(_w[0].x + _w[_degree].x));
return;
}
if( isControlPolygonLinear(_w, _degree) )
{
t->push_back(computeXIntercept(_w, _degree));
return;
}
break;
}
// Otherwise, solve recursively after subdividing control polygon
std::vector<vec2> left, right;
subdivide(_w, 0.5, &left, &right);
findRoots(t, left, _degree, _depth+1);
findRoots(t, right, _degree, _depth+1);
}
static std::pair<float,float> closestPointToSegment(vec2 pointA, vec2 pointB, vec2 pointC)
{
float dot1 = glm::dot(pointB - pointA, pointC - pointB);
if (dot1 >= 0)
return std::pair<float,float>(1.0f, glm::distance(pointB, pointC));
float dot2 = glm::dot(pointA - pointB, pointC - pointA);
if (dot2 >= 0)
return std::pair<float,float>(0.0f, glm::distance(pointA, pointC));
float len = glm::distance(pointA, pointB);
float cross = glm::cross(glm::vec3(pointB - pointA, 0.0f), glm::vec3(pointC - pointA, 0.0f)).z;
float dist = std::abs(cross / len);
return std::pair<float,float>(0.5f, dist);
}
std::pair<float,float> closestPointToBezier(const std::vector<vec2> &curve, vec2 p)
{
if (curve.size() == 2)
return closestPointToSegment(curve[0], curve[1], p);
if (curve.size() != 3 && curve.size() != 4)
return std::pair<float,float>(0, 0);;
int n = curve.size()-1;
vec2 pt0 = curve[0];
vec2 pt1 = curve[n];
float d0 = glm::distance(pt0, p);
float d1 = glm::distance(pt1, p);
std::vector<vec2> w = toBezierForm(p, curve);
std::vector<float> roots;
findRoots(&roots, w, 2*n-1, 0);
float dmin = std::min(d0, d1);
float tmin = (d0 < d1) ? 0 : 1;
for (unsigned i = 0; i < roots.size(); ++i) {
float t = roots[i];
if (t < 0 || t > 1) continue;
vec2 tp = bezierPoint(curve, t);
float d = glm::distance(p, tp);
if (d < dmin) {
tmin = t; dmin = d;
}
}
return std::pair<float,float>(tmin, dmin);
}
| 28.853801 | 119 | 0.585428 | [
"vector"
] |
9bc28477ba2aa7e86c6d25b3bb74bda79068e4d0 | 4,629 | cpp | C++ | leetcode/weekly/167.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | 1 | 2020-05-05T13:06:51.000Z | 2020-05-05T13:06:51.000Z | leetcode/weekly/167.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | leetcode/weekly/167.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | /****************************************************
Date: December 15th, 2019
Successful submissions : 1
Time expiration : 0
Not Solved : 3
Wrong Answer/ Partial result : 1
link: https://leetcode.com/contest/weekly-contest-167
****************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <unordered_map>
#include <math.h>
using namespace std;
/*
Q: 1290. Convert Binary Number in a Linked List to Integer
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution1_t
{
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
public:
int getDecimalValue(ListNode *head)
{
vector<int> b;
ListNode *t = head;
while (t != NULL)
{
b.push_back(t->val);
t = t->next;
}
int retVal = 0;
int l = b.size();
int p = (l - 1);
for (int i = 0; i < l; i++)
{
retVal += b[i] * (pow(2, p));
p--;
}
return retVal;
}
};
/*
Q: 1291. Sequential Digits
Not complete!
*/
class Solution2_t
{
private:
int getNum(vector<int> n)
{
int retVal = 0;
int p = n.size() - 1;
for (int i = 0; i < p; i++)
{
retVal += n[i] * pow(10, p);
}
return retVal;
}
void updateToNextSequence(vector<int> &n)
{
int start = n[0];
n[0]++;
for (int i = 1; i < n.size(); i++)
{
n[i] = n[i - 1] + 1;
}
}
public:
vector<int> sequentialDigits(int low, int high)
{
stack<int> s;
int l = low;
while (l > 0)
{
s.push(l % 10);
l = l / 10;
}
vector<int> num;
while (!s.empty())
{
num.push_back(s.top());
s.pop();
}
int lSeq = low;
bool goToNext = false;
for (int i = 0; i < (num.size() - 1); i++)
{
if ((num[i + 1] - num[i]) > 1)
{
goToNext = true;
break;
}
else
{
if (num[i + 1] < num[i])
{
num[i + 1] = num[i] + 1;
}
}
}
if (goToNext)
{
updateToNextSequence(num);
}
vector<int> retVal;
while (true)
{
int n = getNum(num);
if (n > high)
{
break;
}
retVal.push_back(n);
updateToNextSequence(num);
}
return retVal;
}
};
/*
Q: 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold
*/
class Solution3_t
{
public:
int maxSideLength(vector<vector<int>> &mat, int threshold)
{
}
};
/*
Q: 1293. Shortest Path in a Grid with Obstacles Elimination
Not completed
*/
class Solution
{
public:
int shortestPath(vector<vector<int>> &g, int k)
{
int r = g.size();
int c = g[0].size();
vector<vector<vector<int>>> r(k - 1, vector<vector<int>>(r, vector<int>(c, 0)));
for (int x = 0; x < k; x++)
{
bool nextK = false;
int n = x;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
// row == 0 && column == 0
if ((i == 0) && (j == 0))
{
if (g[i][j] == 1)
{
if (n > 0)
{
n--;
}
else
{
nextK = true;
break;
}
}
}
else if ((i == 0) && (j > 0))
{
if (g[i][j])
{
//TODO
}
}
}
if (nextK)
{
break;
}
}
}
return ((r[k - 1][r - 1][c - 1] == 0) ? -1 : r[k - 1][r - 1][c - 1]);
}
}; | 20.213974 | 88 | 0.356016 | [
"vector"
] |
9bc3d9306b82c134f4f46fbfec3f5f172484f69e | 44,952 | cpp | C++ | ace/tao/tao/IORManipulation/iorc.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/tao/tao/IORManipulation/iorc.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/tao/tao/IORManipulation/iorc.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | // -*- C++ -*-
//
// IORC.cpp,v 1.6 2001/08/21 19:00:27 parsons Exp
// **** Code generated by the The ACE ORB (TAO) IDL Compiler ****
// TAO and the TAO IDL Compiler have been developed by:
// Center for Distributed Object Computing
// Washington University
// St. Louis, MO
// USA
// http://www.cs.wustl.edu/~schmidt/doc-center.html
// and
// Distributed Object Computing Laboratory
// University of California at Irvine
// Irvine, CA
// USA
// http://doc.ece.uci.edu/
//
// Information about TAO is available at:
// http://www.cs.wustl.edu/~schmidt/TAO.html
#include "IORManip_Loader.h"
#include "tao/Typecode.h"
#include "tao/Any.h"
#include "tao/ORB.h"
#if defined (__BORLANDC__)
#pragma option -w-rvl -w-rch -w-ccc -w-aus
#endif /* __BORLANDC__ */
#if !defined (__ACE_INLINE__)
#include "IORC.i"
#endif /* !defined INLINE */
// Default constructor.
TAO_IOP::EmptyProfileList::EmptyProfileList (void)
: CORBA_UserException ("IDL:TAO_IOP/EmptyProfileList:1.0")
{
}
// Destructor - all members are of self managing types.
TAO_IOP::EmptyProfileList::~EmptyProfileList (void)
{
}
void TAO_IOP::EmptyProfileList::_tao_any_destructor (void *x)
{
EmptyProfileList *tmp = ACE_static_cast (EmptyProfileList*,x);
delete tmp;
}
// Copy constructor.
TAO_IOP::EmptyProfileList::EmptyProfileList (const ::TAO_IOP::EmptyProfileList &_tao_excp)
: CORBA_UserException (_tao_excp._id ())
{
}
// Assignment operator.
TAO_IOP::EmptyProfileList&
TAO_IOP::EmptyProfileList::operator= (const ::TAO_IOP::EmptyProfileList &_tao_excp)
{
this->CORBA_UserException::operator= (_tao_excp);
return *this;
}
// Narrow.
TAO_IOP::EmptyProfileList *
TAO_IOP::EmptyProfileList::_downcast (CORBA::Exception *exc)
{
if (!ACE_OS::strcmp ("IDL:TAO_IOP/EmptyProfileList:1.0", exc->_id ()))
{
return ACE_dynamic_cast (EmptyProfileList *, exc);
}
else
{
return 0;
}
}
void TAO_IOP::EmptyProfileList::_raise ()
{
TAO_RAISE (*this);
}
void TAO_IOP::EmptyProfileList::_tao_encode (
TAO_OutputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
) const
{
if (cdr << *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
void TAO_IOP::EmptyProfileList::_tao_decode (
TAO_InputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
)
{
if (cdr >> *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
// TAO extension - the _alloc method.
CORBA::Exception *TAO_IOP::EmptyProfileList::_alloc (void)
{
CORBA::Exception *retval = 0;
ACE_NEW_RETURN (retval, ::TAO_IOP::EmptyProfileList, 0);
return retval;
}
static const CORBA::Long _oc_TAO_IOP_EmptyProfileList[] =
{
TAO_ENCAP_BYTE_ORDER, // byte order
33,
ACE_NTOHL (0x49444c3a),
ACE_NTOHL (0x54414f5f),
ACE_NTOHL (0x494f502f),
ACE_NTOHL (0x456d7074),
ACE_NTOHL (0x7950726f),
ACE_NTOHL (0x66696c65),
ACE_NTOHL (0x4c697374),
ACE_NTOHL (0x3a312e30),
ACE_NTOHL (0x0), // repository ID = IDL:TAO_IOP/EmptyProfileList:1.0
17,
ACE_NTOHL (0x456d7074),
ACE_NTOHL (0x7950726f),
ACE_NTOHL (0x66696c65),
ACE_NTOHL (0x4c697374),
ACE_NTOHL (0x0), // name = EmptyProfileList
0, // member count
};
static CORBA::TypeCode _tc_TAO_tc_TAO_IOP_EmptyProfileList (
CORBA::tk_except,
sizeof (_oc_TAO_IOP_EmptyProfileList),
(char *) &_oc_TAO_IOP_EmptyProfileList,
0,
sizeof (TAO_IOP::EmptyProfileList)
);
TAO_NAMESPACE_TYPE (CORBA::TypeCode_ptr)
TAO_NAMESPACE_BEGIN (TAO_IOP)
TAO_NAMESPACE_DEFINE (CORBA::TypeCode_ptr, _tc_EmptyProfileList, &_tc_TAO_tc_TAO_IOP_EmptyProfileList)
TAO_NAMESPACE_END
// TAO extension - the virtual _type method.
CORBA::TypeCode_ptr TAO_IOP::EmptyProfileList::_type (void) const
{
return ::TAO_IOP::_tc_EmptyProfileList;
}
// Default constructor.
TAO_IOP::NotFound::NotFound (void)
: CORBA_UserException ("IDL:TAO_IOP/NotFound:1.0")
{
}
// Destructor - all members are of self managing types.
TAO_IOP::NotFound::~NotFound (void)
{
}
void TAO_IOP::NotFound::_tao_any_destructor (void *x)
{
NotFound *tmp = ACE_static_cast (NotFound*,x);
delete tmp;
}
// Copy constructor.
TAO_IOP::NotFound::NotFound (const ::TAO_IOP::NotFound &_tao_excp)
: CORBA_UserException (_tao_excp._id ())
{
}
// Assignment operator.
TAO_IOP::NotFound&
TAO_IOP::NotFound::operator= (const ::TAO_IOP::NotFound &_tao_excp)
{
this->CORBA_UserException::operator= (_tao_excp);
return *this;
}
// Narrow.
TAO_IOP::NotFound *
TAO_IOP::NotFound::_downcast (CORBA::Exception *exc)
{
if (!ACE_OS::strcmp ("IDL:TAO_IOP/NotFound:1.0", exc->_id ()))
{
return ACE_dynamic_cast (NotFound *, exc);
}
else
{
return 0;
}
}
void TAO_IOP::NotFound::_raise ()
{
TAO_RAISE (*this);
}
void TAO_IOP::NotFound::_tao_encode (
TAO_OutputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
) const
{
if (cdr << *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
void TAO_IOP::NotFound::_tao_decode (
TAO_InputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
)
{
if (cdr >> *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
// TAO extension - the _alloc method.
CORBA::Exception *TAO_IOP::NotFound::_alloc (void)
{
CORBA::Exception *retval = 0;
ACE_NEW_RETURN (retval, ::TAO_IOP::NotFound, 0);
return retval;
}
static const CORBA::Long _oc_TAO_IOP_NotFound[] =
{
TAO_ENCAP_BYTE_ORDER, // byte order
25,
ACE_NTOHL (0x49444c3a),
ACE_NTOHL (0x54414f5f),
ACE_NTOHL (0x494f502f),
ACE_NTOHL (0x4e6f7446),
ACE_NTOHL (0x6f756e64),
ACE_NTOHL (0x3a312e30),
ACE_NTOHL (0x0), // repository ID = IDL:TAO_IOP/NotFound:1.0
9,
ACE_NTOHL (0x4e6f7446),
ACE_NTOHL (0x6f756e64),
ACE_NTOHL (0x0), // name = NotFound
0, // member count
};
static CORBA::TypeCode _tc_TAO_tc_TAO_IOP_NotFound (
CORBA::tk_except,
sizeof (_oc_TAO_IOP_NotFound),
(char *) &_oc_TAO_IOP_NotFound,
0,
sizeof (TAO_IOP::NotFound)
);
TAO_NAMESPACE_TYPE (CORBA::TypeCode_ptr)
TAO_NAMESPACE_BEGIN (TAO_IOP)
TAO_NAMESPACE_DEFINE (CORBA::TypeCode_ptr, _tc_NotFound, &_tc_TAO_tc_TAO_IOP_NotFound)
TAO_NAMESPACE_END
// TAO extension - the virtual _type method.
CORBA::TypeCode_ptr TAO_IOP::NotFound::_type (void) const
{
return ::TAO_IOP::_tc_NotFound;
}
// Default constructor.
TAO_IOP::Duplicate::Duplicate (void)
: CORBA_UserException ("IDL:TAO_IOP/Duplicate:1.0")
{
}
// Destructor - all members are of self managing types.
TAO_IOP::Duplicate::~Duplicate (void)
{
}
void TAO_IOP::Duplicate::_tao_any_destructor (void *x)
{
Duplicate *tmp = ACE_static_cast (Duplicate*,x);
delete tmp;
}
// Copy constructor.
TAO_IOP::Duplicate::Duplicate (const ::TAO_IOP::Duplicate &_tao_excp)
: CORBA_UserException (_tao_excp._id ())
{
}
// Assignment operator.
TAO_IOP::Duplicate&
TAO_IOP::Duplicate::operator= (const ::TAO_IOP::Duplicate &_tao_excp)
{
this->CORBA_UserException::operator= (_tao_excp);
return *this;
}
// Narrow.
TAO_IOP::Duplicate *
TAO_IOP::Duplicate::_downcast (CORBA::Exception *exc)
{
if (!ACE_OS::strcmp ("IDL:TAO_IOP/Duplicate:1.0", exc->_id ()))
{
return ACE_dynamic_cast (Duplicate *, exc);
}
else
{
return 0;
}
}
void TAO_IOP::Duplicate::_raise ()
{
TAO_RAISE (*this);
}
void TAO_IOP::Duplicate::_tao_encode (
TAO_OutputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
) const
{
if (cdr << *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
void TAO_IOP::Duplicate::_tao_decode (
TAO_InputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
)
{
if (cdr >> *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
// TAO extension - the _alloc method.
CORBA::Exception *TAO_IOP::Duplicate::_alloc (void)
{
CORBA::Exception *retval = 0;
ACE_NEW_RETURN (retval, ::TAO_IOP::Duplicate, 0);
return retval;
}
static const CORBA::Long _oc_TAO_IOP_Duplicate[] =
{
TAO_ENCAP_BYTE_ORDER, // byte order
26,
ACE_NTOHL (0x49444c3a),
ACE_NTOHL (0x54414f5f),
ACE_NTOHL (0x494f502f),
ACE_NTOHL (0x4475706c),
ACE_NTOHL (0x69636174),
ACE_NTOHL (0x653a312e),
ACE_NTOHL (0x30000000), // repository ID = IDL:TAO_IOP/Duplicate:1.0
10,
ACE_NTOHL (0x4475706c),
ACE_NTOHL (0x69636174),
ACE_NTOHL (0x65000000), // name = Duplicate
0, // member count
};
static CORBA::TypeCode _tc_TAO_tc_TAO_IOP_Duplicate (
CORBA::tk_except,
sizeof (_oc_TAO_IOP_Duplicate),
(char *) &_oc_TAO_IOP_Duplicate,
0,
sizeof (TAO_IOP::Duplicate)
);
TAO_NAMESPACE_TYPE (CORBA::TypeCode_ptr)
TAO_NAMESPACE_BEGIN (TAO_IOP)
TAO_NAMESPACE_DEFINE (CORBA::TypeCode_ptr, _tc_Duplicate, &_tc_TAO_tc_TAO_IOP_Duplicate)
TAO_NAMESPACE_END
// TAO extension - the virtual _type method.
CORBA::TypeCode_ptr TAO_IOP::Duplicate::_type (void) const
{
return ::TAO_IOP::_tc_Duplicate;
}
// Default constructor.
TAO_IOP::Invalid_IOR::Invalid_IOR (void)
: CORBA_UserException ("IDL:TAO_IOP/Invalid_IOR:1.0")
{
}
// Destructor - all members are of self managing types.
TAO_IOP::Invalid_IOR::~Invalid_IOR (void)
{
}
void TAO_IOP::Invalid_IOR::_tao_any_destructor (void *x)
{
Invalid_IOR *tmp = ACE_static_cast (Invalid_IOR*,x);
delete tmp;
}
// Copy constructor.
TAO_IOP::Invalid_IOR::Invalid_IOR (const ::TAO_IOP::Invalid_IOR &_tao_excp)
: CORBA_UserException (_tao_excp._id ())
{
}
// Assignment operator.
TAO_IOP::Invalid_IOR&
TAO_IOP::Invalid_IOR::operator= (const ::TAO_IOP::Invalid_IOR &_tao_excp)
{
this->CORBA_UserException::operator= (_tao_excp);
return *this;
}
// Narrow.
TAO_IOP::Invalid_IOR *
TAO_IOP::Invalid_IOR::_downcast (CORBA::Exception *exc)
{
if (!ACE_OS::strcmp ("IDL:TAO_IOP/Invalid_IOR:1.0", exc->_id ()))
{
return ACE_dynamic_cast (Invalid_IOR *, exc);
}
else
{
return 0;
}
}
void TAO_IOP::Invalid_IOR::_raise ()
{
TAO_RAISE (*this);
}
void TAO_IOP::Invalid_IOR::_tao_encode (
TAO_OutputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
) const
{
if (cdr << *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
void TAO_IOP::Invalid_IOR::_tao_decode (
TAO_InputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
)
{
if (cdr >> *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
// TAO extension - the _alloc method.
CORBA::Exception *TAO_IOP::Invalid_IOR::_alloc (void)
{
CORBA::Exception *retval = 0;
ACE_NEW_RETURN (retval, ::TAO_IOP::Invalid_IOR, 0);
return retval;
}
static const CORBA::Long _oc_TAO_IOP_Invalid_IOR[] =
{
TAO_ENCAP_BYTE_ORDER, // byte order
28,
ACE_NTOHL (0x49444c3a),
ACE_NTOHL (0x54414f5f),
ACE_NTOHL (0x494f502f),
ACE_NTOHL (0x496e7661),
ACE_NTOHL (0x6c69645f),
ACE_NTOHL (0x494f523a),
ACE_NTOHL (0x312e3000), // repository ID = IDL:TAO_IOP/Invalid_IOR:1.0
12,
ACE_NTOHL (0x496e7661),
ACE_NTOHL (0x6c69645f),
ACE_NTOHL (0x494f5200), // name = Invalid_IOR
0, // member count
};
static CORBA::TypeCode _tc_TAO_tc_TAO_IOP_Invalid_IOR (
CORBA::tk_except,
sizeof (_oc_TAO_IOP_Invalid_IOR),
(char *) &_oc_TAO_IOP_Invalid_IOR,
0,
sizeof (TAO_IOP::Invalid_IOR)
);
TAO_NAMESPACE_TYPE (CORBA::TypeCode_ptr)
TAO_NAMESPACE_BEGIN (TAO_IOP)
TAO_NAMESPACE_DEFINE (CORBA::TypeCode_ptr, _tc_Invalid_IOR, &_tc_TAO_tc_TAO_IOP_Invalid_IOR)
TAO_NAMESPACE_END
// TAO extension - the virtual _type method.
CORBA::TypeCode_ptr TAO_IOP::Invalid_IOR::_type (void) const
{
return ::TAO_IOP::_tc_Invalid_IOR;
}
// Default constructor.
TAO_IOP::MultiProfileList::MultiProfileList (void)
: CORBA_UserException ("IDL:TAO_IOP/MultiProfileList:1.0")
{
}
// Destructor - all members are of self managing types.
TAO_IOP::MultiProfileList::~MultiProfileList (void)
{
}
void TAO_IOP::MultiProfileList::_tao_any_destructor (void *x)
{
MultiProfileList *tmp = ACE_static_cast (MultiProfileList*,x);
delete tmp;
}
// Copy constructor.
TAO_IOP::MultiProfileList::MultiProfileList (const ::TAO_IOP::MultiProfileList &_tao_excp)
: CORBA_UserException (_tao_excp._id ())
{
}
// Assignment operator.
TAO_IOP::MultiProfileList&
TAO_IOP::MultiProfileList::operator= (const ::TAO_IOP::MultiProfileList &_tao_excp)
{
this->CORBA_UserException::operator= (_tao_excp);
return *this;
}
// Narrow.
TAO_IOP::MultiProfileList *
TAO_IOP::MultiProfileList::_downcast (CORBA::Exception *exc)
{
if (!ACE_OS::strcmp ("IDL:TAO_IOP/MultiProfileList:1.0", exc->_id ()))
{
return ACE_dynamic_cast (MultiProfileList *, exc);
}
else
{
return 0;
}
}
void TAO_IOP::MultiProfileList::_raise ()
{
TAO_RAISE (*this);
}
void TAO_IOP::MultiProfileList::_tao_encode (
TAO_OutputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
) const
{
if (cdr << *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
void TAO_IOP::MultiProfileList::_tao_decode (
TAO_InputCDR &cdr,
CORBA::Environment &ACE_TRY_ENV
)
{
if (cdr >> *this)
{
return;
}
ACE_THROW (CORBA::MARSHAL ());
}
// TAO extension - the _alloc method.
CORBA::Exception *TAO_IOP::MultiProfileList::_alloc (void)
{
CORBA::Exception *retval = 0;
ACE_NEW_RETURN (retval, ::TAO_IOP::MultiProfileList, 0);
return retval;
}
static const CORBA::Long _oc_TAO_IOP_MultiProfileList[] =
{
TAO_ENCAP_BYTE_ORDER, // byte order
33,
ACE_NTOHL (0x49444c3a),
ACE_NTOHL (0x54414f5f),
ACE_NTOHL (0x494f502f),
ACE_NTOHL (0x4d756c74),
ACE_NTOHL (0x6950726f),
ACE_NTOHL (0x66696c65),
ACE_NTOHL (0x4c697374),
ACE_NTOHL (0x3a312e30),
ACE_NTOHL (0x0), // repository ID = IDL:TAO_IOP/MultiProfileList:1.0
17,
ACE_NTOHL (0x4d756c74),
ACE_NTOHL (0x6950726f),
ACE_NTOHL (0x66696c65),
ACE_NTOHL (0x4c697374),
ACE_NTOHL (0x0), // name = MultiProfileList
0, // member count
};
static CORBA::TypeCode _tc_TAO_tc_TAO_IOP_MultiProfileList (
CORBA::tk_except,
sizeof (_oc_TAO_IOP_MultiProfileList),
(char *) &_oc_TAO_IOP_MultiProfileList,
0,
sizeof (TAO_IOP::MultiProfileList)
);
TAO_NAMESPACE_TYPE (CORBA::TypeCode_ptr)
TAO_NAMESPACE_BEGIN (TAO_IOP)
TAO_NAMESPACE_DEFINE (CORBA::TypeCode_ptr, _tc_MultiProfileList, &_tc_TAO_tc_TAO_IOP_MultiProfileList)
TAO_NAMESPACE_END
// TAO extension - the virtual _type method.
CORBA::TypeCode_ptr TAO_IOP::MultiProfileList::_type (void) const
{
return ::TAO_IOP::_tc_MultiProfileList;
}
int TAO_IOP::TAO_IOR_Property::_tao_class_id = 0;
// *************************************************************
// Operations for class TAO_IOP::TAO_IOR_Property_var
// *************************************************************
TAO_IOP::TAO_IOR_Property_var::TAO_IOR_Property_var (void) // default constructor
: ptr_ (TAO_IOR_Property::_nil ())
{}
::TAO_IOP::TAO_IOR_Property_ptr
TAO_IOP::TAO_IOR_Property_var::ptr (void) const
{
return this->ptr_;
}
TAO_IOP::TAO_IOR_Property_var::TAO_IOR_Property_var (const ::TAO_IOP::TAO_IOR_Property_var &p) // copy constructor
: TAO_Base_var (),
ptr_ (TAO_IOR_Property::_duplicate (p.ptr ()))
{}
TAO_IOP::TAO_IOR_Property_var::~TAO_IOR_Property_var (void) // destructor
{
CORBA::release (this->ptr_);
}
TAO_IOP::TAO_IOR_Property_var &
TAO_IOP::TAO_IOR_Property_var::operator= (TAO_IOR_Property_ptr p)
{
CORBA::release (this->ptr_);
this->ptr_ = p;
return *this;
}
TAO_IOP::TAO_IOR_Property_var &
TAO_IOP::TAO_IOR_Property_var::operator= (const ::TAO_IOP::TAO_IOR_Property_var &p)
{
if (this != &p)
{
CORBA::release (this->ptr_);
this->ptr_ = ::TAO_IOP::TAO_IOR_Property::_duplicate (p.ptr ());
}
return *this;
}
TAO_IOP::TAO_IOR_Property_var::operator const ::TAO_IOP::TAO_IOR_Property_ptr &() const // cast
{
return this->ptr_;
}
TAO_IOP::TAO_IOR_Property_var::operator ::TAO_IOP::TAO_IOR_Property_ptr &() // cast
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Property_ptr
TAO_IOP::TAO_IOR_Property_var::operator-> (void) const
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Property_ptr
TAO_IOP::TAO_IOR_Property_var::in (void) const
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Property_ptr &
TAO_IOP::TAO_IOR_Property_var::inout (void)
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Property_ptr &
TAO_IOP::TAO_IOR_Property_var::out (void)
{
CORBA::release (this->ptr_);
this->ptr_ = ::TAO_IOP::TAO_IOR_Property::_nil ();
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Property_ptr
TAO_IOP::TAO_IOR_Property_var::_retn (void)
{
// yield ownership of managed obj reference
::TAO_IOP::TAO_IOR_Property_ptr val = this->ptr_;
this->ptr_ = ::TAO_IOP::TAO_IOR_Property::_nil ();
return val;
}
::TAO_IOP::TAO_IOR_Property_ptr
TAO_IOP::TAO_IOR_Property_var::tao_duplicate (TAO_IOR_Property_ptr p)
{
return ::TAO_IOP::TAO_IOR_Property::_duplicate (p);
}
void
TAO_IOP::TAO_IOR_Property_var::tao_release (TAO_IOR_Property_ptr p)
{
CORBA::release (p);
}
::TAO_IOP::TAO_IOR_Property_ptr
TAO_IOP::TAO_IOR_Property_var::tao_nil (void)
{
return ::TAO_IOP::TAO_IOR_Property::_nil ();
}
::TAO_IOP::TAO_IOR_Property_ptr
TAO_IOP::TAO_IOR_Property_var::tao_narrow (
CORBA::Object *p,
CORBA::Environment &ACE_TRY_ENV
)
{
return ::TAO_IOP::TAO_IOR_Property::_narrow (p, ACE_TRY_ENV);
}
CORBA::Object *
TAO_IOP::TAO_IOR_Property_var::tao_upcast (void *src)
{
TAO_IOR_Property **tmp =
ACE_static_cast (TAO_IOR_Property **, src);
return *tmp;
}
// *************************************************************
// Inline operations for class TAO_IOP::TAO_IOR_Property_out
// *************************************************************
TAO_IOP::TAO_IOR_Property_out::TAO_IOR_Property_out (TAO_IOR_Property_ptr &p)
: ptr_ (p)
{
this->ptr_ = ::TAO_IOP::TAO_IOR_Property::_nil ();
}
TAO_IOP::TAO_IOR_Property_out::TAO_IOR_Property_out (TAO_IOR_Property_var &p) // constructor from _var
: ptr_ (p.out ())
{
CORBA::release (this->ptr_);
this->ptr_ = ::TAO_IOP::TAO_IOR_Property::_nil ();
}
TAO_IOP::TAO_IOR_Property_out::TAO_IOR_Property_out (const ::TAO_IOP::TAO_IOR_Property_out &p) // copy constructor
: ptr_ (ACE_const_cast (TAO_IOR_Property_out &, p).ptr_)
{}
::TAO_IOP::TAO_IOR_Property_out &
TAO_IOP::TAO_IOR_Property_out::operator= (const ::TAO_IOP::TAO_IOR_Property_out &p)
{
this->ptr_ = ACE_const_cast (TAO_IOR_Property_out&, p).ptr_;
return *this;
}
TAO_IOP::TAO_IOR_Property_out &
TAO_IOP::TAO_IOR_Property_out::operator= (const ::TAO_IOP::TAO_IOR_Property_var &p)
{
this->ptr_ = ::TAO_IOP::TAO_IOR_Property::_duplicate (p.ptr ());
return *this;
}
TAO_IOP::TAO_IOR_Property_out &
TAO_IOP::TAO_IOR_Property_out::operator= (TAO_IOR_Property_ptr p)
{
this->ptr_ = p;
return *this;
}
TAO_IOP::TAO_IOR_Property_out::operator ::TAO_IOP::TAO_IOR_Property_ptr &() // cast
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Property_ptr &
TAO_IOP::TAO_IOR_Property_out::ptr (void) // ptr
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Property_ptr
TAO_IOP::TAO_IOR_Property_out::operator-> (void)
{
return this->ptr_;
}
// default constructor
TAO_IOP::TAO_IOR_Property::TAO_IOR_Property ()
{
}
// destructor
TAO_IOP::TAO_IOR_Property::~TAO_IOR_Property (void)
{}
TAO_IOP::TAO_IOR_Property_ptr TAO_IOP::TAO_IOR_Property::_narrow (
CORBA::Object_ptr obj,
CORBA::Environment &ACE_TRY_ENV
)
{
return TAO_IOR_Property::_unchecked_narrow (obj, ACE_TRY_ENV);
}
TAO_IOP::TAO_IOR_Property_ptr TAO_IOP::TAO_IOR_Property::_unchecked_narrow (
CORBA::Object_ptr obj,
CORBA::Environment &
)
{
if (CORBA::is_nil (obj))
return TAO_IOR_Property::_nil ();
return
ACE_reinterpret_cast
(
TAO_IOR_Property_ptr,
obj->_tao_QueryInterface
(
ACE_reinterpret_cast
(
ptr_arith_t,
&TAO_IOR_Property::_tao_class_id
)
)
);
}
TAO_IOP::TAO_IOR_Property_ptr
TAO_IOP::TAO_IOR_Property::_duplicate (TAO_IOR_Property_ptr obj)
{
if (!CORBA::is_nil (obj))
obj->_add_ref ();
return obj;
}
void *TAO_IOP::TAO_IOR_Property::_tao_QueryInterface (ptr_arith_t type)
{
void *retv = 0;
if (type == ACE_reinterpret_cast
(ptr_arith_t,
&ACE_NESTED_CLASS (::TAO_IOP, TAO_IOR_Property)::_tao_class_id))
retv = ACE_reinterpret_cast (void*, this);
else if (type == ACE_reinterpret_cast (ptr_arith_t, &CORBA::Object::_tao_class_id))
retv = ACE_reinterpret_cast (void *,
ACE_static_cast (CORBA::Object_ptr, this));
if (retv)
this->_add_ref ();
return retv;
}
const char* TAO_IOP::TAO_IOR_Property::_interface_repository_id (void) const
{
return "IDL:TAO_IOP/TAO_IOR_Property:1.0";
}
int TAO_IOP::TAO_IOR_Manipulation::_tao_class_id = 0;
// *************************************************************
// Operations for class TAO_IOP::TAO_IOR_Manipulation_var
// *************************************************************
TAO_IOP::TAO_IOR_Manipulation_var::TAO_IOR_Manipulation_var (void) // default constructor
: ptr_ (TAO_IOR_Manipulation::_nil ())
{}
::TAO_IOP::TAO_IOR_Manipulation_ptr
TAO_IOP::TAO_IOR_Manipulation_var::ptr (void) const
{
return this->ptr_;
}
TAO_IOP::TAO_IOR_Manipulation_var::TAO_IOR_Manipulation_var (const ::TAO_IOP::TAO_IOR_Manipulation_var &p) // copy constructor
: TAO_Base_var (),
ptr_ (TAO_IOR_Manipulation::_duplicate (p.ptr ()))
{}
TAO_IOP::TAO_IOR_Manipulation_var::~TAO_IOR_Manipulation_var (void) // destructor
{
CORBA::release (this->ptr_);
}
TAO_IOP::TAO_IOR_Manipulation_var &
TAO_IOP::TAO_IOR_Manipulation_var::operator= (TAO_IOR_Manipulation_ptr p)
{
CORBA::release (this->ptr_);
this->ptr_ = p;
return *this;
}
TAO_IOP::TAO_IOR_Manipulation_var &
TAO_IOP::TAO_IOR_Manipulation_var::operator= (const ::TAO_IOP::TAO_IOR_Manipulation_var &p)
{
if (this != &p)
{
CORBA::release (this->ptr_);
this->ptr_ = ::TAO_IOP::TAO_IOR_Manipulation::_duplicate (p.ptr ());
}
return *this;
}
TAO_IOP::TAO_IOR_Manipulation_var::operator const ::TAO_IOP::TAO_IOR_Manipulation_ptr &() const // cast
{
return this->ptr_;
}
TAO_IOP::TAO_IOR_Manipulation_var::operator ::TAO_IOP::TAO_IOR_Manipulation_ptr &() // cast
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Manipulation_ptr
TAO_IOP::TAO_IOR_Manipulation_var::operator-> (void) const
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Manipulation_ptr
TAO_IOP::TAO_IOR_Manipulation_var::in (void) const
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Manipulation_ptr &
TAO_IOP::TAO_IOR_Manipulation_var::inout (void)
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Manipulation_ptr &
TAO_IOP::TAO_IOR_Manipulation_var::out (void)
{
CORBA::release (this->ptr_);
this->ptr_ = ::TAO_IOP::TAO_IOR_Manipulation::_nil ();
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Manipulation_ptr
TAO_IOP::TAO_IOR_Manipulation_var::_retn (void)
{
// yield ownership of managed obj reference
::TAO_IOP::TAO_IOR_Manipulation_ptr val = this->ptr_;
this->ptr_ = ::TAO_IOP::TAO_IOR_Manipulation::_nil ();
return val;
}
::TAO_IOP::TAO_IOR_Manipulation_ptr
TAO_IOP::TAO_IOR_Manipulation_var::tao_duplicate (TAO_IOR_Manipulation_ptr p)
{
return ::TAO_IOP::TAO_IOR_Manipulation::_duplicate (p);
}
void
TAO_IOP::TAO_IOR_Manipulation_var::tao_release (TAO_IOR_Manipulation_ptr p)
{
CORBA::release (p);
}
::TAO_IOP::TAO_IOR_Manipulation_ptr
TAO_IOP::TAO_IOR_Manipulation_var::tao_nil (void)
{
return ::TAO_IOP::TAO_IOR_Manipulation::_nil ();
}
::TAO_IOP::TAO_IOR_Manipulation_ptr
TAO_IOP::TAO_IOR_Manipulation_var::tao_narrow (
CORBA::Object *p,
CORBA::Environment &ACE_TRY_ENV
)
{
return ::TAO_IOP::TAO_IOR_Manipulation::_narrow (p, ACE_TRY_ENV);
}
CORBA::Object *
TAO_IOP::TAO_IOR_Manipulation_var::tao_upcast (void *src)
{
TAO_IOR_Manipulation **tmp =
ACE_static_cast (TAO_IOR_Manipulation **, src);
return *tmp;
}
// *************************************************************
// Inline operations for class TAO_IOP::TAO_IOR_Manipulation_out
// *************************************************************
TAO_IOP::TAO_IOR_Manipulation_out::TAO_IOR_Manipulation_out (TAO_IOR_Manipulation_ptr &p)
: ptr_ (p)
{
this->ptr_ = ::TAO_IOP::TAO_IOR_Manipulation::_nil ();
}
TAO_IOP::TAO_IOR_Manipulation_out::TAO_IOR_Manipulation_out (TAO_IOR_Manipulation_var &p) // constructor from _var
: ptr_ (p.out ())
{
CORBA::release (this->ptr_);
this->ptr_ = ::TAO_IOP::TAO_IOR_Manipulation::_nil ();
}
TAO_IOP::TAO_IOR_Manipulation_out::TAO_IOR_Manipulation_out (const ::TAO_IOP::TAO_IOR_Manipulation_out &p) // copy constructor
: ptr_ (ACE_const_cast (TAO_IOR_Manipulation_out &, p).ptr_)
{}
::TAO_IOP::TAO_IOR_Manipulation_out &
TAO_IOP::TAO_IOR_Manipulation_out::operator= (const ::TAO_IOP::TAO_IOR_Manipulation_out &p)
{
this->ptr_ = ACE_const_cast (TAO_IOR_Manipulation_out&, p).ptr_;
return *this;
}
TAO_IOP::TAO_IOR_Manipulation_out &
TAO_IOP::TAO_IOR_Manipulation_out::operator= (const ::TAO_IOP::TAO_IOR_Manipulation_var &p)
{
this->ptr_ = ::TAO_IOP::TAO_IOR_Manipulation::_duplicate (p.ptr ());
return *this;
}
TAO_IOP::TAO_IOR_Manipulation_out &
TAO_IOP::TAO_IOR_Manipulation_out::operator= (TAO_IOR_Manipulation_ptr p)
{
this->ptr_ = p;
return *this;
}
TAO_IOP::TAO_IOR_Manipulation_out::operator ::TAO_IOP::TAO_IOR_Manipulation_ptr &() // cast
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Manipulation_ptr &
TAO_IOP::TAO_IOR_Manipulation_out::ptr (void) // ptr
{
return this->ptr_;
}
::TAO_IOP::TAO_IOR_Manipulation_ptr
TAO_IOP::TAO_IOR_Manipulation_out::operator-> (void)
{
return this->ptr_;
}
// default constructor
TAO_IOP::TAO_IOR_Manipulation::TAO_IOR_Manipulation ()
{
}
// destructor
TAO_IOP::TAO_IOR_Manipulation::~TAO_IOR_Manipulation (void)
{}
TAO_IOP::TAO_IOR_Manipulation_ptr TAO_IOP::TAO_IOR_Manipulation::_narrow (
CORBA::Object_ptr obj,
CORBA::Environment &ACE_TRY_ENV
)
{
return TAO_IOR_Manipulation::_unchecked_narrow (obj, ACE_TRY_ENV);
}
TAO_IOP::TAO_IOR_Manipulation_ptr TAO_IOP::TAO_IOR_Manipulation::_unchecked_narrow (
CORBA::Object_ptr obj,
CORBA::Environment &
)
{
if (CORBA::is_nil (obj))
return TAO_IOR_Manipulation::_nil ();
return
ACE_reinterpret_cast
(
TAO_IOR_Manipulation_ptr,
obj->_tao_QueryInterface
(
ACE_reinterpret_cast
(
ptr_arith_t,
&TAO_IOR_Manipulation::_tao_class_id
)
)
);
}
TAO_IOP::TAO_IOR_Manipulation_ptr
TAO_IOP::TAO_IOR_Manipulation::_duplicate (TAO_IOR_Manipulation_ptr obj)
{
if (!CORBA::is_nil (obj))
obj->_add_ref ();
return obj;
}
void *TAO_IOP::TAO_IOR_Manipulation::_tao_QueryInterface (ptr_arith_t type)
{
void *retv = 0;
if (type == ACE_reinterpret_cast
(ptr_arith_t,
&ACE_NESTED_CLASS (::TAO_IOP, TAO_IOR_Manipulation)::_tao_class_id))
retv = ACE_reinterpret_cast (void*, this);
else if (type == ACE_reinterpret_cast (ptr_arith_t, &CORBA::Object::_tao_class_id))
retv = ACE_reinterpret_cast (void *,
ACE_static_cast (CORBA::Object_ptr, this));
if (retv)
this->_add_ref ();
return retv;
}
const char* TAO_IOP::TAO_IOR_Manipulation::_interface_repository_id (void) const
{
return "IDL:TAO_IOP/TAO_IOR_Manipulation:1.0";
}
#if !defined (TAO_USE_SEQUENCE_TEMPLATES)
#if !defined (__TAO_UNBOUNDED_OBJECT_SEQUENCE_TAO_IOP_TAO_IOR_MANIPULATION_IORLIST_CS_)
#define __TAO_UNBOUNDED_OBJECT_SEQUENCE_TAO_IOP_TAO_IOR_MANIPULATION_IORLIST_CS_
// The Base_Sequence functions, please see tao/Sequence.h
void
TAO_IOP::TAO_IOR_Manipulation::_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList::_allocate_buffer (CORBA::ULong length)
{
CORBA::Object **tmp = 0;
tmp = _TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList::allocbuf (length);
if (this->buffer_ != 0)
{
CORBA::Object **old = ACE_reinterpret_cast (CORBA::Object**, this->buffer_);
for (CORBA::ULong i = 0; i < this->length_; ++i)
{
if (!this->release_)
{
tmp[i] = CORBA::Object::_duplicate (old[i]);
}
else
{
tmp[i] = old[i];
}
}
if (this->release_)
{
delete[] old;
}
}
this->buffer_ = tmp;
}
void
TAO_IOP::TAO_IOR_Manipulation::_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList::_deallocate_buffer (void)
{
if (this->buffer_ == 0 || this->release_ == 0)
return;
CORBA::Object **tmp = ACE_reinterpret_cast (CORBA::Object**, this->buffer_);
for (CORBA::ULong i = 0; i < this->length_; ++i)
{
CORBA::release (tmp[i]);
tmp[i] = CORBA::Object::_nil ();
}
_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList::freebuf (tmp);
this->buffer_ = 0;
}
TAO_IOP::TAO_IOR_Manipulation::_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList::~_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList (void)
{
this->_deallocate_buffer ();
}
void
TAO_IOP::TAO_IOR_Manipulation::_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList::_shrink_buffer (CORBA::ULong nl, CORBA::ULong ol)
{
CORBA::Object **tmp = ACE_reinterpret_cast (CORBA::Object**, this->buffer_);
for (CORBA::ULong i = nl; i < ol; ++i)
{
CORBA::release (tmp[i]);
tmp[i] = CORBA::Object::_nil ();
}
}
void
TAO_IOP::TAO_IOR_Manipulation::_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList::_downcast (
void* target,
CORBA_Object *src,
CORBA_Environment &ACE_TRY_ENV
)
{
CORBA::Object **tmp = ACE_static_cast (CORBA::Object**, target);
*tmp = CORBA::Object::_narrow (src, ACE_TRY_ENV);
ACE_CHECK;
}
CORBA_Object*
TAO_IOP::TAO_IOR_Manipulation::_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList::_upcast (void *src) const
{
CORBA::Object **tmp = ACE_static_cast (CORBA::Object**, src);
return *tmp;
}
#endif /* end #if !defined */
#endif /* !TAO_USE_SEQUENCE_TEMPLATES */
#if !defined (_TAO_IOP_TAO_IOR_MANIPULATION_IORLIST_CS_)
#define _TAO_IOP_TAO_IOR_MANIPULATION_IORLIST_CS_
// *************************************************************
// TAO_IOP::TAO_IOR_Manipulation::IORList
// *************************************************************
TAO_IOP::TAO_IOR_Manipulation::IORList::IORList (void)
{}
TAO_IOP::TAO_IOR_Manipulation::IORList::IORList (CORBA::ULong max) // uses max size
:
#if !defined (TAO_USE_SEQUENCE_TEMPLATES)
_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList
#else /* TAO_USE_SEQUENCE_TEMPLATES */
TAO_Unbounded_Object_Sequence<CORBA::Object,CORBA::Object_var>
#endif /* !TAO_USE_SEQUENCE_TEMPLATES */
(max)
{}
TAO_IOP::TAO_IOR_Manipulation::IORList::IORList (CORBA::ULong max, CORBA::ULong length, CORBA::Object_ptr *buffer, CORBA::Boolean release)
:
#if !defined (TAO_USE_SEQUENCE_TEMPLATES)
_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList
#else /* TAO_USE_SEQUENCE_TEMPLATES */
TAO_Unbounded_Object_Sequence<CORBA::Object,CORBA::Object_var>
#endif /* !TAO_USE_SEQUENCE_TEMPLATES */
(max, length, buffer, release)
{}
TAO_IOP::TAO_IOR_Manipulation::IORList::IORList (const IORList &seq) // copy ctor
:
#if !defined (TAO_USE_SEQUENCE_TEMPLATES)
_TAO_Unbounded_Object_Sequence_TAO_IOP_TAO_IOR_Manipulation_IORList
#else /* TAO_USE_SEQUENCE_TEMPLATES */
TAO_Unbounded_Object_Sequence<CORBA::Object,CORBA::Object_var>
#endif /* !TAO_USE_SEQUENCE_TEMPLATES */
(seq)
{}
TAO_IOP::TAO_IOR_Manipulation::IORList::~IORList (void) // dtor
{}
void TAO_IOP::TAO_IOR_Manipulation::IORList::_tao_any_destructor (void *x)
{
IORList *tmp = ACE_static_cast (IORList*,x);
delete tmp;
}
#endif /* end #if !defined */
void operator<<= (CORBA::Any &_tao_any, const TAO_IOP::EmptyProfileList &_tao_elem) // copying
{
TAO_OutputCDR stream;
stream << _tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_EmptyProfileList,
TAO_ENCAP_BYTE_ORDER,
stream.begin ()
);
}
void operator<<= (CORBA::Any &_tao_any, TAO_IOP::EmptyProfileList *_tao_elem) // non copying
{
TAO_OutputCDR stream;
stream << *_tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_EmptyProfileList,
TAO_ENCAP_BYTE_ORDER,
stream.begin (),
1,
_tao_elem,
TAO_IOP::EmptyProfileList::_tao_any_destructor
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, TAO_IOP::EmptyProfileList *&_tao_elem)
{
return _tao_any >>= ACE_const_cast(
const TAO_IOP::EmptyProfileList*&,
_tao_elem
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, const TAO_IOP::EmptyProfileList *&_tao_elem)
{
_tao_elem = 0;
ACE_TRY_NEW_ENV
{
CORBA::TypeCode_var type = _tao_any.type ();
CORBA::Boolean result = type->equivalent (TAO_IOP::_tc_EmptyProfileList, ACE_TRY_ENV);
ACE_TRY_CHECK;
if (!result)
return 0; // not equivalent
if (_tao_any.any_owns_data ())
{
_tao_elem = (TAO_IOP::EmptyProfileList *)_tao_any.value ();
return 1;
}
else
{
TAO_IOP::EmptyProfileList *tmp;
ACE_NEW_RETURN (tmp, TAO_IOP::EmptyProfileList, 0);
TAO_InputCDR stream (
_tao_any._tao_get_cdr (),
_tao_any._tao_byte_order ()
);
CORBA::String_var interface_repository_id;
if (!(stream >> interface_repository_id.out ()))
return 0;
if (ACE_OS::strcmp (
interface_repository_id.in (),
"IDL:TAO_IOP/EmptyProfileList:1.0"))
return 0;
if (stream >> *tmp)
{
((CORBA::Any *)&_tao_any)->_tao_replace (
TAO_IOP::_tc_EmptyProfileList,
1,
tmp,
TAO_IOP::EmptyProfileList::_tao_any_destructor
);
_tao_elem = tmp;
return 1;
}
else
{
delete tmp;
}
}
}
ACE_CATCHANY
{
}
ACE_ENDTRY;
return 0;
}
void operator<<= (CORBA::Any &_tao_any, const TAO_IOP::NotFound &_tao_elem) // copying
{
TAO_OutputCDR stream;
stream << _tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_NotFound,
TAO_ENCAP_BYTE_ORDER,
stream.begin ()
);
}
void operator<<= (CORBA::Any &_tao_any, TAO_IOP::NotFound *_tao_elem) // non copying
{
TAO_OutputCDR stream;
stream << *_tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_NotFound,
TAO_ENCAP_BYTE_ORDER,
stream.begin (),
1,
_tao_elem,
TAO_IOP::NotFound::_tao_any_destructor
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, TAO_IOP::NotFound *&_tao_elem)
{
return _tao_any >>= ACE_const_cast(
const TAO_IOP::NotFound*&,
_tao_elem
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, const TAO_IOP::NotFound *&_tao_elem)
{
_tao_elem = 0;
ACE_TRY_NEW_ENV
{
CORBA::TypeCode_var type = _tao_any.type ();
CORBA::Boolean result = type->equivalent (TAO_IOP::_tc_NotFound, ACE_TRY_ENV);
ACE_TRY_CHECK;
if (!result)
return 0; // not equivalent
if (_tao_any.any_owns_data ())
{
_tao_elem = (TAO_IOP::NotFound *)_tao_any.value ();
return 1;
}
else
{
TAO_IOP::NotFound *tmp;
ACE_NEW_RETURN (tmp, TAO_IOP::NotFound, 0);
TAO_InputCDR stream (
_tao_any._tao_get_cdr (),
_tao_any._tao_byte_order ()
);
CORBA::String_var interface_repository_id;
if (!(stream >> interface_repository_id.out ()))
return 0;
if (ACE_OS::strcmp (
interface_repository_id.in (),
"IDL:TAO_IOP/NotFound:1.0"))
return 0;
if (stream >> *tmp)
{
((CORBA::Any *)&_tao_any)->_tao_replace (
TAO_IOP::_tc_NotFound,
1,
tmp,
TAO_IOP::NotFound::_tao_any_destructor
);
_tao_elem = tmp;
return 1;
}
else
{
delete tmp;
}
}
}
ACE_CATCHANY
{
}
ACE_ENDTRY;
return 0;
}
void operator<<= (CORBA::Any &_tao_any, const TAO_IOP::Duplicate &_tao_elem) // copying
{
TAO_OutputCDR stream;
stream << _tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_Duplicate,
TAO_ENCAP_BYTE_ORDER,
stream.begin ()
);
}
void operator<<= (CORBA::Any &_tao_any, TAO_IOP::Duplicate *_tao_elem) // non copying
{
TAO_OutputCDR stream;
stream << *_tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_Duplicate,
TAO_ENCAP_BYTE_ORDER,
stream.begin (),
1,
_tao_elem,
TAO_IOP::Duplicate::_tao_any_destructor
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, TAO_IOP::Duplicate *&_tao_elem)
{
return _tao_any >>= ACE_const_cast(
const TAO_IOP::Duplicate*&,
_tao_elem
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, const TAO_IOP::Duplicate *&_tao_elem)
{
_tao_elem = 0;
ACE_TRY_NEW_ENV
{
CORBA::TypeCode_var type = _tao_any.type ();
CORBA::Boolean result = type->equivalent (TAO_IOP::_tc_Duplicate, ACE_TRY_ENV);
ACE_TRY_CHECK;
if (!result)
return 0; // not equivalent
if (_tao_any.any_owns_data ())
{
_tao_elem = (TAO_IOP::Duplicate *)_tao_any.value ();
return 1;
}
else
{
TAO_IOP::Duplicate *tmp;
ACE_NEW_RETURN (tmp, TAO_IOP::Duplicate, 0);
TAO_InputCDR stream (
_tao_any._tao_get_cdr (),
_tao_any._tao_byte_order ()
);
CORBA::String_var interface_repository_id;
if (!(stream >> interface_repository_id.out ()))
return 0;
if (ACE_OS::strcmp (
interface_repository_id.in (),
"IDL:TAO_IOP/Duplicate:1.0"))
return 0;
if (stream >> *tmp)
{
((CORBA::Any *)&_tao_any)->_tao_replace (
TAO_IOP::_tc_Duplicate,
1,
tmp,
TAO_IOP::Duplicate::_tao_any_destructor
);
_tao_elem = tmp;
return 1;
}
else
{
delete tmp;
}
}
}
ACE_CATCHANY
{
}
ACE_ENDTRY;
return 0;
}
void operator<<= (CORBA::Any &_tao_any, const TAO_IOP::Invalid_IOR &_tao_elem) // copying
{
TAO_OutputCDR stream;
stream << _tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_Invalid_IOR,
TAO_ENCAP_BYTE_ORDER,
stream.begin ()
);
}
void operator<<= (CORBA::Any &_tao_any, TAO_IOP::Invalid_IOR *_tao_elem) // non copying
{
TAO_OutputCDR stream;
stream << *_tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_Invalid_IOR,
TAO_ENCAP_BYTE_ORDER,
stream.begin (),
1,
_tao_elem,
TAO_IOP::Invalid_IOR::_tao_any_destructor
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, TAO_IOP::Invalid_IOR *&_tao_elem)
{
return _tao_any >>= ACE_const_cast(
const TAO_IOP::Invalid_IOR*&,
_tao_elem
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, const TAO_IOP::Invalid_IOR *&_tao_elem)
{
_tao_elem = 0;
ACE_TRY_NEW_ENV
{
CORBA::TypeCode_var type = _tao_any.type ();
CORBA::Boolean result = type->equivalent (TAO_IOP::_tc_Invalid_IOR, ACE_TRY_ENV);
ACE_TRY_CHECK;
if (!result)
return 0; // not equivalent
if (_tao_any.any_owns_data ())
{
_tao_elem = (TAO_IOP::Invalid_IOR *)_tao_any.value ();
return 1;
}
else
{
TAO_IOP::Invalid_IOR *tmp;
ACE_NEW_RETURN (tmp, TAO_IOP::Invalid_IOR, 0);
TAO_InputCDR stream (
_tao_any._tao_get_cdr (),
_tao_any._tao_byte_order ()
);
CORBA::String_var interface_repository_id;
if (!(stream >> interface_repository_id.out ()))
return 0;
if (ACE_OS::strcmp (
interface_repository_id.in (),
"IDL:TAO_IOP/Invalid_IOR:1.0"))
return 0;
if (stream >> *tmp)
{
((CORBA::Any *)&_tao_any)->_tao_replace (
TAO_IOP::_tc_Invalid_IOR,
1,
tmp,
TAO_IOP::Invalid_IOR::_tao_any_destructor
);
_tao_elem = tmp;
return 1;
}
else
{
delete tmp;
}
}
}
ACE_CATCHANY
{
}
ACE_ENDTRY;
return 0;
}
void operator<<= (CORBA::Any &_tao_any, const TAO_IOP::MultiProfileList &_tao_elem) // copying
{
TAO_OutputCDR stream;
stream << _tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_MultiProfileList,
TAO_ENCAP_BYTE_ORDER,
stream.begin ()
);
}
void operator<<= (CORBA::Any &_tao_any, TAO_IOP::MultiProfileList *_tao_elem) // non copying
{
TAO_OutputCDR stream;
stream << *_tao_elem;
_tao_any._tao_replace (
TAO_IOP::_tc_MultiProfileList,
TAO_ENCAP_BYTE_ORDER,
stream.begin (),
1,
_tao_elem,
TAO_IOP::MultiProfileList::_tao_any_destructor
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, TAO_IOP::MultiProfileList *&_tao_elem)
{
return _tao_any >>= ACE_const_cast(
const TAO_IOP::MultiProfileList*&,
_tao_elem
);
}
CORBA::Boolean operator>>= (const CORBA::Any &_tao_any, const TAO_IOP::MultiProfileList *&_tao_elem)
{
_tao_elem = 0;
ACE_TRY_NEW_ENV
{
CORBA::TypeCode_var type = _tao_any.type ();
CORBA::Boolean result = type->equivalent (TAO_IOP::_tc_MultiProfileList, ACE_TRY_ENV);
ACE_TRY_CHECK;
if (!result)
return 0; // not equivalent
if (_tao_any.any_owns_data ())
{
_tao_elem = (TAO_IOP::MultiProfileList *)_tao_any.value ();
return 1;
}
else
{
TAO_IOP::MultiProfileList *tmp;
ACE_NEW_RETURN (tmp, TAO_IOP::MultiProfileList, 0);
TAO_InputCDR stream (
_tao_any._tao_get_cdr (),
_tao_any._tao_byte_order ()
);
CORBA::String_var interface_repository_id;
if (!(stream >> interface_repository_id.out ()))
return 0;
if (ACE_OS::strcmp (
interface_repository_id.in (),
"IDL:TAO_IOP/MultiProfileList:1.0"))
return 0;
if (stream >> *tmp)
{
((CORBA::Any *)&_tao_any)->_tao_replace (
TAO_IOP::_tc_MultiProfileList,
1,
tmp,
TAO_IOP::MultiProfileList::_tao_any_destructor
);
_tao_elem = tmp;
return 1;
}
else
{
delete tmp;
}
}
}
ACE_CATCHANY
{
}
ACE_ENDTRY;
return 0;
}
#if defined (ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION) || \
defined (ACE_HAS_GNU_REPO)
template class TAO_Object_Manager<TAO_IOP::TAO_IOR_Property,TAO_IOP::TAO_IOR_Property_var>;
#elif defined (ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA)
# pragma instantiate TAO_Object_Manager<TAO_IOP::TAO_IOR_Property,TAO_IOP::TAO_IOR_Property_var>
#endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION */
#if defined (ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION) || \
defined (ACE_HAS_GNU_REPO)
template class TAO_Object_Manager<TAO_IOP::TAO_IOR_Manipulation,TAO_IOP::TAO_IOR_Manipulation_var>;
#elif defined (ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA)
# pragma instantiate TAO_Object_Manager<TAO_IOP::TAO_IOR_Manipulation,TAO_IOP::TAO_IOR_Manipulation_var>
#endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION */
| 25.482993 | 178 | 0.64838 | [
"object"
] |
9bc91f6c66ea6d65f5c7305b12e925dc3fef3684 | 39,205 | hpp | C++ | sparse/L2/include/sw/fp32/gen_cscmv.hpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | 1 | 2021-09-11T01:05:01.000Z | 2021-09-11T01:05:01.000Z | sparse/L2/include/sw/fp32/gen_cscmv.hpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | null | null | null | sparse/L2/include/sw/fp32/gen_cscmv.hpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | 1 | 2021-04-28T05:58:38.000Z | 2021-04-28T05:58:38.000Z | /*
* Copyright 2019 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file gen_cscmv.hpp
* @brief header file for generating data images of cscmv operation.
*
* This file is part of Vitis SPARSE Library.
*/
#ifndef XF_SPARSE_GEN_CSCMV_HPP
#define XF_SPARSE_GEN_CSCMV_HPP
#include <ctime>
#include <cstdlib>
#include <vector>
#include "L2_types.hpp"
#include "program.hpp"
#include "mtxFile.hpp"
using namespace std;
namespace xf {
namespace sparse {
template <typename t_DataType, unsigned int t_MemBits, unsigned int t_PageSize = 4096>
class GenVec {
public:
const unsigned int t_MemWords = t_MemBits / (8 * sizeof(t_DataType));
public:
GenVec() {}
void genEntVecFromRnd(unsigned int p_entries,
t_DataType p_maxVal,
t_DataType p_valStep,
vector<t_DataType>& p_entryVec) {
t_DataType l_val = 0;
for (unsigned int i = 0; i < p_entries; ++i) {
p_entryVec.push_back(l_val);
l_val += p_valStep;
if (l_val > p_maxVal) {
l_val = 0;
}
}
}
bool genColVecFromEnt(vector<t_DataType>& p_entryVec,
Program<t_PageSize>& p_program,
ColVec<t_DataType, t_MemBits>& p_colVec) {
unsigned int l_entries = p_entryVec.size();
while (l_entries % t_MemWords != 0) {
cout << "INFO: padding col vector with 0 entry" << endl;
p_entryVec.push_back(0);
l_entries++;
}
unsigned long long l_vecSz = l_entries * sizeof(t_DataType);
void* l_valAddr = p_program.allocMem(l_vecSz);
if (l_valAddr == nullptr) {
return false;
}
p_colVec.setEntries(l_entries);
p_colVec.setValAddr(reinterpret_cast<uint8_t*>(l_valAddr));
p_colVec.storeVal(p_entryVec);
return true;
}
bool genColVecFromRnd(unsigned int p_entries,
t_DataType p_maxVal,
t_DataType p_valStep,
Program<t_PageSize>& p_program,
ColVec<t_DataType, t_MemBits>& p_colVec) {
vector<t_DataType> l_entryVec;
p_colVec.setEntries(p_entries);
genEntVecFromRnd(p_entries, p_maxVal, p_valStep, l_entryVec);
bool l_res = false;
l_res = genColVecFromEnt(l_entryVec, p_program, p_colVec);
return l_res;
}
bool genEmptyColVec(unsigned int p_entries,
Program<t_PageSize>& p_program,
ColVec<t_DataType, t_MemBits>& p_colVec) {
unsigned long long l_vecSz = p_entries * sizeof(t_DataType);
void* l_valAddr = p_program.allocMem(l_vecSz);
if (l_valAddr == nullptr) {
return false;
}
p_colVec.setEntries(p_entries);
p_colVec.setValAddr(reinterpret_cast<uint8_t*>(l_valAddr));
for (unsigned int i = 0; i < p_entries; ++i) {
p_colVec.setEntryVal(i, 0);
}
return true;
}
};
template <typename t_DataType, typename t_IndexType, unsigned int t_PageSize = 4096>
class GenMatCsc {
public:
typedef NnzUnit<t_DataType, t_IndexType> t_NnzUnitType;
typedef MatCsc<t_DataType, t_IndexType> t_MatCscType;
public:
GenMatCsc() {}
bool genMatFromUnits(unsigned int p_rows,
unsigned int p_cols,
unsigned int p_nnzs,
vector<t_NnzUnitType>& p_nnzUnits,
Program<t_PageSize>& p_program,
t_MatCscType& p_matCsc) {
// sort p_nnzUnits along cols
sort(p_nnzUnits.begin(), p_nnzUnits.end());
p_matCsc.setRows(p_rows);
p_matCsc.setCols(p_cols);
p_matCsc.setNnzs(p_nnzs);
unsigned long long l_valSz = p_nnzs * sizeof(t_DataType);
void* l_valAddr = p_program.allocMem(l_valSz);
unsigned long long l_rowSz = p_nnzs * sizeof(t_IndexType);
void* l_rowAddr = p_program.allocMem(l_rowSz);
unsigned long long l_colPtrSz = p_cols * sizeof(t_IndexType);
void* l_colPtrAddr = p_program.allocMem(l_colPtrSz);
if (l_valAddr == nullptr) {
return false;
}
if (l_rowAddr == nullptr) {
return false;
}
if (l_colPtrAddr == nullptr) {
return false;
}
p_matCsc.setValAddr(l_valAddr);
p_matCsc.setRowAddr(l_rowAddr);
p_matCsc.setColPtrAddr(l_colPtrAddr);
// populate data
t_DataType* l_val = reinterpret_cast<t_DataType*>(l_valAddr);
for (unsigned int i = 0; i < p_nnzs; ++i) {
l_val[i] = p_nnzUnits[i].getVal();
}
t_IndexType* l_rowIdx = reinterpret_cast<t_IndexType*>(l_rowAddr);
for (unsigned int i = 0; i < p_nnzs; ++i) {
l_rowIdx[i] = p_nnzUnits[i].getRow();
}
t_IndexType* l_colPtr = reinterpret_cast<t_IndexType*>(l_colPtrAddr);
unsigned int l_id = 0;
l_colPtr[l_id] = 0;
unsigned int l_nnzId = 0;
while (l_nnzId < p_nnzs) {
if (p_nnzUnits[l_nnzId].getCol() > l_id) {
l_id++;
l_colPtr[l_id] = l_colPtr[l_id - 1];
} else if (p_nnzUnits[l_nnzId].getCol() == l_id) {
l_colPtr[l_id]++;
l_nnzId++;
}
}
return true;
}
bool genMatFromCscFiles(string p_valFileName,
string p_rowFileName,
string p_colPtrFileName,
Program<t_PageSize>& p_program,
t_MatCscType& p_matCsc) {
size_t l_valSz = getFileSize(p_valFileName);
size_t l_rowSz = getFileSize(p_rowFileName);
size_t l_colPtrSz = getFileSize(p_colPtrFileName);
assert(l_valSz == l_rowSz);
assert(l_valSz % (sizeof(t_DataType)) == 0);
unsigned int l_nnzs = l_valSz / sizeof(t_DataType);
unsigned int l_cols = l_colPtrSz / sizeof(t_IndexType);
ifstream l_ifVal(p_valFileName.c_str(), ios::binary);
if (!l_ifVal.is_open()) {
cout << "ERROR: Open " << p_valFileName << endl;
return false;
}
ifstream l_ifRow(p_rowFileName.c_str(), ios::binary);
if (!l_ifRow.is_open()) {
cout << "ERROR: Open " << p_rowFileName << endl;
return false;
}
ifstream l_ifColPtr(p_colPtrFileName.c_str(), ios::binary);
if (!l_ifColPtr.is_open()) {
cout << "ERROR: Open " << p_colPtrFileName << endl;
return false;
}
void* l_valAddr = p_program.allocMem(l_valSz);
void* l_rowAddr = p_program.allocMem(l_rowSz);
void* l_colPtrAddr = p_program.allocMem(l_colPtrSz);
l_ifVal.read(reinterpret_cast<char*>(l_valAddr), l_valSz);
l_ifRow.read(reinterpret_cast<char*>(l_rowAddr), l_rowSz);
l_ifColPtr.read(reinterpret_cast<char*>(l_colPtrAddr), l_colPtrSz);
p_matCsc.setNnzs(l_nnzs);
p_matCsc.setCols(l_cols);
p_matCsc.setValAddr(l_valAddr);
p_matCsc.setRowAddr(l_rowAddr);
p_matCsc.setColPtrAddr(l_colPtrAddr);
t_IndexType* l_rowIdx = reinterpret_cast<t_IndexType*>(l_rowAddr);
t_IndexType l_rowIdxMax = 0;
for (unsigned int i = 0; i < l_nnzs; ++i) {
if (l_rowIdx[i] > l_rowIdxMax) {
l_rowIdxMax = l_rowIdx[i];
}
}
p_matCsc.setRows(l_rowIdxMax + 1);
return true;
}
bool genMatFromMtxFile(string p_mtxFileName, Program<t_PageSize>& p_program, t_MatCscType& p_matCsc) {
MtxFile<t_DataType, t_IndexType> l_mtxFile;
l_mtxFile.loadFile(p_mtxFileName);
vector<t_NnzUnitType> l_nnzUnits;
if (!l_mtxFile.good()) {
return false;
}
l_nnzUnits = l_mtxFile.getNnzUnits();
unsigned int l_rows = l_mtxFile.rows();
unsigned int l_cols = l_mtxFile.cols();
unsigned int l_nnzs = l_mtxFile.nnzs();
if (!genMatFromUnits(l_rows, l_cols, l_nnzs, l_nnzUnits, p_program, p_matCsc)) {
return false;
}
return true;
}
};
template <typename t_DataType,
typename t_IndexType,
unsigned int t_MaxRowsPerPar,
unsigned int t_MaxColsPerPar,
unsigned int t_ParEntries,
unsigned int t_ParGroups,
unsigned int t_DdrMemBits,
unsigned int t_HbmChannels>
class GenMatPar {
public:
typedef NnzUnit<t_DataType, t_IndexType> t_NnzUnitType;
typedef struct ChBlockDesp t_ChBlockDespType;
typedef struct ColParDesp<t_HbmChannels> t_ColParDespType;
typedef MatPar<t_DataType, t_IndexType, t_MaxRowsPerPar, t_MaxColsPerPar, t_HbmChannels> t_MatParType;
typedef RoCooPar<t_DataType, t_IndexType, t_MaxRowsPerPar, t_MaxColsPerPar, t_HbmChannels> t_RoCooParType;
typedef KrnColParDesp<t_HbmChannels> t_KrnColParDespType;
typedef KrnRowParDesp<t_HbmChannels> t_KrnRowParDespType;
static const unsigned int t_ColsPerMem = t_DdrMemBits / (8 * sizeof(t_DataType));
static const unsigned int t_ParWordsPerMem = t_ColsPerMem / t_ParEntries;
public:
GenMatPar() {}
void genRoCooPar(vector<t_NnzUnitType>& p_nnzUnits, t_RoCooParType& p_roCooPar) {
// assume memory has already been allocated for p_roCooPar
unsigned int l_nnzs = p_nnzUnits.size();
p_roCooPar.nnzs() = l_nnzs;
unsigned int l_colPars = p_roCooPar.colPars();
for (unsigned int i = 0; i < l_nnzs; ++i) {
t_NnzUnitType l_nnzUnit = p_nnzUnits[i];
unsigned int l_rowId = l_nnzUnit.getRow();
unsigned int l_colId = l_nnzUnit.getCol();
unsigned int l_rowParId = l_rowId / t_MaxRowsPerPar;
unsigned int l_colParId = l_colId / t_MaxColsPerPar;
unsigned int l_parId = l_rowParId * l_colPars + l_colParId;
p_roCooPar.addNnzUnit(l_parId, l_nnzUnit);
}
unsigned int l_totalPars = p_roCooPar.totalPars();
for (unsigned int i = 0; i < l_totalPars; ++i) {
// sort(p_roCooPar[i].begin(), p_roCooPar[i].end(), compareRow<t_DataType, t_IndexType>());
sort(p_roCooPar[i].begin(), p_roCooPar[i].end());
}
}
void genNextParDesp(vector<t_NnzUnitType>& p_nnzUnits,
unsigned int p_nnzsPerCh,
unsigned int p_chId,
unsigned int& p_startId,
t_ColParDespType& p_colParDesp,
t_KrnRowParDespType& p_krnRowParDesp) {
unsigned int l_nnzs = p_nnzUnits.size();
unsigned int l_chNnzs =
(p_startId >= l_nnzs) ? 0 : ((p_startId + p_nnzsPerCh) > l_nnzs) ? (l_nnzs - p_startId) : p_nnzsPerCh;
t_ChBlockDespType l_chBlockDesp;
if (l_nnzs == 0) {
p_krnRowParDesp.addChBlockDesp(l_chBlockDesp);
p_colParDesp.m_minColId[p_chId] = 1;
p_colParDesp.m_maxColId[p_chId] = 0;
p_colParDesp.m_cols[p_chId] = 0;
p_colParDesp.m_colBlocks[p_chId] = 0;
p_colParDesp.m_nnzs[p_chId] = 0;
p_colParDesp.m_nnzBlocks[p_chId] = 0;
p_colParDesp.m_parMinColId = 1;
p_colParDesp.m_parMaxColId = 0;
p_colParDesp.m_nnzColMemBlocks = 0;
return;
}
if (l_chNnzs == 0) {
p_krnRowParDesp.addChBlockDesp(l_chBlockDesp);
p_colParDesp.m_minColId[p_chId] = 1;
p_colParDesp.m_maxColId[p_chId] = 0;
p_colParDesp.m_cols[p_chId] = 0;
p_colParDesp.m_colBlocks[p_chId] = 0;
p_colParDesp.m_nnzs[p_chId] = 0;
p_colParDesp.m_nnzBlocks[p_chId] = 0;
return;
}
l_chBlockDesp.m_startId = p_startId;
t_NnzUnitType l_nnzUnit = p_nnzUnits[p_startId];
l_chBlockDesp.m_minRowId = l_nnzUnit.getRow();
l_chBlockDesp.m_maxRowId = l_chBlockDesp.m_minRowId;
l_chBlockDesp.m_minColId = l_nnzUnit.getCol();
l_chBlockDesp.m_maxColId = l_chBlockDesp.m_minColId;
l_chBlockDesp.m_nnzs = l_chNnzs;
for (unsigned int i = p_startId; i < p_startId + l_chNnzs; ++i) {
l_nnzUnit = p_nnzUnits[i];
unsigned int l_rowId = l_nnzUnit.getRow();
unsigned int l_colId = l_nnzUnit.getCol();
l_chBlockDesp.m_minRowId = (l_chBlockDesp.m_minRowId > l_rowId) ? l_rowId : l_chBlockDesp.m_minRowId;
l_chBlockDesp.m_maxRowId = (l_chBlockDesp.m_maxRowId < l_rowId) ? l_rowId : l_chBlockDesp.m_maxRowId;
l_chBlockDesp.m_minColId = (l_chBlockDesp.m_minColId > l_colId) ? l_colId : l_chBlockDesp.m_minColId;
l_chBlockDesp.m_maxColId = (l_chBlockDesp.m_maxColId < l_colId) ? l_colId : l_chBlockDesp.m_maxColId;
}
l_chBlockDesp.m_rows = (l_chBlockDesp.m_maxRowId + 1) - l_chBlockDesp.m_minRowId;
l_chBlockDesp.m_cols = (l_chBlockDesp.m_maxColId + 1) - l_chBlockDesp.m_minColId;
l_chBlockDesp.m_nnzBlocks = alignedBlock(l_chBlockDesp.m_nnzs, t_ParEntries);
l_chBlockDesp.m_colBlocks = alignedBlock(l_chBlockDesp.m_cols, t_ParEntries);
l_chBlockDesp.m_rowBlocks = alignedBlock(l_chBlockDesp.m_rows, t_ParEntries * t_ParGroups);
l_chBlockDesp.m_rowResBlocks = alignedNum(l_chBlockDesp.m_rowBlocks * t_ParGroups, 2);
p_krnRowParDesp.minRowId() = (p_krnRowParDesp.minRowId() > l_chBlockDesp.m_minRowId)
? l_chBlockDesp.m_minRowId
: p_krnRowParDesp.minRowId();
p_krnRowParDesp.maxRowId() = (p_krnRowParDesp.maxRowId() < l_chBlockDesp.m_maxRowId)
? l_chBlockDesp.m_maxRowId
: p_krnRowParDesp.maxRowId();
p_krnRowParDesp.nnzs() = p_krnRowParDesp.nnzs() + l_chBlockDesp.m_nnzs;
p_krnRowParDesp.nnzBlocks() = p_krnRowParDesp.nnzBlocks() + l_chBlockDesp.m_nnzBlocks;
p_krnRowParDesp.addChBlockDesp(l_chBlockDesp);
p_colParDesp.m_minColId[p_chId] = l_chBlockDesp.m_minColId;
p_colParDesp.m_maxColId[p_chId] = l_chBlockDesp.m_maxColId;
p_colParDesp.m_cols[p_chId] = l_chBlockDesp.m_cols;
p_colParDesp.m_colBlocks[p_chId] = l_chBlockDesp.m_colBlocks;
p_colParDesp.m_nnzs[p_chId] = l_chBlockDesp.m_nnzs;
p_colParDesp.m_nnzBlocks[p_chId] = l_chBlockDesp.m_nnzBlocks;
p_colParDesp.m_parMinColId = (p_colParDesp.m_parMinColId > l_chBlockDesp.m_minColId)
? l_chBlockDesp.m_minColId
: p_colParDesp.m_parMinColId;
p_colParDesp.m_parMaxColId = (p_colParDesp.m_parMaxColId < l_chBlockDesp.m_maxColId)
? l_chBlockDesp.m_maxColId
: p_colParDesp.m_parMaxColId;
p_colParDesp.m_nnzColMemBlocks += p_colParDesp.m_colBlocks[p_chId];
p_startId = ((p_startId + p_nnzsPerCh) > l_nnzs) ? l_nnzs : (p_startId + p_nnzsPerCh);
}
void genMatPar(vector<t_NnzUnitType>& p_nnzUnits,
unsigned int p_rows,
unsigned int p_cols,
t_MatParType& p_matPar) {
p_matPar.init(p_rows, p_cols);
genRoCooPar(p_nnzUnits, p_matPar.roCooPar());
unsigned int l_rowPars = p_matPar.roCooPar().rowPars();
unsigned int l_colPars = p_matPar.roCooPar().colPars();
unsigned int l_matRows = p_matPar.roCooPar().rows();
unsigned int l_matCols = p_matPar.roCooPar().cols();
for (unsigned int ch = 0; ch < t_HbmChannels; ++ch) {
for (unsigned int i = 0; i < l_rowPars; ++i) {
p_matPar.krnRowParDesps(ch, i).minRowId() = l_matRows;
p_matPar.krnRowParDesps(ch, i).maxRowId() = 0;
p_matPar.krnRowParDesps(ch, i).rows() = 0;
p_matPar.krnRowParDesps(ch, i).nnzs() = 0;
p_matPar.krnRowParDesps(ch, i).nnzBlocks() = 0;
p_matPar.krnRowParDesps(ch, i).rowBlocks() = 0;
p_matPar.krnRowParDesps(ch, i).rowResBlocks() = 0;
}
}
for (unsigned int i = 0; i < l_rowPars; ++i) {
for (unsigned int j = 0; j < l_colPars; ++j) {
unsigned int l_parId = i * l_colPars + j;
unsigned int l_nnzs = p_matPar.roCooPar(l_parId).size();
unsigned int l_alignedNnzs = alignedNum(l_nnzs, t_HbmChannels);
unsigned int l_nnzsPerCh = l_alignedNnzs / t_HbmChannels;
unsigned int l_startId = 0;
p_matPar.krnColParDesp(l_parId).m_parMinColId = l_matCols;
p_matPar.krnColParDesp(l_parId).m_parMaxColId = 0;
p_matPar.krnColParDesp(l_parId).m_nnzColMemBlocks = 0;
for (unsigned int ch = 0; ch < t_HbmChannels; ++ch) {
genNextParDesp(p_matPar.roCooPar(l_parId), l_nnzsPerCh, ch, l_startId,
p_matPar.krnColParDesp(l_parId), p_matPar.krnRowParDesps(ch, i));
p_matPar.nnzBlocks()[ch] += p_matPar.krnRowParDesps(ch, i).nnzBlocks();
}
p_matPar.krnColParDesp(l_parId).m_nnzColMemBlocks =
alignedBlock(p_matPar.krnColParDesp(l_parId).m_nnzColMemBlocks, t_ParWordsPerMem);
unsigned int l_colBlocks = p_matPar.krnColParDesp(l_parId).m_parMinColId / t_ColsPerMem;
unsigned int l_colsInPar =
(l_nnzs == 0) ? 0 : p_matPar.krnColParDesp(l_parId).m_parMaxColId + 1 - l_colBlocks * t_ColsPerMem;
p_matPar.krnColParDesp(l_parId).m_colVecMemBlocks = alignedBlock(l_colsInPar, t_ColsPerMem);
if (p_matPar.krnColParDesp(l_parId).m_nnzColMemBlocks != 0) {
p_matPar.validPars() += 1;
}
}
}
for (unsigned int i = 0; i < l_rowPars; ++i) {
for (unsigned int ch = 0; ch < t_HbmChannels; ++ch) {
if (p_matPar.krnRowParDesps(ch, i).nnzs() != 0) {
p_matPar.validRowPars()[ch] += 1;
}
p_matPar.krnRowParDesps(ch, i).rows() =
(p_matPar.krnRowParDesps(ch, i).nnzs() == 0)
? 0
: p_matPar.krnRowParDesps(ch, i).maxRowId() + 1 - p_matPar.krnRowParDesps(ch, i).minRowId();
p_matPar.krnRowParDesps(ch, i).rowBlocks() =
alignedBlock(p_matPar.krnRowParDesps(ch, i).rows(), t_ParEntries * t_ParGroups);
p_matPar.krnRowParDesps(ch, i).rowResBlocks() =
alignedNum(p_matPar.krnRowParDesps(ch, i).rowBlocks() * t_ParGroups, 2);
p_matPar.rowResBlocks()[ch] += alignedNum(p_matPar.krnRowParDesps(ch, i).rowResBlocks(), 2);
}
}
}
};
template <typename t_DataType,
typename t_IndexType,
unsigned int t_MaxRowsPerPar,
unsigned int t_MaxColsPerPar,
unsigned int t_MaxParamDdrBlocks,
unsigned int t_MaxParamHbmBlocks,
unsigned int t_ParEntries,
unsigned int t_ParGroups,
unsigned int t_DdrMemBits,
unsigned int t_HbmMemBits,
unsigned int t_HbmChannels,
unsigned int t_ParamOffset = 1024,
unsigned int t_PageSize = 4096>
class GenRunConfig {
public:
static const unsigned int t_BytesPerHbmRd = t_HbmMemBits / 8;
static const unsigned int t_BytesPerDdrRd = t_DdrMemBits / 8;
static const unsigned int t_IntsPerDdrRd = t_DdrMemBits / (8 * sizeof(uint32_t));
static const unsigned int t_IntsPerHbmRd = t_HbmMemBits / (8 * sizeof(uint32_t));
static const unsigned int t_IntsPerColParam = 2 + t_HbmChannels * 2;
static const unsigned int t_DdrBlocks4ColParam = (t_IntsPerColParam + t_IntsPerDdrRd - 1) / t_IntsPerDdrRd;
static const unsigned int t_MaxColParams = t_MaxParamDdrBlocks / t_DdrBlocks4ColParam;
static const unsigned int t_IntsPerRwHbmParam = 4;
static const unsigned int t_HbmBlocks4HbmParam = (t_IntsPerRwHbmParam + t_IntsPerHbmRd - 1) / t_IntsPerHbmRd;
static const unsigned int t_MaxHbmParams = t_MaxParamHbmBlocks / t_HbmBlocks4HbmParam;
static const unsigned int t_DatasPerDdrRd = t_DdrMemBits / (8 * sizeof(t_DataType));
public:
typedef Program<t_PageSize> t_ProgramType;
typedef NnzUnit<t_DataType, t_IndexType> t_NnzUnitType;
typedef struct ParamColPtr<t_HbmChannels> t_ParamColPtrType;
typedef struct ParamColVec<t_HbmChannels> t_ParamColVecType;
typedef struct ParamRwHbm t_ParamRwHbmType;
typedef struct ChBlockDesp t_ChBlockDespType;
typedef struct ColParDesp<t_HbmChannels> t_ColParDespType;
typedef RoCooPar<t_DataType, t_IndexType, t_MaxRowsPerPar, t_MaxColsPerPar, t_HbmChannels> t_RoCooParType;
typedef KrnColParDesp<t_HbmChannels> t_KrnColParDespType;
typedef KrnRowParDesp<t_HbmChannels> t_KrnRowParDespType;
typedef MatPar<t_DataType, t_IndexType, t_MaxRowsPerPar, t_MaxColsPerPar, t_HbmChannels> t_MatParType;
typedef GenMatPar<t_DataType,
t_IndexType,
t_MaxRowsPerPar,
t_MaxColsPerPar,
t_ParEntries,
t_ParGroups,
t_DdrMemBits,
t_HbmChannels>
t_GenMatParType;
typedef RunConfig<t_DataType,
t_IndexType,
t_ParEntries,
t_ParGroups,
t_DdrMemBits,
t_HbmMemBits,
t_HbmChannels,
t_ParamOffset,
t_PageSize>
t_RunConfigType;
public:
GenRunConfig() {}
void genConfigParams(t_MatParType& p_matPar, t_RunConfigType& p_config) {
// generate host params
t_KrnColParDespType l_krnColParDesp = p_matPar.krnColParDesp();
p_config.krnColParDesp() = l_krnColParDesp;
for (unsigned int i = 0; i < t_HbmChannels; ++i) {
vector<t_KrnRowParDespType> l_krnRowParDesps = p_matPar.krnRowParDesps(i);
p_config.krnRowParDesps(i) = l_krnRowParDesps;
}
unsigned int l_rows = p_matPar.roCooPar().rows();
unsigned int l_cols = p_matPar.roCooPar().cols();
unsigned int l_nnzs = p_matPar.roCooPar().nnzs();
unsigned int l_rowPars = p_matPar.roCooPar().rowPars();
unsigned int l_colPars = p_matPar.roCooPar().colPars();
unsigned int l_totalPars = p_matPar.roCooPar().totalPars();
unsigned int l_validPars = p_matPar.validPars();
unsigned int* l_validRowPars = p_matPar.validRowPars();
unsigned int* l_nnzBlocks = p_matPar.nnzBlocks();
unsigned int* l_rowResBlocks = p_matPar.rowResBlocks();
p_config.rows() = l_rows;
p_config.cols() = l_cols;
p_config.nnzs() = l_nnzs;
p_config.rowPars() = l_rowPars;
p_config.colPars() = l_colPars;
p_config.totalPars() = l_totalPars;
p_config.validPars() = l_validPars;
p_config.nnzColMemBlocks() = 0;
for (unsigned int i = 0; i < t_HbmChannels; ++i) {
p_config.validRowPars()[i] = l_validRowPars[i];
p_config.nnzBlocks()[i] = l_nnzBlocks[i];
p_config.rowResBlocks()[i] = l_rowResBlocks[i];
}
for (unsigned int i = 0; i < l_totalPars; ++i) {
p_config.nnzColMemBlocks() += p_config.krnColParDesp()[i].m_nnzColMemBlocks;
}
}
void genConfigMem(t_ProgramType& p_program, t_RunConfigType& p_config) {
unsigned int l_validPars = p_config.validPars();
unsigned int l_colPtrParamBlocks = l_validPars * t_DdrBlocks4ColParam;
p_config.colPtrParamBlocks() = l_colPtrParamBlocks;
p_config.colVecParamBlocks() = l_colPtrParamBlocks;
unsigned long long l_colPtrSz =
(l_colPtrParamBlocks + p_config.nnzColMemBlocks()) * t_BytesPerDdrRd + t_ParamOffset;
unsigned long long l_colVecSz = t_ParamOffset + l_colPtrParamBlocks * t_BytesPerDdrRd +
alignedNum(p_config.cols(), t_DatasPerDdrRd) * sizeof(t_DataType);
p_config.setColPtrAddr(p_program.allocMem(l_colPtrSz));
p_config.setColVecAddr(p_program.allocMem(l_colVecSz));
for (unsigned int i = 0; i < t_HbmChannels; ++i) {
unsigned int l_paramBlocks = p_config.validRowPars()[i] * t_HbmBlocks4HbmParam;
p_config.paramBlocks()[i] = l_paramBlocks;
unsigned long long l_rdHbmSz = t_ParamOffset + (l_paramBlocks + p_config.nnzBlocks()[i]) * t_BytesPerHbmRd;
p_config.setRdHbmAddr(p_program.allocMem(l_rdHbmSz), i);
unsigned long long l_wrHbmSz = p_config.rowResBlocks()[i] * t_ParEntries * sizeof(t_DataType);
p_config.setWrHbmAddr(p_program.allocMem(l_wrHbmSz), i);
p_config.setRefHbmAddr(p_program.allocMem(l_wrHbmSz), i);
}
}
void genCscFromNnzUnits(vector<t_NnzUnitType>& p_nnzUnits,
unsigned int p_minRowId,
unsigned int p_minColId,
vector<t_DataType>& p_val,
vector<t_IndexType>& p_rowIdx,
vector<t_IndexType>& p_colPtr) {
sort(p_nnzUnits.begin(), p_nnzUnits.end());
unsigned l_nnzs = p_nnzUnits.size();
for (unsigned int i = 0; i < l_nnzs; ++i) {
p_val[i] = p_nnzUnits[i].getVal();
p_rowIdx[i] = p_nnzUnits[i].getRow() - p_minRowId;
unsigned int l_colId = p_nnzUnits[i].getCol();
p_colPtr[l_colId - p_minColId]++;
}
for (unsigned int i = 1; i < p_colPtr.size(); ++i) {
p_colPtr[i] += p_colPtr[i - 1];
}
}
void genCsc(vector<t_NnzUnitType>& p_nnzUnits,
t_ChBlockDespType& p_desp,
unsigned int p_minRowId,
vector<t_DataType>& p_val,
vector<t_IndexType>& p_rowIdx,
vector<t_IndexType>& p_colPtr) {
unsigned int l_startId = p_desp.m_startId;
unsigned int l_minColId = p_desp.m_minColId;
unsigned int l_colBlocks = p_desp.m_colBlocks;
unsigned int l_nnzs = p_desp.m_nnzs;
unsigned int l_nnzBlocks = p_desp.m_nnzBlocks;
unsigned int l_valIdxSize = l_nnzBlocks * t_ParEntries;
unsigned int l_colPtrSize = l_colBlocks * t_ParEntries;
vector<t_NnzUnitType> l_nnzUnits(p_nnzUnits.begin() + l_startId, p_nnzUnits.begin() + l_startId + l_nnzs);
assert(l_nnzUnits.size() == l_nnzs);
p_val.resize(l_valIdxSize);
p_rowIdx.resize(l_valIdxSize);
p_colPtr.resize(l_colPtrSize, 0);
genCscFromNnzUnits(l_nnzUnits, p_minRowId, l_minColId, p_val, p_rowIdx, p_colPtr);
for (unsigned int i = l_nnzs; i < l_valIdxSize; ++i) {
p_val[i] = 0;
p_rowIdx[i] = p_rowIdx[l_nnzs - 1];
}
unsigned int l_cols = p_desp.m_cols;
for (unsigned int i = l_cols; i < l_colPtrSize; ++i) {
p_colPtr[i] = l_valIdxSize;
}
if ((l_cols == l_colPtrSize) && (l_cols != 0)) {
p_colPtr[l_cols - 1] = l_valIdxSize;
}
}
void genRowRes(vector<t_NnzUnitType>& p_nnzUnits,
vector<t_DataType>& p_inVec,
t_ChBlockDespType& p_desp,
unsigned int p_minRowId,
vector<t_DataType>& p_res) {
unsigned int l_startId = p_desp.m_startId;
unsigned int l_nnzs = p_desp.m_nnzs;
for (unsigned int i = 0; i < l_nnzs; ++i) {
t_NnzUnitType l_nnzUnit = p_nnzUnits[i + l_startId];
t_IndexType l_rowId = l_nnzUnit.getRow();
t_IndexType l_colId = l_nnzUnit.getCol();
t_DataType l_val = l_nnzUnit.getVal();
t_DataType l_mulVal = l_val * p_inVec[l_colId];
p_res[l_rowId - p_minRowId] += l_mulVal;
}
}
void setColPtrParamMem(t_ColParDespType& p_desp,
unsigned int& p_offset,
vector<t_ParamColPtrType>& p_paramColPtr,
void*& p_colPtrParamAddr) {
t_ParamColPtrType l_param;
l_param.m_offset = p_offset;
l_param.m_memBlocks = p_desp.m_nnzColMemBlocks;
for (unsigned int i = 0; i < t_HbmChannels; ++i) {
l_param.m_parBlocks[i] = p_desp.m_colBlocks[i];
l_param.m_nnzBlocks[i] = p_desp.m_nnzBlocks[i];
}
p_paramColPtr.push_back(l_param);
memcpy(reinterpret_cast<char*>(p_colPtrParamAddr), reinterpret_cast<char*>(&l_param), sizeof(l_param));
p_colPtrParamAddr = reinterpret_cast<char*>(p_colPtrParamAddr) + t_DdrBlocks4ColParam * t_BytesPerDdrRd;
p_offset += p_desp.m_nnzColMemBlocks;
}
void setColVecParamMem(t_ColParDespType& p_desp,
unsigned int& p_offset,
vector<t_ParamColVecType>& p_paramColVec,
void*& p_colVecParamAddr) {
unsigned int l_parMinBlockId = p_desp.m_parMinColId / t_DatasPerDdrRd;
t_ParamColVecType l_param;
l_param.m_offset = p_offset;
l_param.m_memBlocks = p_desp.m_colVecMemBlocks;
for (unsigned int i = 0; i < t_HbmChannels; ++i) {
l_param.m_minId[i] = (p_desp.m_minColId[i] < p_desp.m_parMinColId)
? p_desp.m_minColId[i]
: p_desp.m_minColId[i] - (l_parMinBlockId * t_DatasPerDdrRd);
l_param.m_maxId[i] = (p_desp.m_maxColId[i] < p_desp.m_parMinColId)
? p_desp.m_maxColId[i]
: p_desp.m_maxColId[i] - (l_parMinBlockId * t_DatasPerDdrRd);
}
p_paramColVec.push_back(l_param);
memcpy(reinterpret_cast<char*>(p_colVecParamAddr), reinterpret_cast<char*>(&l_param), sizeof(l_param));
p_colVecParamAddr = reinterpret_cast<char*>(p_colVecParamAddr) + t_DdrBlocks4ColParam * t_BytesPerDdrRd;
p_offset += p_desp.m_colVecMemBlocks;
}
void setColPtrDatMem(vector<t_IndexType>& p_colPtr, void*& p_colPtrDatAddr) {
unsigned long long l_colPtrSz = p_colPtr.size() * sizeof(t_IndexType);
memcpy(reinterpret_cast<char*>(p_colPtrDatAddr), reinterpret_cast<char*>(p_colPtr.data()), l_colPtrSz);
p_colPtrDatAddr = reinterpret_cast<char*>(p_colPtrDatAddr) + l_colPtrSz;
}
void setHbmDatMem(vector<t_DataType>& p_nnzVal, vector<t_IndexType>& p_rowIdx, void*& p_rdHbmDatAddr) {
unsigned int l_nnzs = p_nnzVal.size();
unsigned int l_nnzBlocks = l_nnzs / t_ParEntries;
for (unsigned int i = 0; i < l_nnzBlocks; ++i) {
memcpy(reinterpret_cast<char*>(p_rdHbmDatAddr), reinterpret_cast<char*>(&(p_rowIdx[i * t_ParEntries])),
t_ParEntries * sizeof(t_IndexType));
p_rdHbmDatAddr = reinterpret_cast<char*>(p_rdHbmDatAddr) + t_ParEntries * sizeof(t_IndexType);
memcpy(reinterpret_cast<char*>(p_rdHbmDatAddr), reinterpret_cast<char*>(&(p_nnzVal[i * t_ParEntries])),
t_ParEntries * sizeof(t_DataType));
p_rdHbmDatAddr = reinterpret_cast<char*>(p_rdHbmDatAddr) + t_ParEntries * sizeof(t_DataType);
}
}
void setRefHbmMem(void* p_refHbmAddr,
unsigned int p_wrOffset,
vector<t_DataType>& p_res,
t_KrnRowParDespType& p_desp) {
unsigned int l_rows = p_desp.rows();
unsigned int l_sz = l_rows * sizeof(t_DataType);
unsigned int l_byteOffset = p_wrOffset * t_BytesPerHbmRd;
char* l_wrAddr = reinterpret_cast<char*>(p_refHbmAddr) + l_byteOffset;
memcpy(l_wrAddr, reinterpret_cast<char*>(p_res.data()), l_sz);
}
void setHbmParamMem(t_KrnRowParDespType& p_desp,
unsigned int& p_rdOffset,
unsigned int& p_wrOffset,
vector<t_ParamRwHbmType>& p_param,
void*& p_rdHbmParamAddr) {
unsigned int l_nnzBlocks = p_desp.nnzBlocks();
unsigned int l_rowBlocks = p_desp.rowBlocks();
unsigned int l_rowResBlocks = p_desp.rowResBlocks();
if (l_nnzBlocks != 0) {
t_ParamRwHbmType l_param;
l_param.m_rdOffset = p_rdOffset;
l_param.m_wrOffset = p_wrOffset;
l_param.m_nnzBlocks = l_nnzBlocks;
l_param.m_rowBlocks = l_rowBlocks;
p_param.push_back(l_param);
memcpy(reinterpret_cast<char*>(p_rdHbmParamAddr), reinterpret_cast<char*>(&l_param), sizeof(l_param));
p_rdHbmParamAddr = reinterpret_cast<char*>(p_rdHbmParamAddr) + t_HbmBlocks4HbmParam * t_BytesPerHbmRd;
p_rdOffset += l_nnzBlocks;
p_wrOffset += alignedBlock(l_rowResBlocks, 2);
}
}
void setConfigMem(t_RoCooParType& p_par, vector<t_DataType>& p_inVec, t_RunConfigType& p_config) {
memcpy(reinterpret_cast<char*>(p_config.getColPtrAddr()),
reinterpret_cast<char*>(&(p_config.colPtrParamBlocks())), sizeof(uint32_t));
memcpy(reinterpret_cast<char*>(p_config.getColVecAddr()),
reinterpret_cast<char*>(&(p_config.colVecParamBlocks())), sizeof(uint32_t));
for (unsigned int i = 0; i < t_HbmChannels; ++i) {
memcpy(reinterpret_cast<char*>(p_config.getRdHbmAddr(i)),
reinterpret_cast<char*>(&(p_config.paramBlocks()[i])), sizeof(uint32_t));
}
unsigned int l_rowPars = p_config.rowPars();
unsigned int l_colPars = p_config.colPars();
void* l_colPtrParamAddr = reinterpret_cast<char*>(p_config.getColPtrAddr()) + t_ParamOffset;
void* l_colPtrDatAddr =
reinterpret_cast<char*>(l_colPtrParamAddr) + p_config.validPars() * t_DdrBlocks4ColParam * t_BytesPerDdrRd;
void* l_colVecParamAddr = reinterpret_cast<char*>(p_config.getColVecAddr()) + t_ParamOffset;
void* l_colVecDatAddr =
reinterpret_cast<char*>(l_colVecParamAddr) + p_config.validPars() * t_DdrBlocks4ColParam * t_BytesPerDdrRd;
assert(p_inVec.size() == p_config.cols());
unsigned long long l_colVecSz = p_config.cols() * sizeof(t_DataType);
memcpy(reinterpret_cast<char*>(l_colVecDatAddr), reinterpret_cast<char*>(p_inVec.data()), l_colVecSz);
void* l_rdHbmParamAddr[t_HbmChannels];
void* l_rdHbmDatAddr[t_HbmChannels];
unsigned int l_rdOffset[t_HbmChannels];
unsigned int l_wrOffset[t_HbmChannels];
unsigned int l_colPtrMemBlockOffset =
(t_ParamOffset / t_BytesPerDdrRd) + p_config.validPars() * t_DdrBlocks4ColParam;
unsigned int l_colVecMemBlockOffset = l_colPtrMemBlockOffset;
for (unsigned int i = 0; i < t_HbmChannels; ++i) {
void* l_addr = p_config.getRdHbmAddr(i);
l_rdHbmParamAddr[i] = reinterpret_cast<char*>(l_addr) + t_ParamOffset;
l_rdHbmDatAddr[i] = reinterpret_cast<char*>(l_rdHbmParamAddr[i]) +
p_config.validRowPars()[i] * t_HbmBlocks4HbmParam * t_BytesPerHbmRd;
l_rdOffset[i] = (t_ParamOffset / t_BytesPerHbmRd) + p_config.validRowPars()[i] * t_HbmBlocks4HbmParam;
l_wrOffset[i] = 0;
}
for (unsigned int i = 0; i < l_rowPars; ++i) {
vector<t_DataType> l_rowRes[t_HbmChannels];
for (unsigned int ch = 0; ch < t_HbmChannels; ++ch) {
l_rowRes[ch].resize(p_config.rows(), 0);
}
for (unsigned int j = 0; j < l_colPars; ++j) {
unsigned int l_parId = i * l_colPars + j;
if (p_par[l_parId].size() != 0) {
setColPtrParamMem(p_config.krnColParDesp(l_parId), l_colPtrMemBlockOffset, p_config.paramColPtr(),
l_colPtrParamAddr);
setColVecParamMem(p_config.krnColParDesp(l_parId), l_colVecMemBlockOffset, p_config.paramColVec(),
l_colVecParamAddr);
void* l_blockColPtrDatAddr = l_colPtrDatAddr;
for (unsigned int ch = 0; ch < t_HbmChannels; ++ch) {
vector<t_DataType> l_nnzVal;
vector<t_IndexType> l_rowIdx;
vector<t_IndexType> l_colPtr;
unsigned int l_minRowId = p_config.krnRowParDesps(ch, i).minRowId();
t_ChBlockDespType l_chBlockDesp = p_config.krnRowParDesps(ch, i)[j];
if (l_chBlockDesp.m_nnzs == 0) {
continue;
}
genCsc(p_par[l_parId], l_chBlockDesp, l_minRowId, l_nnzVal, l_rowIdx, l_colPtr);
genRowRes(p_par[l_parId], p_inVec, l_chBlockDesp, l_minRowId, l_rowRes[ch]);
setColPtrDatMem(l_colPtr, l_blockColPtrDatAddr);
setHbmDatMem(l_nnzVal, l_rowIdx, l_rdHbmDatAddr[ch]);
}
l_colPtrDatAddr = reinterpret_cast<char*>(l_colPtrDatAddr) +
p_config.krnColParDesp(l_parId).m_nnzColMemBlocks * t_BytesPerDdrRd;
}
}
for (unsigned int ch = 0; ch < t_HbmChannels; ++ch) {
setRefHbmMem(p_config.getRefHbmAddr(ch), l_wrOffset[ch], l_rowRes[ch], p_config.krnRowParDesps(ch, i));
setHbmParamMem(p_config.krnRowParDesps(ch, i), l_rdOffset[ch], l_wrOffset[ch], p_config.paramRwHbm(ch),
l_rdHbmParamAddr[ch]);
}
}
}
void genRunConfig(t_ProgramType& p_program,
vector<t_NnzUnitType>& p_nnzUnits,
vector<t_DataType>& p_inVec,
unsigned int l_rows,
unsigned int l_cols,
t_RunConfigType& p_config) {
t_GenMatParType l_genMatPar;
t_MatParType l_matPar;
l_genMatPar.genMatPar(p_nnzUnits, l_rows, l_cols, l_matPar);
genConfigParams(l_matPar, p_config);
genConfigMem(p_program, p_config);
setConfigMem(l_matPar.roCooPar(), p_inVec, p_config);
}
};
} // end namespace sparse
} // end namespace xf
#endif
| 49.129073 | 119 | 0.612626 | [
"vector"
] |
9be20dc2705be8241f84ad8e4e1b12935ef68021 | 5,828 | cpp | C++ | main.cpp | rajvirsamrai/SmolRenderer | cfd55b7e2c636db9b98ef4cc325eeb4c60cdc3d2 | [
"BSD-2-Clause"
] | null | null | null | main.cpp | rajvirsamrai/SmolRenderer | cfd55b7e2c636db9b98ef4cc325eeb4c60cdc3d2 | [
"BSD-2-Clause"
] | null | null | null | main.cpp | rajvirsamrai/SmolRenderer | cfd55b7e2c636db9b98ef4cc325eeb4c60cdc3d2 | [
"BSD-2-Clause"
] | null | null | null | #include "image.h"
#include "model.h"
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <utility>
extern void line(int x0, int y0, int x1, int y1, Colour &c, Image &i);
extern void wireframe(Model &obj, Colour &c, Image &img);
extern void flat_shade_render(Model &obj, Image &img);
extern void triangle_ls(int x0, int y0, int x1, int y1, int x2, int y2, Colour &c, Image &img);
extern void triangle_bb(int x0, int y0, int x1, int y1, int x2, int y2, Colour &c, Image &img);
// TODO: MAKE A GEOMETRY CLASS
const int height = 800;
const int width = 800;
int main(int argc, char** argv){
if(argc != 2){
std::cerr << "usage: " << argv[0] << " FILENAME" << "\n";
}
Image render(height, width);
Model head;
head.load(argv[1]);
flat_shade_render(head, render);
render.save("test.tga");
}
void flat_shade_render(Model &obj, Image &img){
Face f;
Colour c(0, 0, 0);
for(int i = 0; i < (int) obj.faces.size(); i++){
f = obj.faces[i];
Vec3 v0 = obj.vertices[f.v[0] - 1];
Vec3 v1 = obj.vertices[f.v[1] - 1];
Vec3 v2 = obj.vertices[f.v[2] - 1];
int x0 = (v0.x + 1.0) * width/2.0;
int y0 = (v0.y + 1.0) * height/2.0;
int x1 = (v1.x + 1.0) * width/2.0;
int y1 = (v1.y + 1.0) * height/2.0;
int x2 = (v2.x + 1.0) * width/2.0;
int y2 = (v2.y + 1.0) * height/2.0;
for(int i = 0; i < 3; i++){
c.rgb[i] = rand()%255;
}
triangle_bb(x0, y0, x1, y1, x2, y2, c, img);
}
}
Vec3 cross(float Vx, float Vy, float Vz, float Wx, float Wy, float Wz){
return Vec3(Vy*Wz - Vz*Wy, Vz*Wx - Vx*Wz, Vx*Wy - Vy*Wx);
}
bool in_bounding_box(int x0, int y0, int x1, int y1, int x2, int y2, int Px, int Py){
// Let x0/y0 be A, x1/y1 be B, x2/y2 be C
int ABx = x1 - x0;
int ACx = x2 - x0;
int PAx = x0 - Px;
int ABy = y1 - y0;
int ACy = y2 - y0;
int PAy = y0 - Py;
Vec3 bc_cords = cross(ABx, ACx, PAx, ABy, ACy, PAy);
// Check if triangle is degenerate
if(std::abs(bc_cords.z) < 1){
return false;
}
float a = 1.0 - (bc_cords.x + bc_cords.y)/bc_cords.z;
float b = bc_cords.y/bc_cords.z;
float c = bc_cords.x/bc_cords.z;
return (0 <= a && 0 <= b && 0 <= c);
}
void triangle_bb(int x0, int y0, int x1, int y1, int x2, int y2, Colour &c, Image &img){
int bb_min_x = std::max(std::min(std::min(x0, x1), x2), 0);
int bb_min_y = std::max(std::min(std::min(y0, y1), y2), 0);
int bb_max_x = std::min(std::max(std::max(x0, x1), x2), img.width);
int bb_max_y = std::min(std::max(std::max(y0, y1), y2), img.height);
for(int x = bb_min_x; x <= bb_max_x; x++){
for(int y = bb_min_y; y <= bb_max_y; y++){
if(in_bounding_box(x0, y0, x1, y1, x2, y2, x, y)){
img.set(x, y, c);
}
}
}
return;
}
void triangle_ls(int x0, int y0, int x1, int y1, int x2, int y2, Colour &c, Image &img){
if(y0 < y1){
std::swap(x0, x1);
std::swap(y0, y1);
}
if(y0 < y2){
std::swap(x0, x2);
std::swap(y0, y2);
}
if(y1 < y2){
std::swap(x1, x2);
std::swap(y1, y2);
}
int total_height = y0 - y2 + 1;
int short_side_a_height = y1 - y2 + 1;
int short_side_b_height = y0 - y1 + 1;
float tallest_side_progress;
float short_side_progress;
int x_left_bound;
int x_right_bound;
for(int y = y2; y <= y0; y++){
tallest_side_progress = (float) (y - y2)/total_height;
x_left_bound = tallest_side_progress*(x0 - x2) + x2;
if(y <= y1){
short_side_progress = (float) (y-y2)/short_side_a_height;
x_right_bound = x2 + short_side_progress*(x1 - x2);
} else {
short_side_progress = (float) (y-y1)/short_side_b_height;
x_right_bound = x1 + short_side_progress*(x0 - x1);
}
line(x_left_bound, y, x_right_bound, y, c, img);
}
return;
}
void wireframe(Model &obj, Colour &c, Image &img){
Face f;
for(int i = 0; i < (int) obj.faces.size(); i++){
f = obj.faces[i];
Vec3 v0 = obj.vertices[f.v[0] - 1];
Vec3 v1 = obj.vertices[f.v[1] - 1];
Vec3 v2 = obj.vertices[f.v[2] - 1];
int x0 = (v0.x + 1.0) * width/2.0;
int y0 = (v0.y + 1.0) * height/2.0;
int x1 = (v1.x + 1.0) * width/2.0;
int y1 = (v1.y + 1.0) * height/2.0;
int x2 = (v2.x + 1.0) * width/2.0;
int y2 = (v2.y + 1.0) * height/2.0;
line(x0, y0, x1, y1, c, img);
line(x0, y0, x2, y2, c, img);
line(x1, y1, x2, y2, c, img);
}
}
void line(int x0, int y0, int x1, int y1, Colour &c, Image &i){
bool transposed = false;
if(std::abs(x0 - x1) < std::abs(y0 - y1)){ // Transpose because we want the "longer" side to "stretch across" the X axis
std::swap(x0, y0);
std::swap(x1, y1);
transposed = true;
}
if(x1 < x0){ // We want to progress from left to right
std::swap(x0, x1);
std::swap(y0, y1);
}
int dy = y1-y0;
int dx = x1-x0;
int derror = std::abs(dy)*2;
int error = 0;
int y = y0;
int yinc = (y1 > y0) ? 1 : -1;
if(transposed){ // Moved the if statement outside the for loop
for(int x = x0; x <= x1; x++){
i.set(y, x, c);
error += derror;
if(error > dx){
y += yinc;
error -= dx*2;
}
}
} else {
for(int x = x0; x <= x1; x++){
i.set(x, y, c);
error += derror;
if(error > dx){
y += yinc;
error -= dx*2;
}
}
}
} | 27.361502 | 129 | 0.50652 | [
"geometry",
"render",
"model"
] |
9be3c5846bf44cd52d187d46c1444f6eec4f1aee | 3,343 | cpp | C++ | apps/3dscanx/main.cpp | jaeh/OpenLiDAR | 3d0559c2b153dfb815f9e43732bb4a757c89b39d | [
"BSD-3-Clause"
] | 144 | 2020-03-22T03:24:26.000Z | 2022-03-21T23:09:06.000Z | apps/3dscanx/main.cpp | jaeh/OpenLiDAR | 3d0559c2b153dfb815f9e43732bb4a757c89b39d | [
"BSD-3-Clause"
] | 1 | 2020-07-23T12:04:13.000Z | 2020-07-23T12:04:13.000Z | apps/3dscanx/main.cpp | jaeh/OpenLiDAR | 3d0559c2b153dfb815f9e43732bb4a757c89b39d | [
"BSD-3-Clause"
] | 14 | 2020-03-24T03:36:13.000Z | 2021-12-12T16:09:51.000Z | #include "OpenLiDAR.h"
#include "ada/window.h"
#include "ada/gl/gl.h"
#include "ada/gl/mesh.h"
#include "ada/gl/shader.h"
ada::Mesh rect (float _x, float _y, float _w, float _h) {
float x = _x-1.0f;
float y = _y-1.0f;
float w = _w*2.0f;
float h = _h*2.0f;
ada::Mesh mesh;
mesh.addVertex(glm::vec3(x, y, 0.0));
// mesh.addColor(glm::vec4(1.0));
// mesh.addNormal(glm::vec3(0.0, 0.0, 1.0));
mesh.addTexCoord(glm::vec2(0.0, 0.0));
mesh.addVertex(glm::vec3(x+w, y, 0.0));
// mesh.addColor(glm::vec4(1.0));
// mesh.addNormal(glm::vec3(0.0, 0.0, 1.0));
mesh.addTexCoord(glm::vec2(1.0, 0.0));
mesh.addVertex(glm::vec3(x+w, y+h, 0.0));
// mesh.addColor(glm::vec4(1.0));
// mesh.addNormal(glm::vec3(0.0, 0.0, 1.0));
mesh.addTexCoord(glm::vec2(1.0, 1.0));
mesh.addVertex(glm::vec3(x, y+h, 0.0));
// mesh.addColor(glm::vec4(1.0));
// mesh.addNormal(glm::vec3(0.0, 0.0, 1.0));
mesh.addTexCoord(glm::vec2(0.0, 1.0));
mesh.addIndex(0); mesh.addIndex(1); mesh.addIndex(2);
mesh.addIndex(2); mesh.addIndex(3); mesh.addIndex(0);
return mesh;
}
const std::string vert = R"(
#ifdef GL_ES
precision mediump float;
#endif
attribute vec4 a_position;
attribute vec2 a_texcoord;
varying vec4 v_position;
varying vec2 v_texcoord;
void main(void) {
v_position = a_position;
v_texcoord = a_texcoord;
gl_Position = v_position;
}
)";
const std::string frag = R"(
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
uniform float u_time;
varying vec2 v_texcoord;
void main(void) {
vec3 color = vec3(1.0);
vec2 st = gl_FragCoord.xy/u_resolution.xy;
st = v_texcoord;
color = vec3(st.x,st.y,abs(sin(u_time)));
gl_FragColor = vec4(color, 1.0);
}
)";
// Main program
//============================================================================
int main(int argc, char **argv){
OpenLiDAR scanner;
OpenLiDARSettings settings;
std::string filename = "pcl.ply";
float toDegree = 359.0f; // Full loop
float atSpeed = 0.75f; // 75% of speed
// Initialize openGL context
ada::initGL(argc, argv);
glm::ivec2 screenSize = ada::getScreenSize();
ada::setWindowSize(screenSize.x, screenSize.y);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
ada::Vbo* billboard_vbo = rect(0.0,0.0,1.0,1.0).getVbo();
ada::Shader shader;
shader.load(frag, vert);
shader.use();
// Render Loop
while( ada::isGL() ) {
glClear(GL_COLOR_BUFFER_BIT);
// Update
ada::updateGL();
shader.setUniform("u_resolution", (float)ada::getWindowWidth(), (float)ada::getWindowHeight() );
shader.setUniform("u_time", (float)ada::getTime());
billboard_vbo->render( &shader );
ada::renderGL();
ada::updateViewport();
}
ada::closeGL();
return 0;
}
// Events
//============================================================================
void ada::onKeyPress (int _key) {
}
void ada::onMouseMove(float _x, float _y) {
}
void ada::onMouseClick(float _x, float _y, int _button) {
}
void ada::onScroll(float _yoffset) {
}
void ada::onMouseDrag(float _x, float _y, int _button) {
}
void ada::onViewportResize(int _newWidth, int _newHeight) {
} | 23.377622 | 104 | 0.589889 | [
"mesh",
"render"
] |
9bebf3c1bbfe2a0de398e6310584be217ed37fdd | 23,330 | cpp | C++ | openbr/plugins/stream.cpp | vollingerm/openbr | 3d52092c9ef07ff6767afdbf50011fc476ce1bc9 | [
"Apache-2.0"
] | 2 | 2016-04-12T08:11:30.000Z | 2016-08-10T03:48:31.000Z | openbr/plugins/stream.cpp | vollingerm/openbr | 3d52092c9ef07ff6767afdbf50011fc476ce1bc9 | [
"Apache-2.0"
] | null | null | null | openbr/plugins/stream.cpp | vollingerm/openbr | 3d52092c9ef07ff6767afdbf50011fc476ce1bc9 | [
"Apache-2.0"
] | null | null | null | #include <QReadWriteLock>
#include <QWaitCondition>
#include <QThreadPool>
#include <QSemaphore>
#include <QMap>
#include <opencv/highgui.h>
#include <QtConcurrent>
#include "openbr_internal.h"
#include "openbr/core/common.h"
#include "openbr/core/opencvutils.h"
#include "openbr/core/qtutils.h"
using namespace cv;
namespace br
{
class FrameData
{
public:
int sequenceNumber;
TemplateList data;
};
// A buffer shared between adjacent processing stages in a stream
class SharedBuffer
{
public:
SharedBuffer() {}
virtual ~SharedBuffer() {}
virtual void addItem(FrameData * input)=0;
virtual FrameData * tryGetItem()=0;
};
// for n - 1 boundaries, multiple threads call addItem, the frames are
// sequenced based on FrameData::sequence_number, and calls to getItem
// receive them in that order
class SequencingBuffer : public SharedBuffer
{
public:
SequencingBuffer()
{
next_target = 0;
}
void addItem(FrameData * input)
{
QMutexLocker bufferLock(&bufferGuard);
buffer.insert(input->sequenceNumber, input);
}
FrameData * tryGetItem()
{
QMutexLocker bufferLock(&bufferGuard);
if (buffer.empty() || buffer.begin().key() != this->next_target) {
return NULL;
}
QMap<int, FrameData *>::Iterator result = buffer.begin();
if (next_target != result.value()->sequenceNumber) {
qFatal("mismatched targets!");
}
next_target = next_target + 1;
FrameData * output = result.value();
buffer.erase(result);
return output;
}
private:
QMutex bufferGuard;
int next_target;
QMap<int, FrameData *> buffer;
};
// For 1 - 1 boundaries, a double buffering scheme
// Producer/consumer read/write from separate buffers, and switch if their
// buffer runs out/overflows. Synchronization is handled by a read/write lock
// threads are "reading" if they are adding to/removing from their individual
// buffer, and writing if they access or swap with the other buffer.
class DoubleBuffer : public SharedBuffer
{
public:
DoubleBuffer()
{
inputBuffer = &buffer1;
outputBuffer = &buffer2;
}
// called from the producer thread
void addItem(FrameData * input)
{
QReadLocker readLock(&bufferGuard);
inputBuffer->append(input);
}
FrameData * tryGetItem()
{
QReadLocker readLock(&bufferGuard);
// There is something for us to get
if (!outputBuffer->empty()) {
FrameData * output = outputBuffer->first();
outputBuffer->removeFirst();
return output;
}
// Outputbuffer is empty, try to swap with the input buffer, we need a
// write lock to do that.
readLock.unlock();
QWriteLocker writeLock(&bufferGuard);
// Nothing on the input buffer either?
if (inputBuffer->empty()) {
return NULL;
}
// input buffer is non-empty, so swap the buffers
std::swap(inputBuffer, outputBuffer);
// Return a frame
FrameData * output = outputBuffer->first();
outputBuffer->removeFirst();
return output;
}
private:
// The read-write lock. The thread adding to this buffer can add
// to the current input buffer if it has a read lock. The thread
// removing from this buffer can remove things from the current
// output buffer if it has a read lock, or swap the buffers if it
// has a write lock.
QReadWriteLock bufferGuard;
// The buffer that is currently being added to
QList<FrameData *> * inputBuffer;
// The buffer that is currently being removed from
QList<FrameData *> * outputBuffer;
// The buffers pointed at by inputBuffer/outputBuffer
QList<FrameData *> buffer1;
QList<FrameData *> buffer2;
};
// Interface for sequentially getting data from some data source.
// Initialized off of a template, can represent a video file (stored in the template's filename)
// or a set of images already loaded into memory stored as multiple matrices in an input template.
class DataSource
{
public:
DataSource(int maxFrames=500)
{
final_frame = -1;
last_issued = -2;
last_received = -3;
for (int i=0; i < maxFrames;i++)
{
allFrames.addItem(new FrameData());
}
}
virtual ~DataSource()
{
while (true)
{
FrameData * frame = allFrames.tryGetItem();
if (frame == NULL)
break;
delete frame;
}
}
// non-blocking version of getFrame
FrameData * tryGetFrame()
{
FrameData * aFrame = allFrames.tryGetItem();
if (aFrame == NULL)
return NULL;
aFrame->data.clear();
aFrame->sequenceNumber = -1;
bool res = getNext(*aFrame);
// The datasource broke.
if (!res) {
allFrames.addItem(aFrame);
QMutexLocker lock(&last_frame_update);
// Did we already receive the last frame?
final_frame = last_issued;
// We got the last frame before the data source broke,
// better pulse lastReturned
if (final_frame == last_received) {
lastReturned.wakeAll();
}
else if (final_frame < last_received)
std::cout << "Bad last frame " << final_frame << " but received " << last_received << std::endl;
return NULL;
}
last_issued = aFrame->sequenceNumber;
return aFrame;
}
// Returns true if the frame returned was the last
// frame issued, false otherwise
bool returnFrame(FrameData * inputFrame)
{
allFrames.addItem(inputFrame);
bool rval = false;
QMutexLocker lock(&last_frame_update);
last_received = inputFrame->sequenceNumber;
if (inputFrame->sequenceNumber == final_frame) {
// We just received the last frame, better pulse
lastReturned.wakeAll();
rval = true;
}
return rval;
}
void waitLast()
{
QMutexLocker lock(&last_frame_update);
lastReturned.wait(&last_frame_update);
}
virtual void close() = 0;
virtual bool open(Template & output) = 0;
virtual bool isOpen() = 0;
virtual bool getNext(FrameData & input) = 0;
protected:
DoubleBuffer allFrames;
int final_frame;
int last_issued;
int last_received;
QWaitCondition lastReturned;
QMutex last_frame_update;
};
// Read a video frame by frame using cv::VideoCapture
class VideoDataSource : public DataSource
{
public:
VideoDataSource(int maxFrames) : DataSource(maxFrames) {}
bool open(Template &input)
{
final_frame = -1;
last_issued = -2;
last_received = -3;
next_idx = 0;
basis = input;
bool is_int = false;
int anInt = input.file.name.toInt(&is_int);
if (is_int)
{
bool rc = video.open(anInt);
if (!rc)
{
qDebug("open failed!");
}
if (!video.isOpened())
{
qDebug("Video not open!");
}
}
else video.open(input.file.name.toStdString());
return video.isOpened();
}
bool isOpen() { return video.isOpened(); }
void close() {
video.release();
}
private:
bool getNext(FrameData & output)
{
if (!isOpen())
return false;
output.data.append(Template(basis.file));
output.data.last().append(cv::Mat());
output.sequenceNumber = next_idx;
next_idx++;
bool res = video.read(output.data.last().last());
output.data.last().last() = output.data.last().last().clone();
if (!res) {
close();
return false;
}
output.data.last().file.set("FrameNumber", output.sequenceNumber);
return true;
}
cv::VideoCapture video;
Template basis;
int next_idx;
};
// Given a template as input, return its matrices one by one on subsequent calls
// to getNext
class TemplateDataSource : public DataSource
{
public:
TemplateDataSource(int maxFrames) : DataSource(maxFrames)
{
current_idx = INT_MAX;
data_ok = false;
}
bool data_ok;
bool open(Template &input)
{
basis = input;
current_idx = 0;
next_sequence = 0;
final_frame = -1;
last_issued = -2;
last_received = -3;
data_ok = current_idx < basis.size();
return data_ok;
}
bool isOpen() {
return data_ok;
}
void close()
{
current_idx = INT_MAX;
basis.clear();
}
private:
bool getNext(FrameData & output)
{
data_ok = current_idx < basis.size();
if (!data_ok)
return false;
output.data.append(basis[current_idx]);
current_idx++;
output.sequenceNumber = next_sequence;
next_sequence++;
output.data.last().file.set("FrameNumber", output.sequenceNumber);
return true;
}
Template basis;
int current_idx;
int next_sequence;
};
// Given a template as input, create a VideoDataSource or a TemplateDataSource
// depending on whether or not it looks like the input template has already
// loaded frames into memory.
class DataSourceManager : public DataSource
{
public:
DataSourceManager()
{
actualSource = NULL;
}
~DataSourceManager()
{
close();
}
void close()
{
if (actualSource) {
actualSource->close();
delete actualSource;
actualSource = NULL;
}
}
bool open(Template & input)
{
close();
final_frame = -1;
last_issued = -2;
last_received = -3;
// Input has no matrices? Its probably a video that hasn't been loaded yet
if (input.empty()) {
actualSource = new VideoDataSource(0);
actualSource->open(input);
}
else {
// create frame dealer
actualSource = new TemplateDataSource(0);
actualSource->open(input);
}
if (!isOpen()) {
delete actualSource;
actualSource = NULL;
return false;
}
return true;
}
bool isOpen() { return !actualSource ? false : actualSource->isOpen(); }
protected:
DataSource * actualSource;
bool getNext(FrameData & output)
{
return actualSource->getNext(output);
}
};
class ProcessingStage;
class BasicLoop : public QRunnable
{
public:
void run();
QList<ProcessingStage *> * stages;
int start_idx;
FrameData * startItem;
};
class ProcessingStage
{
public:
friend class StreamTransform;
public:
ProcessingStage(int nThreads = 1)
{
thread_count = nThreads;
}
virtual ~ProcessingStage() {}
virtual FrameData* run(FrameData * input, bool & should_continue)=0;
virtual bool tryAcquireNextStage(FrameData *& input)=0;
int stage_id;
virtual void reset()=0;
protected:
int thread_count;
SharedBuffer * inputBuffer;
ProcessingStage * nextStage;
QList<ProcessingStage *> * stages;
Transform * transform;
};
void BasicLoop::run()
{
int current_idx = start_idx;
FrameData * target_item = startItem;
bool should_continue = true;
forever
{
target_item = stages->at(current_idx)->run(target_item, should_continue);
if (!should_continue) {
break;
}
current_idx++;
current_idx = current_idx % stages->size();
}
}
class MultiThreadStage : public ProcessingStage
{
public:
MultiThreadStage(int _input) : ProcessingStage(_input) {}
FrameData * run(FrameData * input, bool & should_continue)
{
if (input == NULL) {
qFatal("null input to multi-thread stage");
}
// Project the input we got
transform->projectUpdate(input->data);
should_continue = nextStage->tryAcquireNextStage(input);
return input;
}
// Called from a different thread than run
virtual bool tryAcquireNextStage(FrameData *& input)
{
(void) input;
return true;
}
void reset()
{
// nothing to do.
}
};
class SingleThreadStage : public ProcessingStage
{
public:
SingleThreadStage(bool input_variance) : ProcessingStage(1)
{
currentStatus = STOPPING;
next_target = 0;
if (input_variance) {
this->inputBuffer = new DoubleBuffer();
}
else {
this->inputBuffer = new SequencingBuffer();
}
}
~SingleThreadStage()
{
delete inputBuffer;
}
void reset()
{
QWriteLocker writeLock(&statusLock);
currentStatus = STOPPING;
next_target = 0;
}
int next_target;
enum Status
{
STARTING,
STOPPING
};
QReadWriteLock statusLock;
Status currentStatus;
FrameData * run(FrameData * input, bool & should_continue)
{
if (input == NULL)
qFatal("NULL input to stage %d", this->stage_id);
if (input->sequenceNumber != next_target)
{
qFatal("out of order frames for stage %d, got %d expected %d", this->stage_id, input->sequenceNumber, this->next_target);
}
next_target = input->sequenceNumber + 1;
// Project the input we got
transform->projectUpdate(input->data);
should_continue = nextStage->tryAcquireNextStage(input);
// Is there anything on our input buffer? If so we should start a thread with that.
QWriteLocker lock(&statusLock);
FrameData * newItem = inputBuffer->tryGetItem();
if (!newItem)
{
this->currentStatus = STOPPING;
}
lock.unlock();
if (newItem)
{
BasicLoop * next = new BasicLoop();
next->stages = stages;
next->start_idx = this->stage_id;
next->startItem = newItem;
QThreadPool::globalInstance()->start(next, stages->size() - this->stage_id);
}
return input;
}
// Calledfrom a different thread than run.
bool tryAcquireNextStage(FrameData *& input)
{
inputBuffer->addItem(input);
QReadLocker lock(&statusLock);
// Thread is already running, we should just return
if (currentStatus == STARTING)
{
return false;
}
// Have to change to a write lock to modify currentStatus
lock.unlock();
QWriteLocker writeLock(&statusLock);
// But someone else might have started a thread in the meantime
if (currentStatus == STARTING)
{
return false;
}
// Ok we might start a thread, as long as we can get something back
// from the input buffer
input = inputBuffer->tryGetItem();
if (!input)
return false;
currentStatus = STARTING;
return true;
}
};
// No input buffer, instead we draw templates from some data source
// Will be operated by the main thread for the stream
class FirstStage : public SingleThreadStage
{
public:
FirstStage() : SingleThreadStage(true) {}
DataSourceManager dataSource;
FrameData * run(FrameData * input, bool & should_continue)
{
// Is there anything on our input buffer? If so we should start a thread with that.
QWriteLocker lock(&statusLock);
input = dataSource.tryGetFrame();
// Datasource broke?
if (!input)
{
currentStatus = STOPPING;
should_continue = false;
return NULL;
}
lock.unlock();
should_continue = nextStage->tryAcquireNextStage(input);
BasicLoop * next = new BasicLoop();
next->stages = stages;
next->start_idx = this->stage_id;
next->startItem = NULL;
QThreadPool::globalInstance()->start(next, stages->size() - this->stage_id);
return input;
}
// Calledfrom a different thread than run.
bool tryAcquireNextStage(FrameData *& input)
{
bool was_last = dataSource.returnFrame(input);
input = NULL;
if (was_last) {
return false;
}
if (!dataSource.isOpen())
return false;
QReadLocker lock(&statusLock);
// Thread is already running, we should just return
if (currentStatus == STARTING)
{
return false;
}
// Have to change to a write lock to modify currentStatus
lock.unlock();
QWriteLocker writeLock(&statusLock);
// But someone else might have started a thread in the meantime
if (currentStatus == STARTING)
{
return false;
}
// Ok we'll start a thread
currentStatus = STARTING;
// We always start a readstage thread with null input, so nothing to do here
return true;
}
};
class LastStage : public SingleThreadStage
{
public:
LastStage(bool _prev_stage_variance) : SingleThreadStage(_prev_stage_variance) {}
TemplateList getOutput()
{
return collectedOutput;
}
private:
TemplateList collectedOutput;
public:
void reset()
{
collectedOutput.clear();
SingleThreadStage::reset();
}
FrameData * run(FrameData * input, bool & should_continue)
{
if (input == NULL) {
qFatal("NULL input to stage %d", this->stage_id);
}
if (input->sequenceNumber != next_target)
{
qFatal("out of order frames for stage %d, got %d expected %d", this->stage_id, input->sequenceNumber, this->next_target);
}
next_target = input->sequenceNumber + 1;
collectedOutput.append(input->data);
should_continue = nextStage->tryAcquireNextStage(input);
// Is there anything on our input buffer? If so we should start a thread with that.
QWriteLocker lock(&statusLock);
FrameData * newItem = inputBuffer->tryGetItem();
if (!newItem)
{
this->currentStatus = STOPPING;
}
lock.unlock();
if (newItem)
{
BasicLoop * next = new BasicLoop();
next->stages = stages;
next->start_idx = this->stage_id;
next->startItem = newItem;
QThreadPool::globalInstance()->start(next, stages->size() - this->stage_id);
}
return input;
}
};
class StreamTransform : public CompositeTransform
{
Q_OBJECT
public:
void train(const TemplateList & data)
{
foreach(Transform * transform, transforms) {
transform->train(data);
}
}
bool timeVarying() const { return true; }
void project(const Template &src, Template &dst) const
{
(void) src; (void) dst;
qFatal("nope");
}
void projectUpdate(const Template &src, Template &dst)
{
(void) src; (void) dst;
qFatal("whatever");
}
// start processing
void projectUpdate(const TemplateList & src, TemplateList & dst)
{
if (src.size() != 1)
qFatal("Expected single template input to stream");
dst = src;
bool res = readStage->dataSource.open(dst[0]);
if (!res) return;
QThreadPool::globalInstance()->releaseThread();
readStage->currentStatus = SingleThreadStage::STARTING;
BasicLoop loop;
loop.stages = &this->processingStages;
loop.start_idx = 0;
loop.startItem = NULL;
loop.setAutoDelete(false);
QThreadPool::globalInstance()->start(&loop, processingStages.size() - processingStages[0]->stage_id);
// Wait for the end.
readStage->dataSource.waitLast();
QThreadPool::globalInstance()->reserveThread();
TemplateList final_output;
// Push finalize through the stages
for (int i=0; i < this->transforms.size(); i++)
{
TemplateList output_set;
transforms[i]->finalize(output_set);
for (int j=i+1; j < transforms.size();j++)
{
transforms[j]->projectUpdate(output_set);
}
final_output.append(output_set);
}
// dst is set to all output received by the final stage
dst = collectionStage->getOutput();
dst.append(final_output);
foreach(ProcessingStage * stage, processingStages) {
stage->reset();
}
}
virtual void finalize(TemplateList & output)
{
(void) output;
// Not handling this yet -cao
}
// Create and link stages
void init()
{
if (transforms.isEmpty()) return;
stage_variance.reserve(transforms.size());
foreach (const br::Transform *transform, transforms) {
stage_variance.append(transform->timeVarying());
}
readStage = new FirstStage();
processingStages.push_back(readStage);
readStage->stage_id = 0;
readStage->stages = &this->processingStages;
int next_stage_id = 1;
bool prev_stage_variance = true;
for (int i =0; i < transforms.size(); i++)
{
if (stage_variance[i])
{
processingStages.append(new SingleThreadStage(prev_stage_variance));
}
else
processingStages.append(new MultiThreadStage(Globals->parallelism));
processingStages.last()->stage_id = next_stage_id++;
// link nextStage pointers, the stage we just appeneded is i+1 since
// the read stage was added before this loop
processingStages[i]->nextStage = processingStages[i+1];
processingStages.last()->stages = &this->processingStages;
processingStages.last()->transform = transforms[i];
prev_stage_variance = stage_variance[i];
}
collectionStage = new LastStage(prev_stage_variance);
processingStages.append(collectionStage);
collectionStage->stage_id = next_stage_id;
collectionStage->stages = &this->processingStages;
processingStages[processingStages.size() - 2]->nextStage = collectionStage;
// It's a ring buffer, get it?
collectionStage->nextStage = readStage;
}
~StreamTransform()
{
for (int i = 0; i < processingStages.size(); i++) {
delete processingStages[i];
}
}
protected:
QList<bool> stage_variance;
FirstStage * readStage;
LastStage * collectionStage;
QList<ProcessingStage *> processingStages;
void _project(const Template &src, Template &dst) const
{
(void) src; (void) dst;
qFatal("nope");
}
void _project(const TemplateList & src, TemplateList & dst) const
{
(void) src; (void) dst;
qFatal("nope");
}
};
BR_REGISTER(Transform, StreamTransform)
} // namespace br
#include "stream.moc"
| 24.925214 | 133 | 0.592242 | [
"transform"
] |
9bf3bdb9a12de0901f79e2be06aeafb158e515f2 | 318,929 | cpp | C++ | src/mdb.cpp | styac/sxmdb | 7787417b68c6f253a0041e2706fea20009f5cdeb | [
"OLDAP-2.8"
] | null | null | null | src/mdb.cpp | styac/sxmdb | 7787417b68c6f253a0041e2706fea20009f5cdeb | [
"OLDAP-2.8"
] | null | null | null | src/mdb.cpp | styac/sxmdb | 7787417b68c6f253a0041e2706fea20009f5cdeb | [
"OLDAP-2.8"
] | null | null | null | /** @file mdb.c
* @brief Lightning memory-mapped database library
*
* A Btree-based database management library modeled loosely on the
* BerkeleyDB API, but much simplified.
*/
/*
* Copyright 2011-2018 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*
* This code is derived from btree.c written by Martin Hedenfalk.
*
* Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
//#if defined(MDB_VL32) || defined(__WIN64__)
#define _FILE_OFFSET_BITS 64
//#endif
#ifdef _WIN32
#include <malloc.h>
#include <windows.h>
#include <wchar.h> /* get wcscpy() */
/* We use native NT APIs to setup the memory map, so that we can
* let the DB file grow incrementally instead of always preallocating
* the full size. These APIs are defined in <wdm.h> and <ntifs.h>
* but those headers are meant for driver-level development and
* conflict with the regular user-level headers, so we explicitly
* declare them here. We get pointers to these functions from
* NTDLL.DLL at runtime, to avoid buildtime dependencies on any
* NTDLL import libraries.
*/
typedef NTSTATUS (WINAPI NtCreateSectionFunc)
(OUT PHANDLE sh, IN ACCESS_MASK acc,
IN void * oa OPTIONAL,
IN PLARGE_INTEGER ms OPTIONAL,
IN ULONG pp, IN ULONG aa, IN HANDLE fh OPTIONAL);
static NtCreateSectionFunc *NtCreateSection;
typedef enum _SECTION_INHERIT {
ViewShare = 1,
ViewUnmap = 2
} SECTION_INHERIT;
typedef NTSTATUS (WINAPI NtMapViewOfSectionFunc)
(IN PHANDLE sh, IN HANDLE ph,
IN OUT PVOID *addr, IN ULONG_PTR zbits,
IN SIZE_T cs, IN OUT PLARGE_INTEGER off OPTIONAL,
IN OUT PSIZE_T vs, IN SECTION_INHERIT ih,
IN ULONG at, IN ULONG pp);
static NtMapViewOfSectionFunc *NtMapViewOfSection;
typedef NTSTATUS (WINAPI NtCloseFunc)(HANDLE h);
static NtCloseFunc *NtClose;
/** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
* as int64 which is wrong. MSVC doesn't define it at all, so just
* don't use it.
*/
#define MDB_PID_T int
#define MDB_THR_T DWORD
#include <sys/types.h>
#include <sys/stat.h>
#ifdef __GNUC__
# include <sys/param.h>
#else
//# define LITTLE_ENDIAN 1234
//# define BIG_ENDIAN 4321
//# define BYTE_ORDER LITTLE_ENDIAN
# ifndef SSIZE_MAX
# define SSIZE_MAX INT_MAX
# endif
#endif
#else
#include <sys/types.h>
#include <sys/stat.h>
#define MDB_PID_T pid_t
#define MDB_THR_T pthread_t
#include <sys/param.h>
#include <sys/uio.h>
#include <sys/mman.h>
#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#include <fcntl.h>
#endif
#if defined(__mips) && defined(__linux)
/* MIPS has cache coherency issues, requires explicit cache control */
#include <asm/cachectl.h>
extern int cacheflush(char *addr, int nbytes, int cache);
#define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
#else
#define CACHEFLUSH(addr, bytes, cache)
#endif
//#if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
///** fdatasync is broken on ext3/ext4fs on older kernels, see
// * description in #mdb_env_open2 comments. You can safely
// * define MDB_FDATASYNC_WORKS if this code will only be run
// * on kernels 3.6 and newer.
// */
//#define BROKEN_FDATASYNC
//#endif
#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef _MSC_VER
#include <io.h>
typedef SSIZE_T ssize_t;
#else
#include <unistd.h>
#endif
#if defined(__sun) || defined(ANDROID)
/* Most platforms have posix_memalign, older may only have memalign */
#define HAVE_MEMALIGN 1
#include <malloc.h>
/* On Solaris, we need the POSIX sigwait function */
#if defined (__sun)
# define _POSIX_PTHREAD_SEMANTICS 1
#endif
#endif
#if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
#include <netinet/in.h>
#include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
#endif
#if defined(__APPLE__) || defined (BSD) || defined(__FreeBSD_kernel__)
# if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
# define MDB_USE_SYSV_SEM 1
# endif
# define MDB_FDATASYNC fsync
#elif defined(ANDROID)
# define MDB_FDATASYNC fsync
#endif
#ifndef _WIN32
#include <pthread.h>
#include <signal.h>
#ifdef MDB_USE_POSIX_SEM
# define MDB_USE_HASH 1
#include <semaphore.h>
#elif defined(MDB_USE_SYSV_SEM)
#include <sys/ipc.h>
#include <sys/sem.h>
#ifdef _SEM_SEMUN_UNDEFINED
union semun {
int val;
struct semid_ds *buf;
uint16_t *array;
};
#endif /* _SEM_SEMUN_UNDEFINED */
#else
#define MDB_USE_POSIX_MUTEX 1
#endif /* MDB_USE_POSIX_SEM */
#endif /* !_WIN32 */
#if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
+ defined(MDB_USE_POSIX_MUTEX) != 1
# error "Ambiguous shared-lock implementation"
#endif
#ifdef USE_VALGRIND
#include <valgrind/memcheck.h>
#define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
#define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
#define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
#define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
#define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
#else
#define VGMEMP_CREATE(h,r,z)
#define VGMEMP_ALLOC(h,a,s)
#define VGMEMP_FREE(h,a)
#define VGMEMP_DESTROY(h)
#define VGMEMP_DEFINED(a,s)
#endif
#ifdef __SIZEOF_POINTER__
#if __SIZEOF_POINTER__ != 8
#error "only 64 bit systems are supported"
#endif
#endif
#ifdef __BYTE_ORDER__
#if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
#error "only LITTLE ENDIAN systems are supported"
#endif
#endif
#if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
#define MISALIGNED_OK 1
#endif
#include "lmdb.h"
#include "midl.h"
#define ESECT
#ifdef _WIN32
#define CALL_CONV WINAPI
#else
#define CALL_CONV
#endif
/** @defgroup internal LMDB Internals
* @{
*/
/** @defgroup compat Compatibility Macros
* A bunch of macros to minimize the amount of platform-specific ifdefs
* needed throughout the rest of the code. When the features this library
* needs are similar enough to POSIX to be hidden in a one-or-two line
* replacement, this macro approach is used.
* @{
*/
/** Features under development */
#ifndef MDB_DEVEL
#define MDB_DEVEL 0
#endif
/** Wrapper around __func__, which is a C99 feature */
#if __STDC_VERSION__ >= 199901L
# define mdb_func_ __func__
#elif __GNUC__ >= 2 || _MSC_VER >= 1300
# define mdb_func_ __FUNCTION__
#else
/* If a debug message says <mdb_unknown>(), update the #if statements above */
# define mdb_func_ "<mdb_unknown>"
#endif
/* Internal error codes, not exposed outside liblmdb */
#define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
#ifdef _WIN32
#define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
#elif defined MDB_USE_SYSV_SEM
#define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
#elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
#define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
#endif
#ifdef __GLIBC__
#define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
#endif
/** Some platforms define the EOWNERDEAD error code
* even though they don't support Robust Mutexes.
* Compile with -DMDB_USE_ROBUST=0, or use some other
* mechanism like -DMDB_USE_SYSV_SEM instead of
* -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
* also Robust, but some systems don't support them
* either.)
*/
#ifndef MDB_USE_ROBUST
/* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
# if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
(defined(__GLIBC__) && GLIBC_VER < 0x020004))
# define MDB_USE_ROBUST 0
# else
# define MDB_USE_ROBUST 1
# endif
#endif /* !MDB_USE_ROBUST */
#if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
/* glibc < 2.12 only provided _np API */
# if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
(defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
# define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
# define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
# define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
# endif
#endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
#if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
#define MDB_ROBUST_SUPPORTED 1
#endif
#ifdef _WIN32
#define MDB_USE_HASH 1
#define MDB_PIDLOCK 0
#define THREAD_RET DWORD
#define pthread_t HANDLE
#define pthread_mutex_t HANDLE
#define pthread_cond_t HANDLE
typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
#define pthread_key_t DWORD
#define pthread_self() GetCurrentThreadId()
#define pthread_key_create(x,y) \
((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
#define pthread_key_delete(x) TlsFree(x)
#define pthread_getspecific(x) TlsGetValue(x)
#define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
#define pthread_mutex_unlock(x) ReleaseMutex(*x)
#define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
#define pthread_cond_signal(x) SetEvent(*x)
#define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
#define THREAD_CREATE(thr,start,arg) \
(((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
#define THREAD_FINISH(thr) \
(WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
#define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
#define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
#define mdb_mutex_consistent(mutex) 0
#define getpid() GetCurrentProcessId()
#define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
#define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
#define ErrCode() GetLastError()
#define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
#define close(fd) (CloseHandle(fd) ? 0 : -1)
#define munmap(ptr,len) UnmapViewOfFile(ptr)
#ifdef PROCESS_QUERY_LIMITED_INFORMATION
#define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
#else
#define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
#endif
#else
#define THREAD_RET void *
#define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
#define THREAD_FINISH(thr) pthread_join(thr,NULL)
/** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
#define MDB_PIDLOCK 1
#ifdef MDB_USE_POSIX_SEM
typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
#define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
#define UNLOCK_MUTEX(mutex) sem_post(mutex)
static int
mdb_sem_wait(sem_t *sem)
{
int rc;
while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
return rc;
}
#elif defined MDB_USE_SYSV_SEM
typedef struct mdb_mutex {
int semid;
int semnum;
int *locked;
} mdb_mutex_t[1], *mdb_mutexref_t;
#define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
#define UNLOCK_MUTEX(mutex) do { \
struct sembuf sb = { 0, 1, SEM_UNDO }; \
sb.sem_num = (mutex)->semnum; \
*(mutex)->locked = 0; \
semop((mutex)->semid, &sb, 1); \
} while(0)
static int
mdb_sem_wait(mdb_mutexref_t sem)
{
int rc, *locked = sem->locked;
struct sembuf sb = { 0, -1, SEM_UNDO };
sb.sem_num = sem->semnum;
do {
if (!semop(sem->semid, &sb, 1)) {
rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
*locked = 1;
break;
}
} while ((rc = errno) == EINTR);
return rc;
}
#define mdb_mutex_consistent(mutex) 0
#else /* MDB_USE_POSIX_MUTEX: */
/** Shared mutex/semaphore as the original is stored.
*
* Not for copies. Instead it can be assigned to an #mdb_mutexref_t.
* When mdb_mutexref_t is a pointer and mdb_mutex_t is not, then it
* is array[size 1] so it can be assigned to the pointer.
*/
typedef pthread_mutex_t mdb_mutex_t[1];
/** Reference to an #mdb_mutex_t */
typedef pthread_mutex_t *mdb_mutexref_t;
/** Lock the reader or writer mutex.
* Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
*/
#define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
/** Unlock the reader or writer mutex.
*/
#define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
/** Mark mutex-protected data as repaired, after death of previous owner.
*/
#define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
#endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
/** Get the error code for the last failed system function.
*/
#define ErrCode() errno
/** An abstraction for a file handle.
* On POSIX systems file handles are small integers. On Windows
* they're opaque pointers.
*/
#define HANDLE int
/** A value for an invalid file handle.
* Mainly used to initialize file variables and signify that they are
* unused.
*/
#define INVALID_HANDLE_VALUE (-1)
/** Get the size of a memory page for the system.
* This is the basic size that the platform's memory manager uses, and is
* fundamental to the use of memory-mapped files.
*/
#define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
#endif
#define Z MDB_FMT_Z /**< printf/scanf format modifier for size_t */
#define Yu MDB_PRIy(u) /**< printf format for #mdb_size_t */
#define Yd MDB_PRIy(d) /**< printf format for 'signed #mdb_size_t' */
#ifdef MDB_USE_SYSV_SEM
#define MNAME_LEN (sizeof(int))
#else
#define MNAME_LEN (sizeof(pthread_mutex_t))
#endif
/** Initial part of #MDB_env.me_mutexname[].
* Changes to this code must be reflected in #MDB_LOCK_FORMAT.
*/
#ifdef _WIN32
#define MUTEXNAME_PREFIX "Global\\MDB"
#elif defined MDB_USE_POSIX_SEM
#define MUTEXNAME_PREFIX "/MDB"
#endif
/** @} */
#ifdef MDB_ROBUST_SUPPORTED
/** Lock mutex, handle any error, set rc = result.
* Return 0 on success, nonzero (not rc) on error.
*/
#define LOCK_MUTEX(rc, env, mutex) \
(((rc) = LOCK_MUTEX0(mutex)) && \
((rc) = mdb_mutex_failed(env, mutex, rc)))
static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
#else
#define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
#define mdb_mutex_failed(env, mutex, rc) (rc)
#endif
#ifndef _WIN32
/** A flag for opening a file and requesting synchronous data writes.
* This is only used when writing a meta page. It's not strictly needed;
* we could just do a normal write and then immediately perform a flush.
* But if this flag is available it saves us an extra system call.
*
* @note If O_DSYNC is undefined but exists in /usr/include,
* preferably set some compiler flag to get the definition.
*/
#ifndef MDB_DSYNC
# ifdef O_DSYNC
# define MDB_DSYNC O_DSYNC
# else
# define MDB_DSYNC O_SYNC
# endif
#endif
#endif
/** Function for flushing the data of a file. Define this to fsync
* if fdatasync() is not supported.
*/
#ifndef MDB_FDATASYNC
# define MDB_FDATASYNC fdatasync
#endif
#ifndef MDB_MSYNC
# define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
#endif
#ifndef MS_SYNC
#define MS_SYNC 1
#endif
#ifndef MS_ASYNC
#define MS_ASYNC 0
#endif
/** A page number in the database.
* Note that 64 bit page numbers are overkill, since pages themselves
* already represent 12-13 bits of addressable memory, and the OS will
* always limit applications to a maximum of 63 bits of address space.
*
* @note In the #MDB_node structure, we only store 48 bits of this value,
* which thus limits us to only 60 bits of addressable data.
*/
typedef MDB_ID pgno_t;
/** A transaction ID.
* See struct MDB_txn.mt_txnid for details.
*/
typedef MDB_ID txnid_t;
/** @defgroup debug Debug Macros
* @{
*/
#ifndef MDB_DEBUG
/** Enable debug output. Needs variable argument macros (a C99 feature).
* Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
* read from and written to the database (used for free space management).
*/
#define MDB_DEBUG 0
#endif
#if MDB_DEBUG
static int mdb_debug;
static txnid_t mdb_debug_start;
/** Print a debug message with printf formatting.
* Requires double parenthesis around 2 or more args.
*/
# define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
# define DPRINTF0(fmt, ...) \
fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
#else
# define DPRINTF(args) ((void) 0)
#endif
/** Print a debug string.
* The string is printed literally, with no format processing.
*/
#define DPUTS(arg) DPRINTF(("%s", arg))
/** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
#define DDBI(mc) \
(((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
/** @} */
/** @brief The maximum size of a database page.
*
* It is 32k or 64k, since value-PAGEBASE must fit in
* #MDB_page.%mp_upper.
*
* LMDB will use database pages < OS pages if needed.
* That causes more I/O in write transactions: The OS must
* know (read) the whole page before writing a partial page.
*
* Note that we don't currently support Huge pages. On Linux,
* regular data files cannot use Huge pages, and in general
* Huge pages aren't actually pageable. We rely on the OS
* demand-pager to read our data and page it out when memory
* pressure from other processes is high. So until OSs have
* actual paging support for Huge pages, they're not viable.
*/
#define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
/** The minimum number of keys required in a database page.
* Setting this to a larger value will place a smaller bound on the
* maximum size of a data item. Data items larger than this size will
* be pushed into overflow pages instead of being stored directly in
* the B-tree node. This value used to default to 4. With a page size
* of 4096 bytes that meant that any item larger than 1024 bytes would
* go into an overflow page. That also meant that on average 2-3KB of
* each overflow page was wasted space. The value cannot be lower than
* 2 because then there would no longer be a tree structure. With this
* value, items larger than 2KB will go into overflow pages, and on
* average only 1KB will be wasted.
*/
#define MDB_MINKEYS 2
/** A stamp that identifies a file as an LMDB file.
* There's nothing special about this value other than that it is easily
* recognizable, and it will reflect any byte order mismatches.
*/
#define MDB_MAGIC 0xBEEFC0DE
/** The version number for a database's datafile format. */
#define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
/** The version number for a database's lockfile format. */
#define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 2)
/** Number of bits representing #MDB_LOCK_VERSION in #MDB_LOCK_FORMAT.
* The remaining bits must leave room for #MDB_lock_desc.
*/
#define MDB_LOCK_VERSION_BITS 12
/** @brief The max size of a key we can write, or 0 for computed max.
*
* This macro should normally be left alone or set to 0.
* Note that a database with big keys or dupsort data cannot be
* reliably modified by a liblmdb which uses a smaller max.
* The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
*
* Other values are allowed, for backwards compat. However:
* A value bigger than the computed max can break if you do not
* know what you are doing, and liblmdb <= 0.9.10 can break when
* modifying a DB with keys/dupsort data bigger than its max.
*
* Data items in an #MDB_DUPSORT database are also limited to
* this size, since they're actually keys of a sub-DB. Keys and
* #MDB_DUPSORT data items must fit on a node in a regular page.
*/
#ifndef MDB_MAXKEYSIZE
#define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
#endif
/** The maximum size of a key we can write to the environment. */
#if MDB_MAXKEYSIZE
#define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
#else
#define ENV_MAXKEY(env) ((env)->me_maxkey)
#endif
/** @brief The maximum size of a data item.
*
* We only store a 32 bit value for node sizes.
*/
#define MAXDATASIZE 0xffffffffUL
#if MDB_DEBUG
/** Key size which fits in a #DKBUF.
* @ingroup debug
*/
#define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
/** A key buffer.
* @ingroup debug
* This is used for printing a hex dump of a key's contents.
*/
#define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
/** Display a key in hex.
* @ingroup debug
* Invoke a function to display a key in hex.
*/
#define DKEY(x) mdb_dkey(x, kbuf)
#else
#define DKBUF
#define DKEY(x) 0
#endif
/** An invalid page number.
* Mainly used to denote an empty tree.
*/
#define P_INVALID (~(pgno_t)0)
/** Test if the flags \b f are set in a flag word \b w. */
#define F_ISSET(w, f) (((w) & (f)) == (f))
/** Round \b n up to an even number. */
#define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
/** Least significant 1-bit of \b n. n must be of an unsigned type. */
#define LOW_BIT(n) ((n) & (-(n)))
/** (log2(\b p2) % \b n), for p2 = power of 2 and 0 < n < 8. */
#define LOG2_MOD(p2, n) (7 - 86 / ((p2) % ((1U<<(n))-1) + 11))
/* Explanation: Let p2 = 2**(n*y + x), x<n and M = (1U<<n)-1. Now p2 =
* (M+1)**y * 2**x = 2**x (mod M). Finally "/" "happens" to return 7-x.
*/
/** Should be alignment of \b type. Ensure it is a power of 2. */
#define ALIGNOF2(type) \
LOW_BIT(offsetof(struct { char ch_; type align_; }, align_))
/** Used for offsets within a single page.
* Since memory pages are typically 4 or 8KB in size, 12-13 bits,
* this is plenty.
*/
typedef uint16_t indx_t;
typedef unsigned long long mdb_hash_t;
/** Default size of memory map.
* This is certainly too small for any actual applications. Apps should always set
* the size explicitly using #mdb_env_set_mapsize().
*/
#define DEFAULT_MAPSIZE 1048576
/** @defgroup readers Reader Lock Table
* Readers don't acquire any locks for their data access. Instead, they
* simply record their transaction ID in the reader table. The reader
* mutex is needed just to find an empty slot in the reader table. The
* slot's address is saved in thread-specific data so that subsequent read
* transactions started by the same thread need no further locking to proceed.
*
* If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
*
* No reader table is used if the database is on a read-only filesystem, or
* if #MDB_NOLOCK is set.
*
* Since the database uses multi-version concurrency control, readers don't
* actually need any locking. This table is used to keep track of which
* readers are using data from which old transactions, so that we'll know
* when a particular old transaction is no longer in use. Old transactions
* that have discarded any data pages can then have those pages reclaimed
* for use by a later write transaction.
*
* The lock table is constructed such that reader slots are aligned with the
* processor's cache line size. Any slot is only ever used by one thread.
* This alignment guarantees that there will be no contention or cache
* thrashing as threads update their own slot info, and also eliminates
* any need for locking when accessing a slot.
*
* A writer thread will scan every slot in the table to determine the oldest
* outstanding reader transaction. Any freed pages older than this will be
* reclaimed by the writer. The writer doesn't use any locks when scanning
* this table. This means that there's no guarantee that the writer will
* see the most up-to-date reader info, but that's not required for correct
* operation - all we need is to know the upper bound on the oldest reader,
* we don't care at all about the newest reader. So the only consequence of
* reading stale information here is that old pages might hang around a
* while longer before being reclaimed. That's actually good anyway, because
* the longer we delay reclaiming old pages, the more likely it is that a
* string of contiguous pages can be found after coalescing old pages from
* many old transactions together.
* @{
*/
/** Number of slots in the reader table.
* This value was chosen somewhat arbitrarily. 126 readers plus a
* couple mutexes fit exactly into 8KB on my development machine.
* Applications should set the table size using #mdb_env_set_maxreaders().
*/
#define DEFAULT_READERS 126
/** The size of a CPU cache line in bytes. We want our lock structures
* aligned to this size to avoid false cache line sharing in the
* lock table.
* This value works for most CPUs. For Itanium this should be 128.
*/
#ifndef CACHELINE
#define CACHELINE 64
#endif
/** The information we store in a single slot of the reader table.
* In addition to a transaction ID, we also record the process and
* thread ID that owns a slot, so that we can detect stale information,
* e.g. threads or processes that went away without cleaning up.
* @note We currently don't check for stale records. We simply re-init
* the table when we know that we're the only process opening the
* lock file.
*/
typedef struct MDB_rxbody {
/** Current Transaction ID when this transaction began, or (txnid_t)-1.
* Multiple readers that start at the same time will probably have the
* same ID here. Again, it's not important to exclude them from
* anything; all we need to know is which version of the DB they
* started from so we can avoid overwriting any data used in that
* particular version.
*/
volatile txnid_t mrb_txnid;
/** The process ID of the process owning this reader txn. */
volatile MDB_PID_T mrb_pid;
/** The thread ID of the thread owning this txn. */
volatile MDB_THR_T mrb_tid;
} MDB_rxbody;
/** The actual reader record, with cacheline padding. */
typedef struct MDB_reader {
union {
MDB_rxbody mrx;
/** shorthand for mrb_txnid */
#define mr_txnid mru.mrx.mrb_txnid
#define mr_pid mru.mrx.mrb_pid
#define mr_tid mru.mrx.mrb_tid
/** cache line alignment */
char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
} mru;
} MDB_reader;
/** The header for the reader table.
* The table resides in a memory-mapped file. (This is a different file
* than is used for the main database.)
*
* For POSIX the actual mutexes reside in the shared memory of this
* mapped file. On Windows, mutexes are named objects allocated by the
* kernel; we store the mutex names in this mapped file so that other
* processes can grab them. This same approach is also used on
* MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
* process-shared POSIX mutexes. For these cases where a named object
* is used, the object name is derived from a 64 bit FNV hash of the
* environment pathname. As such, naming collisions are extremely
* unlikely. If a collision occurs, the results are unpredictable.
*/
typedef struct MDB_txbody {
/** Stamp identifying this as an LMDB file. It must be set
* to #MDB_MAGIC. */
uint32_t mtb_magic;
/** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
uint32_t mtb_format;
/** The ID of the last transaction committed to the database.
* This is recorded here only for convenience; the value can always
* be determined by reading the main database meta pages.
*/
volatile txnid_t mtb_txnid;
/** The number of slots that have been used in the reader table.
* This always records the maximum count, it is not decremented
* when readers release their slots.
*/
volatile unsigned mtb_numreaders;
#if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
/** Binary form of names of the reader/writer locks */
mdb_hash_t mtb_mutexid;
#elif defined(MDB_USE_SYSV_SEM)
int mtb_semid;
int mtb_rlocked;
#else
/** Mutex protecting access to this table.
* This is the reader table lock used with LOCK_MUTEX().
*/
mdb_mutex_t mtb_rmutex;
#endif
} MDB_txbody;
/** The actual reader table definition. */
typedef struct MDB_txninfo {
union {
MDB_txbody mtb;
#define mti_magic mt1.mtb.mtb_magic
#define mti_format mt1.mtb.mtb_format
#define mti_rmutex mt1.mtb.mtb_rmutex
#define mti_txnid mt1.mtb.mtb_txnid
#define mti_numreaders mt1.mtb.mtb_numreaders
#define mti_mutexid mt1.mtb.mtb_mutexid
#ifdef MDB_USE_SYSV_SEM
#define mti_semid mt1.mtb.mtb_semid
#define mti_rlocked mt1.mtb.mtb_rlocked
#endif
char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
} mt1;
#if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM))
union {
#ifdef MDB_USE_SYSV_SEM
int mt2_wlocked;
#define mti_wlocked mt2.mt2_wlocked
#else
mdb_mutex_t mt2_wmutex;
#define mti_wmutex mt2.mt2_wmutex
#endif
char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
} mt2;
#endif
MDB_reader mti_readers[1];
} MDB_txninfo;
/** Lockfile format signature: version, features and field layout */
#define MDB_LOCK_FORMAT \
((uint32_t) \
(((MDB_LOCK_VERSION) % (1U << MDB_LOCK_VERSION_BITS)) \
+ MDB_lock_desc * (1U << MDB_LOCK_VERSION_BITS)))
/** Lock type and layout. Values 0-119. _WIN32 implies #MDB_PIDLOCK.
* Some low values are reserved for future tweaks.
*/
#ifdef _WIN32
# define MDB_LOCK_TYPE (0 + ALIGNOF2(mdb_hash_t)/8 % 2)
#elif defined MDB_USE_POSIX_SEM
# define MDB_LOCK_TYPE (4 + ALIGNOF2(mdb_hash_t)/8 % 2)
#elif defined MDB_USE_SYSV_SEM
# define MDB_LOCK_TYPE (8)
#elif defined MDB_USE_POSIX_MUTEX
/* We do not know the inside of a POSIX mutex and how to check if mutexes
* used by two executables are compatible. Just check alignment and size.
*/
# define MDB_LOCK_TYPE (10 + \
LOG2_MOD(ALIGNOF2(pthread_mutex_t), 5) + \
sizeof(pthread_mutex_t) / 4U % 22 * 5)
#endif
enum {
/** Magic number for lockfile layout and features.
*
* This *attempts* to stop liblmdb variants compiled with conflicting
* options from using the lockfile at the same time and thus breaking
* it. It describes locking types, and sizes and sometimes alignment
* of the various lockfile items.
*
* The detected ranges are mostly guesswork, or based simply on how
* big they could be without using more bits. So we can tweak them
* in good conscience when updating #MDB_LOCK_VERSION.
*/
MDB_lock_desc =
/* Default CACHELINE=64 vs. other values (have seen mention of 32-256) */
(CACHELINE==64 ? 0 : 1 + LOG2_MOD(CACHELINE >> (CACHELINE>64), 5))
+ 6 * (sizeof(MDB_PID_T)/4 % 3) /* legacy(2) to word(4/8)? */
+ 18 * (sizeof(pthread_t)/4 % 5) /* can be struct{id, active data} */
+ 90 * (sizeof(MDB_txbody) / CACHELINE % 3)
+ 270 * (MDB_LOCK_TYPE % 120)
/* The above is < 270*120 < 2**15 */
+ ((sizeof(txnid_t) == 8) << 15) /* 32bit/64bit */
+ ((sizeof(MDB_reader) > CACHELINE) << 16)
/* Not really needed - implied by MDB_LOCK_TYPE != (_WIN32 locking) */
+ (((MDB_PIDLOCK) != 0) << 17)
/* 18 bits total: Must be <= (32 - MDB_LOCK_VERSION_BITS). */
};
/** @} */
/** Common header for all page types. The page type depends on #mp_flags.
*
* #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
* sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
* omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
*
* #P_OVERFLOW records occupy one or more contiguous pages where only the
* first has a page header. They hold the real data of #F_BIGDATA nodes.
*
* #P_SUBP sub-pages are small leaf "pages" with duplicate data.
* A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
* (Duplicate data can also go in sub-databases, which use normal pages.)
*
* #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
*
* Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
* in the snapshot: Either used by a database or listed in a freeDB record.
*/
typedef struct MDB_page {
#define mp_pgno mp_p.p_pgno
#define mp_next mp_p.p_next
union {
pgno_t p_pgno; /**< page number */
struct MDB_page *p_next; /**< for in-memory list of freed pages */
} mp_p;
uint16_t mp_pad; /**< key size if this is a LEAF2 page */
/** @defgroup mdb_page Page Flags
* @ingroup internal
* Flags for the page headers.
* @{
*/
#define P_BRANCH 0x01 /**< branch page */
#define P_LEAF 0x02 /**< leaf page */
#define P_OVERFLOW 0x04 /**< overflow page */
#define P_META 0x08 /**< meta page */
#define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
#define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
#define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
#define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
#define P_KEEP 0x8000 /**< leave this page alone during spill */
/** @} */
uint16_t mp_flags; /**< @ref mdb_page */
#define mp_lower mp_pb.pb.pb_lower
#define mp_upper mp_pb.pb.pb_upper
#define mp_pages mp_pb.pb_pages
union {
struct {
indx_t pb_lower; /**< lower bound of free space */
indx_t pb_upper; /**< upper bound of free space */
} pb;
uint32_t pb_pages; /**< number of overflow pages */
} mp_pb;
indx_t mp_ptrs[1]; /**< dynamic size */
} MDB_page;
/** Size of the page header, excluding dynamic data at the end */
#define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
/** Address of first usable data byte in a page, after the header */
#define METADATA(p) ((MDB_meta *)((char *)(p) + PAGEHDRSZ))
/** ITS#7713, change PAGEBASE to handle 65536 byte pages */
#define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
/** Number of nodes on a page */
#define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
/** The amount of space remaining in the page */
#define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
/** The percentage of space used in the page, in tenths of a percent. */
#define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
((env)->me_psize - PAGEHDRSZ))
/** The minimum page fill factor, in tenths of a percent.
* Pages emptier than this are candidates for merging.
*/
#define FILL_THRESHOLD 250
/** Test if a page is a leaf page */
#define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
/** Test if a page is a LEAF2 page */
#define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
/** Test if a page is a branch page */
#define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
/** Test if a page is an overflow page */
#define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
/** Test if a page is a sub page */
#define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
/** The number of overflow pages needed to store the given size. */
#define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
/** Link in #MDB_txn.%mt_loose_pgs list.
* Kept outside the page header, which is needed when reusing the page.
*/
#define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
/** Header for a single key/data pair within a page.
* Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
* We guarantee 2-byte alignment for 'MDB_node's.
*
* #mn_lo and #mn_hi are used for data size on leaf nodes, and for child
* pgno on branch nodes. On 64 bit platforms, #mn_flags is also used
* for pgno. (Branch nodes have no flags). Lo and hi are in host byte
* order in case some accesses can be optimized to 32-bit word access.
*
* Leaf node flags describe node contents. #F_BIGDATA says the node's
* data part is the page number of an overflow page with actual data.
* #F_DUPDATA and #F_SUBDATA can be combined giving duplicate data in
* a sub-page/sub-database, and named databases (just #F_SUBDATA).
*/
typedef struct MDB_node {
/** part of data size or pgno
* @{ */
#if BYTE_ORDER == LITTLE_ENDIAN
uint16_t mn_lo, mn_hi;
#else
uint16_t mn_hi, mn_lo;
#endif
/** @} */
/** @defgroup mdb_node Node Flags
* @ingroup internal
* Flags for node headers.
* @{
*/
#define F_BIGDATA 0x01 /**< data put on overflow page */
#define F_SUBDATA 0x02 /**< data is a sub-database */
#define F_DUPDATA 0x04 /**< data has duplicates */
/** valid flags for #mdb_node_add() */
#define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
/** @} */
uint16_t mn_flags; /**< @ref mdb_node */
uint16_t mn_ksize; /**< key size */
char mn_data[1]; /**< key and data are appended here */
} MDB_node;
/** Size of the node header, excluding dynamic data at the end */
#define NODESIZE offsetof(MDB_node, mn_data)
/** Bit position of top word in page number, for shifting mn_flags */
#define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
/** Size of a node in a branch page with a given key.
* This is just the node header plus the key, there is no data.
*/
#define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
/** Size of a node in a leaf page with a given key and data.
* This is node header plus key plus data size.
*/
#define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
/** Address of node \b i in page \b p */
#define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
/** Address of the key for the node */
#define NODEKEY(node) (void *)((node)->mn_data)
/** Address of the data for a node */
#define NODEDATA(node) (MDB_page *)((char *)(node)->mn_data + (node)->mn_ksize)
/** Get the page number pointed to by a branch node */
#define NODEPGNO(node) \
((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
(PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
/** Set the page number in a branch node */
#define SETPGNO(node,pgno) do { \
(node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
/** Get the size of the data in a leaf node */
#define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
/** Set the size of the data for a leaf node */
#define SETDSZ(node,size) do { \
(node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
/** The size of a key in a node */
#define NODEKSZ(node) ((node)->mn_ksize)
/** Copy a page number from src to dst */
#ifdef MISALIGNED_OK
#define COPY_PGNO(dst,src) dst = src
#else
#if MDB_SIZE_MAX > 0xffffffffU
#define COPY_PGNO(dst,src) do { \
uint16_t *s, *d; \
s = (uint16_t *)&(src); \
d = (uint16_t *)&(dst); \
*d++ = *s++; \
*d++ = *s++; \
*d++ = *s++; \
*d = *s; \
} while (0)
#else
#define COPY_PGNO(dst,src) do { \
uint16_t *s, *d; \
s = (uint16_t *)&(src); \
d = (uint16_t *)&(dst); \
*d++ = *s++; \
*d = *s; \
} while (0)
#endif
#endif
/** The address of a key in a LEAF2 page.
* LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
* There are no node headers, keys are stored contiguously.
*/
#define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
/** Set the \b node's key into \b keyptr, if requested. */
#define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
(keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
/** Set the \b node's key into \b key. */
#define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
/** Information about a single database in the environment. */
typedef struct MDB_db {
uint32_t md_pad; /**< also ksize for LEAF2 pages */
uint16_t md_flags; /**< @ref mdb_dbi_open */
uint16_t md_depth; /**< depth of this tree */
pgno_t md_branch_pages; /**< number of internal pages */
pgno_t md_leaf_pages; /**< number of leaf pages */
pgno_t md_overflow_pages; /**< number of overflow pages */
mdb_size_t md_entries; /**< number of data items */
pgno_t md_root; /**< the root page of this tree */
} MDB_db;
#define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
#define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
/** #mdb_dbi_open() flags */
#define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
/** Handle for the DB used to track free pages. */
#define FREE_DBI 0
/** Handle for the default DB. */
#define MAIN_DBI 1
/** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
#define CORE_DBS 2
/** Number of meta pages - also hardcoded elsewhere */
#define NUM_METAS 2
/** Meta page content.
* A meta page is the start point for accessing a database snapshot.
* Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
*/
typedef struct MDB_meta {
/** Stamp identifying this as an LMDB file. It must be set
* to #MDB_MAGIC. */
uint32_t mm_magic;
/** Version number of this file. Must be set to #MDB_DATA_VERSION. */
uint32_t mm_version;
//#ifdef MDB_VL32
// union { /* always zero since we don't support fixed mapping in MDB_VL32 */
// MDB_ID mmun_ull;
// void *mmun_address;
// } mm_un;
//#define mm_address mm_un.mmun_address
//#else
void *mm_address; /**< address for fixed mapping */
//#endif
mdb_size_t mm_mapsize; /**< size of mmap region */
MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
/** The size of pages used in this DB */
#define mm_psize mm_dbs[FREE_DBI].md_pad
/** Any persistent environment flags. @ref mdb_env */
#define mm_flags mm_dbs[FREE_DBI].md_flags
/** Last used page in the datafile.
* Actually the file may be shorter if the freeDB lists the final pages.
*/
pgno_t mm_last_pg;
volatile txnid_t mm_txnid; /**< txnid that committed this page */
} MDB_meta;
/** Buffer for a stack-allocated meta page.
* The members define size and alignment, and silence type
* aliasing warnings. They are not used directly; that could
* mean incorrectly using several union members in parallel.
*/
typedef union MDB_metabuf {
MDB_page mb_page;
struct {
char mm_pad[PAGEHDRSZ];
MDB_meta mm_meta;
} mb_metabuf;
} MDB_metabuf;
/** Auxiliary DB info.
* The information here is mostly static/read-only. There is
* only a single copy of this record in the environment.
*/
typedef struct MDB_dbx {
static_assert( sizeof(void *) == 8, "only 64 bit platform is supported" );
MDB_val md_name; /**< name of the database */
MDB_cmp_func *md_cmp; /**< function for comparing keys */
MDB_cmp_func *md_dcmp; /**< function for comparing data items */
MDB_rel_func *md_rel; /**< user relocate function */
void *md_relctx; /**< user-provided context for md_rel */
} MDB_dbx;
/** A database transaction.
* Every operation requires a transaction handle.
*/
struct MDB_txn {
MDB_txn *mt_parent; /**< parent of a nested txn */
/** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
MDB_txn *mt_child;
pgno_t mt_next_pgno; /**< next unallocated page */
//#ifdef MDB_VL32
// pgno_t mt_last_pgno; /**< last written page */
//#endif
/** The ID of this transaction. IDs are integers incrementing from 1.
* Only committed write transactions increment the ID. If a transaction
* aborts, the ID may be re-used by the next writer.
*/
txnid_t mt_txnid;
MDB_env *mt_env; /**< the DB environment */
/** The list of pages that became unused during this transaction.
*/
MDB_IDL mt_free_pgs;
/** The list of loose pages that became unused and may be reused
* in this transaction, linked through #NEXT_LOOSE_PAGE(page).
*/
MDB_page *mt_loose_pgs;
/** Number of loose pages (#mt_loose_pgs) */
int mt_loose_count;
/** The sorted list of dirty pages we temporarily wrote to disk
* because the dirty list was full. page numbers in here are
* shifted left by 1, deleted slots have the LSB set.
*/
MDB_IDL mt_spill_pgs;
union {
/** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
MDB_ID2L dirty_list;
/** For read txns: This thread/txn's reader table slot, or NULL. */
MDB_reader *reader;
} mt_u;
/** Array of records for each DB known in the environment. */
MDB_dbx *mt_dbxs;
/** Array of MDB_db records for each known DB */
MDB_db *mt_dbs;
/** Array of sequence numbers for each DB handle */
uint64_t *mt_dbiseqs;
/** @defgroup mt_dbflag Transaction DB Flags
* @ingroup internal
* @{
*/
#define DB_DIRTY 0x01 /**< DB was written in this txn */
#define DB_STALE 0x02 /**< Named-DB record is older than txnID */
#define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
#define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
#define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
#define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
/** @} */
/** In write txns, array of cursors for each DB */
MDB_cursor **mt_cursors;
/** Array of flags for each DB */
uint8_t *mt_dbflags;
//#ifdef MDB_VL32
// /** List of read-only pages (actually chunks) */
// MDB_ID3L mt_rpages;
// /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
// * mappings must begin on 64KB boundaries. So we round off all pgnos to
// * a chunk boundary. We do the same on Linux for symmetry, and also to
// * reduce the frequency of mmap/munmap calls.
// */
//#define MDB_RPAGE_CHUNK 16
//#define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
//#define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
// uint64_t mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
//#endif
/** Number of DB records in use, or 0 when the txn is finished.
* This number only ever increments until the txn finishes; we
* don't decrement it when individual DB handles are closed.
*/
MDB_dbi mt_numdbs;
/** @defgroup mdb_txn Transaction Flags
* @ingroup internal
* @{
*/
/** #mdb_txn_begin() flags */
#define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
#define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
#define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
#define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
/* internal txn flags */
#define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
#define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
#define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
#define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
#define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
#define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
/** most operations on the txn are currently illegal */
#define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
/** @} */
uint64_t mt_flags; /**< @ref mdb_txn */
/** #dirty_list room: Array size - \#dirty pages visible to this txn.
* Includes ancestor txns' dirty pages not hidden by other txns'
* dirty/spilled pages. Thus commit(nested txn) has room to merge
* dirty_list into mt_parent after freeing hidden mt_parent pages.
*/
uint64_t mt_dirty_room;
};
/** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
* At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
* raise this on a 64 bit machine.
*/
#define CURSOR_STACK 32
struct MDB_xcursor;
/** Cursors are used for all DB operations.
* A cursor holds a path of (page pointer, key index) from the DB
* root to a position in the DB, plus other state. #MDB_DUPSORT
* cursors include an xcursor to the current data item. Write txns
* track their cursors and keep them up to date when data moves.
* Exception: An xcursor's pointer to a #P_SUBP page can be stale.
* (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
*/
struct MDB_cursor {
/** Next cursor on this DB in this txn */
MDB_cursor *mc_next;
/** Backup of the original cursor if this cursor is a shadow */
MDB_cursor *mc_backup;
/** Context used for databases with #MDB_DUPSORT, otherwise NULL */
struct MDB_xcursor *mc_xcursor;
/** The transaction that owns this cursor */
MDB_txn *mc_txn;
/** The database handle this cursor operates on */
MDB_dbi mc_dbi;
/** The database record for this cursor */
MDB_db *mc_db;
/** The database auxiliary record for this cursor */
MDB_dbx *mc_dbx;
/** The @ref mt_dbflag for this database */
uint8_t *mc_dbflag;
uint16_t mc_snum; /**< number of pushed pages */
uint16_t mc_top; /**< index of top page, normally mc_snum-1 */
/** @defgroup mdb_cursor Cursor Flags
* @ingroup internal
* Cursor state flags.
* @{
*/
#define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
#define C_EOF 0x02 /**< No more data */
#define C_SUB 0x04 /**< Cursor is a sub-cursor */
#define C_DEL 0x08 /**< last op was a cursor_del */
#define C_UNTRACK 0x40 /**< Un-track cursor when closing */
#define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
/** Read-only cursor into the txn's original snapshot in the map.
* Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
* #MDB_DEVEL & 2. Only implements code which is necessary for this.
*/
#define C_ORIG_RDONLY MDB_TXN_RDONLY
/** @} */
uint64_t mc_flags; /**< @ref mdb_cursor */
MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
//#ifdef MDB_VL32
// MDB_page *mc_ovpg; /**< a referenced overflow page */
//# define MC_OVPG(mc) ((mc)->mc_ovpg)
//# define MC_SET_OVPG(mc, pg) ((mc)->mc_ovpg = (pg))
//#else
# define MC_OVPG(mc) ((MDB_page *)0)
# define MC_SET_OVPG(mc, pg) ((void)0)
//#endif
};
/** Context for sorted-dup records.
* We could have gone to a fully recursive design, with arbitrarily
* deep nesting of sub-databases. But for now we only handle these
* levels - main DB, optional sub-DB, sorted-duplicate DB.
*/
typedef struct MDB_xcursor {
/** A sub-cursor for traversing the Dup DB */
MDB_cursor mx_cursor;
/** The database record for this Dup DB */
MDB_db mx_db;
/** The auxiliary DB record for this Dup DB */
MDB_dbx mx_dbx;
/** The @ref mt_dbflag for this Dup DB */
uint8_t mx_dbflag;
} MDB_xcursor;
/** Check if there is an inited xcursor */
#define XCURSOR_INITED(mc) \
((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
/** Update the xcursor's sub-page pointer, if any, in \b mc. Needed
* when the node which contains the sub-page may have moved. Called
* with leaf page \b mp = mc->mc_pg[\b top].
*/
#define XCURSOR_REFRESH(mc, top, mp) do { \
MDB_page *xr_pg = (mp); \
MDB_node *xr_node; \
if (!XCURSOR_INITED(mc) || (mc)->mc_ki[top] >= NUMKEYS(xr_pg)) break; \
xr_node = NODEPTR(xr_pg, (mc)->mc_ki[top]); \
if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
(mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
} while (0)
/** State of FreeDB old pages, stored in the MDB_env */
typedef struct MDB_pgstate {
pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
} MDB_pgstate;
/** The database environment. */
struct MDB_env {
HANDLE me_fd; /**< The main data file */
HANDLE me_lfd; /**< The lock file */
HANDLE me_mfd; /**< For writing and syncing the meta pages */
//#if defined(MDB_VL32) && defined(_WIN32)
// HANDLE me_fmh; /**< File Mapping handle */
//#endif
/** Failed to update the meta page. Probably an I/O error. */
#define MDB_FATAL_ERROR 0x80000000U
/** Some fields are initialized. */
#define MDB_ENV_ACTIVE 0x20000000U
/** me_txkey is set */
#define MDB_ENV_TXKEY 0x10000000U
/** fdatasync is unreliable */
#define MDB_FSYNCONLY 0x08000000U
uint32_t me_flags; /**< @ref mdb_env */
uint64_t me_psize; /**< DB page size, inited from me_os_psize */
uint64_t me_os_psize; /**< OS page size, from #GET_PAGESIZE */
uint64_t me_maxreaders; /**< size of the reader table */
/** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
volatile int me_close_readers;
MDB_dbi me_numdbs; /**< number of DBs opened */
MDB_dbi me_maxdbs; /**< size of the DB table */
MDB_PID_T me_pid; /**< process ID of this env */
char *me_path; /**< path to the DB files */
char *me_map; /**< the memory map of the data file */
MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
void *me_pbuf; /**< scratch area for DUPSORT put() */
MDB_txn *me_txn; /**< current write transaction */
MDB_txn *me_txn0; /**< prealloc'd write transaction */
mdb_size_t me_mapsize; /**< size of the data memory map */
off_t me_size; /**< current file size */
pgno_t me_maxpg; /**< me_mapsize / me_psize */
MDB_dbx *me_dbxs; /**< array of static DB info */
uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
uint64_t *me_dbiseqs; /**< array of dbi sequence numbers */
pthread_key_t me_txkey; /**< thread-key for readers */
txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
# define me_pglast me_pgstate.mf_pglast
# define me_pghead me_pgstate.mf_pghead
MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
/** IDL of pages that became unused in a write txn */
MDB_IDL me_free_pgs;
/** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
MDB_ID2L me_dirty_list;
/** Max number of freelist items that can fit in a single overflow page */
int me_maxfree_1pg;
/** Max size of a node on a page */
uint64_t me_nodemax;
#if !(MDB_MAXKEYSIZE)
uint64_t me_maxkey; /**< max size of a key */
#endif
int me_live_reader; /**< have liveness lock in reader table */
#ifdef _WIN32
int me_pidquery; /**< Used in OpenProcess */
#endif
#ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
# define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
# define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
#else
mdb_mutex_t me_rmutex;
mdb_mutex_t me_wmutex;
# if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
/** Half-initialized name of mutexes, to be completed by #MUTEXNAME() */
char me_mutexname[sizeof(MUTEXNAME_PREFIX) + 11];
# endif
#endif
//#ifdef MDB_VL32
// MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
// pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
//#define MDB_ERPAGE_SIZE 16384
//#define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
// uint64_t me_rpcheck;
//#endif
void *me_userctx; /**< User-settable context */
MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
};
/** Nested transaction */
typedef struct MDB_ntxn {
MDB_txn mnt_txn; /**< the transaction */
MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
} MDB_ntxn;
/** max number of pages to commit in one writev() call */
#define MDB_COMMIT_PAGES 64
#if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
#undef MDB_COMMIT_PAGES
#define MDB_COMMIT_PAGES IOV_MAX
#endif
/** max bytes to write in one call */
#define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
/** Check \b txn and \b dbi arguments to a function */
#define TXN_DBI_EXIST(txn, dbi, validity) \
((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
/** Check for misused \b dbi handles */
#define TXN_DBI_CHANGED(txn, dbi) \
((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
static int mdb_page_touch(MDB_cursor *mc);
#define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
"reset-tmp", "fail-begin", "fail-beginchild"}
enum {
/* mdb_txn_end operation number, for logging */
MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
};
#define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
#define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
#define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
#define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
static void mdb_txn_end(MDB_txn *txn, unsigned mode);
static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
static int mdb_page_search_root(MDB_cursor *mc,
MDB_val *key, int modify);
#define MDB_PS_MODIFY 1
#define MDB_PS_ROOTONLY 2
#define MDB_PS_FIRST 4
#define MDB_PS_LAST 8
static int mdb_page_search(MDB_cursor *mc,
MDB_val *key, int flags);
static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
#define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
pgno_t newpgno, uint64_t nflags);
static int mdb_env_read_header(MDB_env *env, int prev, MDB_meta *meta);
static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
static int mdb_env_write_meta(MDB_txn *txn);
#ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
# define mdb_env_close0(env, excl) mdb_env_close1(env)
#endif
static void mdb_env_close0(MDB_env *env, int excl);
static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
static int mdb_node_add(MDB_cursor *mc, indx_t indx,
MDB_val *key, MDB_val *data, pgno_t pgno, uint64_t flags);
static void mdb_node_del(MDB_cursor *mc, int ksize);
static void mdb_node_shrink(MDB_page *mp, indx_t indx);
static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
static int mdb_rebalance(MDB_cursor *mc);
static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
static void mdb_cursor_pop(MDB_cursor *mc);
static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
static int mdb_cursor_del0(MDB_cursor *mc);
static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
int *exactp);
static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
static void mdb_xcursor_init0(MDB_cursor *mc);
static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
static int mdb_drop0(MDB_cursor *mc, int subs);
static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
/** @cond */
static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
/** @endcond */
/** Compare two items pointing at '#mdb_size_t's of unknown alignment. */
#ifdef MISALIGNED_OK
# define mdb_cmp_clong mdb_cmp_long
#else
# define mdb_cmp_clong mdb_cmp_cint
#endif
/** True if we need #mdb_cmp_clong() instead of \b cmp for #MDB_INTEGERDUP */
#define NEED_CMP_CLONG(cmp, ksize) \
(UINT_MAX < MDB_SIZE_MAX && \
(cmp) == mdb_cmp_int && (ksize) == sizeof(mdb_size_t))
#ifdef _WIN32
static SECURITY_DESCRIPTOR mdb_null_sd;
static SECURITY_ATTRIBUTES mdb_all_sa;
static int mdb_sec_inited;
struct MDB_name;
static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
#endif
/** Return the library version info. */
char const * ESECT
mdb_version(int *major, int *minor, int *patch)
{
if (major) *major = MDB_VERSION_MAJOR;
if (minor) *minor = MDB_VERSION_MINOR;
if (patch) *patch = MDB_VERSION_PATCH;
return MDB_VERSION_STRING;
}
/** Table of descriptions for LMDB @ref errors */
static char const * const mdb_errstr[] = {
"MDB_KEYEXIST: Key/data pair already exists",
"MDB_NOTFOUND: No matching key/data pair found",
"MDB_PAGE_NOTFOUND: Requested page not found",
"MDB_CORRUPTED: Located page was wrong type",
"MDB_PANIC: Update of meta page failed or environment had fatal error",
"MDB_VERSION_MISMATCH: Database environment version mismatch",
"MDB_INVALID: File is not an LMDB file",
"MDB_MAP_FULL: Environment mapsize limit reached",
"MDB_DBS_FULL: Environment maxdbs limit reached",
"MDB_READERS_FULL: Environment maxreaders limit reached",
"MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
"MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
"MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
"MDB_PAGE_FULL: Internal error - page has no more space",
"MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
"MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
"MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
"MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
"MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
"MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
"MDB_PROBLEM: Unexpected problem - txn should abort",
};
char const *
mdb_strerror(int err)
{
#ifdef _WIN32
/** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
* This works as long as no function between the call to mdb_strerror
* and the actual use of the message uses more than 4K of stack.
*/
#define MSGSIZE 1024
#define PADSIZE 4096
char buf[MSGSIZE+PADSIZE], *ptr = buf;
#endif
int i;
if (!err)
return "Successful return: 0";
if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
i = err - MDB_KEYEXIST;
return mdb_errstr[i];
}
#ifdef _WIN32
/* These are the C-runtime error codes we use. The comment indicates
* their numeric value, and the Win32 error they would correspond to
* if the error actually came from a Win32 API. A major mess, we should
* have used LMDB-specific error codes for everything.
*/
switch(err) {
case ENOENT: /* 2, FILE_NOT_FOUND */
case EIO: /* 5, ACCESS_DENIED */
case ENOMEM: /* 12, INVALID_ACCESS */
case EACCES: /* 13, INVALID_DATA */
case EBUSY: /* 16, CURRENT_DIRECTORY */
case EINVAL: /* 22, BAD_COMMAND */
case ENOSPC: /* 28, OUT_OF_PAPER */
return strerror(err);
default:
;
}
buf[0] = 0;
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
return ptr;
#else
return (const char *) strerror(err);
#endif
}
/** assert(3) variant in cursor context */
#define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
/** assert(3) variant in transaction context */
#define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
/** assert(3) variant in environment context */
#define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
#ifndef NDEBUG
# define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
static void ESECT
mdb_assert_fail(MDB_env *env, const char *expr_txt,
const char *func, const char *file, int line)
{
char buf[400];
sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
file, line, expr_txt, func);
if (env->me_assert_func)
env->me_assert_func(env, buf);
fprintf(stderr, "%s\n", buf);
abort();
}
#else
# define mdb_assert0(env, expr, expr_txt) ((void) 0)
#endif /* NDEBUG */
#if MDB_DEBUG
/** Return the page number of \b mp which may be sub-page, for debug output */
static pgno_t
mdb_dbg_pgno(MDB_page *mp)
{
pgno_t ret;
COPY_PGNO(ret, mp->mp_pgno);
return ret;
}
/** Display a key in hexadecimal and return the address of the result.
* @param[in] key the key to display
* @param[in] buf the buffer to write into. Should always be #DKBUF.
* @return The key in hexadecimal form.
*/
char *
mdb_dkey(MDB_val *key, char *buf)
{
char *ptr = buf;
uint8_t *c = key->mv_data;
uint64_t i;
if (!key)
return "";
if (key->mv_size > DKBUF_MAXKEYSIZE)
return "MDB_MAXKEYSIZE";
/* may want to make this a dynamic check: if the key is mostly
* printable characters, print it as-is instead of converting to hex.
*/
#if 1
buf[0] = '\0';
for (i=0; i<key->mv_size; i++)
ptr += sprintf(ptr, "%02x", *c++);
#else
sprintf(buf, "%.*s", key->mv_size, key->mv_data);
#endif
return buf;
}
static const char *
mdb_leafnode_type(MDB_node *n)
{
static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
}
/** Display all the keys in the page. */
void
mdb_page_list(MDB_page *mp)
{
pgno_t pgno = mdb_dbg_pgno(mp);
const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
MDB_node *node;
uint64_t i, nkeys, nsize, total = 0;
MDB_val key;
DKBUF;
switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
case P_BRANCH: type = "Branch page"; break;
case P_LEAF: type = "Leaf page"; break;
case P_LEAF|P_SUBP: type = "Sub-page"; break;
case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
case P_OVERFLOW:
fprintf(stderr, "Overflow page %" Yu" pages %u%s\n",
pgno, mp->mp_pages, state);
return;
case P_META:
fprintf(stderr, "Meta-page %" Yu" txnid %" Yu"\n",
pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
return;
default:
fprintf(stderr, "Bad page %" Yu" flags 0x%X\n", pgno, mp->mp_flags);
return;
}
nkeys = NUMKEYS(mp);
fprintf(stderr, "%s %" Yu" numkeys %d%s\n", type, pgno, nkeys, state);
for (i=0; i<nkeys; i++) {
if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
key.mv_size = nsize = mp->mp_pad;
key.mv_data = LEAF2KEY(mp, i, nsize);
total += nsize;
fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
continue;
}
node = NODEPTR(mp, i);
key.mv_size = node->mn_ksize;
key.mv_data = node->mn_data;
nsize = NODESIZE + key.mv_size;
if (IS_BRANCH(mp)) {
fprintf(stderr, "key %d: page %" Yu", %s\n", i, NODEPGNO(node),
DKEY(&key));
total += nsize;
} else {
if (F_ISSET(node->mn_flags, F_BIGDATA))
nsize += sizeof(pgno_t);
else
nsize += NODEDSZ(node);
total += nsize;
nsize += sizeof(indx_t);
fprintf(stderr, "key %d: nsize %d, %s%s\n",
i, nsize, DKEY(&key), mdb_leafnode_type(node));
}
total = EVEN(total);
}
fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
}
void
mdb_cursor_chk(MDB_cursor *mc)
{
uint64_t i;
MDB_node *node;
MDB_page *mp;
if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
for (i=0; i<mc->mc_top; i++) {
mp = mc->mc_pg[i];
node = NODEPTR(mp, mc->mc_ki[i]);
if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
printf("oops!\n");
}
if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
printf("ack!\n");
if (XCURSOR_INITED(mc)) {
node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
printf("blah!\n");
}
}
}
#endif
#if (MDB_DEBUG) > 2
/** Count all the pages in each DB and in the freelist
* and make sure it matches the actual number of pages
* being used.
* All named DBs must be open for a correct count.
*/
static void mdb_audit(MDB_txn *txn)
{
MDB_cursor mc;
MDB_val key, data;
MDB_ID freecount, count;
MDB_dbi i;
int rc;
freecount = 0;
mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
freecount += *(MDB_ID *)data.mv_data;
mdb_tassert(txn, rc == MDB_NOTFOUND);
count = 0;
for (i = 0; i<txn->mt_numdbs; i++) {
MDB_xcursor mx;
if (!(txn->mt_dbflags[i] & DB_VALID))
continue;
mdb_cursor_init(&mc, txn, i, &mx);
if (txn->mt_dbs[i].md_root == P_INVALID)
continue;
count += txn->mt_dbs[i].md_branch_pages +
txn->mt_dbs[i].md_leaf_pages +
txn->mt_dbs[i].md_overflow_pages;
if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
unsigned j;
MDB_page *mp;
mp = mc.mc_pg[mc.mc_top];
for (j=0; j<NUMKEYS(mp); j++) {
MDB_node *leaf = NODEPTR(mp, j);
if (leaf->mn_flags & F_SUBDATA) {
MDB_db db;
memcpy(&db, NODEDATA(leaf), sizeof(db));
count += db.md_branch_pages + db.md_leaf_pages +
db.md_overflow_pages;
}
}
}
mdb_tassert(txn, rc == MDB_NOTFOUND);
}
}
if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
fprintf(stderr, "audit: %" Yu" freecount: %" Yu" count: %" Yu" total: %" Yu" next_pgno: %" Yu"\n",
txn->mt_txnid, freecount, count+NUM_METAS,
freecount+count+NUM_METAS, txn->mt_next_pgno);
}
}
#endif
int
mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
{
return txn->mt_dbxs[dbi].md_cmp(a, b);
}
int
mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
{
MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
if (NEED_CMP_CLONG(dcmp, a->mv_size))
dcmp = mdb_cmp_clong;
return dcmp(a, b);
}
/** Allocate memory for a page.
* Re-use old malloc'd pages first for singletons, otherwise just malloc.
* Set #MDB_TXN_ERROR on failure.
*/
static MDB_page *
mdb_page_malloc(MDB_txn *txn, unsigned num)
{
MDB_env *env = txn->mt_env;
MDB_page *ret = env->me_dpages;
size_t psize = env->me_psize, sz = psize, off;
/* For ! #MDB_NOMEMINIT, psize counts how much to init.
* For a single page alloc, we init everything after the page header.
* For multi-page, we init the final page; if the caller needed that
* many pages they will be filling in at least up to the last page.
*/
if (num == 1) {
if (ret) {
VGMEMP_ALLOC(env, ret, sz);
VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
env->me_dpages = ret->mp_next;
return ret;
}
psize -= off = PAGEHDRSZ;
} else {
sz *= num;
off = sz - psize;
}
if ((ret = (MDB_page *) malloc(sz)) != NULL) {
VGMEMP_ALLOC(env, ret, sz);
if (!(env->me_flags & MDB_NOMEMINIT)) {
memset((char *)ret + off, 0, psize);
ret->mp_pad = 0;
}
} else {
txn->mt_flags |= MDB_TXN_ERROR;
}
return ret;
}
/** Free a single page.
* Saves single pages to a list, for future reuse.
* (This is not used for multi-page overflow pages.)
*/
static void
mdb_page_free(MDB_env *env, MDB_page *mp)
{
mp->mp_next = env->me_dpages;
VGMEMP_FREE(env, mp);
env->me_dpages = mp;
}
/** Free a dirty page */
static void
mdb_dpage_free(MDB_env *env, MDB_page *dp)
{
if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
mdb_page_free(env, dp);
} else {
/* large pages just get freed directly */
VGMEMP_FREE(env, dp);
free(dp);
}
}
/** Return all dirty pages to dpage list */
static void
mdb_dlist_free(MDB_txn *txn)
{
MDB_env *env = txn->mt_env;
MDB_ID2L dl = txn->mt_u.dirty_list;
unsigned i, n = dl[0].mid;
for (i = 1; i <= n; i++) {
mdb_dpage_free(env, (MDB_page *)dl[i].mptr);
}
dl[0].mid = 0;
}
//#ifdef MDB_VL32
//static void
//mdb_page_unref(MDB_txn *txn, MDB_page *mp)
//{
// pgno_t pgno;
// MDB_ID3L tl = txn->mt_rpages;
// unsigned x, rem;
// if (mp->mp_flags & (P_SUBP|P_DIRTY))
// return;
// rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
// pgno = mp->mp_pgno ^ rem;
// x = mdb_mid3l_search(tl, pgno);
// if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
// x++;
// if (tl[x].mref)
// tl[x].mref--;
//}
//#define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
//static void
//mdb_cursor_unref(MDB_cursor *mc)
//{
// int i;
// if (mc->mc_txn->mt_rpages[0].mid) {
// if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
// return;
// for (i=0; i<mc->mc_snum; i++)
// mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
// if (mc->mc_ovpg) {
// mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
// mc->mc_ovpg = 0;
// }
// }
// mc->mc_snum = mc->mc_top = 0;
// mc->mc_pg[0] = NULL;
// mc->mc_flags &= ~C_INITIALIZED;
//}
//#define MDB_CURSOR_UNREF(mc, force) \
// (((force) || ((mc)->mc_flags & C_INITIALIZED)) \
// ? mdb_cursor_unref(mc) \
// : (void)0)
//#else
#define MDB_PAGE_UNREF(txn, mp)
#define MDB_CURSOR_UNREF(mc, force) ((void)0)
//#endif /* MDB_VL32 */
/** Loosen or free a single page.
* Saves single pages to a list for future reuse
* in this same txn. It has been pulled from the freeDB
* and already resides on the dirty list, but has been
* deleted. Use these pages first before pulling again
* from the freeDB.
*
* If the page wasn't dirtied in this txn, just add it
* to this txn's free list.
*/
static int
mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
{
int loose = 0;
pgno_t pgno = mp->mp_pgno;
MDB_txn *txn = mc->mc_txn;
if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
if (txn->mt_parent) {
MDB_ID2 *dl = txn->mt_u.dirty_list;
/* If txn has a parent, make sure the page is in our
* dirty list.
*/
if (dl[0].mid) {
unsigned x = mdb_mid2l_search(dl, pgno);
if (x <= dl[0].mid && dl[x].mid == pgno) {
if (mp != dl[x].mptr) { /* bad cursor? */
mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
txn->mt_flags |= MDB_TXN_ERROR;
return MDB_PROBLEM;
}
/* ok, it's ours */
loose = 1;
}
}
} else {
/* no parent txn, so it's just ours */
loose = 1;
}
}
if (loose) {
DPRINTF(("loosen db %d page %" Yu, DDBI(mc), mp->mp_pgno));
NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
txn->mt_loose_pgs = mp;
txn->mt_loose_count++;
mp->mp_flags |= P_LOOSE;
} else {
int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
if (rc)
return rc;
}
return MDB_SUCCESS;
}
/** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
* @param[in] mc A cursor handle for the current operation.
* @param[in] pflags Flags of the pages to update:
* P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
* @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
* @return 0 on success, non-zero on failure.
*/
static int
mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
{
enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
MDB_txn *txn = mc->mc_txn;
MDB_cursor *m3, *m0 = mc;
MDB_xcursor *mx;
MDB_page *dp, *mp;
MDB_node *leaf;
unsigned i, j;
int rc = MDB_SUCCESS, level;
/* Mark pages seen by cursors: First m0, then tracked cursors */
for (i = txn->mt_numdbs;; ) {
if (mc->mc_flags & C_INITIALIZED) {
for (m3 = mc;; m3 = &mx->mx_cursor) {
mp = NULL;
for (j=0; j<m3->mc_snum; j++) {
mp = m3->mc_pg[j];
if ((mp->mp_flags & Mask) == pflags)
mp->mp_flags ^= P_KEEP;
}
mx = m3->mc_xcursor;
/* Proceed to mx if it is at a sub-database */
if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
break;
if (! (mp && (mp->mp_flags & P_LEAF)))
break;
leaf = NODEPTR(mp, m3->mc_ki[j-1]);
if (!(leaf->mn_flags & F_SUBDATA))
break;
}
}
mc = mc->mc_next;
for (; !mc || mc == m0; mc = txn->mt_cursors[--i])
if (i == 0)
goto mark_done;
}
mark_done:
if (all) {
/* Mark dirty root pages */
for (i=0; i<txn->mt_numdbs; i++) {
if (txn->mt_dbflags[i] & DB_DIRTY) {
pgno_t pgno = txn->mt_dbs[i].md_root;
if (pgno == P_INVALID)
continue;
if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
break;
if ((dp->mp_flags & Mask) == pflags && level <= 1)
dp->mp_flags ^= P_KEEP;
}
}
}
return rc;
}
static int mdb_page_flush(MDB_txn *txn, int keep);
/** Spill pages from the dirty list back to disk.
* This is intended to prevent running into #MDB_TXN_FULL situations,
* but note that they may still occur in a few cases:
* 1) our estimate of the txn size could be too small. Currently this
* seems unlikely, except with a large number of #MDB_MULTIPLE items.
* 2) child txns may run out of space if their parents dirtied a
* lot of pages and never spilled them. TODO: we probably should do
* a preemptive spill during #mdb_txn_begin() of a child txn, if
* the parent's dirty_room is below a given threshold.
*
* Otherwise, if not using nested txns, it is expected that apps will
* not run into #MDB_TXN_FULL any more. The pages are flushed to disk
* the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
* If the txn never references them again, they can be left alone.
* If the txn only reads them, they can be used without any fuss.
* If the txn writes them again, they can be dirtied immediately without
* going thru all of the work of #mdb_page_touch(). Such references are
* handled by #mdb_page_unspill().
*
* Also note, we never spill DB root pages, nor pages of active cursors,
* because we'll need these back again soon anyway. And in nested txns,
* we can't spill a page in a child txn if it was already spilled in a
* parent txn. That would alter the parent txns' data even though
* the child hasn't committed yet, and we'd have no way to undo it if
* the child aborted.
*
* @param[in] m0 cursor A cursor handle identifying the transaction and
* database for which we are checking space.
* @param[in] key For a put operation, the key being stored.
* @param[in] data For a put operation, the data being stored.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
{
MDB_txn *txn = m0->mc_txn;
MDB_page *dp;
MDB_ID2L dl = txn->mt_u.dirty_list;
uint64_t i, j, need;
int rc;
if (m0->mc_flags & C_SUB)
return MDB_SUCCESS;
/* Estimate how much space this op will take */
i = m0->mc_db->md_depth;
/* Named DBs also dirty the main DB */
if (m0->mc_dbi >= CORE_DBS)
i += txn->mt_dbs[MAIN_DBI].md_depth;
/* For puts, roughly factor in the key+data size */
if (key)
i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
i += i; /* double it for good measure */
need = i;
if (txn->mt_dirty_room > i)
return MDB_SUCCESS;
if (!txn->mt_spill_pgs) {
txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
if (!txn->mt_spill_pgs)
return ENOMEM;
} else {
/* purge deleted slots */
MDB_IDL sl = txn->mt_spill_pgs;
uint64_t num = sl[0];
j=0;
for (i=1; i<=num; i++) {
if (!(sl[i] & 1))
sl[++j] = sl[i];
}
sl[0] = j;
}
/* Preserve pages which may soon be dirtied again */
if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
goto done;
/* Less aggressive spill - we originally spilled the entire dirty list,
* with a few exceptions for cursor pages and DB root pages. But this
* turns out to be a lot of wasted effort because in a large txn many
* of those pages will need to be used again. So now we spill only 1/8th
* of the dirty pages. Testing revealed this to be a good tradeoff,
* better than 1/2, 1/4, or 1/10.
*/
if (need < MDB_IDL_UM_MAX / 8)
need = MDB_IDL_UM_MAX / 8;
/* Save the page IDs of all the pages we're flushing */
/* flush from the tail forward, this saves a lot of shifting later on. */
for (i=dl[0].mid; i && need; i--) {
MDB_ID pn = dl[i].mid << 1;
dp = (MDB_page *) dl[i].mptr;
if (dp->mp_flags & (P_LOOSE|P_KEEP))
continue;
/* Can't spill twice, make sure it's not already in a parent's
* spill list.
*/
if (txn->mt_parent) {
MDB_txn *tx2;
for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
if (tx2->mt_spill_pgs) {
j = mdb_midl_search(tx2->mt_spill_pgs, pn);
if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
dp->mp_flags |= P_KEEP;
break;
}
}
}
if (tx2)
continue;
}
if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
goto done;
need--;
}
mdb_midl_sort(txn->mt_spill_pgs);
/* Flush the spilled part of dirty list */
if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
goto done;
/* Reset any dirty pages we kept that page_flush didn't see */
rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
done:
txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
return rc;
}
/** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
static txnid_t
mdb_find_oldest(MDB_txn *txn)
{
int i;
txnid_t mr, oldest = txn->mt_txnid - 1;
if (txn->mt_env->me_txns) {
MDB_reader *r = txn->mt_env->me_txns->mti_readers;
for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
if (r[i].mr_pid) {
mr = r[i].mr_txnid;
if (oldest > mr)
oldest = mr;
}
}
}
return oldest;
}
/** Add a page to the txn's dirty list */
static void
mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
{
MDB_ID2 mid;
int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
if (txn->mt_flags & MDB_TXN_WRITEMAP) {
insert = mdb_mid2l_append;
} else {
insert = mdb_mid2l_insert;
}
mid.mid = mp->mp_pgno;
mid.mptr = mp;
rc = insert(txn->mt_u.dirty_list, &mid);
mdb_tassert(txn, rc == 0);
txn->mt_dirty_room--;
}
/** Allocate page numbers and memory for writing. Maintain me_pglast,
* me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
*
* If there are free pages available from older transactions, they
* are re-used first. Otherwise allocate a new page at mt_next_pgno.
* Do not modify the freedB, just merge freeDB records into me_pghead[]
* and move me_pglast to say which records were consumed. Only this
* function can create me_pghead and move me_pglast/mt_next_pgno.
* When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
* then uses the transaction's original snapshot of the freeDB.
* @param[in] mc cursor A cursor handle identifying the transaction and
* database for which we are allocating.
* @param[in] num the number of pages to allocate.
* @param[out] mp Address of the allocated page(s). Requests for multiple pages
* will always be satisfied by a single contiguous chunk of memory.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
{
#ifdef MDB_PARANOID /* Seems like we can ignore this now */
/* Get at most <Max_retries> more freeDB records once me_pghead
* has enough pages. If not enough, use new pages from the map.
* If <Paranoid> and mc is updating the freeDB, only get new
* records if me_pghead is empty. Then the freelist cannot play
* catch-up with itself by growing while trying to save it.
*/
enum { Paranoid = 1, Max_retries = 500 };
#else
enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
#endif
int rc, retry = num * 60;
MDB_txn *txn = mc->mc_txn;
MDB_env *env = txn->mt_env;
pgno_t pgno, *mop = env->me_pghead;
unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
MDB_page *np;
txnid_t oldest = 0, last;
MDB_cursor_op op;
MDB_cursor m2;
int found_old = 0;
/* If there are any loose pages, just use them */
if (num == 1 && txn->mt_loose_pgs) {
np = txn->mt_loose_pgs;
txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
txn->mt_loose_count--;
DPRINTF(("db %d use loose page %" Yu, DDBI(mc), np->mp_pgno));
*mp = np;
return MDB_SUCCESS;
}
*mp = NULL;
/* If our dirty list is already full, we can't do anything */
if (txn->mt_dirty_room == 0) {
rc = MDB_TXN_FULL;
goto fail;
}
for (op = MDB_FIRST;; op = MDB_NEXT) {
MDB_val key, data;
MDB_node *leaf;
pgno_t *idl;
/* Seek a big enough contiguous page range. Prefer
* pages at the tail, just truncating the list.
*/
if (mop_len > n2) {
i = mop_len;
do {
pgno = mop[i];
if (mop[i-n2] == pgno+n2)
goto search_done;
} while (--i > n2);
if (--retry < 0)
break;
}
if (op == MDB_FIRST) { /* 1st iteration */
/* Prepare to fetch more and coalesce */
last = env->me_pglast;
oldest = env->me_pgoldest;
mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
#if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
/* Use original snapshot. TODO: Should need less care in code
* which modifies the database. Maybe we can delete some code?
*/
m2.mc_flags |= C_ORIG_RDONLY;
m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
m2.mc_dbflag = (uint8_t *)""; /* probably unnecessary */
#endif
if (last) {
op = MDB_SET_RANGE;
key.mv_data = &last; /* will look up last+1 */
key.mv_size = sizeof(last);
}
if (Paranoid && mc->mc_dbi == FREE_DBI)
retry = -1;
}
if (Paranoid && retry < 0 && mop_len)
break;
last++;
/* Do not fetch more if the record will be too recent */
if (oldest <= last) {
if (!found_old) {
oldest = mdb_find_oldest(txn);
env->me_pgoldest = oldest;
found_old = 1;
}
if (oldest <= last)
break;
}
rc = mdb_cursor_get(&m2, &key, NULL, op);
if (rc) {
if (rc == MDB_NOTFOUND)
break;
goto fail;
}
last = *(txnid_t*)key.mv_data;
if (oldest <= last) {
if (!found_old) {
oldest = mdb_find_oldest(txn);
env->me_pgoldest = oldest;
found_old = 1;
}
if (oldest <= last)
break;
}
np = m2.mc_pg[m2.mc_top];
leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
goto fail;
idl = (MDB_ID *) data.mv_data;
i = idl[0];
if (!mop) {
if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
rc = ENOMEM;
goto fail;
}
} else {
if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
goto fail;
mop = env->me_pghead;
}
env->me_pglast = last;
#if (MDB_DEBUG) > 1
DPRINTF(("IDL read txn %" Yu" root %" Yu" num %u",
last, txn->mt_dbs[FREE_DBI].md_root, i));
for (j = i; j; j--)
DPRINTF(("IDL %" Yu, idl[j]));
#endif
/* Merge in descending sorted order */
mdb_midl_xmerge(mop, idl);
mop_len = mop[0];
}
/* Use new pages from the map when nothing suitable in the freeDB */
i = 0;
pgno = txn->mt_next_pgno;
if (pgno + num >= env->me_maxpg) {
DPUTS("DB size maxed out");
rc = MDB_MAP_FULL;
goto fail;
}
#if defined(_WIN32) && !defined(MDB_VL32)
if (!(env->me_flags & MDB_RDONLY)) {
void *p;
p = (MDB_page *)(env->me_map + env->me_psize * pgno);
p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
(env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
PAGE_READONLY);
if (!p) {
DPUTS("VirtualAlloc failed");
rc = ErrCode();
goto fail;
}
}
#endif
search_done:
if (env->me_flags & MDB_WRITEMAP) {
np = (MDB_page *)(env->me_map + env->me_psize * pgno);
} else {
if (!(np = mdb_page_malloc(txn, num))) {
rc = ENOMEM;
goto fail;
}
}
if (i) {
mop[0] = mop_len -= num;
/* Move any stragglers down */
for (j = i-num; j < mop_len; )
mop[++j] = mop[++i];
} else {
txn->mt_next_pgno = pgno + num;
}
np->mp_pgno = pgno;
mdb_page_dirty(txn, np);
*mp = np;
return MDB_SUCCESS;
fail:
txn->mt_flags |= MDB_TXN_ERROR;
return rc;
}
/** Copy the used portions of a non-overflow page.
* @param[in] dst page to copy into
* @param[in] src page to copy from
* @param[in] psize size of a page
*/
static void
mdb_page_copy(MDB_page *dst, MDB_page *src, uint64_t psize)
{
enum { Align = sizeof(pgno_t) };
indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
/* If page isn't full, just copy the used portion. Adjust
* alignment so memcpy may copy words instead of bytes.
*/
if ((unused &= -Align) && !IS_LEAF2(src)) {
upper = (upper + PAGEBASE) & -Align;
memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
psize - upper);
} else {
memcpy(dst, src, psize - unused);
}
}
/** Pull a page off the txn's spill list, if present.
* If a page being referenced was spilled to disk in this txn, bring
* it back and make it dirty/writable again.
* @param[in] txn the transaction handle.
* @param[in] mp the page being referenced. It must not be dirty.
* @param[out] ret the writable page, if any. ret is unchanged if
* mp wasn't spilled.
*/
static int
mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
{
MDB_env *env = txn->mt_env;
const MDB_txn *tx2;
unsigned x;
pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
if (!tx2->mt_spill_pgs)
continue;
x = mdb_midl_search(tx2->mt_spill_pgs, pn);
if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
MDB_page *np;
int num;
if (txn->mt_dirty_room == 0)
return MDB_TXN_FULL;
if (IS_OVERFLOW(mp))
num = mp->mp_pages;
else
num = 1;
if (env->me_flags & MDB_WRITEMAP) {
np = mp;
} else {
np = mdb_page_malloc(txn, num);
if (!np)
return ENOMEM;
if (num > 1)
memcpy(np, mp, num * env->me_psize);
else
mdb_page_copy(np, mp, env->me_psize);
}
if (tx2 == txn) {
/* If in current txn, this page is no longer spilled.
* If it happens to be the last page, truncate the spill list.
* Otherwise mark it as deleted by setting the LSB.
*/
if (x == txn->mt_spill_pgs[0])
txn->mt_spill_pgs[0]--;
else
txn->mt_spill_pgs[x] |= 1;
} /* otherwise, if belonging to a parent txn, the
* page remains spilled until child commits
*/
mdb_page_dirty(txn, np);
np->mp_flags |= P_DIRTY;
*ret = np;
break;
}
}
return MDB_SUCCESS;
}
/** Touch a page: make it dirty and re-insert into tree with updated pgno.
* Set #MDB_TXN_ERROR on failure.
* @param[in] mc cursor pointing to the page to be touched
* @return 0 on success, non-zero on failure.
*/
static int
mdb_page_touch(MDB_cursor *mc)
{
MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
MDB_txn *txn = mc->mc_txn;
MDB_cursor *m2, *m3;
pgno_t pgno;
int rc;
if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
if (txn->mt_flags & MDB_TXN_SPILLS) {
np = NULL;
rc = mdb_page_unspill(txn, mp, &np);
if (rc)
goto fail;
if (np)
goto done;
}
if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
(rc = mdb_page_alloc(mc, 1, &np)))
goto fail;
pgno = np->mp_pgno;
DPRINTF(("touched db %d page %" Yu" -> %" Yu, DDBI(mc),
mp->mp_pgno, pgno));
mdb_cassert(mc, mp->mp_pgno != pgno);
mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
/* Update the parent page, if any, to point to the new page */
if (mc->mc_top) {
MDB_page *parent = mc->mc_pg[mc->mc_top-1];
MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
SETPGNO(node, pgno);
} else {
mc->mc_db->md_root = pgno;
}
} else if (txn->mt_parent && !IS_SUBP(mp)) {
MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
pgno = mp->mp_pgno;
/* If txn has a parent, make sure the page is in our
* dirty list.
*/
if (dl[0].mid) {
unsigned x = mdb_mid2l_search(dl, pgno);
if (x <= dl[0].mid && dl[x].mid == pgno) {
if (mp != dl[x].mptr) { /* bad cursor? */
mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
txn->mt_flags |= MDB_TXN_ERROR;
return MDB_PROBLEM;
}
return 0;
}
}
mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
/* No - copy it */
np = mdb_page_malloc(txn, 1);
if (!np)
return ENOMEM;
mid.mid = pgno;
mid.mptr = np;
rc = mdb_mid2l_insert(dl, &mid);
mdb_cassert(mc, rc == 0);
} else {
return 0;
}
mdb_page_copy(np, mp, txn->mt_env->me_psize);
np->mp_pgno = pgno;
np->mp_flags |= P_DIRTY;
done:
/* Adjust cursors pointing to mp */
mc->mc_pg[mc->mc_top] = np;
m2 = txn->mt_cursors[mc->mc_dbi];
if (mc->mc_flags & C_SUB) {
for (; m2; m2=m2->mc_next) {
m3 = &m2->mc_xcursor->mx_cursor;
if (m3->mc_snum < mc->mc_snum) continue;
if (m3->mc_pg[mc->mc_top] == mp)
m3->mc_pg[mc->mc_top] = np;
}
} else {
for (; m2; m2=m2->mc_next) {
if (m2->mc_snum < mc->mc_snum) continue;
if (m2 == mc) continue;
if (m2->mc_pg[mc->mc_top] == mp) {
m2->mc_pg[mc->mc_top] = np;
if (IS_LEAF(np))
XCURSOR_REFRESH(m2, mc->mc_top, np);
}
}
}
MDB_PAGE_UNREF(mc->mc_txn, mp);
return 0;
fail:
txn->mt_flags |= MDB_TXN_ERROR;
return rc;
}
int
mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
{
int rc = 0;
if (env->me_flags & MDB_RDONLY)
return EACCES;
if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
if (env->me_flags & MDB_WRITEMAP) {
int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
? MS_ASYNC : MS_SYNC;
if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
rc = ErrCode();
#ifdef _WIN32
else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
rc = ErrCode();
#endif
} else {
//#ifdef BROKEN_FDATASYNC
// if (env->me_flags & MDB_FSYNCONLY) {
// if (fsync(env->me_fd))
// rc = ErrCode();
// } else
//#endif
if (MDB_FDATASYNC(env->me_fd))
rc = ErrCode();
}
}
return rc;
}
int
mdb_env_sync(MDB_env *env, int force)
{
MDB_meta *m = mdb_env_pick_meta(env);
return mdb_env_sync0(env, force, m->mm_last_pg+1);
}
/** Back up parent txn's cursors, then grab the originals for tracking */
static int
mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
{
MDB_cursor *mc, *bk;
MDB_xcursor *mx;
size_t size;
int i;
for (i = src->mt_numdbs; --i >= 0; ) {
if ((mc = src->mt_cursors[i]) != NULL) {
size = sizeof(MDB_cursor);
if (mc->mc_xcursor)
size += sizeof(MDB_xcursor);
for (; mc; mc = (MDB_cursor *)bk->mc_next) {
bk = (MDB_cursor *) malloc(size);
if (!bk)
return ENOMEM;
*bk = *mc;
mc->mc_backup = bk;
mc->mc_db = &dst->mt_dbs[i];
/* Kill pointers into src to reduce abuse: The
* user may not use mc until dst ends. But we need a valid
* txn pointer here for cursor fixups to keep working.
*/
mc->mc_txn = dst;
mc->mc_dbflag = &dst->mt_dbflags[i];
if ((mx = mc->mc_xcursor) != NULL) {
*(MDB_xcursor *)(bk+1) = *mx;
mx->mx_cursor.mc_txn = dst;
}
mc->mc_next = dst->mt_cursors[i];
dst->mt_cursors[i] = mc;
}
}
}
return MDB_SUCCESS;
}
/** Close this write txn's cursors, give parent txn's cursors back to parent.
* @param[in] txn the transaction handle.
* @param[in] merge true to keep changes to parent cursors, false to revert.
* @return 0 on success, non-zero on failure.
*/
static void
mdb_cursors_close(MDB_txn *txn, unsigned merge)
{
MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
MDB_xcursor *mx;
int i;
for (i = txn->mt_numdbs; --i >= 0; ) {
for (mc = cursors[i]; mc; mc = next) {
next = mc->mc_next;
if ((bk = mc->mc_backup) != NULL) {
if (merge) {
/* Commit changes to parent txn */
mc->mc_next = bk->mc_next;
mc->mc_backup = bk->mc_backup;
mc->mc_txn = bk->mc_txn;
mc->mc_db = bk->mc_db;
mc->mc_dbflag = bk->mc_dbflag;
if ((mx = mc->mc_xcursor) != NULL)
mx->mx_cursor.mc_txn = bk->mc_txn;
} else {
/* Abort nested txn */
*mc = *bk;
if ((mx = mc->mc_xcursor) != NULL)
*mx = *(MDB_xcursor *)(bk+1);
}
mc = bk;
}
/* Only malloced cursors are permanently tracked. */
free(mc);
}
cursors[i] = NULL;
}
}
#if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
enum Pidlock_op {
Pidset, Pidcheck
};
#else
enum Pidlock_op {
Pidset = F_SETLK, Pidcheck = F_GETLK
};
#endif
/** Set or check a pid lock. Set returns 0 on success.
* Check returns 0 if the process is certainly dead, nonzero if it may
* be alive (the lock exists or an error happened so we do not know).
*
* On Windows Pidset is a no-op, we merely check for the existence
* of the process with the given pid. On POSIX we use a single byte
* lock on the lockfile, set at an offset equal to the pid.
*/
static int
mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
{
#if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
int ret = 0;
HANDLE h;
if (op == Pidcheck) {
h = OpenProcess(env->me_pidquery, FALSE, pid);
/* No documented "no such process" code, but other program use this: */
if (!h)
return ErrCode() != ERROR_INVALID_PARAMETER;
/* A process exists until all handles to it close. Has it exited? */
ret = WaitForSingleObject(h, 0) != 0;
CloseHandle(h);
}
return ret;
#else
for (;;) {
int rc;
struct flock lock_info;
memset(&lock_info, 0, sizeof(lock_info));
lock_info.l_type = F_WRLCK;
lock_info.l_whence = SEEK_SET;
lock_info.l_start = pid;
lock_info.l_len = 1;
if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
if (op == F_GETLK && lock_info.l_type != F_UNLCK)
rc = -1;
} else if ((rc = ErrCode()) == EINTR) {
continue;
}
return rc;
}
#endif
}
/** Common code for #mdb_txn_begin() and #mdb_txn_renew().
* @param[in] txn the transaction handle to initialize
* @return 0 on success, non-zero on failure.
*/
static int
mdb_txn_renew0(MDB_txn *txn)
{
MDB_env *env = txn->mt_env;
MDB_txninfo *ti = env->me_txns;
MDB_meta *meta;
uint64_t i, nr, flags = txn->mt_flags;
uint16_t x;
int rc, new_notls = 0;
if ((flags &= MDB_TXN_RDONLY) != 0) {
if (!ti) {
meta = mdb_env_pick_meta(env);
txn->mt_txnid = meta->mm_txnid;
txn->mt_u.reader = NULL;
} else {
MDB_reader *r = (env->me_flags & MDB_NOTLS) ? (MDB_reader *) txn->mt_u.reader :
(MDB_reader *) pthread_getspecific(env->me_txkey);
if (r) {
if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
return MDB_BAD_RSLOT;
} else {
MDB_PID_T pid = env->me_pid;
MDB_THR_T tid = pthread_self();
mdb_mutexref_t rmutex = env->me_rmutex;
if (!env->me_live_reader) {
rc = mdb_reader_pid(env, Pidset, pid);
if (rc)
return rc;
env->me_live_reader = 1;
}
if (LOCK_MUTEX(rc, env, rmutex))
return rc;
nr = ti->mti_numreaders;
for (i=0; i<nr; i++)
if (ti->mti_readers[i].mr_pid == 0)
break;
if (i == env->me_maxreaders) {
UNLOCK_MUTEX(rmutex);
return MDB_READERS_FULL;
}
r = &ti->mti_readers[i];
/* Claim the reader slot, carefully since other code
* uses the reader table un-mutexed: First reset the
* slot, next publish it in mti_numreaders. After
* that, it is safe for mdb_env_close() to touch it.
* When it will be closed, we can finally claim it.
*/
r->mr_pid = 0;
r->mr_txnid = (txnid_t)-1;
r->mr_tid = tid;
if (i == nr)
ti->mti_numreaders = ++nr;
env->me_close_readers = nr;
r->mr_pid = pid;
UNLOCK_MUTEX(rmutex);
new_notls = (env->me_flags & MDB_NOTLS);
if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
r->mr_pid = 0;
return rc;
}
}
do /* LY: Retry on a race, ITS#7970. */
r->mr_txnid = ti->mti_txnid;
while(r->mr_txnid != ti->mti_txnid);
txn->mt_txnid = r->mr_txnid;
txn->mt_u.reader = r;
meta = env->me_metas[txn->mt_txnid & 1];
}
} else {
/* Not yet touching txn == env->me_txn0, it may be active */
if (ti) {
if (LOCK_MUTEX(rc, env, env->me_wmutex))
return rc;
txn->mt_txnid = ti->mti_txnid;
meta = env->me_metas[txn->mt_txnid & 1];
} else {
meta = mdb_env_pick_meta(env);
txn->mt_txnid = meta->mm_txnid;
}
txn->mt_txnid++;
#if MDB_DEBUG
if (txn->mt_txnid == mdb_debug_start)
mdb_debug = 1;
#endif
txn->mt_child = NULL;
txn->mt_loose_pgs = NULL;
txn->mt_loose_count = 0;
txn->mt_dirty_room = MDB_IDL_UM_MAX;
txn->mt_u.dirty_list = env->me_dirty_list;
txn->mt_u.dirty_list[0].mid = 0;
txn->mt_free_pgs = env->me_free_pgs;
txn->mt_free_pgs[0] = 0;
txn->mt_spill_pgs = NULL;
env->me_txn = txn;
memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(uint64_t));
}
/* Copy the DB info and flags */
memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
/* Moved to here to avoid a data race in read TXNs */
txn->mt_next_pgno = meta->mm_last_pg+1;
//#ifdef MDB_VL32
// txn->mt_last_pgno = txn->mt_next_pgno - 1;
//#endif
txn->mt_flags = flags;
/* Setup db info */
txn->mt_numdbs = env->me_numdbs;
for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
x = env->me_dbflags[i];
txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
}
txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
txn->mt_dbflags[FREE_DBI] = DB_VALID;
if (env->me_flags & MDB_FATAL_ERROR) {
DPUTS("environment had fatal error, must shutdown!");
rc = MDB_PANIC;
} else if (env->me_maxpg < txn->mt_next_pgno) {
rc = MDB_MAP_RESIZED;
} else {
return MDB_SUCCESS;
}
mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
return rc;
}
int
mdb_txn_renew(MDB_txn *txn)
{
int rc;
if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
return EINVAL;
rc = mdb_txn_renew0(txn);
if (rc == MDB_SUCCESS) {
DPRINTF(("renew txn %" Yu"%c %p on mdbenv %p, root page %" Yu,
txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
(void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
}
return rc;
}
int
mdb_txn_begin(MDB_env *env, MDB_txn *parent, uint64_t flags, MDB_txn **ret)
{
MDB_txn *txn;
MDB_ntxn *ntxn;
int rc, size, tsize;
flags &= MDB_TXN_BEGIN_FLAGS;
flags |= env->me_flags & MDB_WRITEMAP;
if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
return EACCES;
if (parent) {
/* Nested transactions: Max 1 child, write txns only, no writemap */
flags |= parent->mt_flags;
if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
}
/* Child txns save MDB_pgstate and use own copy of cursors */
size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
size += tsize = sizeof(MDB_ntxn);
} else if (flags & MDB_RDONLY) {
size = env->me_maxdbs * (sizeof(MDB_db)+1);
size += tsize = sizeof(MDB_txn);
} else {
/* Reuse preallocated write txn. However, do not touch it until
* mdb_txn_renew0() succeeds, since it currently may be active.
*/
txn = env->me_txn0;
goto renew;
}
if ((txn = (MDB_txn *) calloc(1, size)) == NULL) {
DPRINTF(("calloc: %s", strerror(errno)));
return ENOMEM;
}
//#ifdef MDB_VL32
// if (!parent) {
// txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
// if (!txn->mt_rpages) {
// free(txn);
// return ENOMEM;
// }
// txn->mt_rpages[0].mid = 0;
// txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
// }
//#endif
txn->mt_dbxs = env->me_dbxs; /* static */
txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
txn->mt_dbflags = (uint8_t *)txn + size - env->me_maxdbs;
txn->mt_flags = flags;
txn->mt_env = env;
if (parent) {
uint64_t i;
txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
txn->mt_dbiseqs = parent->mt_dbiseqs;
txn->mt_u.dirty_list = (MDB_ID2 *) malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
if (!txn->mt_u.dirty_list ||
!(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
{
free(txn->mt_u.dirty_list);
free(txn);
return ENOMEM;
}
txn->mt_txnid = parent->mt_txnid;
txn->mt_dirty_room = parent->mt_dirty_room;
txn->mt_u.dirty_list[0].mid = 0;
txn->mt_spill_pgs = NULL;
txn->mt_next_pgno = parent->mt_next_pgno;
parent->mt_flags |= MDB_TXN_HAS_CHILD;
parent->mt_child = txn;
txn->mt_parent = parent;
txn->mt_numdbs = parent->mt_numdbs;
//#ifdef MDB_VL32
// txn->mt_rpages = parent->mt_rpages;
//#endif
memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
/* Copy parent's mt_dbflags, but clear DB_NEW */
for (i=0; i<txn->mt_numdbs; i++)
txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
rc = 0;
ntxn = (MDB_ntxn *)txn;
ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
if (env->me_pghead) {
size = MDB_IDL_SIZEOF(env->me_pghead);
env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
if (env->me_pghead)
memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
else
rc = ENOMEM;
}
if (!rc)
rc = mdb_cursor_shadow(parent, txn);
if (rc)
mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
} else { /* MDB_RDONLY */
txn->mt_dbiseqs = env->me_dbiseqs;
renew:
rc = mdb_txn_renew0(txn);
}
if (rc) {
if (txn != env->me_txn0) {
//#ifdef MDB_VL32
// free(txn->mt_rpages);
//#endif
free(txn);
}
} else {
txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
*ret = txn;
DPRINTF(("begin txn %" Yu"%c %p on mdbenv %p, root page %" Yu,
txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
(void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
}
return rc;
}
MDB_env *
mdb_txn_env(MDB_txn *txn)
{
if(!txn) return NULL;
return txn->mt_env;
}
mdb_size_t
mdb_txn_id(MDB_txn *txn)
{
if(!txn) return 0;
return txn->mt_txnid;
}
/** Export or close DBI handles opened in this txn. */
static void
mdb_dbis_update(MDB_txn *txn, int keep)
{
int i;
MDB_dbi n = txn->mt_numdbs;
MDB_env *env = txn->mt_env;
uint8_t *tdbflags = txn->mt_dbflags;
for (i = n; --i >= CORE_DBS;) {
if (tdbflags[i] & DB_NEW) {
if (keep) {
env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
} else {
char *ptr = (char *) env->me_dbxs[i].md_name.mv_data;
if (ptr) {
env->me_dbxs[i].md_name.mv_data = NULL;
env->me_dbxs[i].md_name.mv_size = 0;
env->me_dbflags[i] = 0;
env->me_dbiseqs[i]++;
free(ptr);
}
}
}
}
if (keep && env->me_numdbs < n)
env->me_numdbs = n;
}
/** End a transaction, except successful commit of a nested transaction.
* May be called twice for readonly txns: First reset it, then abort.
* @param[in] txn the transaction handle to end
* @param[in] mode why and how to end the transaction
*/
static void
mdb_txn_end(MDB_txn *txn, unsigned mode)
{
MDB_env *env = txn->mt_env;
#if MDB_DEBUG
static const char *const names[] = MDB_END_NAMES;
#endif
/* Export or close DBI handles opened in this txn */
mdb_dbis_update(txn, mode & MDB_END_UPDATE);
DPRINTF(("%s txn %" Yu"%c %p on mdbenv %p, root page %" Yu,
names[mode & MDB_END_OPMASK],
txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
(void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
if (txn->mt_u.reader) {
txn->mt_u.reader->mr_txnid = (txnid_t)-1;
if (!(env->me_flags & MDB_NOTLS)) {
txn->mt_u.reader = NULL; /* txn does not own reader */
} else if (mode & MDB_END_SLOT) {
txn->mt_u.reader->mr_pid = 0;
txn->mt_u.reader = NULL;
} /* else txn owns the slot until it does MDB_END_SLOT */
}
txn->mt_numdbs = 0; /* prevent further DBI activity */
txn->mt_flags |= MDB_TXN_FINISHED;
} else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
pgno_t *pghead = env->me_pghead;
if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
mdb_cursors_close(txn, 0);
if (!(env->me_flags & MDB_WRITEMAP)) {
mdb_dlist_free(txn);
}
txn->mt_numdbs = 0;
txn->mt_flags = MDB_TXN_FINISHED;
if (!txn->mt_parent) {
mdb_midl_shrink(&txn->mt_free_pgs);
env->me_free_pgs = txn->mt_free_pgs;
/* me_pgstate: */
env->me_pghead = NULL;
env->me_pglast = 0;
env->me_txn = NULL;
mode = 0; /* txn == env->me_txn0, do not free() it */
/* The writer mutex was locked in mdb_txn_begin. */
if (env->me_txns)
UNLOCK_MUTEX(env->me_wmutex);
} else {
txn->mt_parent->mt_child = NULL;
txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
mdb_midl_free(txn->mt_free_pgs);
mdb_midl_free(txn->mt_spill_pgs);
free(txn->mt_u.dirty_list);
}
mdb_midl_free(pghead);
}
//#ifdef MDB_VL32
// if (!txn->mt_parent) {
// MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
// unsigned i, x, n = tl[0].mid;
// pthread_mutex_lock(&env->me_rpmutex);
// for (i = 1; i <= n; i++) {
// if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
// /* tmp overflow pages that we didn't share in env */
// munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
// } else {
// x = mdb_mid3l_search(el, tl[i].mid);
// if (tl[i].mptr == el[x].mptr) {
// el[x].mref--;
// } else {
// /* another tmp overflow page */
// munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
// }
// }
// }
// pthread_mutex_unlock(&env->me_rpmutex);
// tl[0].mid = 0;
// if (mode & MDB_END_FREE)
// free(tl);
// }
//#endif
if (mode & MDB_END_FREE)
free(txn);
}
void
mdb_txn_reset(MDB_txn *txn)
{
if (txn == NULL)
return;
/* This call is only valid for read-only txns */
if (!(txn->mt_flags & MDB_TXN_RDONLY))
return;
mdb_txn_end(txn, MDB_END_RESET);
}
void
mdb_txn_abort(MDB_txn *txn)
{
if (txn == NULL)
return;
if (txn->mt_child)
mdb_txn_abort(txn->mt_child);
mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
}
/** Save the freelist as of this transaction to the freeDB.
* This changes the freelist. Keep trying until it stabilizes.
*
* When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
* it then uses the transaction's original snapshot of the freeDB.
*/
static int
mdb_freelist_save(MDB_txn *txn)
{
/* env->me_pghead[] can grow and shrink during this call.
* env->me_pglast and txn->mt_free_pgs[] can only grow.
* Page numbers cannot disappear from txn->mt_free_pgs[].
*/
MDB_cursor mc;
MDB_env *env = txn->mt_env;
int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
txnid_t pglast = 0, head_id = 0;
pgno_t freecnt = 0, *free_pgs, *mop;
ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
if (env->me_pghead) {
/* Make sure first page of freeDB is touched and on freelist */
rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
if (rc && rc != MDB_NOTFOUND)
return rc;
}
if (!env->me_pghead && txn->mt_loose_pgs) {
/* Put loose page numbers in mt_free_pgs, since
* we may be unable to return them to me_pghead.
*/
MDB_page *mp = txn->mt_loose_pgs;
MDB_ID2 *dl = txn->mt_u.dirty_list;
unsigned x;
if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
return rc;
for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
/* must also remove from dirty list */
if (txn->mt_flags & MDB_TXN_WRITEMAP) {
for (x=1; x<=dl[0].mid; x++)
if (dl[x].mid == mp->mp_pgno)
break;
mdb_tassert(txn, x <= dl[0].mid);
} else {
x = mdb_mid2l_search(dl, mp->mp_pgno);
mdb_tassert(txn, dl[x].mid == mp->mp_pgno);
}
dl[x].mptr = NULL;
mdb_dpage_free(env, mp);
}
{
/* squash freed slots out of the dirty list */
unsigned y;
for (y=1; dl[y].mptr && y <= dl[0].mid; y++);
if (y <= dl[0].mid) {
for(x=y, y++;;) {
while (!dl[y].mptr && y <= dl[0].mid) y++;
if (y > dl[0].mid) break;
dl[x++] = dl[y++];
}
dl[0].mid = x-1;
} else {
/* all slots freed */
dl[0].mid = 0;
}
}
txn->mt_loose_pgs = NULL;
txn->mt_loose_count = 0;
}
/* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
? SSIZE_MAX : maxfree_1pg;
for (;;) {
/* Come back here after each Put() in case freelist changed */
MDB_val key, data;
pgno_t *pgs;
ssize_t j;
/* If using records from freeDB which we have not yet
* deleted, delete them and any we reserved for me_pghead.
*/
while (pglast < env->me_pglast) {
rc = mdb_cursor_first(&mc, &key, NULL);
if (rc)
return rc;
pglast = head_id = *(txnid_t *)key.mv_data;
total_room = head_room = 0;
mdb_tassert(txn, pglast <= env->me_pglast);
rc = mdb_cursor_del(&mc, 0);
if (rc)
return rc;
}
/* Save the IDL of pages freed by this txn, to a single record */
if (freecnt < txn->mt_free_pgs[0]) {
if (!freecnt) {
/* Make sure last page of freeDB is touched and on freelist */
rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
if (rc && rc != MDB_NOTFOUND)
return rc;
}
free_pgs = txn->mt_free_pgs;
/* Write to last page of freeDB */
key.mv_size = sizeof(txn->mt_txnid);
key.mv_data = &txn->mt_txnid;
do {
freecnt = free_pgs[0];
data.mv_size = MDB_IDL_SIZEOF(free_pgs);
rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
if (rc)
return rc;
/* Retry if mt_free_pgs[] grew during the Put() */
free_pgs = txn->mt_free_pgs;
} while (freecnt < free_pgs[0]);
mdb_midl_sort(free_pgs);
memcpy(data.mv_data, free_pgs, data.mv_size);
#if (MDB_DEBUG) > 1
{
uint64_t i = free_pgs[0];
DPRINTF(("IDL write txn %" Yu" root %" Yu" num %u",
txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
for (; i; i--)
DPRINTF(("IDL %" Yu, free_pgs[i]));
}
#endif
continue;
}
mop = env->me_pghead;
mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
/* Reserve records for me_pghead[]. Split it if multi-page,
* to avoid searching freeDB for a page range. Use keys in
* range [1,me_pglast]: Smaller than txnid of oldest reader.
*/
if (total_room >= mop_len) {
if (total_room == mop_len || --more < 0)
break;
} else if (head_room >= maxfree_1pg && head_id > 1) {
/* Keep current record (overflow page), add a new one */
head_id--;
head_room = 0;
}
/* (Re)write {key = head_id, IDL length = head_room} */
total_room -= head_room;
head_room = mop_len - total_room;
if (head_room > maxfree_1pg && head_id > 1) {
/* Overflow multi-page for part of me_pghead */
head_room /= head_id; /* amortize page sizes */
head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
} else if (head_room < 0) {
/* Rare case, not bothering to delete this record */
head_room = 0;
}
key.mv_size = sizeof(head_id);
key.mv_data = &head_id;
data.mv_size = (head_room + 1) * sizeof(pgno_t);
rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
if (rc)
return rc;
/* IDL is initially empty, zero out at least the length */
pgs = (pgno_t *)data.mv_data;
j = head_room > clean_limit ? head_room : 0;
do {
pgs[j] = 0;
} while (--j >= 0);
total_room += head_room;
}
/* Return loose page numbers to me_pghead, though usually none are
* left at this point. The pages themselves remain in dirty_list.
*/
if (txn->mt_loose_pgs) {
MDB_page *mp = txn->mt_loose_pgs;
unsigned count = txn->mt_loose_count;
MDB_IDL loose;
/* Room for loose pages + temp IDL with same */
if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
return rc;
mop = env->me_pghead;
loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
loose[ ++count ] = mp->mp_pgno;
loose[0] = count;
mdb_midl_sort(loose);
mdb_midl_xmerge(mop, loose);
txn->mt_loose_pgs = NULL;
txn->mt_loose_count = 0;
mop_len = mop[0];
}
/* Fill in the reserved me_pghead records */
rc = MDB_SUCCESS;
if (mop_len) {
MDB_val key, data;
mop += mop_len;
rc = mdb_cursor_first(&mc, &key, &data);
for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
txnid_t id = *(txnid_t *)key.mv_data;
ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
MDB_ID save;
mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
key.mv_data = &id;
if (len > mop_len) {
len = mop_len;
data.mv_size = (len + 1) * sizeof(MDB_ID);
}
data.mv_data = mop -= len;
save = mop[0];
mop[0] = len;
rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
mop[0] = save;
if (rc || !(mop_len -= len))
break;
}
}
return rc;
}
/** Flush (some) dirty pages to the map, after clearing their dirty flag.
* @param[in] txn the transaction that's being committed
* @param[in] keep number of initial pages in dirty_list to keep dirty.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_page_flush(MDB_txn *txn, int keep)
{
MDB_env *env = txn->mt_env;
MDB_ID2L dl = txn->mt_u.dirty_list;
unsigned psize = env->me_psize, j;
int i, pagecount = dl[0].mid, rc;
size_t size = 0;
off_t pos = 0;
pgno_t pgno = 0;
MDB_page *dp = NULL;
#ifdef _WIN32
OVERLAPPED ov;
#else
struct iovec iov[MDB_COMMIT_PAGES];
ssize_t wsize = 0, wres;
off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
int n = 0;
#endif
j = i = keep;
if (env->me_flags & MDB_WRITEMAP) {
/* Clear dirty flags */
while (++i <= pagecount) {
dp = (MDB_page *) dl[i].mptr;
/* Don't flush this page yet */
if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
dp->mp_flags &= ~P_KEEP;
dl[++j] = dl[i];
continue;
}
dp->mp_flags &= ~P_DIRTY;
}
goto done;
}
/* Write the pages */
for (;;) {
if (++i <= pagecount) {
dp = (MDB_page *) dl[i].mptr;
/* Don't flush this page yet */
if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
dp->mp_flags &= ~P_KEEP;
dl[i].mid = 0;
continue;
}
pgno = dl[i].mid;
/* clear dirty flag */
dp->mp_flags &= ~P_DIRTY;
pos = pgno * psize;
size = psize;
if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
}
#ifdef _WIN32
else break;
/* Windows actually supports scatter/gather I/O, but only on
* unbuffered file handles. Since we're relying on the OS page
* cache for all our data, that's self-defeating. So we just
* write pages one at a time. We use the ov structure to set
* the write offset, to at least save the overhead of a Seek
* system call.
*/
DPRINTF(("committing page %" Yu, pgno));
memset(&ov, 0, sizeof(ov));
ov.Offset = pos & 0xffffffff;
ov.OffsetHigh = pos >> 16 >> 16;
if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
rc = ErrCode();
DPRINTF(("WriteFile: %d", rc));
return rc;
}
#else
/* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
if (n) {
retry_write:
/* Write previous page(s) */
#ifdef MDB_USE_PWRITEV
wres = pwritev(env->me_fd, iov, n, wpos);
#else
if (n == 1) {
wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
} else {
retry_seek:
if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
rc = ErrCode();
if (rc == EINTR)
goto retry_seek;
DPRINTF(("lseek: %s", strerror(rc)));
return rc;
}
wres = writev(env->me_fd, iov, n);
}
#endif
if (wres != wsize) {
if (wres < 0) {
rc = ErrCode();
if (rc == EINTR)
goto retry_write;
DPRINTF(("Write error: %s", strerror(rc)));
} else {
rc = EIO; /* TODO: Use which error code? */
DPUTS("short write, filesystem full?");
}
return rc;
}
n = 0;
}
if (i > pagecount)
break;
wpos = pos;
wsize = 0;
}
DPRINTF(("committing page %" Yu, pgno));
next_pos = pos + size;
iov[n].iov_len = size;
iov[n].iov_base = (char *)dp;
wsize += size;
n++;
#endif /* _WIN32 */
}
//#ifdef MDB_VL32
// if (pgno > txn->mt_last_pgno)
// txn->mt_last_pgno = pgno;
//#endif
/* MIPS has cache coherency issues, this is a no-op everywhere else
* Note: for any size >= on-chip cache size, entire on-chip cache is
* flushed.
*/
CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
for (i = keep; ++i <= pagecount; ) {
dp = (MDB_page *) dl[i].mptr;
/* This is a page we skipped above */
if (!dl[i].mid) {
dl[++j] = dl[i];
dl[j].mid = dp->mp_pgno;
continue;
}
mdb_dpage_free(env, dp);
}
done:
i--;
txn->mt_dirty_room += i - j;
dl[0].mid = j;
return MDB_SUCCESS;
}
int
mdb_txn_commit(MDB_txn *txn)
{
int rc;
uint64_t i, end_mode;
MDB_env *env;
if (txn == NULL)
return EINVAL;
/* mdb_txn_end() mode for a commit which writes nothing */
end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
if (txn->mt_child) {
rc = mdb_txn_commit(txn->mt_child);
if (rc)
goto fail;
}
env = txn->mt_env;
if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
goto done;
}
if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
DPUTS("txn has failed/finished, can't commit");
if (txn->mt_parent)
txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
rc = MDB_BAD_TXN;
goto fail;
}
if (txn->mt_parent) {
MDB_txn *parent = txn->mt_parent;
MDB_page **lp;
MDB_ID2L dst, src;
MDB_IDL pspill;
unsigned x, y, len, ps_len;
/* Append our free list to parent's */
rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
if (rc)
goto fail;
mdb_midl_free(txn->mt_free_pgs);
/* Failures after this must either undo the changes
* to the parent or set MDB_TXN_ERROR in the parent.
*/
parent->mt_next_pgno = txn->mt_next_pgno;
parent->mt_flags = txn->mt_flags;
/* Merge our cursors into parent's and close them */
mdb_cursors_close(txn, 1);
/* Update parent's DB table. */
memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
parent->mt_numdbs = txn->mt_numdbs;
parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
/* preserve parent's DB_NEW status */
x = parent->mt_dbflags[i] & DB_NEW;
parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
}
dst = parent->mt_u.dirty_list;
src = txn->mt_u.dirty_list;
/* Remove anything in our dirty list from parent's spill list */
if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
x = y = ps_len;
pspill[0] = (pgno_t)-1;
/* Mark our dirty pages as deleted in parent spill list */
for (i=0, len=src[0].mid; ++i <= len; ) {
MDB_ID pn = src[i].mid << 1;
while (pn > pspill[x])
x--;
if (pn == pspill[x]) {
pspill[x] = 1;
y = --x;
}
}
/* Squash deleted pagenums if we deleted any */
for (x=y; ++x <= ps_len; )
if (!(pspill[x] & 1))
pspill[++y] = pspill[x];
pspill[0] = y;
}
/* Remove anything in our spill list from parent's dirty list */
if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
MDB_ID pn = txn->mt_spill_pgs[i];
if (pn & 1)
continue; /* deleted spillpg */
pn >>= 1;
y = mdb_mid2l_search(dst, pn);
if (y <= dst[0].mid && dst[y].mid == pn) {
free(dst[y].mptr);
while (y < dst[0].mid) {
dst[y] = dst[y+1];
y++;
}
dst[0].mid--;
}
}
}
/* Find len = length of merging our dirty list with parent's */
x = dst[0].mid;
dst[0].mid = 0; /* simplify loops */
if (parent->mt_parent) {
len = x + src[0].mid;
y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
for (i = x; y && i; y--) {
pgno_t yp = src[y].mid;
while (yp < dst[i].mid)
i--;
if (yp == dst[i].mid) {
i--;
len--;
}
}
} else { /* Simplify the above for single-ancestor case */
len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
}
/* Merge our dirty list with parent's */
y = src[0].mid;
for (i = len; y; dst[i--] = src[y--]) {
pgno_t yp = src[y].mid;
while (yp < dst[x].mid)
dst[i--] = dst[x--];
if (yp == dst[x].mid)
free(dst[x--].mptr);
}
mdb_tassert(txn, i == x);
dst[0].mid = len;
free(txn->mt_u.dirty_list);
parent->mt_dirty_room = txn->mt_dirty_room;
if (txn->mt_spill_pgs) {
if (parent->mt_spill_pgs) {
/* TODO: Prevent failure here, so parent does not fail */
rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
if (rc)
parent->mt_flags |= MDB_TXN_ERROR;
mdb_midl_free(txn->mt_spill_pgs);
mdb_midl_sort(parent->mt_spill_pgs);
} else {
parent->mt_spill_pgs = txn->mt_spill_pgs;
}
}
/* Append our loose page list to parent's */
for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
;
*lp = txn->mt_loose_pgs;
parent->mt_loose_count += txn->mt_loose_count;
parent->mt_child = NULL;
mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
free(txn);
return rc;
}
if (txn != env->me_txn) {
DPUTS("attempt to commit unknown transaction");
rc = EINVAL;
goto fail;
}
mdb_cursors_close(txn, 0);
if (!txn->mt_u.dirty_list[0].mid &&
!(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
goto done;
DPRINTF(("committing txn %" Yu" %p on mdbenv %p, root page %" Yu,
txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
/* Update DB root pointers */
if (txn->mt_numdbs > CORE_DBS) {
MDB_cursor mc;
MDB_dbi i;
MDB_val data;
data.mv_size = sizeof(MDB_db);
mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
if (txn->mt_dbflags[i] & DB_DIRTY) {
if (TXN_DBI_CHANGED(txn, i)) {
rc = MDB_BAD_DBI;
goto fail;
}
data.mv_data = &txn->mt_dbs[i];
rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
F_SUBDATA);
if (rc)
goto fail;
}
}
}
rc = mdb_freelist_save(txn);
if (rc)
goto fail;
mdb_midl_free(env->me_pghead);
env->me_pghead = NULL;
mdb_midl_shrink(&txn->mt_free_pgs);
#if (MDB_DEBUG) > 2
mdb_audit(txn);
#endif
if ((rc = mdb_page_flush(txn, 0)))
goto fail;
if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
(rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
goto fail;
if ((rc = mdb_env_write_meta(txn)))
goto fail;
end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
done:
mdb_txn_end(txn, end_mode);
return MDB_SUCCESS;
fail:
mdb_txn_abort(txn);
return rc;
}
/** Read the environment parameters of a DB environment before
* mapping it into memory.
* @param[in] env the environment handle
* @param[in] prev whether to read the backup meta page
* @param[out] meta address of where to store the meta information
* @return 0 on success, non-zero on failure.
*/
static int ESECT
mdb_env_read_header(MDB_env *env, int prev, MDB_meta *meta)
{
MDB_metabuf pbuf;
MDB_page *p;
MDB_meta *m;
int i, rc, off;
enum { Size = sizeof(pbuf) };
/* We don't know the page size yet, so use a minimum value.
* Read both meta pages so we can use the latest one.
*/
for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
#ifdef _WIN32
DWORD len;
OVERLAPPED ov;
memset(&ov, 0, sizeof(ov));
ov.Offset = off;
rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
rc = 0;
#else
rc = pread(env->me_fd, &pbuf, Size, off);
#endif
if (rc != Size) {
if (rc == 0 && off == 0)
return ENOENT;
rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
DPRINTF(("read: %s", mdb_strerror(rc)));
return rc;
}
p = (MDB_page *)&pbuf;
if (!F_ISSET(p->mp_flags, P_META)) {
DPRINTF(("page %" Yu" not a meta page", p->mp_pgno));
return MDB_INVALID;
}
m = METADATA(p);
if (m->mm_magic != MDB_MAGIC) {
DPUTS("meta has invalid magic");
return MDB_INVALID;
}
if (m->mm_version != MDB_DATA_VERSION) {
DPRINTF(("database is version %u, expected version %u",
m->mm_version, MDB_DATA_VERSION));
return MDB_VERSION_MISMATCH;
}
if (off == 0 || (prev ? m->mm_txnid < meta->mm_txnid : m->mm_txnid > meta->mm_txnid))
*meta = *m;
}
return 0;
}
/** Fill in most of the zeroed #MDB_meta for an empty database environment */
static void ESECT
mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
{
meta->mm_magic = MDB_MAGIC;
meta->mm_version = MDB_DATA_VERSION;
meta->mm_mapsize = env->me_mapsize;
meta->mm_psize = env->me_psize;
meta->mm_last_pg = NUM_METAS-1;
meta->mm_flags = env->me_flags & 0xffff;
meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
}
/** Write the environment parameters of a freshly created DB environment.
* @param[in] env the environment handle
* @param[in] meta the #MDB_meta to write
* @return 0 on success, non-zero on failure.
*/
static int ESECT
mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
{
MDB_page *p, *q;
int rc;
uint64_t psize;
#ifdef _WIN32
DWORD len;
OVERLAPPED ov;
memset(&ov, 0, sizeof(ov));
#define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
ov.Offset = pos; \
rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
#else
int len;
#define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
len = pwrite(fd, ptr, size, pos); \
if (len == -1 && ErrCode() == EINTR) continue; \
rc = (len >= 0); break; } while(1)
#endif
DPUTS("writing new meta page");
psize = env->me_psize;
p = (MDB_page *) calloc(NUM_METAS, psize);
if (!p)
return ENOMEM;
p->mp_pgno = 0;
p->mp_flags = P_META;
*(MDB_meta *)METADATA(p) = *meta;
q = (MDB_page *)((char *)p + psize);
q->mp_pgno = 1;
q->mp_flags = P_META;
*(MDB_meta *)METADATA(q) = *meta;
DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
if (!rc)
rc = ErrCode();
else if ((unsigned) len == psize * NUM_METAS)
rc = MDB_SUCCESS;
else
rc = ENOSPC;
free(p);
return rc;
}
/** Update the environment info to commit a transaction.
* @param[in] txn the transaction that's being committed
* @return 0 on success, non-zero on failure.
*/
static int
mdb_env_write_meta(MDB_txn *txn)
{
MDB_env *env;
MDB_meta meta, metab, *mp;
unsigned flags;
mdb_size_t mapsize;
off_t off;
int rc, len, toggle;
char *ptr;
HANDLE mfd;
#ifdef _WIN32
OVERLAPPED ov;
#else
int r2;
#endif
toggle = txn->mt_txnid & 1;
DPRINTF(("writing meta page %d for root page %" Yu,
toggle, txn->mt_dbs[MAIN_DBI].md_root));
env = txn->mt_env;
flags = txn->mt_flags | env->me_flags;
mp = env->me_metas[toggle];
mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
/* Persist any increases of mapsize config */
if (mapsize < env->me_mapsize)
mapsize = env->me_mapsize;
if (flags & MDB_WRITEMAP) {
mp->mm_mapsize = mapsize;
mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
mp->mm_last_pg = txn->mt_next_pgno - 1;
#if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
!(defined(__i386__) || defined(__x86_64__))
/* LY: issue a memory barrier, if not x86. ITS#7969 */
__sync_synchronize();
#endif
mp->mm_txnid = txn->mt_txnid;
if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
unsigned meta_size = env->me_psize;
rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
ptr = (char *)mp - PAGEHDRSZ;
#ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
ptr -= r2;
meta_size += r2;
#endif
if (MDB_MSYNC(ptr, meta_size, rc)) {
rc = ErrCode();
goto fail;
}
}
goto done;
}
metab.mm_txnid = mp->mm_txnid;
metab.mm_last_pg = mp->mm_last_pg;
meta.mm_mapsize = mapsize;
meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
meta.mm_last_pg = txn->mt_next_pgno - 1;
meta.mm_txnid = txn->mt_txnid;
off = offsetof(MDB_meta, mm_mapsize);
ptr = (char *)&meta + off;
len = sizeof(MDB_meta) - off;
off += (char *)mp - env->me_map;
/* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
* (me_mfd goes to the same file as me_fd, but writing to it
* also syncs to disk. Avoids a separate fdatasync() call.)
*/
mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
#ifdef _WIN32
{
memset(&ov, 0, sizeof(ov));
ov.Offset = off;
if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
rc = -1;
}
#else
retry_write:
rc = pwrite(mfd, ptr, len, off);
#endif
if (rc != len) {
rc = rc < 0 ? ErrCode() : EIO;
#ifndef _WIN32
if (rc == EINTR)
goto retry_write;
#endif
DPUTS("write failed, disk error?");
/* On a failure, the pagecache still contains the new data.
* Write some old data back, to prevent it from being used.
* Use the non-SYNC fd; we know it will fail anyway.
*/
meta.mm_last_pg = metab.mm_last_pg;
meta.mm_txnid = metab.mm_txnid;
#ifdef _WIN32
memset(&ov, 0, sizeof(ov));
ov.Offset = off;
WriteFile(env->me_fd, ptr, len, NULL, &ov);
#else
r2 = pwrite(env->me_fd, ptr, len, off);
(void)r2; /* Silence warnings. We don't care about pwrite's return value */
#endif
fail:
env->me_flags |= MDB_FATAL_ERROR;
return rc;
}
/* MIPS has cache coherency issues, this is a no-op everywhere else */
CACHEFLUSH(env->me_map + off, len, DCACHE);
done:
/* Memory ordering issues are irrelevant; since the entire writer
* is wrapped by wmutex, all of these changes will become visible
* after the wmutex is unlocked. Since the DB is multi-version,
* readers will get consistent data regardless of how fresh or
* how stale their view of these values is.
*/
if (env->me_txns)
env->me_txns->mti_txnid = txn->mt_txnid;
return MDB_SUCCESS;
}
/** Check both meta pages to see which one is newer.
* @param[in] env the environment handle
* @return newest #MDB_meta.
*/
static MDB_meta *
mdb_env_pick_meta(const MDB_env *env)
{
MDB_meta *const *metas = env->me_metas;
return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
}
int ESECT
mdb_env_create(MDB_env **env)
{
MDB_env *e;
e = (MDB_env *) calloc(1, sizeof(MDB_env));
if (!e)
return ENOMEM;
e->me_maxreaders = DEFAULT_READERS;
e->me_maxdbs = e->me_numdbs = CORE_DBS;
e->me_fd = INVALID_HANDLE_VALUE;
e->me_lfd = INVALID_HANDLE_VALUE;
e->me_mfd = INVALID_HANDLE_VALUE;
#ifdef MDB_USE_POSIX_SEM
e->me_rmutex = SEM_FAILED;
e->me_wmutex = SEM_FAILED;
#elif defined MDB_USE_SYSV_SEM
e->me_rmutex->semid = -1;
e->me_wmutex->semid = -1;
#endif
e->me_pid = getpid();
GET_PAGESIZE(e->me_os_psize);
VGMEMP_CREATE(e,0,0);
*env = e;
return MDB_SUCCESS;
}
#ifdef _WIN32
/** @brief Map a result from an NTAPI call to WIN32. */
static DWORD
mdb_nt2win32(NTSTATUS st)
{
OVERLAPPED o = {0};
DWORD br;
o.Internal = st;
GetOverlappedResult(NULL, &o, &br, FALSE);
return GetLastError();
}
#endif
static int ESECT
mdb_env_map(MDB_env *env, void *addr)
{
MDB_page *p;
uint64_t flags = env->me_flags;
#ifdef _WIN32
int rc;
int access = SECTION_MAP_READ;
HANDLE mh;
void *map;
SIZE_T msize;
ULONG pageprot = PAGE_READONLY, secprot, alloctype;
if (flags & MDB_WRITEMAP) {
access |= SECTION_MAP_WRITE;
pageprot = PAGE_READWRITE;
}
if (flags & MDB_RDONLY) {
secprot = PAGE_READONLY;
msize = 0;
alloctype = 0;
} else {
secprot = PAGE_READWRITE;
msize = env->me_mapsize;
alloctype = MEM_RESERVE;
}
rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
if (rc)
return mdb_nt2win32(rc);
map = addr;
//#ifdef MDB_VL32
// msize = NUM_METAS * env->me_psize;
//#endif
rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
//#ifdef MDB_VL32
// env->me_fmh = mh;
//#else
NtClose(mh);
//#endif
if (rc)
return mdb_nt2win32(rc);
env->me_map = map;
#else
#ifdef MDB_VL32
// (void) flags;
// env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
// env->me_fd, 0);
// if (env->me_map == MAP_FAILED) {
// env->me_map = NULL;
// return ErrCode();
// }
#else
int prot = PROT_READ;
if (flags & MDB_WRITEMAP) {
prot |= PROT_WRITE;
if (ftruncate(env->me_fd, env->me_mapsize) < 0)
return ErrCode();
}
env->me_map = (char *) mmap(addr, env->me_mapsize, prot, MAP_SHARED,
env->me_fd, 0);
if (env->me_map == MAP_FAILED) {
env->me_map = NULL;
return ErrCode();
}
if (flags & MDB_NORDAHEAD) {
/* Turn off readahead. It's harmful when the DB is larger than RAM. */
#ifdef MADV_RANDOM
madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
#else
#ifdef POSIX_MADV_RANDOM
posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
#endif /* POSIX_MADV_RANDOM */
#endif /* MADV_RANDOM */
}
#endif /* _WIN32 */
/* Can happen because the address argument to mmap() is just a
* hint. mmap() can pick another, e.g. if the range is in use.
* The MAP_FIXED flag would prevent that, but then mmap could
* instead unmap existing pages to make room for the new map.
*/
if (addr && env->me_map != addr)
return EBUSY; /* TODO: Make a new MDB_* error code? */
#endif
p = (MDB_page *)env->me_map;
env->me_metas[0] = (MDB_meta *) METADATA(p);
env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
return MDB_SUCCESS;
}
int ESECT
mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
{
/* If env is already open, caller is responsible for making
* sure there are no active txns.
*/
if (env->me_map) {
MDB_meta *meta;
//#ifndef MDB_VL32
void *old;
int rc;
//#endif
if (env->me_txn)
return EINVAL;
meta = mdb_env_pick_meta(env);
if (!size)
size = meta->mm_mapsize;
{
/* Silently round up to minimum if the size is too small */
mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
if (size < minsize)
size = minsize;
}
//#ifndef MDB_VL32
/* For MDB_VL32 this bit is a noop since we dynamically remap
* chunks of the DB anyway.
*/
munmap(env->me_map, env->me_mapsize);
env->me_mapsize = size;
old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
rc = mdb_env_map(env, old);
if (rc)
return rc;
//#endif /* !MDB_VL32 */
}
env->me_mapsize = size;
if (env->me_psize)
env->me_maxpg = env->me_mapsize / env->me_psize;
return MDB_SUCCESS;
}
int ESECT
mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
{
if (env->me_map)
return EINVAL;
env->me_maxdbs = dbs + CORE_DBS;
return MDB_SUCCESS;
}
int ESECT
mdb_env_set_maxreaders(MDB_env *env, uint64_t readers)
{
if (env->me_map || readers < 1)
return EINVAL;
env->me_maxreaders = readers;
return MDB_SUCCESS;
}
int ESECT
mdb_env_get_maxreaders(MDB_env *env, uint64_t *readers)
{
if (!env || !readers)
return EINVAL;
*readers = env->me_maxreaders;
return MDB_SUCCESS;
}
static int ESECT
mdb_fsize(HANDLE fd, mdb_size_t *size)
{
#ifdef _WIN32
LARGE_INTEGER fsize;
if (!GetFileSizeEx(fd, &fsize))
return ErrCode();
*size = fsize.QuadPart;
#else
struct stat st;
if (fstat(fd, &st))
return ErrCode();
*size = st.st_size;
#endif
return MDB_SUCCESS;
}
#ifdef _WIN32
typedef wchar_t mdb_nchar_t;
# define MDB_NAME(str) L##str
# define mdb_name_cpy wcscpy
#else
/** Character type for file names: char on Unix, wchar_t on Windows */
typedef char mdb_nchar_t;
# define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
# define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
#endif
/** Filename - string of #mdb_nchar_t[] */
typedef struct MDB_name {
int mn_len; /**< Length */
int mn_alloced; /**< True if #mn_val was malloced */
mdb_nchar_t *mn_val; /**< Contents */
} MDB_name;
/** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
static const mdb_nchar_t *const mdb_suffixes[2][2] = {
{ MDB_NAME("/data.mdb"), MDB_NAME("") },
{ MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
};
#define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
/** Set up filename + scratch area for filename suffix, for opening files.
* It should be freed with #mdb_fname_destroy().
* On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
*
* @param[in] path Pathname for #mdb_env_open().
* @param[in] envflags Whether a subdir and/or lockfile will be used.
* @param[out] fname Resulting filename, with room for a suffix if necessary.
*/
static int ESECT
mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
{
int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
fname->mn_alloced = 0;
#ifdef _WIN32
return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
#else
fname->mn_len = strlen(path);
if (no_suffix)
fname->mn_val = (char *) path;
else if ((fname->mn_val = (char *) malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
fname->mn_alloced = 1;
strcpy(fname->mn_val, path);
}
else
return ENOMEM;
return MDB_SUCCESS;
#endif
}
/** Destroy \b fname from #mdb_fname_init() */
#define mdb_fname_destroy(fname) \
do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
#ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
# define MDB_CLOEXEC O_CLOEXEC
#else
# define MDB_CLOEXEC 0
#endif
/** File type, access mode etc. for #mdb_fopen() */
enum mdb_fopen_type {
#ifdef _WIN32
MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
#else
/* A comment in mdb_fopen() explains some O_* flag choices. */
MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
/** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
* distinguish otherwise-equal MDB_O_* constants from each other.
*/
MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
#endif
};
/** Open an LMDB file.
* @param[in] env The LMDB environment.
* @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
* appended if necessary to create the filename, without changing mn_len.
* @param[in] which Determines file type, access mode, etc.
* @param[in] mode The Unix permissions for the file, if we create it.
* @param[out] res Resulting file handle.
* @return 0 on success, non-zero on failure.
*/
static int ESECT
mdb_fopen(const MDB_env *env, MDB_name *fname,
enum mdb_fopen_type which, mdb_mode_t mode,
HANDLE *res)
{
int rc = MDB_SUCCESS;
HANDLE fd;
#ifdef _WIN32
DWORD acc, share, disp, attrs;
#else
int flags;
#endif
if (fname->mn_alloced) /* modifiable copy */
mdb_name_cpy(fname->mn_val + fname->mn_len,
mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
/* The directory must already exist. Usually the file need not.
* MDB_O_META requires the file because we already created it using
* MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
*
* With MDB_O_COPY we do not want the OS to cache the writes, since
* the source data is already in the OS cache.
*
* The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
* to avoid the flock() issues noted under Caveats in lmdb.h.
* Also set it for other filehandles which the user cannot get at
* and close himself, which he may need after fork(). I.e. all but
* me_fd, which programs do use via mdb_env_get_fd().
*/
#ifdef _WIN32
acc = GENERIC_READ|GENERIC_WRITE;
share = FILE_SHARE_READ|FILE_SHARE_WRITE;
disp = OPEN_ALWAYS;
attrs = FILE_ATTRIBUTE_NORMAL;
switch (which) {
case MDB_O_RDONLY: /* read-only datafile */
acc = GENERIC_READ;
disp = OPEN_EXISTING;
break;
case MDB_O_META: /* for writing metapages */
acc = GENERIC_WRITE;
disp = OPEN_EXISTING;
attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
break;
case MDB_O_COPY: /* mdb_env_copy() & co */
acc = GENERIC_WRITE;
share = 0;
disp = CREATE_NEW;
attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
break;
default: break; /* silence gcc -Wswitch (not all enum values handled) */
}
fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
#else
fd = open(fname->mn_val, which & MDB_O_MASK, mode);
#endif
if (fd == INVALID_HANDLE_VALUE)
rc = ErrCode();
#ifndef _WIN32
else {
if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
/* Set CLOEXEC if we could not pass it to open() */
if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
(void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}
if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
/* This may require buffer alignment. There is no portable
* way to ask how much, so we require OS pagesize alignment.
*/
# ifdef F_NOCACHE /* __APPLE__ */
(void) fcntl(fd, F_NOCACHE, 1);
# elif defined O_DIRECT
/* open(...O_DIRECT...) would break on filesystems without
* O_DIRECT support (ITS#7682). Try to set it here instead.
*/
if ((flags = fcntl(fd, F_GETFL)) != -1)
(void) fcntl(fd, F_SETFL, flags | O_DIRECT);
# endif
}
}
#endif /* !_WIN32 */
*res = fd;
return rc;
}
//#ifdef BROKEN_FDATASYNC
//#include <sys/utsname.h>
//#include <sys/vfs.h>
//#endif
/** Further setup required for opening an LMDB environment
*/
static int ESECT
mdb_env_open2(MDB_env *env, int prev)
{
uint64_t flags = env->me_flags;
int i, newenv = 0, rc;
MDB_meta meta;
#ifdef _WIN32
/* See if we should use QueryLimited */
rc = GetVersion();
if ((rc & 0xff) > 5)
env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
else
env->me_pidquery = PROCESS_QUERY_INFORMATION;
/* Grab functions we need from NTDLL */
if (!NtCreateSection) {
HMODULE h = GetModuleHandle("NTDLL.DLL");
if (!h)
return MDB_PROBLEM;
NtClose = (NtCloseFunc *)GetProcAddress(h, "NtClose");
if (!NtClose)
return MDB_PROBLEM;
NtMapViewOfSection = (NtMapViewOfSectionFunc *)GetProcAddress(h, "NtMapViewOfSection");
if (!NtMapViewOfSection)
return MDB_PROBLEM;
NtCreateSection = (NtCreateSectionFunc *)GetProcAddress(h, "NtCreateSection");
if (!NtCreateSection)
return MDB_PROBLEM;
}
#endif /* _WIN32 */
//#ifdef BROKEN_FDATASYNC
// /* ext3/ext4 fdatasync is broken on some older Linux kernels.
// * https://lkml.org/lkml/2012/9/3/83
// * Kernels after 3.6-rc6 are known good.
// * https://lkml.org/lkml/2012/9/10/556
// * See if the DB is on ext3/ext4, then check for new enough kernel
// * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
// * to be patched.
// */
// {
// struct statfs st;
// fstatfs(env->me_fd, &st);
// while (st.f_type == 0xEF53) {
// struct utsname uts;
// int i;
// uname(&uts);
// if (uts.release[0] < '3') {
// if (!strncmp(uts.release, "2.6.32.", 7)) {
// i = atoi(uts.release+7);
// if (i >= 60)
// break; /* 2.6.32.60 and newer is OK */
// } else if (!strncmp(uts.release, "2.6.34.", 7)) {
// i = atoi(uts.release+7);
// if (i >= 15)
// break; /* 2.6.34.15 and newer is OK */
// }
// } else if (uts.release[0] == '3') {
// i = atoi(uts.release+2);
// if (i > 5)
// break; /* 3.6 and newer is OK */
// if (i == 5) {
// i = atoi(uts.release+4);
// if (i >= 4)
// break; /* 3.5.4 and newer is OK */
// } else if (i == 2) {
// i = atoi(uts.release+4);
// if (i >= 30)
// break; /* 3.2.30 and newer is OK */
// }
// } else { /* 4.x and newer is OK */
// break;
// }
// env->me_flags |= MDB_FSYNCONLY;
// break;
// }
// }
//#endif
if ((i = mdb_env_read_header(env, prev, &meta)) != 0) {
if (i != ENOENT)
return i;
DPUTS("new mdbenv");
newenv = 1;
env->me_psize = env->me_os_psize;
if (env->me_psize > MAX_PAGESIZE)
env->me_psize = MAX_PAGESIZE;
memset(&meta, 0, sizeof(meta));
mdb_env_init_meta0(env, &meta);
meta.mm_mapsize = DEFAULT_MAPSIZE;
} else {
env->me_psize = meta.mm_psize;
}
/* Was a mapsize configured? */
if (!env->me_mapsize) {
env->me_mapsize = meta.mm_mapsize;
}
{
/* Make sure mapsize >= committed data size. Even when using
* mm_mapsize, which could be broken in old files (ITS#7789).
*/
mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
if (env->me_mapsize < minsize)
env->me_mapsize = minsize;
}
meta.mm_mapsize = env->me_mapsize;
if (newenv && !(flags & MDB_FIXEDMAP)) {
/* mdb_env_map() may grow the datafile. Write the metapages
* first, so the file will be valid if initialization fails.
* Except with FIXEDMAP, since we do not yet know mm_address.
* We could fill in mm_address later, but then a different
* program might end up doing that - one with a memory layout
* and map address which does not suit the main program.
*/
rc = mdb_env_init_meta(env, &meta);
if (rc)
return rc;
newenv = 0;
}
#ifdef _WIN32
/* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
if (newenv) {
char dummy = 0;
DWORD len;
rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
if (!rc) {
rc = ErrCode();
return rc;
}
}
#endif
rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
if (rc)
return rc;
if (newenv) {
if (flags & MDB_FIXEDMAP)
meta.mm_address = env->me_map;
i = mdb_env_init_meta(env, &meta);
if (i != MDB_SUCCESS) {
return i;
}
}
env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
- sizeof(indx_t);
#if !(MDB_MAXKEYSIZE)
env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
#endif
env->me_maxpg = env->me_mapsize / env->me_psize;
#if MDB_DEBUG
{
MDB_meta *meta = mdb_env_pick_meta(env);
MDB_db *db = &meta->mm_dbs[MAIN_DBI];
DPRINTF(("opened database version %u, pagesize %u",
meta->mm_version, env->me_psize));
DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
DPRINTF(("depth: %u", db->md_depth));
DPRINTF(("entries: %" Yu, db->md_entries));
DPRINTF(("branch pages: %" Yu, db->md_branch_pages));
DPRINTF(("leaf pages: %" Yu, db->md_leaf_pages));
DPRINTF(("overflow pages: %" Yu, db->md_overflow_pages));
DPRINTF(("root: %" Yu, db->md_root));
}
#endif
return MDB_SUCCESS;
}
/** Release a reader thread's slot in the reader lock table.
* This function is called automatically when a thread exits.
* @param[in] ptr This points to the slot in the reader lock table.
*/
static void
mdb_env_reader_dest(void *ptr)
{
MDB_reader *reader = (MDB_reader *) ptr;
#ifndef _WIN32
if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
#endif
/* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
reader->mr_pid = 0;
}
#ifdef _WIN32
/** Junk for arranging thread-specific callbacks on Windows. This is
* necessarily platform and compiler-specific. Windows supports up
* to 1088 keys. Let's assume nobody opens more than 64 environments
* in a single process, for now. They can override this if needed.
*/
#ifndef MAX_TLS_KEYS
#define MAX_TLS_KEYS 64
#endif
static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
static int mdb_tls_nkeys;
static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
{
int i;
switch(reason) {
case DLL_PROCESS_ATTACH: break;
case DLL_THREAD_ATTACH: break;
case DLL_THREAD_DETACH:
for (i=0; i<mdb_tls_nkeys; i++) {
MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
if (r) {
mdb_env_reader_dest(r);
}
}
break;
case DLL_PROCESS_DETACH: break;
}
}
#ifdef __GNUC__
#ifdef _WIN64
const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
#else
PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
#endif
#else
#ifdef _WIN64
/* Force some symbol references.
* _tls_used forces the linker to create the TLS directory if not already done
* mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
*/
#pragma comment(linker, "/INCLUDE:_tls_used")
#pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
#pragma const_seg(".CRT$XLB")
extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
#pragma const_seg()
#else /* _WIN32 */
#pragma comment(linker, "/INCLUDE:__tls_used")
#pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
#pragma data_seg(".CRT$XLB")
PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
#pragma data_seg()
#endif /* WIN 32/64 */
#endif /* !__GNUC__ */
#endif
/** Downgrade the exclusive lock on the region back to shared */
static int ESECT
mdb_env_share_locks(MDB_env *env, int *excl)
{
int rc = 0;
MDB_meta *meta = mdb_env_pick_meta(env);
env->me_txns->mti_txnid = meta->mm_txnid;
#ifdef _WIN32
{
OVERLAPPED ov;
/* First acquire a shared lock. The Unlock will
* then release the existing exclusive lock.
*/
memset(&ov, 0, sizeof(ov));
if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
rc = ErrCode();
} else {
UnlockFile(env->me_lfd, 0, 0, 1, 0);
*excl = 0;
}
}
#else
{
struct flock lock_info;
/* The shared lock replaces the existing lock */
memset((void *)&lock_info, 0, sizeof(lock_info));
lock_info.l_type = F_RDLCK;
lock_info.l_whence = SEEK_SET;
lock_info.l_start = 0;
lock_info.l_len = 1;
while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
(rc = ErrCode()) == EINTR) ;
*excl = rc ? -1 : 0; /* error may mean we lost the lock */
}
#endif
return rc;
}
/** Try to get exclusive lock, otherwise shared.
* Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
*/
static int ESECT
mdb_env_excl_lock(MDB_env *env, int *excl)
{
int rc = 0;
#ifdef _WIN32
if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
*excl = 1;
} else {
OVERLAPPED ov;
memset(&ov, 0, sizeof(ov));
if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
*excl = 0;
} else {
rc = ErrCode();
}
}
#else
struct flock lock_info;
memset((void *)&lock_info, 0, sizeof(lock_info));
lock_info.l_type = F_WRLCK;
lock_info.l_whence = SEEK_SET;
lock_info.l_start = 0;
lock_info.l_len = 1;
while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
(rc = ErrCode()) == EINTR) ;
if (!rc) {
*excl = 1;
} else
# ifndef MDB_USE_POSIX_MUTEX
if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
# endif
{
lock_info.l_type = F_RDLCK;
while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
(rc = ErrCode()) == EINTR) ;
if (rc == 0)
*excl = 0;
}
#endif
return rc;
}
#ifdef MDB_USE_HASH
/*
* hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
*
* @(#) $Revision: 5.1 $
* @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
* @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
*
* http://www.isthe.com/chongo/tech/comp/fnv/index.html
*
***
*
* Please do not copyright this code. This code is in the public domain.
*
* LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
* EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* By:
* chongo <Landon Curt Noll> /\oo/\
* http://www.isthe.com/chongo/
*
* Share and Enjoy! :-)
*/
/** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
* @param[in] val value to hash
* @param[in] len length of value
* @return 64 bit hash
*/
static mdb_hash_t
mdb_hash(const void *val, size_t len)
{
const uint8_t *s = (const uint8_t *) val, *end = s + len;
mdb_hash_t hval = 0xcbf29ce484222325ULL;
/*
* FNV-1a hash each octet of the buffer
*/
while (s < end) {
hval = (hval ^ *s++) * 0x100000001b3ULL;
}
/* return our new hash value */
return hval;
}
/** Hash the string and output the encoded hash.
* This uses modified RFC1924 Ascii85 encoding to accommodate systems with
* very short name limits. We don't care about the encoding being reversible,
* we just want to preserve as many bits of the input as possible in a
* small printable string.
* @param[in] str string to hash
* @param[out] encbuf an array of 11 chars to hold the hash
*/
static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
static void ESECT
mdb_pack85(unsigned long long l, char *out)
{
int i;
for (i=0; i<10 && l; i++) {
*out++ = mdb_a85[l % 85];
l /= 85;
}
*out = '\0';
}
/** Init #MDB_env.me_mutexname[] except the char which #MUTEXNAME() will set.
* Changes to this code must be reflected in #MDB_LOCK_FORMAT.
*/
static void ESECT
mdb_env_mname_init(MDB_env *env)
{
char *nm = env->me_mutexname;
strcpy(nm, MUTEXNAME_PREFIX);
mdb_pack85(env->me_txns->mti_mutexid, nm + sizeof(MUTEXNAME_PREFIX));
}
/** Return env->me_mutexname after filling in ch ('r'/'w') for convenience */
#define MUTEXNAME(env, ch) ( \
(void) ((env)->me_mutexname[sizeof(MUTEXNAME_PREFIX)-1] = (ch)), \
(env)->me_mutexname)
#endif
/** Open and/or initialize the lock region for the environment.
* @param[in] env The LMDB environment.
* @param[in] fname Filename + scratch area, from #mdb_fname_init().
* @param[in] mode The Unix permissions for the file, if we create it.
* @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
* @return 0 on success, non-zero on failure.
*/
static int ESECT
mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
{
#ifdef _WIN32
# define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
#else
# define MDB_ERRCODE_ROFS EROFS
#endif
#ifdef MDB_USE_SYSV_SEM
int semid;
union semun semu;
#endif
int rc;
off_t size, rsize;
rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
if (rc) {
/* Omit lockfile if read-only env on read-only filesystem */
if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
return MDB_SUCCESS;
}
goto fail;
}
if (!(env->me_flags & MDB_NOTLS)) {
rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
if (rc)
goto fail;
env->me_flags |= MDB_ENV_TXKEY;
#ifdef _WIN32
/* Windows TLS callbacks need help finding their TLS info. */
if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
rc = MDB_TLS_FULL;
goto fail;
}
mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
#endif
}
/* Try to get exclusive lock. If we succeed, then
* nobody is using the lock region and we should initialize it.
*/
if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
#ifdef _WIN32
size = GetFileSize(env->me_lfd, NULL);
#else
size = lseek(env->me_lfd, 0, SEEK_END);
if (size == -1) goto fail_errno;
#endif
rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
if (size < rsize && *excl > 0) {
#ifdef _WIN32
if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
|| !SetEndOfFile(env->me_lfd))
goto fail_errno;
#else
if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
#endif
} else {
rsize = size;
size = rsize - sizeof(MDB_txninfo);
env->me_maxreaders = size/sizeof(MDB_reader) + 1;
}
{
#ifdef _WIN32
HANDLE mh;
mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
0, 0, NULL);
if (!mh) goto fail_errno;
env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
CloseHandle(mh);
if (!env->me_txns) goto fail_errno;
#else
void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
env->me_lfd, 0);
if (m == MAP_FAILED) goto fail_errno;
env->me_txns =(MDB_txninfo *) m;
#endif
}
if (*excl > 0) {
#ifdef _WIN32
BY_HANDLE_FILE_INFORMATION stbuf;
struct {
DWORD volume;
DWORD nhigh;
DWORD nlow;
} idbuf;
if (!mdb_sec_inited) {
InitializeSecurityDescriptor(&mdb_null_sd,
SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
mdb_all_sa.bInheritHandle = FALSE;
mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
mdb_sec_inited = 1;
}
if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
idbuf.volume = stbuf.dwVolumeSerialNumber;
idbuf.nhigh = stbuf.nFileIndexHigh;
idbuf.nlow = stbuf.nFileIndexLow;
env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf));
mdb_env_mname_init(env);
env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'r'));
if (!env->me_rmutex) goto fail_errno;
env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'w'));
if (!env->me_wmutex) goto fail_errno;
#elif defined(MDB_USE_POSIX_SEM)
struct stat stbuf;
struct {
dev_t dev;
ino_t ino;
} idbuf;
#if defined(__NetBSD__)
#define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
#endif
if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
memset(&idbuf, 0, sizeof(idbuf));
idbuf.dev = stbuf.st_dev;
idbuf.ino = stbuf.st_ino;
env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf))
#ifdef MDB_SHORT_SEMNAMES
/* Max 9 base85-digits. We truncate here instead of in
* mdb_env_mname_init() to keep the latter portable.
*/
% ((mdb_hash_t)85*85*85*85*85*85*85*85*85)
#endif
;
mdb_env_mname_init(env);
/* Clean up after a previous run, if needed: Try to
* remove both semaphores before doing anything else.
*/
sem_unlink(MUTEXNAME(env, 'r'));
sem_unlink(MUTEXNAME(env, 'w'));
env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), O_CREAT|O_EXCL, mode, 1);
if (env->me_rmutex == SEM_FAILED) goto fail_errno;
env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), O_CREAT|O_EXCL, mode, 1);
if (env->me_wmutex == SEM_FAILED) goto fail_errno;
#elif defined(MDB_USE_SYSV_SEM)
uint16_t vals[2] = {1, 1};
key_t key = ftok(fname->mn_val, 'M'); /* fname is lockfile path now */
if (key == -1)
goto fail_errno;
semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
if (semid < 0)
goto fail_errno;
semu.array = vals;
if (semctl(semid, 0, SETALL, semu) < 0)
goto fail_errno;
env->me_txns->mti_semid = semid;
env->me_txns->mti_rlocked = 0;
env->me_txns->mti_wlocked = 0;
#else /* MDB_USE_POSIX_MUTEX: */
pthread_mutexattr_t mattr;
/* Solaris needs this before initing a robust mutex. Otherwise
* it may skip the init and return EBUSY "seems someone already
* inited" or EINVAL "it was inited differently".
*/
memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
if ((rc = pthread_mutexattr_init(&mattr)) != 0)
goto fail;
rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
#ifdef MDB_ROBUST_SUPPORTED
if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
#endif
if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
pthread_mutexattr_destroy(&mattr);
if (rc)
goto fail;
#endif /* _WIN32 || ... */
env->me_txns->mti_magic = MDB_MAGIC;
env->me_txns->mti_format = MDB_LOCK_FORMAT;
env->me_txns->mti_txnid = 0;
env->me_txns->mti_numreaders = 0;
} else {
#ifdef MDB_USE_SYSV_SEM
struct semid_ds buf;
#endif
if (env->me_txns->mti_magic != MDB_MAGIC) {
DPUTS("lock region has invalid magic");
rc = MDB_INVALID;
goto fail;
}
if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
env->me_txns->mti_format, MDB_LOCK_FORMAT));
rc = MDB_VERSION_MISMATCH;
goto fail;
}
rc = ErrCode();
if (rc && rc != EACCES && rc != EAGAIN) {
goto fail;
}
#ifdef _WIN32
mdb_env_mname_init(env);
env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'r'));
if (!env->me_rmutex) goto fail_errno;
env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'w'));
if (!env->me_wmutex) goto fail_errno;
#elif defined(MDB_USE_POSIX_SEM)
mdb_env_mname_init(env);
env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), 0);
if (env->me_rmutex == SEM_FAILED) goto fail_errno;
env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), 0);
if (env->me_wmutex == SEM_FAILED) goto fail_errno;
#elif defined(MDB_USE_SYSV_SEM)
semid = env->me_txns->mti_semid;
semu.buf = &buf;
/* check for read access */
if (semctl(semid, 0, IPC_STAT, semu) < 0)
goto fail_errno;
/* check for write access */
if (semctl(semid, 0, IPC_SET, semu) < 0)
goto fail_errno;
#endif
}
#ifdef MDB_USE_SYSV_SEM
env->me_rmutex->semid = semid;
env->me_wmutex->semid = semid;
env->me_rmutex->semnum = 0;
env->me_wmutex->semnum = 1;
env->me_rmutex->locked = &env->me_txns->mti_rlocked;
env->me_wmutex->locked = &env->me_txns->mti_wlocked;
#endif
return MDB_SUCCESS;
fail_errno:
rc = ErrCode();
fail:
return rc;
}
/** Only a subset of the @ref mdb_env flags can be changed
* at runtime. Changing other flags requires closing the
* environment and re-opening it with the new flags.
*/
#define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
#define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD|MDB_PREVMETA)
#if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
# error "Persistent DB flags & env flags overlap, but both go in mm_flags"
#endif
int ESECT
mdb_env_open(MDB_env *env, const char *path, uint64_t flags, mdb_mode_t mode)
{
int rc, excl = -1;
MDB_name fname;
if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
return EINVAL;
//#ifdef MDB_VL32
// if (flags & MDB_WRITEMAP) {
// /* silently ignore WRITEMAP in 32 bit mode */
// flags ^= MDB_WRITEMAP;
// }
// if (flags & MDB_FIXEDMAP) {
// /* cannot support FIXEDMAP */
// return EINVAL;
// }
//#endif
flags |= env->me_flags;
rc = mdb_fname_init(path, flags, &fname);
if (rc)
return rc;
//#ifdef MDB_VL32
//#ifdef _WIN32
// env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
// if (!env->me_rpmutex) {
// rc = ErrCode();
// goto leave;
// }
//#else
// rc = pthread_mutex_init(&env->me_rpmutex, NULL);
// if (rc)
// goto leave;
//#endif
//#endif
flags |= MDB_ENV_ACTIVE; /* tell mdb_env_close0() to clean up */
if (flags & MDB_RDONLY) {
/* silently ignore WRITEMAP when we're only getting read access */
flags &= ~MDB_WRITEMAP;
} else {
if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
(env->me_dirty_list = (MDB_ID2 *) calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
rc = ENOMEM;
}
env->me_flags = flags;
if (rc)
goto leave;
//#ifdef MDB_VL32
// {
// env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
// if (!env->me_rpages) {
// rc = ENOMEM;
// goto leave;
// }
// env->me_rpages[0].mid = 0;
// env->me_rpcheck = MDB_ERPAGE_SIZE/2;
// }
//#endif
env->me_path = strdup(path);
env->me_dbxs = (MDB_dbx *) calloc(env->me_maxdbs, sizeof(MDB_dbx));
env->me_dbflags = (uint16_t *) calloc(env->me_maxdbs, sizeof(uint16_t));
env->me_dbiseqs = (uint64_t *) calloc(env->me_maxdbs, sizeof(uint64_t));
if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
rc = ENOMEM;
goto leave;
}
env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
/* For RDONLY, get lockfile after we know datafile exists */
if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
rc = mdb_env_setup_locks(env, &fname, mode, &excl);
if (rc)
goto leave;
}
rc = mdb_fopen(env, &fname,
(flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
mode, &env->me_fd);
if (rc)
goto leave;
if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
rc = mdb_env_setup_locks(env, &fname, mode, &excl);
if (rc)
goto leave;
}
if ((rc = mdb_env_open2(env, flags & MDB_PREVMETA)) == MDB_SUCCESS) {
if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
/* Synchronous fd for meta writes. Needed even with
* MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
*/
rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
if (rc)
goto leave;
}
DPRINTF(("opened dbenv %p", (void *) env));
if (excl > 0) {
rc = mdb_env_share_locks(env, &excl);
if (rc)
goto leave;
}
if (!(flags & MDB_RDONLY)) {
MDB_txn *txn;
int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
(sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(uint64_t)+1);
if ((env->me_pbuf = (MDB_txn *) calloc(1, env->me_psize)) &&
(txn = (MDB_txn *) calloc(1, size)))
{
txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
txn->mt_dbiseqs = (uint64_t *)(txn->mt_cursors + env->me_maxdbs);
txn->mt_dbflags = (uint8_t *)(txn->mt_dbiseqs + env->me_maxdbs);
txn->mt_env = env;
//#ifdef MDB_VL32
// txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
// if (!txn->mt_rpages) {
// free(txn);
// rc = ENOMEM;
// goto leave;
// }
// txn->mt_rpages[0].mid = 0;
// txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
//#endif
txn->mt_dbxs = env->me_dbxs;
txn->mt_flags = MDB_TXN_FINISHED;
env->me_txn0 = txn;
} else {
rc = ENOMEM;
}
}
}
leave:
if (rc) {
mdb_env_close0(env, excl);
}
mdb_fname_destroy(fname);
return rc;
}
/** Destroy resources from mdb_env_open(), clear our readers & DBIs */
static void ESECT
mdb_env_close0(MDB_env *env, int excl)
{
int i;
if (!(env->me_flags & MDB_ENV_ACTIVE))
return;
/* Doing this here since me_dbxs may not exist during mdb_env_close */
if (env->me_dbxs) {
for (i = env->me_maxdbs; --i >= CORE_DBS; )
free(env->me_dbxs[i].md_name.mv_data);
free(env->me_dbxs);
}
free(env->me_pbuf);
free(env->me_dbiseqs);
free(env->me_dbflags);
free(env->me_path);
free(env->me_dirty_list);
//#ifdef MDB_VL32
// if (env->me_txn0 && env->me_txn0->mt_rpages)
// free(env->me_txn0->mt_rpages);
// if (env->me_rpages) {
// MDB_ID3L el = env->me_rpages;
// uint64_t x;
// for (x=1; x<=el[0].mid; x++)
// munmap(el[x].mptr, el[x].mcnt * env->me_psize);
// free(el);
// }
//#endif
free(env->me_txn0);
mdb_midl_free(env->me_free_pgs);
if (env->me_flags & MDB_ENV_TXKEY) {
pthread_key_delete(env->me_txkey);
#ifdef _WIN32
/* Delete our key from the global list */
for (i=0; i<mdb_tls_nkeys; i++)
if (mdb_tls_keys[i] == env->me_txkey) {
mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
mdb_tls_nkeys--;
break;
}
#endif
}
if (env->me_map) {
//#ifdef MDB_VL32
// munmap(env->me_map, NUM_METAS*env->me_psize);
//#else
munmap(env->me_map, env->me_mapsize);
//#endif
}
if (env->me_mfd != INVALID_HANDLE_VALUE)
(void) close(env->me_mfd);
if (env->me_fd != INVALID_HANDLE_VALUE)
(void) close(env->me_fd);
if (env->me_txns) {
MDB_PID_T pid = getpid();
/* Clearing readers is done in this function because
* me_txkey with its destructor must be disabled first.
*
* We skip the the reader mutex, so we touch only
* data owned by this process (me_close_readers and
* our readers), and clear each reader atomically.
*/
for (i = env->me_close_readers; --i >= 0; )
if (env->me_txns->mti_readers[i].mr_pid == pid)
env->me_txns->mti_readers[i].mr_pid = 0;
#ifdef _WIN32
if (env->me_rmutex) {
CloseHandle(env->me_rmutex);
if (env->me_wmutex) CloseHandle(env->me_wmutex);
}
/* Windows automatically destroys the mutexes when
* the last handle closes.
*/
#elif defined(MDB_USE_POSIX_SEM)
if (env->me_rmutex != SEM_FAILED) {
sem_close(env->me_rmutex);
if (env->me_wmutex != SEM_FAILED)
sem_close(env->me_wmutex);
/* If we have the filelock: If we are the
* only remaining user, clean up semaphores.
*/
if (excl == 0)
mdb_env_excl_lock(env, &excl);
if (excl > 0) {
sem_unlink(MUTEXNAME(env, 'r'));
sem_unlink(MUTEXNAME(env, 'w'));
}
}
#elif defined(MDB_USE_SYSV_SEM)
if (env->me_rmutex->semid != -1) {
/* If we have the filelock: If we are the
* only remaining user, clean up semaphores.
*/
if (excl == 0)
mdb_env_excl_lock(env, &excl);
if (excl > 0)
semctl(env->me_rmutex->semid, 0, IPC_RMID);
}
#endif
munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
}
if (env->me_lfd != INVALID_HANDLE_VALUE) {
#ifdef _WIN32
if (excl >= 0) {
/* Unlock the lockfile. Windows would have unlocked it
* after closing anyway, but not necessarily at once.
*/
UnlockFile(env->me_lfd, 0, 0, 1, 0);
}
#endif
(void) close(env->me_lfd);
}
//#ifdef MDB_VL32
//#ifdef _WIN32
// if (env->me_fmh) CloseHandle(env->me_fmh);
// if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
//#else
// pthread_mutex_destroy(&env->me_rpmutex);
//#endif
//#endif
env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
}
void ESECT
mdb_env_close(MDB_env *env)
{
MDB_page *dp;
if (env == NULL)
return;
VGMEMP_DESTROY(env);
while ((dp = env->me_dpages) != NULL) {
VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
env->me_dpages = dp->mp_next;
free(dp);
}
mdb_env_close0(env, 0);
free(env);
}
/** Compare two items pointing at aligned #mdb_size_t's */
static int
mdb_cmp_long(const MDB_val *a, const MDB_val *b)
{
return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
*(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
}
/** Compare two items pointing at aligned uint64_t's.
*
* This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
* but #mdb_cmp_clong() is called instead if the data type is #mdb_size_t.
*/
static int
mdb_cmp_int(const MDB_val *a, const MDB_val *b)
{
return (*(uint64_t *)a->mv_data < *(uint64_t *)b->mv_data) ? -1 :
*(uint64_t *)a->mv_data > *(uint64_t *)b->mv_data;
}
/** Compare two items pointing at unsigned ints of unknown alignment.
* Nodes and keys are guaranteed to be 2-byte aligned.
*/
static int
mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
{
#if BYTE_ORDER == LITTLE_ENDIAN
uint16_t *u, *c;
int x;
u = (uint16_t *) ((char *) a->mv_data + a->mv_size);
c = (uint16_t *) ((char *) b->mv_data + a->mv_size);
do {
x = *--u - *--c;
} while(!x && u > (uint16_t *)a->mv_data);
return x;
#else
uint16_t *u, *c, *end;
int x;
end = (uint16_t *) ((char *) a->mv_data + a->mv_size);
u = (uint16_t *)a->mv_data;
c = (uint16_t *)b->mv_data;
do {
x = *u++ - *c++;
} while(!x && u < end);
return x;
#endif
}
/** Compare two items lexically */
static int
mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
{
int diff;
ssize_t len_diff;
uint64_t len;
len = a->mv_size;
len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
if (len_diff > 0) {
len = b->mv_size;
len_diff = 1;
}
diff = memcmp(a->mv_data, b->mv_data, len);
return diff ? diff : len_diff<0 ? -1 : len_diff;
}
/** Compare two items in reverse byte order */
static int
mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
{
const uint8_t *p1, *p2, *p1_lim;
ssize_t len_diff;
int diff;
p1_lim = (const uint8_t *)a->mv_data;
p1 = (const uint8_t *)a->mv_data + a->mv_size;
p2 = (const uint8_t *)b->mv_data + b->mv_size;
len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
if (len_diff > 0) {
p1_lim += len_diff;
len_diff = 1;
}
while (p1 > p1_lim) {
diff = *--p1 - *--p2;
if (diff)
return diff;
}
return len_diff<0 ? -1 : len_diff;
}
/** Search for key within a page, using binary search.
* Returns the smallest entry larger or equal to the key.
* If exactp is non-null, stores whether the found entry was an exact match
* in *exactp (1 or 0).
* Updates the cursor index with the index of the found entry.
* If no entry larger or equal to the key is found, returns NULL.
*/
static MDB_node *
mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
{
uint64_t i = 0, nkeys;
int low, high;
int rc = 0;
MDB_page *mp = mc->mc_pg[mc->mc_top];
MDB_node *node = NULL;
MDB_val nodekey;
MDB_cmp_func *cmp;
DKBUF;
nkeys = NUMKEYS(mp);
DPRINTF(("searching %u keys in %s %spage %" Yu,
nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
mdb_dbg_pgno(mp)));
low = IS_LEAF(mp) ? 0 : 1;
high = nkeys - 1;
cmp = mc->mc_dbx->md_cmp;
/* Branch pages have no data, so if using integer keys,
* alignment is guaranteed. Use faster mdb_cmp_int.
*/
if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
cmp = mdb_cmp_long;
else
cmp = mdb_cmp_int;
}
if (IS_LEAF2(mp)) {
nodekey.mv_size = mc->mc_db->md_pad;
node = NODEPTR(mp, 0); /* fake */
while (low <= high) {
i = (low + high) >> 1;
nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
rc = cmp(key, &nodekey);
DPRINTF(("found leaf index %u [%s], rc = %i",
i, DKEY(&nodekey), rc));
if (rc == 0)
break;
if (rc > 0)
low = i + 1;
else
high = i - 1;
}
} else {
while (low <= high) {
i = (low + high) >> 1;
node = NODEPTR(mp, i);
nodekey.mv_size = NODEKSZ(node);
nodekey.mv_data = NODEKEY(node);
rc = cmp(key, &nodekey);
#if MDB_DEBUG
if (IS_LEAF(mp))
DPRINTF(("found leaf index %u [%s], rc = %i",
i, DKEY(&nodekey), rc));
else
DPRINTF(("found branch index %u [%s -> %" Yu"], rc = %i",
i, DKEY(&nodekey), NODEPGNO(node), rc));
#endif
if (rc == 0)
break;
if (rc > 0)
low = i + 1;
else
high = i - 1;
}
}
if (rc > 0) { /* Found entry is less than the key. */
i++; /* Skip to get the smallest entry larger than key. */
if (!IS_LEAF2(mp))
node = NODEPTR(mp, i);
}
if (exactp)
*exactp = (rc == 0 && nkeys > 0);
/* store the key index */
mc->mc_ki[mc->mc_top] = i;
if (i >= nkeys)
/* There is no entry larger or equal to the key. */
return NULL;
/* nodeptr is fake for LEAF2 */
return node;
}
#if 0
static void
mdb_cursor_adjust(MDB_cursor *mc, func)
{
MDB_cursor *m2;
for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
func(mc, m2);
}
}
}
#endif
/** Pop a page off the top of the cursor's stack. */
static void
mdb_cursor_pop(MDB_cursor *mc)
{
if (mc->mc_snum) {
DPRINTF(("popping page %" Yu" off db %d cursor %p",
mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
mc->mc_snum--;
if (mc->mc_snum) {
mc->mc_top--;
} else {
mc->mc_flags &= ~C_INITIALIZED;
}
}
}
/** Push a page onto the top of the cursor's stack.
* Set #MDB_TXN_ERROR on failure.
*/
static int
mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
{
DPRINTF(("pushing page %" Yu" on db %d cursor %p", mp->mp_pgno,
DDBI(mc), (void *) mc));
if (mc->mc_snum >= CURSOR_STACK) {
mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
return MDB_CURSOR_FULL;
}
mc->mc_top = mc->mc_snum++;
mc->mc_pg[mc->mc_top] = mp;
mc->mc_ki[mc->mc_top] = 0;
return MDB_SUCCESS;
}
//#ifdef MDB_VL32
///** Map a read-only page.
// * There are two levels of tracking in use, a per-txn list and a per-env list.
// * ref'ing and unref'ing the per-txn list is faster since it requires no
// * locking. Pages are cached in the per-env list for global reuse, and a lock
// * is required. Pages are not immediately unmapped when their refcnt goes to
// * zero; they hang around in case they will be reused again soon.
// *
// * When the per-txn list gets full, all pages with refcnt=0 are purged from the
// * list and their refcnts in the per-env list are decremented.
// *
// * When the per-env list gets full, all pages with refcnt=0 are purged from the
// * list and their pages are unmapped.
// *
// * @note "full" means the list has reached its respective rpcheck threshold.
// * This threshold slowly raises if no pages could be purged on a given check,
// * and returns to its original value when enough pages were purged.
// *
// * If purging doesn't free any slots, filling the per-txn list will return
// * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
// *
// * Reference tracking in a txn is imperfect, pages can linger with non-zero
// * refcnt even without active references. It was deemed to be too invasive
// * to add unrefs in every required location. However, all pages are unref'd
// * at the end of the transaction. This guarantees that no stale references
// * linger in the per-env list.
// *
// * Usually we map chunks of 16 pages at a time, but if an overflow page begins
// * at the tail of the chunk we extend the chunk to include the entire overflow
// * page. Unfortunately, pages can be turned into overflow pages after their
// * chunk was already mapped. In that case we must remap the chunk if the
// * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
// * it, otherwise we temporarily map a new chunk just for the overflow page.
// *
// * @note this chunk handling means we cannot guarantee that a data item
// * returned from the DB will stay alive for the duration of the transaction:
// * We unref pages as soon as a cursor moves away from the page
// * A subsequent op may cause a purge, which may unmap any unref'd chunks
// * The caller must copy the data if it must be used later in the same txn.
// *
// * Also - our reference counting revolves around cursors, but overflow pages
// * aren't pointed to by a cursor's page stack. We have to remember them
// * explicitly, in the added mc_ovpg field. A single cursor can only hold a
// * reference to one overflow page at a time.
// *
// * @param[in] txn the transaction for this access.
// * @param[in] pgno the page number for the page to retrieve.
// * @param[out] ret address of a pointer where the page's address will be stored.
// * @return 0 on success, non-zero on failure.
// */
//static int
//mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
//{
// MDB_env *env = txn->mt_env;
// MDB_page *p;
// MDB_ID3L tl = txn->mt_rpages;
// MDB_ID3L el = env->me_rpages;
// MDB_ID3 id3;
// unsigned x, rem;
// pgno_t pgno;
// int rc, retries = 1;
//#ifdef _WIN32
// LARGE_INTEGER off;
// SIZE_T len;
//#define SET_OFF(off,val) off.QuadPart = val
//#define MAP(rc,env,addr,len,off) \
// addr = NULL; \
// rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
// len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
// if (rc) rc = mdb_nt2win32(rc)
//#else
// off_t off;
// size_t len;
//#define SET_OFF(off,val) off = val
//#define MAP(rc,env,addr,len,off) \
// addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
// rc = (addr == MAP_FAILED) ? errno : 0
//#endif
// /* remember the offset of the actual page number, so we can
// * return the correct pointer at the end.
// */
// rem = pg0 & (MDB_RPAGE_CHUNK-1);
// pgno = pg0 ^ rem;
// id3.mid = 0;
// x = mdb_mid3l_search(tl, pgno);
// if (x <= tl[0].mid && tl[x].mid == pgno) {
// if (x != tl[0].mid && tl[x+1].mid == pg0)
// x++;
// /* check for overflow size */
// p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
// if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
// id3.mcnt = p->mp_pages + rem;
// len = id3.mcnt * env->me_psize;
// SET_OFF(off, pgno * env->me_psize);
// MAP(rc, env, id3.mptr, len, off);
// if (rc)
// return rc;
// /* check for local-only page */
// if (rem) {
// mdb_tassert(txn, tl[x].mid != pg0);
// /* hope there's room to insert this locally.
// * setting mid here tells later code to just insert
// * this id3 instead of searching for a match.
// */
// id3.mid = pg0;
// goto notlocal;
// } else {
// /* ignore the mapping we got from env, use new one */
// tl[x].mptr = id3.mptr;
// tl[x].mcnt = id3.mcnt;
// /* if no active ref, see if we can replace in env */
// if (!tl[x].mref) {
// unsigned i;
// pthread_mutex_lock(&env->me_rpmutex);
// i = mdb_mid3l_search(el, tl[x].mid);
// if (el[i].mref == 1) {
// /* just us, replace it */
// munmap(el[i].mptr, el[i].mcnt * env->me_psize);
// el[i].mptr = tl[x].mptr;
// el[i].mcnt = tl[x].mcnt;
// } else {
// /* there are others, remove ourself */
// el[i].mref--;
// }
// pthread_mutex_unlock(&env->me_rpmutex);
// }
// }
// }
// id3.mptr = tl[x].mptr;
// id3.mcnt = tl[x].mcnt;
// tl[x].mref++;
// goto ok;
// }
//notlocal:
// if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
// unsigned i, y;
// /* purge unref'd pages from our list and unref in env */
// pthread_mutex_lock(&env->me_rpmutex);
//retry:
// y = 0;
// for (i=1; i<=tl[0].mid; i++) {
// if (!tl[i].mref) {
// if (!y) y = i;
// /* tmp overflow pages don't go to env */
// if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
// munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
// continue;
// }
// x = mdb_mid3l_search(el, tl[i].mid);
// el[x].mref--;
// }
// }
// pthread_mutex_unlock(&env->me_rpmutex);
// if (!y) {
// /* we didn't find any unref'd chunks.
// * if we're out of room, fail.
// */
// if (tl[0].mid >= MDB_TRPAGE_MAX)
// return MDB_TXN_FULL;
// /* otherwise, raise threshold for next time around
// * and let this go.
// */
// txn->mt_rpcheck /= 2;
// } else {
// /* we found some unused; consolidate the list */
// for (i=y+1; i<= tl[0].mid; i++)
// if (tl[i].mref)
// tl[y++] = tl[i];
// tl[0].mid = y-1;
// /* decrease the check threshold toward its original value */
// if (!txn->mt_rpcheck)
// txn->mt_rpcheck = 1;
// while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
// txn->mt_rpcheck *= 2;
// }
// }
// if (tl[0].mid < MDB_TRPAGE_SIZE) {
// id3.mref = 1;
// if (id3.mid)
// goto found;
// /* don't map past last written page in read-only envs */
// if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
// id3.mcnt = txn->mt_last_pgno + 1 - pgno;
// else
// id3.mcnt = MDB_RPAGE_CHUNK;
// len = id3.mcnt * env->me_psize;
// id3.mid = pgno;
// /* search for page in env */
// pthread_mutex_lock(&env->me_rpmutex);
// x = mdb_mid3l_search(el, pgno);
// if (x <= el[0].mid && el[x].mid == pgno) {
// id3.mptr = el[x].mptr;
// id3.mcnt = el[x].mcnt;
// /* check for overflow size */
// p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
// if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
// id3.mcnt = p->mp_pages + rem;
// len = id3.mcnt * env->me_psize;
// SET_OFF(off, pgno * env->me_psize);
// MAP(rc, env, id3.mptr, len, off);
// if (rc)
// goto fail;
// if (!el[x].mref) {
// munmap(el[x].mptr, env->me_psize * el[x].mcnt);
// el[x].mptr = id3.mptr;
// el[x].mcnt = id3.mcnt;
// } else {
// id3.mid = pg0;
// pthread_mutex_unlock(&env->me_rpmutex);
// goto found;
// }
// }
// el[x].mref++;
// pthread_mutex_unlock(&env->me_rpmutex);
// goto found;
// }
// if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
// /* purge unref'd pages */
// unsigned i, y = 0;
// for (i=1; i<=el[0].mid; i++) {
// if (!el[i].mref) {
// if (!y) y = i;
// munmap(el[i].mptr, env->me_psize * el[i].mcnt);
// }
// }
// if (!y) {
// if (retries) {
// /* see if we can unref some local pages */
// retries--;
// id3.mid = 0;
// goto retry;
// }
// if (el[0].mid >= MDB_ERPAGE_MAX) {
// pthread_mutex_unlock(&env->me_rpmutex);
// return MDB_MAP_FULL;
// }
// env->me_rpcheck /= 2;
// } else {
// for (i=y+1; i<= el[0].mid; i++)
// if (el[i].mref)
// el[y++] = el[i];
// el[0].mid = y-1;
// if (!env->me_rpcheck)
// env->me_rpcheck = 1;
// while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
// env->me_rpcheck *= 2;
// }
// }
// SET_OFF(off, pgno * env->me_psize);
// MAP(rc, env, id3.mptr, len, off);
// if (rc) {
//fail:
// pthread_mutex_unlock(&env->me_rpmutex);
// return rc;
// }
// /* check for overflow size */
// p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
// if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
// id3.mcnt = p->mp_pages + rem;
// munmap(id3.mptr, len);
// len = id3.mcnt * env->me_psize;
// MAP(rc, env, id3.mptr, len, off);
// if (rc)
// goto fail;
// }
// mdb_mid3l_insert(el, &id3);
// pthread_mutex_unlock(&env->me_rpmutex);
//found:
// mdb_mid3l_insert(tl, &id3);
// } else {
// return MDB_TXN_FULL;
// }
//ok:
// p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
//#if MDB_DEBUG /* we don't need this check any more */
// if (IS_OVERFLOW(p)) {
// mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
// }
//#endif
// *ret = p;
// return MDB_SUCCESS;
//}
//#endif
/** Find the address of the page corresponding to a given page number.
* Set #MDB_TXN_ERROR on failure.
* @param[in] mc the cursor accessing the page.
* @param[in] pgno the page number for the page to retrieve.
* @param[out] ret address of a pointer where the page's address will be stored.
* @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
{
MDB_txn *txn = mc->mc_txn;
MDB_page *p = NULL;
int level;
if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
MDB_txn *tx2 = txn;
level = 1;
do {
MDB_ID2L dl = tx2->mt_u.dirty_list;
unsigned x;
/* Spilled pages were dirtied in this txn and flushed
* because the dirty list got full. Bring this page
* back in from the map (but don't unspill it here,
* leave that unless page_touch happens again).
*/
if (tx2->mt_spill_pgs) {
MDB_ID pn = pgno << 1;
x = mdb_midl_search(tx2->mt_spill_pgs, pn);
if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
goto mapped;
}
}
if (dl[0].mid) {
unsigned x = mdb_mid2l_search(dl, pgno);
if (x <= dl[0].mid && dl[x].mid == pgno) {
p = (MDB_page *) dl[x].mptr;
goto done;
}
}
level++;
} while ((tx2 = tx2->mt_parent) != NULL);
}
if (pgno >= txn->mt_next_pgno) {
DPRINTF(("page %" Yu" not found", pgno));
txn->mt_flags |= MDB_TXN_ERROR;
return MDB_PAGE_NOTFOUND;
}
level = 0;
mapped:
{
//#ifdef MDB_VL32
// int rc = mdb_rpage_get(txn, pgno, &p);
// if (rc) {
// txn->mt_flags |= MDB_TXN_ERROR;
// return rc;
// }
//#else
MDB_env *env = txn->mt_env;
p = (MDB_page *)(env->me_map + env->me_psize * pgno);
//#endif
}
done:
*ret = p;
if (lvl)
*lvl = level;
return MDB_SUCCESS;
}
/** Finish #mdb_page_search() / #mdb_page_search_lowest().
* The cursor is at the root page, set up the rest of it.
*/
static int
mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
{
MDB_page *mp = mc->mc_pg[mc->mc_top];
int rc;
DKBUF;
while (IS_BRANCH(mp)) {
MDB_node *node;
indx_t i;
DPRINTF(("branch page %" Yu" has %u keys", mp->mp_pgno, NUMKEYS(mp)));
/* Don't assert on branch pages in the FreeDB. We can get here
* while in the process of rebalancing a FreeDB branch page; we must
* let that proceed. ITS#8336
*/
mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
DPRINTF(("found index 0 to page %" Yu, NODEPGNO(NODEPTR(mp, 0))));
if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
i = 0;
if (flags & MDB_PS_LAST) {
i = NUMKEYS(mp) - 1;
/* if already init'd, see if we're already in right place */
if (mc->mc_flags & C_INITIALIZED) {
if (mc->mc_ki[mc->mc_top] == i) {
mc->mc_top = mc->mc_snum++;
mp = mc->mc_pg[mc->mc_top];
goto ready;
}
}
}
} else {
int exact;
node = mdb_node_search(mc, key, &exact);
if (node == NULL)
i = NUMKEYS(mp) - 1;
else {
i = mc->mc_ki[mc->mc_top];
if (!exact) {
mdb_cassert(mc, i > 0);
i--;
}
}
DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
}
mdb_cassert(mc, i < NUMKEYS(mp));
node = NODEPTR(mp, i);
if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
return rc;
mc->mc_ki[mc->mc_top] = i;
if ((rc = mdb_cursor_push(mc, mp)))
return rc;
ready:
if (flags & MDB_PS_MODIFY) {
if ((rc = mdb_page_touch(mc)) != 0)
return rc;
mp = mc->mc_pg[mc->mc_top];
}
}
if (!IS_LEAF(mp)) {
DPRINTF(("internal error, index points to a %02X page!?",
mp->mp_flags));
mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
return MDB_CORRUPTED;
}
DPRINTF(("found leaf page %" Yu" for key [%s]", mp->mp_pgno,
key ? DKEY(key) : "null"));
mc->mc_flags |= C_INITIALIZED;
mc->mc_flags &= ~C_EOF;
return MDB_SUCCESS;
}
/** Search for the lowest key under the current branch page.
* This just bypasses a NUMKEYS check in the current page
* before calling mdb_page_search_root(), because the callers
* are all in situations where the current page is known to
* be underfilled.
*/
static int
mdb_page_search_lowest(MDB_cursor *mc)
{
MDB_page *mp = mc->mc_pg[mc->mc_top];
MDB_node *node = NODEPTR(mp, 0);
int rc;
if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
return rc;
mc->mc_ki[mc->mc_top] = 0;
if ((rc = mdb_cursor_push(mc, mp)))
return rc;
return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
}
/** Search for the page a given key should be in.
* Push it and its parent pages on the cursor stack.
* @param[in,out] mc the cursor for this operation.
* @param[in] key the key to search for, or NULL for first/last page.
* @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
* are touched (updated with new page numbers).
* If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
* This is used by #mdb_cursor_first() and #mdb_cursor_last().
* If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
{
int rc;
pgno_t root;
/* Make sure the txn is still viable, then find the root from
* the txn's db table and set it as the root of the cursor's stack.
*/
if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
DPUTS("transaction may not be used now");
return MDB_BAD_TXN;
} else {
/* Make sure we're using an up-to-date root */
if (*mc->mc_dbflag & DB_STALE) {
MDB_cursor mc2;
if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
return MDB_BAD_DBI;
mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
if (rc)
return rc;
{
MDB_val data;
int exact = 0;
uint16_t flags;
MDB_node *leaf = mdb_node_search(&mc2,
&mc->mc_dbx->md_name, &exact);
if (!exact)
return MDB_NOTFOUND;
if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
return MDB_INCOMPATIBLE; /* not a named DB */
rc = mdb_node_read(&mc2, leaf, &data);
if (rc)
return rc;
memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
sizeof(uint16_t));
/* The txn may not know this DBI, or another process may
* have dropped and recreated the DB with other flags.
*/
if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
return MDB_INCOMPATIBLE;
memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
}
*mc->mc_dbflag &= ~DB_STALE;
}
root = mc->mc_db->md_root;
if (root == P_INVALID) { /* Tree is empty. */
DPUTS("tree is empty");
return MDB_NOTFOUND;
}
}
mdb_cassert(mc, root > 1);
if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
//#ifdef MDB_VL32
// if (mc->mc_pg[0])
// MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
//#endif
if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
return rc;
}
//#ifdef MDB_VL32
// {
// int i;
// for (i=1; i<mc->mc_snum; i++)
// MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
// }
//#endif
mc->mc_snum = 1;
mc->mc_top = 0;
DPRINTF(("db %d root page %" Yu" has flags 0x%X",
DDBI(mc), root, mc->mc_pg[0]->mp_flags));
if (flags & MDB_PS_MODIFY) {
if ((rc = mdb_page_touch(mc)))
return rc;
}
if (flags & MDB_PS_ROOTONLY)
return MDB_SUCCESS;
return mdb_page_search_root(mc, key, flags);
}
static int
mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
{
MDB_txn *txn = mc->mc_txn;
pgno_t pg = mp->mp_pgno;
unsigned x = 0, ovpages = mp->mp_pages;
MDB_env *env = txn->mt_env;
MDB_IDL sl = txn->mt_spill_pgs;
MDB_ID pn = pg << 1;
int rc;
DPRINTF(("free ov page %" Yu" (%d)", pg, ovpages));
/* If the page is dirty or on the spill list we just acquired it,
* so we should give it back to our current free list, if any.
* Otherwise put it onto the list of pages we freed in this txn.
*
* Won't create me_pghead: me_pglast must be inited along with it.
* Unsupported in nested txns: They would need to hide the page
* range in ancestor txns' dirty and spilled lists.
*/
if (env->me_pghead &&
!txn->mt_parent &&
((mp->mp_flags & P_DIRTY) ||
(sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
{
unsigned i, j;
pgno_t *mop;
MDB_ID2 *dl, ix, iy;
rc = mdb_midl_need(&env->me_pghead, ovpages);
if (rc)
return rc;
if (!(mp->mp_flags & P_DIRTY)) {
/* This page is no longer spilled */
if (x == sl[0])
sl[0]--;
else
sl[x] |= 1;
goto release;
}
/* Remove from dirty list */
dl = txn->mt_u.dirty_list;
x = dl[0].mid--;
for (ix = dl[x]; ix.mptr != mp; ix = iy) {
if (x > 1) {
x--;
iy = dl[x];
dl[x] = ix;
} else {
mdb_cassert(mc, x > 1);
j = ++(dl[0].mid);
dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
txn->mt_flags |= MDB_TXN_ERROR;
return MDB_PROBLEM;
}
}
txn->mt_dirty_room++;
if (!(env->me_flags & MDB_WRITEMAP))
mdb_dpage_free(env, mp);
release:
/* Insert in me_pghead */
mop = env->me_pghead;
j = mop[0] + ovpages;
for (i = mop[0]; i && mop[i] < pg; i--)
mop[j--] = mop[i];
while (j>i)
mop[j--] = pg++;
mop[0] += ovpages;
} else {
rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
if (rc)
return rc;
}
//#ifdef MDB_VL32
// if (mc->mc_ovpg == mp)
// mc->mc_ovpg = NULL;
//#endif
mc->mc_db->md_overflow_pages -= ovpages;
return 0;
}
/** Return the data associated with a given node.
* @param[in] mc The cursor for this operation.
* @param[in] leaf The node being read.
* @param[out] data Updated to point to the node's data.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
{
MDB_page *omp; /* overflow page */
pgno_t pgno;
int rc;
if (MC_OVPG(mc)) {
MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
MC_SET_OVPG(mc, NULL);
}
if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
data->mv_size = NODEDSZ(leaf);
data->mv_data = NODEDATA(leaf);
return MDB_SUCCESS;
}
/* Read overflow data.
*/
data->mv_size = NODEDSZ(leaf);
memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
DPRINTF(("read overflow page %" Yu" failed", pgno));
return rc;
}
data->mv_data = METADATA(omp);
MC_SET_OVPG(mc, omp);
return MDB_SUCCESS;
}
int
mdb_get(MDB_txn *txn, MDB_dbi dbi,
MDB_val *key, MDB_val *data)
{
MDB_cursor mc;
MDB_xcursor mx;
int exact = 0, rc;
DKBUF;
DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
return EINVAL;
if (txn->mt_flags & MDB_TXN_BLOCKED)
return MDB_BAD_TXN;
mdb_cursor_init(&mc, txn, dbi, &mx);
rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
/* unref all the pages when MDB_VL32 - caller must copy the data
* before doing anything else
*/
MDB_CURSOR_UNREF(&mc, 1);
return rc;
}
/** Find a sibling for a page.
* Replaces the page at the top of the cursor's stack with the
* specified sibling, if one exists.
* @param[in] mc The cursor for this operation.
* @param[in] move_right Non-zero if the right sibling is requested,
* otherwise the left sibling.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_cursor_sibling(MDB_cursor *mc, int move_right)
{
int rc;
MDB_node *indx;
MDB_page *mp;
//#ifdef MDB_VL32
// MDB_page *op;
//#endif
if (mc->mc_snum < 2) {
return MDB_NOTFOUND; /* root has no siblings */
}
//#ifdef MDB_VL32
// op = mc->mc_pg[mc->mc_top];
//#endif
mdb_cursor_pop(mc);
DPRINTF(("parent page is page %" Yu", index %u",
mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
: (mc->mc_ki[mc->mc_top] == 0)) {
DPRINTF(("no more keys left, moving to %s sibling",
move_right ? "right" : "left"));
if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
/* undo cursor_pop before returning */
mc->mc_top++;
mc->mc_snum++;
return rc;
}
} else {
if (move_right)
mc->mc_ki[mc->mc_top]++;
else
mc->mc_ki[mc->mc_top]--;
DPRINTF(("just moving to %s index key %u",
move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
}
mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
MDB_PAGE_UNREF(mc->mc_txn, op);
indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
/* mc will be inconsistent if caller does mc_snum++ as above */
mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
return rc;
}
mdb_cursor_push(mc, mp);
if (!move_right)
mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
return MDB_SUCCESS;
}
/** Move the cursor to the next data item. */
static int
mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
{
MDB_page *mp;
MDB_node *leaf;
int rc;
if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
return MDB_NOTFOUND;
if (!(mc->mc_flags & C_INITIALIZED))
return mdb_cursor_first(mc, key, data);
mp = mc->mc_pg[mc->mc_top];
if (mc->mc_flags & C_EOF) {
if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
return MDB_NOTFOUND;
mc->mc_flags ^= C_EOF;
}
if (mc->mc_db->md_flags & MDB_DUPSORT) {
leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
if (rc == MDB_SUCCESS)
MDB_GET_KEY(leaf, key);
return rc;
}
}
else {
MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
}
} else {
mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
if (op == MDB_NEXT_DUP)
return MDB_NOTFOUND;
}
}
DPRINTF(("cursor_next: top page is %" Yu" in cursor %p",
mdb_dbg_pgno(mp), (void *) mc));
if (mc->mc_flags & C_DEL) {
mc->mc_flags ^= C_DEL;
goto skip;
}
if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
DPUTS("=====> move to next sibling page");
if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
mc->mc_flags |= C_EOF;
return rc;
}
mp = mc->mc_pg[mc->mc_top];
DPRINTF(("next page is %" Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
} else
mc->mc_ki[mc->mc_top]++;
skip:
DPRINTF(("==> cursor points to page %" Yu" with %u keys, key index %u",
mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
if (IS_LEAF2(mp)) {
key->mv_size = mc->mc_db->md_pad;
key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
return MDB_SUCCESS;
}
mdb_cassert(mc, IS_LEAF(mp));
leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
mdb_xcursor_init1(mc, leaf);
}
if (data) {
if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
return rc;
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
if (rc != MDB_SUCCESS)
return rc;
}
}
MDB_GET_KEY(leaf, key);
return MDB_SUCCESS;
}
/** Move the cursor to the previous data item. */
static int
mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
{
MDB_page *mp;
MDB_node *leaf;
int rc;
if (!(mc->mc_flags & C_INITIALIZED)) {
rc = mdb_cursor_last(mc, key, data);
if (rc)
return rc;
mc->mc_ki[mc->mc_top]++;
}
mp = mc->mc_pg[mc->mc_top];
if (mc->mc_db->md_flags & MDB_DUPSORT) {
leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
if (op == MDB_PREV || op == MDB_PREV_DUP) {
rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
if (op != MDB_PREV || rc != MDB_NOTFOUND) {
if (rc == MDB_SUCCESS) {
MDB_GET_KEY(leaf, key);
mc->mc_flags &= ~C_EOF;
}
return rc;
}
}
else {
MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
}
} else {
mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
if (op == MDB_PREV_DUP)
return MDB_NOTFOUND;
}
}
DPRINTF(("cursor_prev: top page is %" Yu" in cursor %p",
mdb_dbg_pgno(mp), (void *) mc));
mc->mc_flags &= ~(C_EOF|C_DEL);
if (mc->mc_ki[mc->mc_top] == 0) {
DPUTS("=====> move to prev sibling page");
if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
return rc;
}
mp = mc->mc_pg[mc->mc_top];
mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
DPRINTF(("prev page is %" Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
} else
mc->mc_ki[mc->mc_top]--;
DPRINTF(("==> cursor points to page %" Yu" with %u keys, key index %u",
mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
if (IS_LEAF2(mp)) {
key->mv_size = mc->mc_db->md_pad;
key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
return MDB_SUCCESS;
}
mdb_cassert(mc, IS_LEAF(mp));
leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
mdb_xcursor_init1(mc, leaf);
}
if (data) {
if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
return rc;
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
if (rc != MDB_SUCCESS)
return rc;
}
}
MDB_GET_KEY(leaf, key);
return MDB_SUCCESS;
}
/** Set the cursor on a specific data item. */
static int
mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
MDB_cursor_op op, int *exactp)
{
int rc;
MDB_page *mp;
MDB_node *leaf = NULL;
DKBUF;
if (key->mv_size == 0)
return MDB_BAD_VALSIZE;
if (mc->mc_xcursor) {
MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
}
/* See if we're already on the right page */
if (mc->mc_flags & C_INITIALIZED) {
MDB_val nodekey;
mp = mc->mc_pg[mc->mc_top];
if (!NUMKEYS(mp)) {
mc->mc_ki[mc->mc_top] = 0;
return MDB_NOTFOUND;
}
if (mp->mp_flags & P_LEAF2) {
nodekey.mv_size = mc->mc_db->md_pad;
nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
} else {
leaf = NODEPTR(mp, 0);
MDB_GET_KEY2(leaf, nodekey);
}
rc = mc->mc_dbx->md_cmp(key, &nodekey);
if (rc == 0) {
/* Probably happens rarely, but first node on the page
* was the one we wanted.
*/
mc->mc_ki[mc->mc_top] = 0;
if (exactp)
*exactp = 1;
goto set1;
}
if (rc > 0) {
uint64_t i;
uint64_t nkeys = NUMKEYS(mp);
if (nkeys > 1) {
if (mp->mp_flags & P_LEAF2) {
nodekey.mv_data = LEAF2KEY(mp,
nkeys-1, nodekey.mv_size);
} else {
leaf = NODEPTR(mp, nkeys-1);
MDB_GET_KEY2(leaf, nodekey);
}
rc = mc->mc_dbx->md_cmp(key, &nodekey);
if (rc == 0) {
/* last node was the one we wanted */
mc->mc_ki[mc->mc_top] = nkeys-1;
if (exactp)
*exactp = 1;
goto set1;
}
if (rc < 0) {
if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
/* This is definitely the right page, skip search_page */
if (mp->mp_flags & P_LEAF2) {
nodekey.mv_data = LEAF2KEY(mp,
mc->mc_ki[mc->mc_top], nodekey.mv_size);
} else {
leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
MDB_GET_KEY2(leaf, nodekey);
}
rc = mc->mc_dbx->md_cmp(key, &nodekey);
if (rc == 0) {
/* current node was the one we wanted */
if (exactp)
*exactp = 1;
goto set1;
}
}
rc = 0;
mc->mc_flags &= ~C_EOF;
goto set2;
}
}
/* If any parents have right-sibs, search.
* Otherwise, there's nothing further.
*/
for (i=0; i<mc->mc_top; i++)
if (mc->mc_ki[i] <
NUMKEYS(mc->mc_pg[i])-1)
break;
if (i == mc->mc_top) {
/* There are no other pages */
mc->mc_ki[mc->mc_top] = nkeys;
return MDB_NOTFOUND;
}
}
if (!mc->mc_top) {
/* There are no other pages */
mc->mc_ki[mc->mc_top] = 0;
if (op == MDB_SET_RANGE && !exactp) {
rc = 0;
goto set1;
} else
return MDB_NOTFOUND;
}
} else {
mc->mc_pg[0] = 0;
}
rc = mdb_page_search(mc, key, 0);
if (rc != MDB_SUCCESS)
return rc;
mp = mc->mc_pg[mc->mc_top];
mdb_cassert(mc, IS_LEAF(mp));
set2:
leaf = mdb_node_search(mc, key, exactp);
if (exactp != NULL && !*exactp) {
/* MDB_SET specified and not an exact match. */
return MDB_NOTFOUND;
}
if (leaf == NULL) {
DPUTS("===> inexact leaf not found, goto sibling");
if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
mc->mc_flags |= C_EOF;
return rc; /* no entries matched */
}
mp = mc->mc_pg[mc->mc_top];
mdb_cassert(mc, IS_LEAF(mp));
leaf = NODEPTR(mp, 0);
}
set1:
mc->mc_flags |= C_INITIALIZED;
mc->mc_flags &= ~C_EOF;
if (IS_LEAF2(mp)) {
if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
key->mv_size = mc->mc_db->md_pad;
key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
}
return MDB_SUCCESS;
}
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
mdb_xcursor_init1(mc, leaf);
}
if (data) {
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
} else {
int ex2, *ex2p;
if (op == MDB_GET_BOTH) {
ex2p = &ex2;
ex2 = 0;
} else {
ex2p = NULL;
}
rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
if (rc != MDB_SUCCESS)
return rc;
}
} else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
MDB_val olddata;
MDB_cmp_func *dcmp;
if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
return rc;
dcmp = mc->mc_dbx->md_dcmp;
if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
dcmp = mdb_cmp_clong;
rc = dcmp(data, &olddata);
if (rc) {
if (op == MDB_GET_BOTH || rc > 0)
return MDB_NOTFOUND;
rc = 0;
}
*data = olddata;
} else {
if (mc->mc_xcursor)
mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
return rc;
}
}
/* The key already matches in all other cases */
if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
MDB_GET_KEY(leaf, key);
DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
return rc;
}
/** Move the cursor to the first item in the database. */
static int
mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
{
int rc;
MDB_node *leaf;
if (mc->mc_xcursor) {
MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
}
if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
if (rc != MDB_SUCCESS)
return rc;
}
mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
mc->mc_flags |= C_INITIALIZED;
mc->mc_flags &= ~C_EOF;
mc->mc_ki[mc->mc_top] = 0;
if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
key->mv_size = mc->mc_db->md_pad;
key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
return MDB_SUCCESS;
}
if (data) {
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
mdb_xcursor_init1(mc, leaf);
rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
if (rc)
return rc;
} else {
if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
return rc;
}
}
MDB_GET_KEY(leaf, key);
return MDB_SUCCESS;
}
/** Move the cursor to the last item in the database. */
static int
mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
{
int rc;
MDB_node *leaf;
if (mc->mc_xcursor) {
MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
}
if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
if (rc != MDB_SUCCESS)
return rc;
}
mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
mc->mc_flags |= C_INITIALIZED|C_EOF;
leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
key->mv_size = mc->mc_db->md_pad;
key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
return MDB_SUCCESS;
}
if (data) {
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
mdb_xcursor_init1(mc, leaf);
rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
if (rc)
return rc;
} else {
if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
return rc;
}
}
MDB_GET_KEY(leaf, key);
return MDB_SUCCESS;
}
int
mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
MDB_cursor_op op)
{
int rc;
int exact = 0;
int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
if (mc == NULL)
return EINVAL;
if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
return MDB_BAD_TXN;
switch (op) {
case MDB_GET_CURRENT:
if (!(mc->mc_flags & C_INITIALIZED)) {
rc = EINVAL;
} else {
MDB_page *mp = mc->mc_pg[mc->mc_top];
int nkeys = NUMKEYS(mp);
if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
mc->mc_ki[mc->mc_top] = nkeys;
rc = MDB_NOTFOUND;
break;
}
rc = MDB_SUCCESS;
if (IS_LEAF2(mp)) {
key->mv_size = mc->mc_db->md_pad;
key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
} else {
MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
MDB_GET_KEY(leaf, key);
if (data) {
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
} else {
rc = mdb_node_read(mc, leaf, data);
}
}
}
}
break;
case MDB_GET_BOTH:
case MDB_GET_BOTH_RANGE:
if (data == NULL) {
rc = EINVAL;
break;
}
if (mc->mc_xcursor == NULL) {
rc = MDB_INCOMPATIBLE;
break;
}
/* FALLTHRU */
case MDB_SET:
case MDB_SET_KEY:
case MDB_SET_RANGE:
if (key == NULL) {
rc = EINVAL;
} else {
rc = mdb_cursor_set(mc, key, data, op,
op == MDB_SET_RANGE ? NULL : &exact);
}
break;
case MDB_GET_MULTIPLE:
if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
rc = EINVAL;
break;
}
if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
rc = MDB_INCOMPATIBLE;
break;
}
rc = MDB_SUCCESS;
if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
(mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
break;
goto fetchm;
case MDB_NEXT_MULTIPLE:
if (data == NULL) {
rc = EINVAL;
break;
}
if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
rc = MDB_INCOMPATIBLE;
break;
}
rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
if (rc == MDB_SUCCESS) {
if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
MDB_cursor *mx;
fetchm:
mx = &mc->mc_xcursor->mx_cursor;
data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
mx->mc_db->md_pad;
data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
} else {
rc = MDB_NOTFOUND;
}
}
break;
case MDB_PREV_MULTIPLE:
if (data == NULL) {
rc = EINVAL;
break;
}
if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
rc = MDB_INCOMPATIBLE;
break;
}
if (!(mc->mc_flags & C_INITIALIZED))
rc = mdb_cursor_last(mc, key, data);
else
rc = MDB_SUCCESS;
if (rc == MDB_SUCCESS) {
MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
if (mx->mc_flags & C_INITIALIZED) {
rc = mdb_cursor_sibling(mx, 0);
if (rc == MDB_SUCCESS)
goto fetchm;
} else {
rc = MDB_NOTFOUND;
}
}
break;
case MDB_NEXT:
case MDB_NEXT_DUP:
case MDB_NEXT_NODUP:
rc = mdb_cursor_next(mc, key, data, op);
break;
case MDB_PREV:
case MDB_PREV_DUP:
case MDB_PREV_NODUP:
rc = mdb_cursor_prev(mc, key, data, op);
break;
case MDB_FIRST:
rc = mdb_cursor_first(mc, key, data);
break;
case MDB_FIRST_DUP:
mfunc = mdb_cursor_first;
mmove:
if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
rc = EINVAL;
break;
}
if (mc->mc_xcursor == NULL) {
rc = MDB_INCOMPATIBLE;
break;
}
if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top])) {
mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
rc = MDB_NOTFOUND;
break;
}
{
MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
MDB_GET_KEY(leaf, key);
rc = mdb_node_read(mc, leaf, data);
break;
}
}
if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
rc = EINVAL;
break;
}
rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
break;
case MDB_LAST:
rc = mdb_cursor_last(mc, key, data);
break;
case MDB_LAST_DUP:
mfunc = mdb_cursor_last;
goto mmove;
default:
DPRINTF(("unhandled/unimplemented cursor operation %u", op));
rc = EINVAL;
break;
}
if (mc->mc_flags & C_DEL)
mc->mc_flags ^= C_DEL;
return rc;
}
/** Touch all the pages in the cursor stack. Set mc_top.
* Makes sure all the pages are writable, before attempting a write operation.
* @param[in] mc The cursor to operate on.
*/
static int
mdb_cursor_touch(MDB_cursor *mc)
{
int rc = MDB_SUCCESS;
if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
/* Touch DB record of named DB */
MDB_cursor mc2;
MDB_xcursor mcx;
if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
return MDB_BAD_DBI;
mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
if (rc)
return rc;
*mc->mc_dbflag |= DB_DIRTY;
}
mc->mc_top = 0;
if (mc->mc_snum) {
do {
rc = mdb_page_touch(mc);
} while (!rc && ++(mc->mc_top) < mc->mc_snum);
mc->mc_top = mc->mc_snum-1;
}
return rc;
}
/** Do not spill pages to disk if txn is getting full, may fail instead */
#define MDB_NOSPILL 0x8000
int
mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
uint64_t flags)
{
MDB_env *env;
MDB_node *leaf = NULL;
MDB_page *fp, *mp, *sub_root = NULL;
uint16_t fp_flags;
MDB_val xdata, *rdata, dkey, olddata;
MDB_db dummy;
int do_sub = 0, insert_key, insert_data;
uint64_t mcount = 0, dcount = 0, nospill;
size_t nsize;
int rc, rc2;
uint64_t nflags;
DKBUF;
if (mc == NULL || key == NULL)
return EINVAL;
env = mc->mc_txn->mt_env;
/* Check this first so counter will always be zero on any
* early failures.
*/
if (flags & MDB_MULTIPLE) {
dcount = data[1].mv_size;
data[1].mv_size = 0;
if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
return MDB_INCOMPATIBLE;
}
nospill = flags & MDB_NOSPILL;
flags &= ~MDB_NOSPILL;
if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
if (key->mv_size-1 >= ENV_MAXKEY(env))
return MDB_BAD_VALSIZE;
#if SIZE_MAX > MAXDATASIZE
if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
return MDB_BAD_VALSIZE;
#else
if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
return MDB_BAD_VALSIZE;
#endif
DPRINTF(("==> put db %d key [%s], size %" Z "u, data size %" Z "u",
DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
dkey.mv_size = 0;
if (flags == MDB_CURRENT) {
if (!(mc->mc_flags & C_INITIALIZED))
return EINVAL;
rc = MDB_SUCCESS;
} else if (mc->mc_db->md_root == P_INVALID) {
/* new database, cursor has nothing to point to */
mc->mc_snum = 0;
mc->mc_top = 0;
mc->mc_flags &= ~C_INITIALIZED;
rc = MDB_NO_ROOT;
} else {
int exact = 0;
MDB_val d2;
if (flags & MDB_APPEND) {
MDB_val k2;
rc = mdb_cursor_last(mc, &k2, &d2);
if (rc == 0) {
rc = mc->mc_dbx->md_cmp(key, &k2);
if (rc > 0) {
rc = MDB_NOTFOUND;
mc->mc_ki[mc->mc_top]++;
} else {
/* new key is <= last key */
rc = MDB_KEYEXIST;
}
}
} else {
rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
}
if ((flags & MDB_NOOVERWRITE) && rc == 0) {
DPRINTF(("duplicate key [%s]", DKEY(key)));
*data = d2;
return MDB_KEYEXIST;
}
if (rc && rc != MDB_NOTFOUND)
return rc;
}
if (mc->mc_flags & C_DEL)
mc->mc_flags ^= C_DEL;
/* Cursor is positioned, check for room in the dirty list */
if (!nospill) {
if (flags & MDB_MULTIPLE) {
rdata = &xdata;
xdata.mv_size = data->mv_size * dcount;
} else {
rdata = data;
}
if ((rc2 = mdb_page_spill(mc, key, rdata)))
return rc2;
}
if (rc == MDB_NO_ROOT) {
MDB_page *np;
/* new database, write a root leaf page */
DPUTS("allocating new root leaf page");
if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
return rc2;
}
mdb_cursor_push(mc, np);
mc->mc_db->md_root = np->mp_pgno;
mc->mc_db->md_depth++;
*mc->mc_dbflag |= DB_DIRTY;
if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
== MDB_DUPFIXED)
np->mp_flags |= P_LEAF2;
mc->mc_flags |= C_INITIALIZED;
} else {
/* make sure all cursor pages are writable */
rc2 = mdb_cursor_touch(mc);
if (rc2)
return rc2;
}
insert_key = insert_data = rc;
if (insert_key) {
/* The key does not exist */
DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
LEAFSIZE(key, data) > env->me_nodemax)
{
/* Too big for a node, insert in sub-DB. Set up an empty
* "old sub-page" for prep_subDB to expand to a full page.
*/
fp_flags = P_LEAF|P_DIRTY;
fp = (MDB_page *) env->me_pbuf;
fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
olddata.mv_size = PAGEHDRSZ;
goto prep_subDB;
}
} else {
/* there's only a key anyway, so this is a no-op */
if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
char *ptr;
uint64_t ksize = mc->mc_db->md_pad;
if (key->mv_size != ksize)
return MDB_BAD_VALSIZE;
ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
memcpy(ptr, key->mv_data, ksize);
fix_parent:
/* if overwriting slot 0 of leaf, need to
* update branch key if there is a parent page
*/
if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
uint16_t dtop = 1;
mc->mc_top--;
/* slot 0 is always an empty key, find real slot */
while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
mc->mc_top--;
dtop++;
}
if (mc->mc_ki[mc->mc_top])
rc2 = mdb_update_key(mc, key);
else
rc2 = MDB_SUCCESS;
mc->mc_top += dtop;
if (rc2)
return rc2;
}
return MDB_SUCCESS;
}
more:
leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
olddata.mv_size = NODEDSZ(leaf);
olddata.mv_data = NODEDATA(leaf);
/* DB has dups? */
if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
/* Prepare (sub-)page/sub-DB to accept the new item,
* if needed. fp: old sub-page or a header faking
* it. mp: new (sub-)page. offset: growth in page
* size. xdata: node data with new page or DB.
*/
unsigned i, offset = 0;
xdata.mv_data = env->me_pbuf;
mp = fp = (MDB_page *) xdata.mv_data;
mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
/* Was a single item before, must convert now */
if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
MDB_cmp_func *dcmp;
/* Just overwrite the current item */
if (flags == MDB_CURRENT)
goto current;
dcmp = mc->mc_dbx->md_dcmp;
if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
dcmp = mdb_cmp_clong;
/* does data match? */
if (!dcmp(data, &olddata)) {
if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
return MDB_KEYEXIST;
/* overwrite it */
goto current;
}
/* Back up original data item */
dkey.mv_size = olddata.mv_size;
dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
/* Make sub-page header for the dup items, with dummy body */
fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
if (mc->mc_db->md_flags & MDB_DUPFIXED) {
fp->mp_flags |= P_LEAF2;
fp->mp_pad = data->mv_size;
xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
} else {
xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
(dkey.mv_size & 1) + (data->mv_size & 1);
}
fp->mp_upper = xdata.mv_size - PAGEBASE;
olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
} else if (leaf->mn_flags & F_SUBDATA) {
/* Data is on sub-DB, just store it */
flags |= F_DUPDATA|F_SUBDATA;
goto put_sub;
} else {
/* Data is on sub-page */
fp = (MDB_page *) olddata.mv_data;
switch (flags) {
default:
if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
offset = EVEN(NODESIZE + sizeof(indx_t) +
data->mv_size);
break;
}
offset = fp->mp_pad;
if (SIZELEFT(fp) < offset) {
offset *= 4; /* space for 4 more */
break;
}
/* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
case MDB_CURRENT:
fp->mp_flags |= P_DIRTY;
COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
flags |= F_DUPDATA;
goto put_sub;
}
xdata.mv_size = olddata.mv_size + offset;
}
fp_flags = fp->mp_flags;
if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
/* Too big for a sub-page, convert to sub-DB */
fp_flags &= ~P_SUBP;
prep_subDB:
if (mc->mc_db->md_flags & MDB_DUPFIXED) {
fp_flags |= P_LEAF2;
dummy.md_pad = fp->mp_pad;
dummy.md_flags = MDB_DUPFIXED;
if (mc->mc_db->md_flags & MDB_INTEGERDUP)
dummy.md_flags |= MDB_INTEGERKEY;
} else {
dummy.md_pad = 0;
dummy.md_flags = 0;
}
dummy.md_depth = 1;
dummy.md_branch_pages = 0;
dummy.md_leaf_pages = 1;
dummy.md_overflow_pages = 0;
dummy.md_entries = NUMKEYS(fp);
xdata.mv_size = sizeof(MDB_db);
xdata.mv_data = &dummy;
if ((rc = mdb_page_alloc(mc, 1, &mp)))
return rc;
offset = env->me_psize - olddata.mv_size;
flags |= F_DUPDATA|F_SUBDATA;
dummy.md_root = mp->mp_pgno;
sub_root = mp;
}
if (mp != fp) {
mp->mp_flags = fp_flags | P_DIRTY;
mp->mp_pad = fp->mp_pad;
mp->mp_lower = fp->mp_lower;
mp->mp_upper = fp->mp_upper + offset;
if (fp_flags & P_LEAF2) {
memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
} else {
memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
olddata.mv_size - fp->mp_upper - PAGEBASE);
memcpy((char *)(&mp->mp_ptrs), (char *)(&fp->mp_ptrs), NUMKEYS(fp) * sizeof(mp->mp_ptrs[0]));
for (i=0; i<NUMKEYS(fp); i++)
mp->mp_ptrs[i] += offset;
}
}
rdata = &xdata;
flags |= F_DUPDATA;
do_sub = 1;
if (!insert_key)
mdb_node_del(mc, 0);
goto new_sub;
}
current:
/* LMDB passes F_SUBDATA in 'flags' to write a DB record */
if ((leaf->mn_flags ^ flags) & F_SUBDATA)
return MDB_INCOMPATIBLE;
/* overflow page overwrites need special handling */
if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
MDB_page *omp;
pgno_t pg;
int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
memcpy(&pg, olddata.mv_data, sizeof(pg));
if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
return rc2;
ovpages = omp->mp_pages;
/* Is the ov page large enough? */
if (ovpages >= dpages) {
if (!(omp->mp_flags & P_DIRTY) &&
(level || (env->me_flags & MDB_WRITEMAP)))
{
rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
if (rc)
return rc;
level = 0; /* dirty in this txn or clean */
}
/* Is it dirty? */
if (omp->mp_flags & P_DIRTY) {
/* yes, overwrite it. Note in this case we don't
* bother to try shrinking the page if the new data
* is smaller than the overflow threshold.
*/
if (level > 1) {
/* It is writable only in a parent txn */
size_t sz = (size_t) env->me_psize * ovpages, off;
MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
MDB_ID2 id2;
if (!np)
return ENOMEM;
id2.mid = pg;
id2.mptr = np;
/* Note - this page is already counted in parent's dirty_room */
rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
mdb_cassert(mc, rc2 == 0);
/* Currently we make the page look as with put() in the
* parent txn, in case the user peeks at MDB_RESERVEd
* or unused parts. Some users treat ovpages specially.
*/
if (!(flags & MDB_RESERVE)) {
/* Skip the part where LMDB will put *data.
* Copy end of page, adjusting alignment so
* compiler may copy words instead of bytes.
*/
off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
memcpy((size_t *)((char *)np + off),
(size_t *)((char *)omp + off), sz - off);
sz = PAGEHDRSZ;
}
memcpy(np, omp, sz); /* Copy beginning of page */
omp = np;
}
SETDSZ(leaf, data->mv_size);
if (F_ISSET(flags, MDB_RESERVE))
data->mv_data = METADATA(omp);
else
memcpy(METADATA(omp), data->mv_data, data->mv_size);
return MDB_SUCCESS;
}
}
if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
return rc2;
} else if (data->mv_size == olddata.mv_size) {
/* same size, just replace it. Note that we could
* also reuse this node if the new data is smaller,
* but instead we opt to shrink the node in that case.
*/
if (F_ISSET(flags, MDB_RESERVE))
data->mv_data = olddata.mv_data;
else if (!(mc->mc_flags & C_SUB))
memcpy(olddata.mv_data, data->mv_data, data->mv_size);
else {
memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
goto fix_parent;
}
return MDB_SUCCESS;
}
mdb_node_del(mc, 0);
}
rdata = data;
new_sub:
nflags = flags & NODE_ADD_FLAGS;
nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
if (!insert_key)
nflags |= MDB_SPLIT_REPLACE;
rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
} else {
/* There is room already in this leaf page. */
rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
if (rc == 0) {
/* Adjust other cursors pointing to mp */
MDB_cursor *m2, *m3;
MDB_dbi dbi = mc->mc_dbi;
unsigned i = mc->mc_top;
MDB_page *mp = mc->mc_pg[i];
for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
if (mc->mc_flags & C_SUB)
m3 = &m2->mc_xcursor->mx_cursor;
else
m3 = m2;
if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
m3->mc_ki[i]++;
}
XCURSOR_REFRESH(m3, i, mp);
}
}
}
if (rc == MDB_SUCCESS) {
/* Now store the actual data in the child DB. Note that we're
* storing the user data in the keys field, so there are strict
* size limits on dupdata. The actual data fields of the child
* DB are all zero size.
*/
if (do_sub) {
int xflags, new_dupdata;
mdb_size_t ecount;
put_sub:
xdata.mv_size = 0;
xdata.mv_data = (void *)"";
leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
if (flags & MDB_CURRENT) {
xflags = MDB_CURRENT|MDB_NOSPILL;
} else {
mdb_xcursor_init1(mc, leaf);
xflags = (flags & MDB_NODUPDATA) ?
MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
}
if (sub_root)
mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
new_dupdata = (int)dkey.mv_size;
/* converted, write the original data first */
if (dkey.mv_size) {
rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
if (rc)
goto bad_sub;
/* we've done our job */
dkey.mv_size = 0;
}
if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
/* Adjust other cursors pointing to mp */
MDB_cursor *m2;
MDB_xcursor *mx = mc->mc_xcursor;
unsigned i = mc->mc_top;
MDB_page *mp = mc->mc_pg[i];
for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
if (!(m2->mc_flags & C_INITIALIZED)) continue;
if (m2->mc_pg[i] == mp) {
if (m2->mc_ki[i] == mc->mc_ki[i]) {
mdb_xcursor_init2(m2, mx, new_dupdata);
} else if (!insert_key) {
XCURSOR_REFRESH(m2, i, mp);
}
}
}
}
ecount = mc->mc_xcursor->mx_db.md_entries;
if (flags & MDB_APPENDDUP)
xflags |= MDB_APPEND;
rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
if (flags & F_SUBDATA) {
void *db = NODEDATA(leaf);
memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
}
insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
}
/* Increment count unless we just replaced an existing item. */
if (insert_data)
mc->mc_db->md_entries++;
if (insert_key) {
/* Invalidate txn if we created an empty sub-DB */
if (rc)
goto bad_sub;
/* If we succeeded and the key didn't exist before,
* make sure the cursor is marked valid.
*/
mc->mc_flags |= C_INITIALIZED;
}
if (flags & MDB_MULTIPLE) {
if (!rc) {
mcount++;
/* let caller know how many succeeded, if any */
data[1].mv_size = mcount;
if (mcount < dcount) {
data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
insert_key = insert_data = 0;
goto more;
}
}
}
return rc;
bad_sub:
if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
rc = MDB_PROBLEM;
}
mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
return rc;
}
int
mdb_cursor_del(MDB_cursor *mc, uint64_t flags)
{
MDB_node *leaf;
MDB_page *mp;
int rc;
if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
if (!(mc->mc_flags & C_INITIALIZED))
return EINVAL;
if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
return MDB_NOTFOUND;
if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
return rc;
rc = mdb_cursor_touch(mc);
if (rc)
return rc;
mp = mc->mc_pg[mc->mc_top];
if (IS_LEAF2(mp))
goto del_key;
leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
if (flags & MDB_NODUPDATA) {
/* mdb_cursor_del0() will subtract the final entry */
mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
} else {
if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
}
rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
if (rc)
return rc;
/* If sub-DB still has entries, we're done */
if (mc->mc_xcursor->mx_db.md_entries) {
if (leaf->mn_flags & F_SUBDATA) {
/* update subDB info */
void *db = NODEDATA(leaf);
memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
} else {
MDB_cursor *m2;
/* shrink fake page */
mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
/* fix other sub-DB cursors pointed at fake pages on this page */
for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
if (!(m2->mc_flags & C_INITIALIZED)) continue;
if (m2->mc_pg[mc->mc_top] == mp) {
XCURSOR_REFRESH(m2, mc->mc_top, mp);
}
}
}
mc->mc_db->md_entries--;
return rc;
} else {
mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
}
/* otherwise fall thru and delete the sub-DB */
}
if (leaf->mn_flags & F_SUBDATA) {
/* add all the child DB's pages to the free list */
rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
if (rc)
goto fail;
}
}
/* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
rc = MDB_INCOMPATIBLE;
goto fail;
}
/* add overflow pages to free list */
if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
MDB_page *omp;
pgno_t pg;
memcpy(&pg, NODEDATA(leaf), sizeof(pg));
if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
(rc = mdb_ovpage_free(mc, omp)))
goto fail;
}
del_key:
return mdb_cursor_del0(mc);
fail:
mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
return rc;
}
/** Allocate and initialize new pages for a database.
* Set #MDB_TXN_ERROR on failure.
* @param[in] mc a cursor on the database being added to.
* @param[in] flags flags defining what type of page is being allocated.
* @param[in] num the number of pages to allocate. This is usually 1,
* unless allocating overflow pages for a large record.
* @param[out] mp Address of a page, or NULL on failure.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
{
MDB_page *np;
int rc;
if ((rc = mdb_page_alloc(mc, num, &np)))
return rc;
DPRINTF(("allocated new mpage %" Yu", page size %u",
np->mp_pgno, mc->mc_txn->mt_env->me_psize));
np->mp_flags = flags | P_DIRTY;
np->mp_lower = (PAGEHDRSZ-PAGEBASE);
np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
if (IS_BRANCH(np))
mc->mc_db->md_branch_pages++;
else if (IS_LEAF(np))
mc->mc_db->md_leaf_pages++;
else if (IS_OVERFLOW(np)) {
mc->mc_db->md_overflow_pages += num;
np->mp_pages = num;
}
*mp = np;
return 0;
}
/** Calculate the size of a leaf node.
* The size depends on the environment's page size; if a data item
* is too large it will be put onto an overflow page and the node
* size will only include the key and not the data. Sizes are always
* rounded up to an even number of bytes, to guarantee 2-byte alignment
* of the #MDB_node headers.
* @param[in] env The environment handle.
* @param[in] key The key for the node.
* @param[in] data The data for the node.
* @return The number of bytes needed to store the node.
*/
static size_t
mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
{
size_t sz;
sz = LEAFSIZE(key, data);
if (sz > env->me_nodemax) {
/* put on overflow page */
sz -= data->mv_size - sizeof(pgno_t);
}
return EVEN(sz + sizeof(indx_t));
}
/** Calculate the size of a branch node.
* The size should depend on the environment's page size but since
* we currently don't support spilling large keys onto overflow
* pages, it's simply the size of the #MDB_node header plus the
* size of the key. Sizes are always rounded up to an even number
* of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
* @param[in] env The environment handle.
* @param[in] key The key for the node.
* @return The number of bytes needed to store the node.
*/
static size_t
mdb_branch_size(MDB_env *env, MDB_val *key)
{
size_t sz;
sz = INDXSIZE(key);
if (sz > env->me_nodemax) {
/* put on overflow page */
/* not implemented */
/* sz -= key->size - sizeof(pgno_t); */
}
return sz + sizeof(indx_t);
}
/** Add a node to the page pointed to by the cursor.
* Set #MDB_TXN_ERROR on failure.
* @param[in] mc The cursor for this operation.
* @param[in] indx The index on the page where the new node should be added.
* @param[in] key The key for the new node.
* @param[in] data The data for the new node, if any.
* @param[in] pgno The page number, if adding a branch node.
* @param[in] flags Flags for the node.
* @return 0 on success, non-zero on failure. Possible errors are:
* <ul>
* <li>ENOMEM - failed to allocate overflow pages for the node.
* <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
* should never happen since all callers already calculate the
* page's free space before calling this function.
* </ul>
*/
static int
mdb_node_add(MDB_cursor *mc, indx_t indx,
MDB_val *key, MDB_val *data, pgno_t pgno, uint64_t flags)
{
uint64_t i;
size_t node_size = NODESIZE;
ssize_t room;
indx_t ofs;
MDB_node *node;
MDB_page *mp = mc->mc_pg[mc->mc_top];
MDB_page *ofp = NULL; /* overflow page */
void *ndata;
DKBUF;
mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
DPRINTF(("add to %s %spage %" Yu " index %i, data size %" Z "u key size %" Z "u [%s]",
IS_LEAF(mp) ? "leaf" : "branch",
IS_SUBP(mp) ? "sub-" : "",
mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
key ? key->mv_size : 0, key ? DKEY(key) : "null"));
if (IS_LEAF2(mp)) {
/* Move higher keys up one slot. */
int ksize = mc->mc_db->md_pad, dif;
char *ptr = LEAF2KEY(mp, indx, ksize);
dif = NUMKEYS(mp) - indx;
if (dif > 0)
memmove(ptr+ksize, ptr, dif*ksize);
/* insert new key */
memcpy(ptr, key->mv_data, ksize);
/* Just using these for counting */
mp->mp_lower += sizeof(indx_t);
mp->mp_upper -= ksize - sizeof(indx_t);
return MDB_SUCCESS;
}
room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
if (key != NULL)
node_size += key->mv_size;
if (IS_LEAF(mp)) {
mdb_cassert(mc, key && data);
if (F_ISSET(flags, F_BIGDATA)) {
/* Data already on overflow page. */
node_size += sizeof(pgno_t);
} else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
int rc;
/* Put data on overflow page. */
DPRINTF(("data size is %" Z "u, node would be %" Z "u, put data on overflow page",
data->mv_size, node_size+data->mv_size));
node_size = EVEN(node_size + sizeof(pgno_t));
if ((ssize_t)node_size > room)
goto full;
if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
return rc;
DPRINTF(("allocated overflow page %" Yu, ofp->mp_pgno));
flags |= F_BIGDATA;
goto update;
} else {
node_size += data->mv_size;
}
}
node_size = EVEN(node_size);
if ((ssize_t)node_size > room)
goto full;
update:
/* Move higher pointers up one slot. */
for (i = NUMKEYS(mp); i > indx; i--)
mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
/* Adjust free space offsets. */
ofs = mp->mp_upper - node_size;
mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
mp->mp_ptrs[indx] = ofs;
mp->mp_upper = ofs;
mp->mp_lower += sizeof(indx_t);
/* Write the node data. */
node = NODEPTR(mp, indx);
node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
node->mn_flags = flags;
if (IS_LEAF(mp))
SETDSZ(node,data->mv_size);
else
SETPGNO(node,pgno);
if (key)
memcpy(NODEKEY(node), key->mv_data, key->mv_size);
if (IS_LEAF(mp)) {
ndata = NODEDATA(node);
if (ofp == NULL) {
if (F_ISSET(flags, F_BIGDATA))
memcpy(ndata, data->mv_data, sizeof(pgno_t));
else if (F_ISSET(flags, MDB_RESERVE))
data->mv_data = ndata;
else
memcpy(ndata, data->mv_data, data->mv_size);
} else {
memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
ndata = METADATA(ofp);
if (F_ISSET(flags, MDB_RESERVE))
data->mv_data = ndata;
else
memcpy(ndata, data->mv_data, data->mv_size);
}
}
return MDB_SUCCESS;
full:
DPRINTF(("not enough room in page %" Yu", got %u ptrs",
mdb_dbg_pgno(mp), NUMKEYS(mp)));
DPRINTF(("upper-lower = %u - %u = %" Z "d", mp->mp_upper,mp->mp_lower,room));
DPRINTF(("node size = %" Z "u", node_size));
mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
return MDB_PAGE_FULL;
}
/** Delete the specified node from a page.
* @param[in] mc Cursor pointing to the node to delete.
* @param[in] ksize The size of a node. Only used if the page is
* part of a #MDB_DUPFIXED database.
*/
static void
mdb_node_del(MDB_cursor *mc, int ksize)
{
MDB_page *mp = mc->mc_pg[mc->mc_top];
indx_t indx = mc->mc_ki[mc->mc_top];
uint64_t sz;
indx_t i, j, numkeys, ptr;
MDB_node *node;
char *base;
DPRINTF(("delete node %u on %s page %" Yu, indx,
IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
numkeys = NUMKEYS(mp);
mdb_cassert(mc, indx < numkeys);
if (IS_LEAF2(mp)) {
int x = numkeys - 1 - indx;
base = LEAF2KEY(mp, indx, ksize);
if (x)
memmove(base, base + ksize, x * ksize);
mp->mp_lower -= sizeof(indx_t);
mp->mp_upper += ksize - sizeof(indx_t);
return;
}
node = NODEPTR(mp, indx);
sz = NODESIZE + node->mn_ksize;
if (IS_LEAF(mp)) {
if (F_ISSET(node->mn_flags, F_BIGDATA))
sz += sizeof(pgno_t);
else
sz += NODEDSZ(node);
}
sz = EVEN(sz);
ptr = mp->mp_ptrs[indx];
for (i = j = 0; i < numkeys; i++) {
if (i != indx) {
mp->mp_ptrs[j] = mp->mp_ptrs[i];
if (mp->mp_ptrs[i] < ptr)
mp->mp_ptrs[j] += sz;
j++;
}
}
base = (char *)mp + mp->mp_upper + PAGEBASE;
memmove(base + sz, base, ptr - mp->mp_upper);
mp->mp_lower -= sizeof(indx_t);
mp->mp_upper += sz;
}
/** Compact the main page after deleting a node on a subpage.
* @param[in] mp The main page to operate on.
* @param[in] indx The index of the subpage on the main page.
*/
static void
mdb_node_shrink(MDB_page *mp, indx_t indx)
{
MDB_node *node;
MDB_page *sp, *xp;
char *base;
indx_t delta, nsize, len, ptr;
int i;
node = NODEPTR(mp, indx);
sp = (MDB_page *)NODEDATA(node);
delta = SIZELEFT(sp);
nsize = NODEDSZ(node) - delta;
/* Prepare to shift upward, set len = length(subpage part to shift) */
if (IS_LEAF2(sp)) {
len = nsize;
if (nsize & 1)
return; /* do not make the node uneven-sized */
} else {
xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
for (i = NUMKEYS(sp); --i >= 0; )
xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
len = PAGEHDRSZ;
}
sp->mp_upper = sp->mp_lower;
COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
SETDSZ(node, nsize);
/* Shift <lower nodes...initial part of subpage> upward */
base = (char *)mp + mp->mp_upper + PAGEBASE;
memmove(base + delta, base, (char *)sp + len - base);
ptr = mp->mp_ptrs[indx];
for (i = NUMKEYS(mp); --i >= 0; ) {
if (mp->mp_ptrs[i] <= ptr)
mp->mp_ptrs[i] += delta;
}
mp->mp_upper += delta;
}
/** Initial setup of a sorted-dups cursor.
* Sorted duplicates are implemented as a sub-database for the given key.
* The duplicate data items are actually keys of the sub-database.
* Operations on the duplicate data items are performed using a sub-cursor
* initialized when the sub-database is first accessed. This function does
* the preliminary setup of the sub-cursor, filling in the fields that
* depend only on the parent DB.
* @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
*/
static void
mdb_xcursor_init0(MDB_cursor *mc)
{
MDB_xcursor *mx = mc->mc_xcursor;
mx->mx_cursor.mc_xcursor = NULL;
mx->mx_cursor.mc_txn = mc->mc_txn;
mx->mx_cursor.mc_db = &mx->mx_db;
mx->mx_cursor.mc_dbx = &mx->mx_dbx;
mx->mx_cursor.mc_dbi = mc->mc_dbi;
mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
mx->mx_cursor.mc_snum = 0;
mx->mx_cursor.mc_top = 0;
MC_SET_OVPG(&mx->mx_cursor, NULL);
mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
mx->mx_dbx.md_name.mv_size = 0;
mx->mx_dbx.md_name.mv_data = NULL;
mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
mx->mx_dbx.md_dcmp = NULL;
mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
}
/** Final setup of a sorted-dups cursor.
* Sets up the fields that depend on the data from the main cursor.
* @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
* @param[in] node The data containing the #MDB_db record for the
* sorted-dup database.
*/
static void
mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
{
MDB_xcursor *mx = mc->mc_xcursor;
mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
if (node->mn_flags & F_SUBDATA) {
memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
mx->mx_cursor.mc_pg[0] = 0;
mx->mx_cursor.mc_snum = 0;
mx->mx_cursor.mc_top = 0;
} else {
MDB_page *fp = NODEDATA(node);
mx->mx_db.md_pad = 0;
mx->mx_db.md_flags = 0;
mx->mx_db.md_depth = 1;
mx->mx_db.md_branch_pages = 0;
mx->mx_db.md_leaf_pages = 1;
mx->mx_db.md_overflow_pages = 0;
mx->mx_db.md_entries = NUMKEYS(fp);
COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
mx->mx_cursor.mc_snum = 1;
mx->mx_cursor.mc_top = 0;
mx->mx_cursor.mc_flags |= C_INITIALIZED;
mx->mx_cursor.mc_pg[0] = fp;
mx->mx_cursor.mc_ki[0] = 0;
if (mc->mc_db->md_flags & MDB_DUPFIXED) {
mx->mx_db.md_flags = MDB_DUPFIXED;
mx->mx_db.md_pad = fp->mp_pad;
if (mc->mc_db->md_flags & MDB_INTEGERDUP)
mx->mx_db.md_flags |= MDB_INTEGERKEY;
}
}
DPRINTF(("Sub-db -%u root page %" Yu, mx->mx_cursor.mc_dbi,
mx->mx_db.md_root));
mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
mx->mx_dbx.md_cmp = mdb_cmp_clong;
}
/** Fixup a sorted-dups cursor due to underlying update.
* Sets up some fields that depend on the data from the main cursor.
* Almost the same as init1, but skips initialization steps if the
* xcursor had already been used.
* @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
* @param[in] src_mx The xcursor of an up-to-date cursor.
* @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
*/
static void
mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
{
MDB_xcursor *mx = mc->mc_xcursor;
if (new_dupdata) {
mx->mx_cursor.mc_snum = 1;
mx->mx_cursor.mc_top = 0;
mx->mx_cursor.mc_flags |= C_INITIALIZED;
mx->mx_cursor.mc_ki[0] = 0;
mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
#if UINT_MAX < MDB_SIZE_MAX /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
#endif
} else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
return;
}
mx->mx_db = src_mx->mx_db;
mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
DPRINTF(("Sub-db -%u root page %" Yu, mx->mx_cursor.mc_dbi,
mx->mx_db.md_root));
}
/** Initialize a cursor for a given transaction and database. */
static void
mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
{
mc->mc_next = NULL;
mc->mc_backup = NULL;
mc->mc_dbi = dbi;
mc->mc_txn = txn;
mc->mc_db = &txn->mt_dbs[dbi];
mc->mc_dbx = &txn->mt_dbxs[dbi];
mc->mc_dbflag = &txn->mt_dbflags[dbi];
mc->mc_snum = 0;
mc->mc_top = 0;
mc->mc_pg[0] = 0;
mc->mc_ki[0] = 0;
MC_SET_OVPG(mc, NULL);
mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
mdb_tassert(txn, mx != NULL);
mc->mc_xcursor = mx;
mdb_xcursor_init0(mc);
} else {
mc->mc_xcursor = NULL;
}
if (*mc->mc_dbflag & DB_STALE) {
mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
}
}
int
mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
{
MDB_cursor *mc;
size_t size = sizeof(MDB_cursor);
if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
return EINVAL;
if (txn->mt_flags & MDB_TXN_BLOCKED)
return MDB_BAD_TXN;
if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
return EINVAL;
if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
size += sizeof(MDB_xcursor);
if ( (mc = ((MDB_cursor *) malloc(size)) ) != NULL) {
mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
if (txn->mt_cursors) {
mc->mc_next = txn->mt_cursors[dbi];
txn->mt_cursors[dbi] = mc;
mc->mc_flags |= C_UNTRACK;
}
} else {
return ENOMEM;
}
*ret = mc;
return MDB_SUCCESS;
}
int
mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
{
if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
return EINVAL;
if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
return EINVAL;
if (txn->mt_flags & MDB_TXN_BLOCKED)
return MDB_BAD_TXN;
mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
return MDB_SUCCESS;
}
/* Return the count of duplicate data items for the current key */
int
mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
{
MDB_node *leaf;
if (mc == NULL || countp == NULL)
return EINVAL;
if (mc->mc_xcursor == NULL)
return MDB_INCOMPATIBLE;
if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
return MDB_BAD_TXN;
if (!(mc->mc_flags & C_INITIALIZED))
return EINVAL;
if (!mc->mc_snum)
return MDB_NOTFOUND;
if (mc->mc_flags & C_EOF) {
if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
return MDB_NOTFOUND;
mc->mc_flags ^= C_EOF;
}
leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
*countp = 1;
} else {
if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
return EINVAL;
*countp = mc->mc_xcursor->mx_db.md_entries;
}
return MDB_SUCCESS;
}
void
mdb_cursor_close(MDB_cursor *mc)
{
if (mc) {
MDB_CURSOR_UNREF(mc, 0);
}
if (mc && !mc->mc_backup) {
/* Remove from txn, if tracked.
* A read-only txn (!C_UNTRACK) may have been freed already,
* so do not peek inside it. Only write txns track cursors.
*/
if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
while (*prev && *prev != mc) prev = &(*prev)->mc_next;
if (*prev == mc)
*prev = mc->mc_next;
}
free(mc);
}
}
MDB_txn *
mdb_cursor_txn(MDB_cursor *mc)
{
if (!mc) return NULL;
return mc->mc_txn;
}
MDB_dbi
mdb_cursor_dbi(MDB_cursor *mc)
{
return mc->mc_dbi;
}
/** Replace the key for a branch node with a new key.
* Set #MDB_TXN_ERROR on failure.
* @param[in] mc Cursor pointing to the node to operate on.
* @param[in] key The new key to use.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_update_key(MDB_cursor *mc, MDB_val *key)
{
MDB_page *mp;
MDB_node *node;
char *base;
size_t len;
int delta, ksize, oksize;
indx_t ptr, i, numkeys, indx;
DKBUF;
indx = mc->mc_ki[mc->mc_top];
mp = mc->mc_pg[mc->mc_top];
node = NODEPTR(mp, indx);
ptr = mp->mp_ptrs[indx];
#if MDB_DEBUG
{
MDB_val k2;
char kbuf2[DKBUF_MAXKEYSIZE*2+1];
k2.mv_data = NODEKEY(node);
k2.mv_size = node->mn_ksize;
DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %" Yu,
indx, ptr,
mdb_dkey(&k2, kbuf2),
DKEY(key),
mp->mp_pgno));
}
#endif
/* Sizes must be 2-byte aligned. */
ksize = EVEN(key->mv_size);
oksize = EVEN(node->mn_ksize);
delta = ksize - oksize;
/* Shift node contents if EVEN(key length) changed. */
if (delta) {
if (delta > 0 && SIZELEFT(mp) < delta) {
pgno_t pgno;
/* not enough space left, do a delete and split */
DPRINTF(("Not enough room, delta = %d, splitting...", delta));
pgno = NODEPGNO(node);
mdb_node_del(mc, 0);
return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
}
numkeys = NUMKEYS(mp);
for (i = 0; i < numkeys; i++) {
if (mp->mp_ptrs[i] <= ptr)
mp->mp_ptrs[i] -= delta;
}
base = (char *)mp + mp->mp_upper + PAGEBASE;
len = ptr - mp->mp_upper + NODESIZE;
memmove(base - delta, base, len);
mp->mp_upper -= delta;
node = NODEPTR(mp, indx);
}
/* But even if no shift was needed, update ksize */
if (node->mn_ksize != key->mv_size)
node->mn_ksize = key->mv_size;
if (key->mv_size)
memcpy(NODEKEY(node), key->mv_data, key->mv_size);
return MDB_SUCCESS;
}
static void
mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
/** Perform \b act while tracking temporary cursor \b mn */
#define WITH_CURSOR_TRACKING(mn, act) do { \
MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
if ((mn).mc_flags & C_SUB) { \
dummy.mc_flags = C_INITIALIZED; \
dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
tracked = &dummy; \
} else { \
tracked = &(mn); \
} \
tracked->mc_next = *tp; \
*tp = tracked; \
{ act; } \
*tp = tracked->mc_next; \
} while (0)
/** Move a node from csrc to cdst.
*/
static int
mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
{
MDB_node *srcnode;
MDB_val key, data;
pgno_t srcpg;
MDB_cursor mn;
int rc;
uint16_t flags;
DKBUF;
/* Mark src and dst as dirty. */
if ((rc = mdb_page_touch(csrc)) ||
(rc = mdb_page_touch(cdst)))
return rc;
if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
key.mv_size = csrc->mc_db->md_pad;
key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
data.mv_size = 0;
data.mv_data = NULL;
srcpg = 0;
flags = 0;
} else {
srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
mdb_cassert(csrc, !((size_t)srcnode & 1));
srcpg = NODEPGNO(srcnode);
flags = srcnode->mn_flags;
if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
uint64_t snum = csrc->mc_snum;
MDB_node *s2;
/* must find the lowest key below src */
rc = mdb_page_search_lowest(csrc);
if (rc)
return rc;
if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
key.mv_size = csrc->mc_db->md_pad;
key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
} else {
s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
key.mv_size = NODEKSZ(s2);
key.mv_data = NODEKEY(s2);
}
csrc->mc_snum = snum--;
csrc->mc_top = snum;
} else {
key.mv_size = NODEKSZ(srcnode);
key.mv_data = NODEKEY(srcnode);
}
data.mv_size = NODEDSZ(srcnode);
data.mv_data = NODEDATA(srcnode);
}
mn.mc_xcursor = NULL;
if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
uint64_t snum = cdst->mc_snum;
MDB_node *s2;
MDB_val bkey;
/* must find the lowest key below dst */
mdb_cursor_copy(cdst, &mn);
rc = mdb_page_search_lowest(&mn);
if (rc)
return rc;
if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
bkey.mv_size = mn.mc_db->md_pad;
bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
} else {
s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
bkey.mv_size = NODEKSZ(s2);
bkey.mv_data = NODEKEY(s2);
}
mn.mc_snum = snum--;
mn.mc_top = snum;
mn.mc_ki[snum] = 0;
rc = mdb_update_key(&mn, &bkey);
if (rc)
return rc;
}
DPRINTF(("moving %s node %u [%s] on page %" Yu" to node %u on page %" Yu,
IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
csrc->mc_ki[csrc->mc_top],
DKEY(&key),
csrc->mc_pg[csrc->mc_top]->mp_pgno,
cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
/* Add the node to the destination page.
*/
rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
if (rc != MDB_SUCCESS)
return rc;
/* Delete the node from the source page.
*/
mdb_node_del(csrc, key.mv_size);
{
/* Adjust other cursors pointing to mp */
MDB_cursor *m2, *m3;
MDB_dbi dbi = csrc->mc_dbi;
MDB_page *mpd, *mps;
mps = csrc->mc_pg[csrc->mc_top];
/* If we're adding on the left, bump others up */
if (fromleft) {
mpd = cdst->mc_pg[csrc->mc_top];
for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
if (csrc->mc_flags & C_SUB)
m3 = &m2->mc_xcursor->mx_cursor;
else
m3 = m2;
if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
continue;
if (m3 != cdst &&
m3->mc_pg[csrc->mc_top] == mpd &&
m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
m3->mc_ki[csrc->mc_top]++;
}
if (m3 !=csrc &&
m3->mc_pg[csrc->mc_top] == mps &&
m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
m3->mc_ki[csrc->mc_top-1]++;
}
if (IS_LEAF(mps))
XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
}
} else
/* Adding on the right, bump others down */
{
for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
if (csrc->mc_flags & C_SUB)
m3 = &m2->mc_xcursor->mx_cursor;
else
m3 = m2;
if (m3 == csrc) continue;
if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
continue;
if (m3->mc_pg[csrc->mc_top] == mps) {
if (!m3->mc_ki[csrc->mc_top]) {
m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
m3->mc_ki[csrc->mc_top-1]--;
} else {
m3->mc_ki[csrc->mc_top]--;
}
if (IS_LEAF(mps))
XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
}
}
}
}
/* Update the parent separators.
*/
if (csrc->mc_ki[csrc->mc_top] == 0) {
if (csrc->mc_ki[csrc->mc_top-1] != 0) {
if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
} else {
srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
key.mv_size = NODEKSZ(srcnode);
key.mv_data = NODEKEY(srcnode);
}
DPRINTF(("update separator for source page %" Yu" to [%s]",
csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
mdb_cursor_copy(csrc, &mn);
mn.mc_snum--;
mn.mc_top--;
/* We want mdb_rebalance to find mn when doing fixups */
WITH_CURSOR_TRACKING(mn,
rc = mdb_update_key(&mn, &key));
if (rc)
return rc;
}
if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
MDB_val nullkey;
indx_t ix = csrc->mc_ki[csrc->mc_top];
nullkey.mv_size = 0;
csrc->mc_ki[csrc->mc_top] = 0;
rc = mdb_update_key(csrc, &nullkey);
csrc->mc_ki[csrc->mc_top] = ix;
mdb_cassert(csrc, rc == MDB_SUCCESS);
}
}
if (cdst->mc_ki[cdst->mc_top] == 0) {
if (cdst->mc_ki[cdst->mc_top-1] != 0) {
if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
} else {
srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
key.mv_size = NODEKSZ(srcnode);
key.mv_data = NODEKEY(srcnode);
}
DPRINTF(("update separator for destination page %" Yu" to [%s]",
cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
mdb_cursor_copy(cdst, &mn);
mn.mc_snum--;
mn.mc_top--;
/* We want mdb_rebalance to find mn when doing fixups */
WITH_CURSOR_TRACKING(mn,
rc = mdb_update_key(&mn, &key));
if (rc)
return rc;
}
if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
MDB_val nullkey;
indx_t ix = cdst->mc_ki[cdst->mc_top];
nullkey.mv_size = 0;
cdst->mc_ki[cdst->mc_top] = 0;
rc = mdb_update_key(cdst, &nullkey);
cdst->mc_ki[cdst->mc_top] = ix;
mdb_cassert(cdst, rc == MDB_SUCCESS);
}
}
return MDB_SUCCESS;
}
/** Merge one page into another.
* The nodes from the page pointed to by \b csrc will
* be copied to the page pointed to by \b cdst and then
* the \b csrc page will be freed.
* @param[in] csrc Cursor pointing to the source page.
* @param[in] cdst Cursor pointing to the destination page.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
{
MDB_page *psrc, *pdst;
MDB_node *srcnode;
MDB_val key, data;
unsigned nkeys;
int rc;
indx_t i, j;
psrc = csrc->mc_pg[csrc->mc_top];
pdst = cdst->mc_pg[cdst->mc_top];
DPRINTF(("merging page %" Yu" into %" Yu, psrc->mp_pgno, pdst->mp_pgno));
mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
mdb_cassert(csrc, cdst->mc_snum > 1);
/* Mark dst as dirty. */
if ((rc = mdb_page_touch(cdst)))
return rc;
/* get dst page again now that we've touched it. */
pdst = cdst->mc_pg[cdst->mc_top];
/* Move all nodes from src to dst.
*/
j = nkeys = NUMKEYS(pdst);
if (IS_LEAF2(psrc)) {
key.mv_size = csrc->mc_db->md_pad;
key.mv_data = METADATA(psrc);
for (i = 0; i < NUMKEYS(psrc); i++, j++) {
rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
if (rc != MDB_SUCCESS)
return rc;
key.mv_data = (char *)key.mv_data + key.mv_size;
}
} else {
for (i = 0; i < NUMKEYS(psrc); i++, j++) {
srcnode = NODEPTR(psrc, i);
if (i == 0 && IS_BRANCH(psrc)) {
MDB_cursor mn;
MDB_node *s2;
mdb_cursor_copy(csrc, &mn);
mn.mc_xcursor = NULL;
/* must find the lowest key below src */
rc = mdb_page_search_lowest(&mn);
if (rc)
return rc;
if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
key.mv_size = mn.mc_db->md_pad;
key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
} else {
s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
key.mv_size = NODEKSZ(s2);
key.mv_data = NODEKEY(s2);
}
} else {
key.mv_size = srcnode->mn_ksize;
key.mv_data = NODEKEY(srcnode);
}
data.mv_size = NODEDSZ(srcnode);
data.mv_data = NODEDATA(srcnode);
rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
if (rc != MDB_SUCCESS)
return rc;
}
}
DPRINTF(("dst page %" Yu" now has %u keys (%.1f%% filled)",
pdst->mp_pgno, NUMKEYS(pdst),
(float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
/* Unlink the src page from parent and add to free list.
*/
csrc->mc_top--;
mdb_node_del(csrc, 0);
if (csrc->mc_ki[csrc->mc_top] == 0) {
key.mv_size = 0;
rc = mdb_update_key(csrc, &key);
if (rc) {
csrc->mc_top++;
return rc;
}
}
csrc->mc_top++;
psrc = csrc->mc_pg[csrc->mc_top];
/* If not operating on FreeDB, allow this page to be reused
* in this txn. Otherwise just add to free list.
*/
rc = mdb_page_loose(csrc, psrc);
if (rc)
return rc;
if (IS_LEAF(psrc))
csrc->mc_db->md_leaf_pages--;
else
csrc->mc_db->md_branch_pages--;
{
/* Adjust other cursors pointing to mp */
MDB_cursor *m2, *m3;
MDB_dbi dbi = csrc->mc_dbi;
uint64_t top = csrc->mc_top;
for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
if (csrc->mc_flags & C_SUB)
m3 = &m2->mc_xcursor->mx_cursor;
else
m3 = m2;
if (m3 == csrc) continue;
if (m3->mc_snum < csrc->mc_snum) continue;
if (m3->mc_pg[top] == psrc) {
m3->mc_pg[top] = pdst;
m3->mc_ki[top] += nkeys;
m3->mc_ki[top-1] = cdst->mc_ki[top-1];
} else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
m3->mc_ki[top-1]--;
}
if (IS_LEAF(psrc))
XCURSOR_REFRESH(m3, top, m3->mc_pg[top]);
}
}
{
uint64_t snum = cdst->mc_snum;
uint16_t depth = cdst->mc_db->md_depth;
mdb_cursor_pop(cdst);
rc = mdb_rebalance(cdst);
/* Did the tree height change? */
if (depth != cdst->mc_db->md_depth)
snum += cdst->mc_db->md_depth - depth;
cdst->mc_snum = snum;
cdst->mc_top = snum-1;
}
return rc;
}
/** Copy the contents of a cursor.
* @param[in] csrc The cursor to copy from.
* @param[out] cdst The cursor to copy to.
*/
static void
mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
{
uint64_t i;
cdst->mc_txn = csrc->mc_txn;
cdst->mc_dbi = csrc->mc_dbi;
cdst->mc_db = csrc->mc_db;
cdst->mc_dbx = csrc->mc_dbx;
cdst->mc_snum = csrc->mc_snum;
cdst->mc_top = csrc->mc_top;
cdst->mc_flags = csrc->mc_flags;
MC_SET_OVPG(cdst, MC_OVPG(csrc));
for (i=0; i<csrc->mc_snum; i++) {
cdst->mc_pg[i] = csrc->mc_pg[i];
cdst->mc_ki[i] = csrc->mc_ki[i];
}
}
/** Rebalance the tree after a delete operation.
* @param[in] mc Cursor pointing to the page where rebalancing
* should begin.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_rebalance(MDB_cursor *mc)
{
MDB_node *node;
int rc, fromleft;
uint64_t ptop, minkeys, thresh;
MDB_cursor mn;
indx_t oldki;
if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
minkeys = 2;
thresh = 1;
} else {
minkeys = 1;
thresh = FILL_THRESHOLD;
}
DPRINTF(("rebalancing %s page %" Yu" (has %u keys, %.1f%% full)",
IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
(float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
DPRINTF(("no need to rebalance page %" Yu", above fill threshold",
mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
return MDB_SUCCESS;
}
if (mc->mc_snum < 2) {
MDB_page *mp = mc->mc_pg[0];
if (IS_SUBP(mp)) {
DPUTS("Can't rebalance a subpage, ignoring");
return MDB_SUCCESS;
}
if (NUMKEYS(mp) == 0) {
DPUTS("tree is completely empty");
mc->mc_db->md_root = P_INVALID;
mc->mc_db->md_depth = 0;
mc->mc_db->md_leaf_pages = 0;
rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
if (rc)
return rc;
/* Adjust cursors pointing to mp */
mc->mc_snum = 0;
mc->mc_top = 0;
mc->mc_flags &= ~C_INITIALIZED;
{
MDB_cursor *m2, *m3;
MDB_dbi dbi = mc->mc_dbi;
for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
if (mc->mc_flags & C_SUB)
m3 = &m2->mc_xcursor->mx_cursor;
else
m3 = m2;
if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
continue;
if (m3->mc_pg[0] == mp) {
m3->mc_snum = 0;
m3->mc_top = 0;
m3->mc_flags &= ~C_INITIALIZED;
}
}
}
} else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
int i;
DPUTS("collapsing root page!");
rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
if (rc)
return rc;
mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
if (rc)
return rc;
mc->mc_db->md_depth--;
mc->mc_db->md_branch_pages--;
mc->mc_ki[0] = mc->mc_ki[1];
for (i = 1; i<mc->mc_db->md_depth; i++) {
mc->mc_pg[i] = mc->mc_pg[i+1];
mc->mc_ki[i] = mc->mc_ki[i+1];
}
{
/* Adjust other cursors pointing to mp */
MDB_cursor *m2, *m3;
MDB_dbi dbi = mc->mc_dbi;
for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
if (mc->mc_flags & C_SUB)
m3 = &m2->mc_xcursor->mx_cursor;
else
m3 = m2;
if (m3 == mc) continue;
if (!(m3->mc_flags & C_INITIALIZED))
continue;
if (m3->mc_pg[0] == mp) {
for (i=0; i<mc->mc_db->md_depth; i++) {
m3->mc_pg[i] = m3->mc_pg[i+1];
m3->mc_ki[i] = m3->mc_ki[i+1];
}
m3->mc_snum--;
m3->mc_top--;
}
}
}
} else
DPUTS("root page doesn't need rebalancing");
return MDB_SUCCESS;
}
/* The parent (branch page) must have at least 2 pointers,
* otherwise the tree is invalid.
*/
ptop = mc->mc_top-1;
mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
/* Leaf page fill factor is below the threshold.
* Try to move keys from left or right neighbor, or
* merge with a neighbor page.
*/
/* Find neighbors.
*/
mdb_cursor_copy(mc, &mn);
mn.mc_xcursor = NULL;
oldki = mc->mc_ki[mc->mc_top];
if (mc->mc_ki[ptop] == 0) {
/* We're the leftmost leaf in our parent.
*/
DPUTS("reading right neighbor");
mn.mc_ki[ptop]++;
node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
if (rc)
return rc;
mn.mc_ki[mn.mc_top] = 0;
mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
fromleft = 0;
} else {
/* There is at least one neighbor to the left.
*/
DPUTS("reading left neighbor");
mn.mc_ki[ptop]--;
node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
if (rc)
return rc;
mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
mc->mc_ki[mc->mc_top] = 0;
fromleft = 1;
}
DPRINTF(("found neighbor page %" Yu" (%u keys, %.1f%% full)",
mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
(float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
/* If the neighbor page is above threshold and has enough keys,
* move one key from it. Otherwise we should try to merge them.
* (A branch page must never have less than 2 keys.)
*/
if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
rc = mdb_node_move(&mn, mc, fromleft);
if (fromleft) {
/* if we inserted on left, bump position up */
oldki++;
}
} else {
if (!fromleft) {
rc = mdb_page_merge(&mn, mc);
} else {
oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
/* We want mdb_rebalance to find mn when doing fixups */
WITH_CURSOR_TRACKING(mn,
rc = mdb_page_merge(mc, &mn));
mdb_cursor_copy(&mn, mc);
}
mc->mc_flags &= ~C_EOF;
}
mc->mc_ki[mc->mc_top] = oldki;
return rc;
}
/** Complete a delete operation started by #mdb_cursor_del(). */
static int
mdb_cursor_del0(MDB_cursor *mc)
{
int rc;
MDB_page *mp;
indx_t ki;
uint64_t nkeys;
MDB_cursor *m2, *m3;
MDB_dbi dbi = mc->mc_dbi;
ki = mc->mc_ki[mc->mc_top];
mp = mc->mc_pg[mc->mc_top];
mdb_node_del(mc, mc->mc_db->md_pad);
mc->mc_db->md_entries--;
{
/* Adjust other cursors pointing to mp */
for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
continue;
if (m3 == mc || m3->mc_snum < mc->mc_snum)
continue;
if (m3->mc_pg[mc->mc_top] == mp) {
if (m3->mc_ki[mc->mc_top] == ki) {
m3->mc_flags |= C_DEL;
if (mc->mc_db->md_flags & MDB_DUPSORT) {
/* Sub-cursor referred into dataset which is gone */
m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
}
continue;
} else if (m3->mc_ki[mc->mc_top] > ki) {
m3->mc_ki[mc->mc_top]--;
}
XCURSOR_REFRESH(m3, mc->mc_top, mp);
}
}
}
rc = mdb_rebalance(mc);
if (rc == MDB_SUCCESS) {
/* DB is totally empty now, just bail out.
* Other cursors adjustments were already done
* by mdb_rebalance and aren't needed here.
*/
if (!mc->mc_snum)
return rc;
mp = mc->mc_pg[mc->mc_top];
nkeys = NUMKEYS(mp);
/* Adjust other cursors pointing to mp */
for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
continue;
if (m3->mc_snum < mc->mc_snum)
continue;
if (m3->mc_pg[mc->mc_top] == mp) {
/* if m3 points past last node in page, find next sibling */
if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
if (m3->mc_ki[mc->mc_top] >= nkeys) {
rc = mdb_cursor_sibling(m3, 1);
if (rc == MDB_NOTFOUND) {
m3->mc_flags |= C_EOF;
rc = MDB_SUCCESS;
continue;
}
}
if (mc->mc_db->md_flags & MDB_DUPSORT) {
MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
/* If this node has dupdata, it may need to be reinited
* because its data has moved.
* If the xcursor was not initd it must be reinited.
* Else if node points to a subDB, nothing is needed.
* Else (xcursor was initd, not a subDB) needs mc_pg[0] reset.
*/
if (node->mn_flags & F_DUPDATA) {
if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
if (!(node->mn_flags & F_SUBDATA))
m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
} else {
mdb_xcursor_init1(m3, node);
m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
}
}
}
}
}
}
mc->mc_flags |= C_DEL;
}
if (rc)
mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
return rc;
}
int
mdb_del(MDB_txn *txn, MDB_dbi dbi,
MDB_val *key, MDB_val *data)
{
if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
return EINVAL;
if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
/* must ignore any data */
data = NULL;
}
return mdb_del0(txn, dbi, key, data, 0);
}
static int
mdb_del0(MDB_txn *txn, MDB_dbi dbi,
MDB_val *key, MDB_val *data, unsigned flags)
{
MDB_cursor mc;
MDB_xcursor mx;
MDB_cursor_op op;
MDB_val rdata, *xdata;
int rc, exact = 0;
DKBUF;
DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
mdb_cursor_init(&mc, txn, dbi, &mx);
if (data) {
op = MDB_GET_BOTH;
rdata = *data;
xdata = &rdata;
} else {
op = MDB_SET;
xdata = NULL;
flags |= MDB_NODUPDATA;
}
rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
if (rc == 0) {
/* let mdb_page_split know about this cursor if needed:
* delete will trigger a rebalance; if it needs to move
* a node from one page to another, it will have to
* update the parent's separator key(s). If the new sepkey
* is larger than the current one, the parent page may
* run out of space, triggering a split. We need this
* cursor to be consistent until the end of the rebalance.
*/
mc.mc_next = txn->mt_cursors[dbi];
txn->mt_cursors[dbi] = &mc;
rc = mdb_cursor_del(&mc, flags);
txn->mt_cursors[dbi] = mc.mc_next;
}
return rc;
}
/** Split a page and insert a new node.
* Set #MDB_TXN_ERROR on failure.
* @param[in,out] mc Cursor pointing to the page and desired insertion index.
* The cursor will be updated to point to the actual page and index where
* the node got inserted after the split.
* @param[in] newkey The key for the newly inserted node.
* @param[in] newdata The data for the newly inserted node.
* @param[in] newpgno The page number, if the new node is a branch node.
* @param[in] nflags The #NODE_ADD_FLAGS for the new node.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
uint64_t nflags)
{
uint64_t flags;
int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
indx_t newindx;
pgno_t pgno = 0;
int i, j, split_indx, nkeys, pmax;
MDB_env *env = mc->mc_txn->mt_env;
MDB_node *node;
MDB_val sepkey, rkey, xdata, *rdata = &xdata;
MDB_page *copy = NULL;
MDB_page *mp, *rp, *pp;
int ptop;
MDB_cursor mn;
DKBUF;
mp = mc->mc_pg[mc->mc_top];
newindx = mc->mc_ki[mc->mc_top];
nkeys = NUMKEYS(mp);
DPRINTF(("-----> splitting %s page %" Yu" and adding [%s] at index %i/%i",
IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
/* Create a right sibling. */
if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
return rc;
rp->mp_pad = mp->mp_pad;
DPRINTF(("new right sibling: page %" Yu, rp->mp_pgno));
/* Usually when splitting the root page, the cursor
* height is 1. But when called from mdb_update_key,
* the cursor height may be greater because it walks
* up the stack while finding the branch slot to update.
*/
if (mc->mc_top < 1) {
if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
goto done;
/* shift current top to make room for new parent */
for (i=mc->mc_snum; i>0; i--) {
mc->mc_pg[i] = mc->mc_pg[i-1];
mc->mc_ki[i] = mc->mc_ki[i-1];
}
mc->mc_pg[0] = pp;
mc->mc_ki[0] = 0;
mc->mc_db->md_root = pp->mp_pgno;
DPRINTF(("root split! new root = %" Yu, pp->mp_pgno));
new_root = mc->mc_db->md_depth++;
/* Add left (implicit) pointer. */
if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
/* undo the pre-push */
mc->mc_pg[0] = mc->mc_pg[1];
mc->mc_ki[0] = mc->mc_ki[1];
mc->mc_db->md_root = mp->mp_pgno;
mc->mc_db->md_depth--;
goto done;
}
mc->mc_snum++;
mc->mc_top++;
ptop = 0;
} else {
ptop = mc->mc_top-1;
DPRINTF(("parent branch page is %" Yu, mc->mc_pg[ptop]->mp_pgno));
}
mdb_cursor_copy(mc, &mn);
mn.mc_xcursor = NULL;
mn.mc_pg[mn.mc_top] = rp;
mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
if (nflags & MDB_APPEND) {
mn.mc_ki[mn.mc_top] = 0;
sepkey = *newkey;
split_indx = newindx;
nkeys = 0;
} else {
split_indx = (nkeys+1) / 2;
if (IS_LEAF2(rp)) {
char *split, *ins;
int x;
uint64_t lsize, rsize, ksize;
/* Move half of the keys to the right sibling */
x = mc->mc_ki[mc->mc_top] - split_indx;
ksize = mc->mc_db->md_pad;
split = LEAF2KEY(mp, split_indx, ksize);
rsize = (nkeys - split_indx) * ksize;
lsize = (nkeys - split_indx) * sizeof(indx_t);
mp->mp_lower -= lsize;
rp->mp_lower += lsize;
mp->mp_upper += rsize - lsize;
rp->mp_upper -= rsize - lsize;
sepkey.mv_size = ksize;
if (newindx == split_indx) {
sepkey.mv_data = newkey->mv_data;
} else {
sepkey.mv_data = split;
}
if (x<0) {
ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
memcpy(rp->mp_ptrs, split, rsize);
sepkey.mv_data = rp->mp_ptrs;
memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
memcpy(ins, newkey->mv_data, ksize);
mp->mp_lower += sizeof(indx_t);
mp->mp_upper -= ksize - sizeof(indx_t);
} else {
if (x)
memcpy(rp->mp_ptrs, split, x * ksize);
ins = LEAF2KEY(rp, x, ksize);
memcpy(ins, newkey->mv_data, ksize);
memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
rp->mp_lower += sizeof(indx_t);
rp->mp_upper -= ksize - sizeof(indx_t);
mc->mc_ki[mc->mc_top] = x;
}
} else {
int psize, nsize, k;
/* Maximum free space in an empty page */
pmax = env->me_psize - PAGEHDRSZ;
if (IS_LEAF(mp))
nsize = mdb_leaf_size(env, newkey, newdata);
else
nsize = mdb_branch_size(env, newkey);
nsize = EVEN(nsize);
/* grab a page to hold a temporary copy */
copy = mdb_page_malloc(mc->mc_txn, 1);
if (copy == NULL) {
rc = ENOMEM;
goto done;
}
copy->mp_pgno = mp->mp_pgno;
copy->mp_flags = mp->mp_flags;
copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
copy->mp_upper = env->me_psize - PAGEBASE;
/* prepare to insert */
for (i=0, j=0; i<nkeys; i++) {
if (i == newindx) {
copy->mp_ptrs[j++] = 0;
}
copy->mp_ptrs[j++] = mp->mp_ptrs[i];
}
/* When items are relatively large the split point needs
* to be checked, because being off-by-one will make the
* difference between success or failure in mdb_node_add.
*
* It's also relevant if a page happens to be laid out
* such that one half of its nodes are all "small" and
* the other half of its nodes are "large." If the new
* item is also "large" and falls on the half with
* "large" nodes, it also may not fit.
*
* As a final tweak, if the new item goes on the last
* spot on the page (and thus, onto the new page), bias
* the split so the new page is emptier than the old page.
* This yields better packing during sequential inserts.
*/
if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
/* Find split point */
psize = 0;
if (newindx <= split_indx || newindx >= nkeys) {
i = 0; j = 1;
k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
} else {
i = nkeys; j = -1;
k = split_indx-1;
}
for (; i!=k; i+=j) {
if (i == newindx) {
psize += nsize;
node = NULL;
} else {
node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
if (IS_LEAF(mp)) {
if (F_ISSET(node->mn_flags, F_BIGDATA))
psize += sizeof(pgno_t);
else
psize += NODEDSZ(node);
}
psize = EVEN(psize);
}
if (psize > pmax || i == k-j) {
split_indx = i + (j<0);
break;
}
}
}
if (split_indx == newindx) {
sepkey.mv_size = newkey->mv_size;
sepkey.mv_data = newkey->mv_data;
} else {
node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
sepkey.mv_size = node->mn_ksize;
sepkey.mv_data = NODEKEY(node);
}
}
}
DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
/* Copy separator key to the parent.
*/
if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
int snum = mc->mc_snum;
mn.mc_snum--;
mn.mc_top--;
did_split = 1;
/* We want other splits to find mn when doing fixups */
WITH_CURSOR_TRACKING(mn,
rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
if (rc)
goto done;
/* root split? */
if (mc->mc_snum > snum) {
ptop++;
}
/* Right page might now have changed parent.
* Check if left page also changed parent.
*/
if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
for (i=0; i<ptop; i++) {
mc->mc_pg[i] = mn.mc_pg[i];
mc->mc_ki[i] = mn.mc_ki[i];
}
mc->mc_pg[ptop] = mn.mc_pg[ptop];
if (mn.mc_ki[ptop]) {
mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
} else {
/* find right page's left sibling */
mc->mc_ki[ptop] = mn.mc_ki[ptop];
rc = mdb_cursor_sibling(mc, 0);
}
}
} else {
mn.mc_top--;
rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
mn.mc_top++;
}
if (rc != MDB_SUCCESS) {
if (rc == MDB_NOTFOUND) /* improper mdb_cursor_sibling() result */
rc = MDB_PROBLEM;
goto done;
}
if (nflags & MDB_APPEND) {
mc->mc_pg[mc->mc_top] = rp;
mc->mc_ki[mc->mc_top] = 0;
rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
if (rc)
goto done;
for (i=0; i<mc->mc_top; i++)
mc->mc_ki[i] = mn.mc_ki[i];
} else if (!IS_LEAF2(mp)) {
/* Move nodes */
mc->mc_pg[mc->mc_top] = rp;
i = split_indx;
j = 0;
do {
if (i == newindx) {
rkey.mv_data = newkey->mv_data;
rkey.mv_size = newkey->mv_size;
if (IS_LEAF(mp)) {
rdata = newdata;
} else
pgno = newpgno;
flags = nflags;
/* Update index for the new key. */
mc->mc_ki[mc->mc_top] = j;
} else {
node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
rkey.mv_data = NODEKEY(node);
rkey.mv_size = node->mn_ksize;
if (IS_LEAF(mp)) {
xdata.mv_data = NODEDATA(node);
xdata.mv_size = NODEDSZ(node);
rdata = &xdata;
} else
pgno = NODEPGNO(node);
flags = node->mn_flags;
}
if (!IS_LEAF(mp) && j == 0) {
/* First branch index doesn't need key data. */
rkey.mv_size = 0;
}
rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
if (rc)
goto done;
if (i == nkeys) {
i = 0;
j = 0;
mc->mc_pg[mc->mc_top] = copy;
} else {
i++;
j++;
}
} while (i != split_indx);
nkeys = NUMKEYS(copy);
for (i=0; i<nkeys; i++)
mp->mp_ptrs[i] = copy->mp_ptrs[i];
mp->mp_lower = copy->mp_lower;
mp->mp_upper = copy->mp_upper;
memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
env->me_psize - copy->mp_upper - PAGEBASE);
/* reset back to original page */
if (newindx < split_indx) {
mc->mc_pg[mc->mc_top] = mp;
} else {
mc->mc_pg[mc->mc_top] = rp;
mc->mc_ki[ptop]++;
/* Make sure mc_ki is still valid.
*/
if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
for (i=0; i<=ptop; i++) {
mc->mc_pg[i] = mn.mc_pg[i];
mc->mc_ki[i] = mn.mc_ki[i];
}
}
}
if (nflags & MDB_RESERVE) {
node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
if (!(node->mn_flags & F_BIGDATA))
newdata->mv_data = NODEDATA(node);
}
} else {
if (newindx >= split_indx) {
mc->mc_pg[mc->mc_top] = rp;
mc->mc_ki[ptop]++;
/* Make sure mc_ki is still valid.
*/
if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
for (i=0; i<=ptop; i++) {
mc->mc_pg[i] = mn.mc_pg[i];
mc->mc_ki[i] = mn.mc_ki[i];
}
}
}
}
{
/* Adjust other cursors pointing to mp */
MDB_cursor *m2, *m3;
MDB_dbi dbi = mc->mc_dbi;
nkeys = NUMKEYS(mp);
for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
if (mc->mc_flags & C_SUB)
m3 = &m2->mc_xcursor->mx_cursor;
else
m3 = m2;
if (m3 == mc)
continue;
if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
continue;
if (new_root) {
int k;
/* sub cursors may be on different DB */
if (m3->mc_pg[0] != mp)
continue;
/* root split */
for (k=new_root; k>=0; k--) {
m3->mc_ki[k+1] = m3->mc_ki[k];
m3->mc_pg[k+1] = m3->mc_pg[k];
}
if (m3->mc_ki[0] >= nkeys) {
m3->mc_ki[0] = 1;
} else {
m3->mc_ki[0] = 0;
}
m3->mc_pg[0] = mc->mc_pg[0];
m3->mc_snum++;
m3->mc_top++;
}
if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
m3->mc_ki[mc->mc_top]++;
if (m3->mc_ki[mc->mc_top] >= nkeys) {
m3->mc_pg[mc->mc_top] = rp;
m3->mc_ki[mc->mc_top] -= nkeys;
for (i=0; i<mc->mc_top; i++) {
m3->mc_ki[i] = mn.mc_ki[i];
m3->mc_pg[i] = mn.mc_pg[i];
}
}
} else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
m3->mc_ki[ptop]++;
}
if (IS_LEAF(mp))
XCURSOR_REFRESH(m3, mc->mc_top, m3->mc_pg[mc->mc_top]);
}
}
DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
done:
if (copy) /* tmp page */
mdb_page_free(env, copy);
if (rc)
mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
return rc;
}
int
mdb_put(MDB_txn *txn, MDB_dbi dbi,
MDB_val *key, MDB_val *data, uint64_t flags)
{
MDB_cursor mc;
MDB_xcursor mx;
int rc;
if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
return EINVAL;
if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
return EINVAL;
if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
mdb_cursor_init(&mc, txn, dbi, &mx);
mc.mc_next = txn->mt_cursors[dbi];
txn->mt_cursors[dbi] = &mc;
rc = mdb_cursor_put(&mc, key, data, flags);
txn->mt_cursors[dbi] = mc.mc_next;
return rc;
}
#ifndef MDB_WBUF
#define MDB_WBUF (1024*1024)
#endif
#define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
/** State needed for a double-buffering compacting copy. */
typedef struct mdb_copy {
MDB_env *mc_env;
MDB_txn *mc_txn;
pthread_mutex_t mc_mutex;
pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
char *mc_wbuf[2];
char *mc_over[2];
int mc_wlen[2];
int mc_olen[2];
pgno_t mc_next_pgno;
HANDLE mc_fd;
int mc_toggle; /**< Buffer number in provider */
int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
/** Error code. Never cleared if set. Both threads can set nonzero
* to fail the copy. Not mutex-protected, LMDB expects atomic int.
*/
volatile int mc_error;
} mdb_copy;
/** Dedicated writer thread for compacting copy. */
static THREAD_RET ESECT CALL_CONV
mdb_env_copythr(void *arg)
{
mdb_copy *my = (mdb_copy *)arg;
char *ptr;
int toggle = 0, wsize, rc;
#ifdef _WIN32
DWORD len;
#define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
#else
int len;
#define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
#ifdef SIGPIPE
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGPIPE);
if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
my->mc_error = rc;
#endif
#endif
pthread_mutex_lock(&my->mc_mutex);
for(;;) {
while (!my->mc_new)
pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
break;
wsize = my->mc_wlen[toggle];
ptr = my->mc_wbuf[toggle];
again:
rc = MDB_SUCCESS;
while (wsize > 0 && !my->mc_error) {
DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
if (!rc) {
rc = ErrCode();
#if defined(SIGPIPE) && !defined(_WIN32)
if (rc == EPIPE) {
/* Collect the pending SIGPIPE, otherwise at least OS X
* gives it to the process on thread-exit (ITS#8504).
*/
int tmp;
sigwait(&set, &tmp);
}
#endif
break;
} else if (len > 0) {
rc = MDB_SUCCESS;
ptr += len;
wsize -= len;
continue;
} else {
rc = EIO;
break;
}
}
if (rc) {
my->mc_error = rc;
}
/* If there's an overflow page tail, write it too */
if (my->mc_olen[toggle]) {
wsize = my->mc_olen[toggle];
ptr = my->mc_over[toggle];
my->mc_olen[toggle] = 0;
goto again;
}
my->mc_wlen[toggle] = 0;
toggle ^= 1;
/* Return the empty buffer to provider */
my->mc_new--;
pthread_cond_signal(&my->mc_cond);
}
pthread_mutex_unlock(&my->mc_mutex);
return (THREAD_RET)0;
#undef DO_WRITE
}
/** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
*
* @param[in] my control structure.
* @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
*/
static int ESECT
mdb_env_cthr_toggle(mdb_copy *my, int adjust)
{
pthread_mutex_lock(&my->mc_mutex);
my->mc_new += adjust;
pthread_cond_signal(&my->mc_cond);
while (my->mc_new & 2) /* both buffers in use */
pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
pthread_mutex_unlock(&my->mc_mutex);
my->mc_toggle ^= (adjust & 1);
/* Both threads reset mc_wlen, to be safe from threading errors */
my->mc_wlen[my->mc_toggle] = 0;
return my->mc_error;
}
/** Depth-first tree traversal for compacting copy.
* @param[in] my control structure.
* @param[in,out] pg database root.
* @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
*/
static int ESECT
mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
{
MDB_cursor mc = {0};
MDB_node *ni;
MDB_page *mo, *mp, *leaf;
char *buf, *ptr;
int rc, toggle;
uint64_t i;
/* Empty DB, nothing to do */
if (*pg == P_INVALID)
return MDB_SUCCESS;
mc.mc_snum = 1;
mc.mc_txn = my->mc_txn;
mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
if (rc)
return rc;
rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
if (rc)
return rc;
/* Make cursor pages writable */
buf = ptr = (char *) malloc(my->mc_env->me_psize * mc.mc_snum);
if (buf == NULL)
return ENOMEM;
for (i=0; i<mc.mc_top; i++) {
mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
mc.mc_pg[i] = (MDB_page *)ptr;
ptr += my->mc_env->me_psize;
}
/* This is writable space for a leaf page. Usually not needed. */
leaf = (MDB_page *)ptr;
toggle = my->mc_toggle;
while (mc.mc_snum > 0) {
unsigned n;
mp = mc.mc_pg[mc.mc_top];
n = NUMKEYS(mp);
if (IS_LEAF(mp)) {
if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
for (i=0; i<n; i++) {
ni = NODEPTR(mp, i);
if (ni->mn_flags & F_BIGDATA) {
MDB_page *omp;
pgno_t pg;
/* Need writable leaf */
if (mp != leaf) {
mc.mc_pg[mc.mc_top] = leaf;
mdb_page_copy(leaf, mp, my->mc_env->me_psize);
mp = leaf;
ni = NODEPTR(mp, i);
}
memcpy(&pg, NODEDATA(ni), sizeof(pg));
memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
rc = mdb_page_get(&mc, pg, &omp, NULL);
if (rc)
goto done;
if (my->mc_wlen[toggle] >= MDB_WBUF) {
rc = mdb_env_cthr_toggle(my, 1);
if (rc)
goto done;
toggle = my->mc_toggle;
}
mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
memcpy(mo, omp, my->mc_env->me_psize);
mo->mp_pgno = my->mc_next_pgno;
my->mc_next_pgno += omp->mp_pages;
my->mc_wlen[toggle] += my->mc_env->me_psize;
if (omp->mp_pages > 1) {
my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
rc = mdb_env_cthr_toggle(my, 1);
if (rc)
goto done;
toggle = my->mc_toggle;
}
} else if (ni->mn_flags & F_SUBDATA) {
MDB_db db;
/* Need writable leaf */
if (mp != leaf) {
mc.mc_pg[mc.mc_top] = leaf;
mdb_page_copy(leaf, mp, my->mc_env->me_psize);
mp = leaf;
ni = NODEPTR(mp, i);
}
memcpy(&db, NODEDATA(ni), sizeof(db));
my->mc_toggle = toggle;
rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
if (rc)
goto done;
toggle = my->mc_toggle;
memcpy(NODEDATA(ni), &db, sizeof(db));
}
}
}
} else {
mc.mc_ki[mc.mc_top]++;
if (mc.mc_ki[mc.mc_top] < n) {
pgno_t pg;
again:
ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
pg = NODEPGNO(ni);
rc = mdb_page_get(&mc, pg, &mp, NULL);
if (rc)
goto done;
mc.mc_top++;
mc.mc_snum++;
mc.mc_ki[mc.mc_top] = 0;
if (IS_BRANCH(mp)) {
/* Whenever we advance to a sibling branch page,
* we must proceed all the way down to its first leaf.
*/
mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
goto again;
} else
mc.mc_pg[mc.mc_top] = mp;
continue;
}
}
if (my->mc_wlen[toggle] >= MDB_WBUF) {
rc = mdb_env_cthr_toggle(my, 1);
if (rc)
goto done;
toggle = my->mc_toggle;
}
mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
mdb_page_copy(mo, mp, my->mc_env->me_psize);
mo->mp_pgno = my->mc_next_pgno++;
my->mc_wlen[toggle] += my->mc_env->me_psize;
if (mc.mc_top) {
/* Update parent if there is one */
ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
SETPGNO(ni, mo->mp_pgno);
mdb_cursor_pop(&mc);
} else {
/* Otherwise we're done */
*pg = mo->mp_pgno;
break;
}
}
done:
free(buf);
return rc;
}
/** Copy environment with compaction. */
static int ESECT
mdb_env_copyfd1(MDB_env *env, HANDLE fd)
{
MDB_meta *mm;
MDB_page *mp;
mdb_copy my = {0};
MDB_txn *txn = NULL;
pthread_t thr;
pgno_t root, new_root;
int rc = MDB_SUCCESS;
#ifdef _WIN32
if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
!(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
rc = ErrCode();
goto done;
}
my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
if (my.mc_wbuf[0] == NULL) {
/* _aligned_malloc() sets errno, but we use Windows error codes */
rc = ERROR_NOT_ENOUGH_MEMORY;
goto done;
}
#else
if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
return rc;
if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
goto done2;
#ifdef HAVE_MEMALIGN
my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
if (my.mc_wbuf[0] == NULL) {
rc = errno;
goto done;
}
#else
{
void *p;
if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
goto done;
my.mc_wbuf[0] = (char *)p;
}
#endif
#endif
memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
my.mc_next_pgno = NUM_METAS;
my.mc_env = env;
my.mc_fd = fd;
rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
if (rc)
goto done;
rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
if (rc)
goto finish;
mp = (MDB_page *)my.mc_wbuf[0];
memset(mp, 0, NUM_METAS * env->me_psize);
mp->mp_pgno = 0;
mp->mp_flags = P_META;
mm = (MDB_meta *)METADATA(mp);
mdb_env_init_meta0(env, mm);
mm->mm_address = env->me_metas[0]->mm_address;
mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
mp->mp_pgno = 1;
mp->mp_flags = P_META;
*(MDB_meta *)METADATA(mp) = *mm;
mm = (MDB_meta *)METADATA(mp);
/* Set metapage 1 with current main DB */
root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
if (root != P_INVALID) {
/* Count free pages + freeDB pages. Subtract from last_pg
* to find the new last_pg, which also becomes the new root.
*/
MDB_ID freecount = 0;
MDB_cursor mc;
MDB_val key, data;
mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
freecount += *(MDB_ID *)data.mv_data;
if (rc != MDB_NOTFOUND)
goto finish;
freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
txn->mt_dbs[FREE_DBI].md_leaf_pages +
txn->mt_dbs[FREE_DBI].md_overflow_pages;
new_root = txn->mt_next_pgno - 1 - freecount;
mm->mm_last_pg = new_root;
mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
mm->mm_dbs[MAIN_DBI].md_root = new_root;
} else {
/* When the DB is empty, handle it specially to
* fix any breakage like page leaks from ITS#8174.
*/
mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
}
if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
mm->mm_txnid = 1; /* use metapage 1 */
}
my.mc_wlen[0] = env->me_psize * NUM_METAS;
my.mc_txn = txn;
rc = mdb_env_cwalk(&my, &root, 0);
if (rc == MDB_SUCCESS && root != new_root) {
rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
}
finish:
if (rc)
my.mc_error = rc;
mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
rc = THREAD_FINISH(thr);
mdb_txn_abort(txn);
done:
#ifdef _WIN32
if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
if (my.mc_cond) CloseHandle(my.mc_cond);
if (my.mc_mutex) CloseHandle(my.mc_mutex);
#else
free(my.mc_wbuf[0]);
pthread_cond_destroy(&my.mc_cond);
done2:
pthread_mutex_destroy(&my.mc_mutex);
#endif
return rc ? rc : my.mc_error;
}
/** Copy environment as-is. */
static int ESECT
mdb_env_copyfd0(MDB_env *env, HANDLE fd)
{
MDB_txn *txn = NULL;
mdb_mutexref_t wmutex = NULL;
int rc;
mdb_size_t wsize, w3;
char *ptr;
#ifdef _WIN32
DWORD len, w2;
#define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
#else
ssize_t len;
size_t w2;
#define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
#endif
/* Do the lock/unlock of the reader mutex before starting the
* write txn. Otherwise other read txns could block writers.
*/
rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
if (rc)
return rc;
if (env->me_txns) {
/* We must start the actual read txn after blocking writers */
mdb_txn_end(txn, MDB_END_RESET_TMP);
/* Temporarily block writers until we snapshot the meta pages */
wmutex = env->me_wmutex;
if (LOCK_MUTEX(rc, env, wmutex))
goto leave;
rc = mdb_txn_renew0(txn);
if (rc) {
UNLOCK_MUTEX(wmutex);
goto leave;
}
}
wsize = env->me_psize * NUM_METAS;
ptr = env->me_map;
w2 = wsize;
while (w2 > 0) {
DO_WRITE(rc, fd, ptr, w2, len);
if (!rc) {
rc = ErrCode();
break;
} else if (len > 0) {
rc = MDB_SUCCESS;
ptr += len;
w2 -= len;
continue;
} else {
/* Non-blocking or async handles are not supported */
rc = EIO;
break;
}
}
if (wmutex)
UNLOCK_MUTEX(wmutex);
if (rc)
goto leave;
w3 = txn->mt_next_pgno * env->me_psize;
{
mdb_size_t fsize = 0;
if ((rc = mdb_fsize(env->me_fd, &fsize)))
goto leave;
if (w3 > fsize)
w3 = fsize;
}
wsize = w3 - wsize;
while (wsize > 0) {
if (wsize > MAX_WRITE)
w2 = MAX_WRITE;
else
w2 = wsize;
DO_WRITE(rc, fd, ptr, w2, len);
if (!rc) {
rc = ErrCode();
break;
} else if (len > 0) {
rc = MDB_SUCCESS;
ptr += len;
wsize -= len;
continue;
} else {
rc = EIO;
break;
}
}
leave:
mdb_txn_abort(txn);
return rc;
}
int ESECT
mdb_env_copyfd2(MDB_env *env, HANDLE fd, uint64_t flags)
{
if (flags & MDB_CP_COMPACT)
return mdb_env_copyfd1(env, fd);
else
return mdb_env_copyfd0(env, fd);
}
int ESECT
mdb_env_copyfd(MDB_env *env, HANDLE fd)
{
return mdb_env_copyfd2(env, fd, 0);
}
int ESECT
mdb_env_copy2(MDB_env *env, const char *path, uint64_t flags)
{
int rc;
MDB_name fname;
HANDLE newfd = INVALID_HANDLE_VALUE;
rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
if (rc == MDB_SUCCESS) {
rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
mdb_fname_destroy(fname);
}
if (rc == MDB_SUCCESS) {
rc = mdb_env_copyfd2(env, newfd, flags);
if (close(newfd) < 0 && rc == MDB_SUCCESS)
rc = ErrCode();
}
return rc;
}
int ESECT
mdb_env_copy(MDB_env *env, const char *path)
{
return mdb_env_copy2(env, path, 0);
}
int ESECT
mdb_env_set_flags(MDB_env *env, uint64_t flag, int onoff)
{
if (flag & ~CHANGEABLE)
return EINVAL;
if (onoff)
env->me_flags |= flag;
else
env->me_flags &= ~flag;
return MDB_SUCCESS;
}
int ESECT
mdb_env_get_flags(MDB_env *env, uint64_t *arg)
{
if (!env || !arg)
return EINVAL;
*arg = env->me_flags & (CHANGEABLE|CHANGELESS);
return MDB_SUCCESS;
}
int ESECT
mdb_env_set_userctx(MDB_env *env, void *ctx)
{
if (!env)
return EINVAL;
env->me_userctx = ctx;
return MDB_SUCCESS;
}
void * ESECT
mdb_env_get_userctx(MDB_env *env)
{
return env ? env->me_userctx : NULL;
}
int ESECT
mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
{
if (!env)
return EINVAL;
#ifndef NDEBUG
env->me_assert_func = func;
#endif
return MDB_SUCCESS;
}
int ESECT
mdb_env_get_path(MDB_env *env, const char **arg)
{
if (!env || !arg)
return EINVAL;
*arg = env->me_path;
return MDB_SUCCESS;
}
int ESECT
mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
{
if (!env || !arg)
return EINVAL;
*arg = env->me_fd;
return MDB_SUCCESS;
}
/** Common code for #mdb_stat() and #mdb_env_stat().
* @param[in] env the environment to operate in.
* @param[in] db the #MDB_db record containing the stats to return.
* @param[out] arg the address of an #MDB_stat structure to receive the stats.
* @return 0, this function always succeeds.
*/
static int ESECT
mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
{
arg->ms_psize = env->me_psize;
arg->ms_depth = db->md_depth;
arg->ms_branch_pages = db->md_branch_pages;
arg->ms_leaf_pages = db->md_leaf_pages;
arg->ms_overflow_pages = db->md_overflow_pages;
arg->ms_entries = db->md_entries;
return MDB_SUCCESS;
}
int ESECT
mdb_env_stat(MDB_env *env, MDB_stat *arg)
{
MDB_meta *meta;
if (env == NULL || arg == NULL)
return EINVAL;
meta = mdb_env_pick_meta(env);
return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
}
int ESECT
mdb_env_info(MDB_env *env, MDB_envinfo *arg)
{
MDB_meta *meta;
if (env == NULL || arg == NULL)
return EINVAL;
meta = mdb_env_pick_meta(env);
arg->me_mapaddr = meta->mm_address;
arg->me_last_pgno = meta->mm_last_pg;
arg->me_last_txnid = meta->mm_txnid;
arg->me_mapsize = env->me_mapsize;
arg->me_maxreaders = env->me_maxreaders;
arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
return MDB_SUCCESS;
}
/** Set the default comparison functions for a database.
* Called immediately after a database is opened to set the defaults.
* The user can then override them with #mdb_set_compare() or
* #mdb_set_dupsort().
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
*/
static void
mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
{
uint16_t f = txn->mt_dbs[dbi].md_flags;
txn->mt_dbxs[dbi].md_cmp =
(f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
(f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
txn->mt_dbxs[dbi].md_dcmp =
!(f & MDB_DUPSORT) ? 0 :
((f & MDB_INTEGERDUP)
? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
: ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
}
int mdb_dbi_open(MDB_txn *txn, const char *name, uint64_t flags, MDB_dbi *dbi)
{
MDB_val key, data;
MDB_dbi i;
MDB_cursor mc;
MDB_db dummy;
int rc, dbflag, exact;
uint64_t unused = 0, seq;
char *namedup;
size_t len;
if (flags & ~VALID_FLAGS)
return EINVAL;
if (txn->mt_flags & MDB_TXN_BLOCKED)
return MDB_BAD_TXN;
/* main DB? */
if (!name) {
*dbi = MAIN_DBI;
if (flags & PERSISTENT_FLAGS) {
uint16_t f2 = flags & PERSISTENT_FLAGS;
/* make sure flag changes get committed */
if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
txn->mt_dbs[MAIN_DBI].md_flags |= f2;
txn->mt_flags |= MDB_TXN_DIRTY;
}
}
mdb_default_cmp(txn, MAIN_DBI);
return MDB_SUCCESS;
}
if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
mdb_default_cmp(txn, MAIN_DBI);
}
/* Is the DB already open? */
len = strlen(name);
for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
if (!txn->mt_dbxs[i].md_name.mv_size) {
/* Remember this free slot */
if (!unused) unused = i;
continue;
}
if (len == txn->mt_dbxs[i].md_name.mv_size &&
!strncmp(name, (const char *)txn->mt_dbxs[i].md_name.mv_data, len)) {
*dbi = i;
return MDB_SUCCESS;
}
}
/* If no free slot and max hit, fail */
if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
return MDB_DBS_FULL;
/* Cannot mix named databases with some mainDB flags */
if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
/* Find the DB info */
dbflag = DB_NEW|DB_VALID|DB_USRVALID;
exact = 0;
key.mv_size = len;
key.mv_data = (void *)name;
mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
if (rc == MDB_SUCCESS) {
/* make sure this is actually a DB */
MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
return MDB_INCOMPATIBLE;
} else {
if (rc != MDB_NOTFOUND || !(flags & MDB_CREATE))
return rc;
if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
return EACCES;
}
/* Done here so we cannot fail after creating a new DB */
if ((namedup = strdup(name)) == NULL)
return ENOMEM;
if (rc) {
/* MDB_NOTFOUND and MDB_CREATE: Create new DB */
data.mv_size = sizeof(MDB_db);
data.mv_data = &dummy;
memset(&dummy, 0, sizeof(dummy));
dummy.md_root = P_INVALID;
dummy.md_flags = flags & PERSISTENT_FLAGS;
WITH_CURSOR_TRACKING(mc,
rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
dbflag |= DB_DIRTY;
}
if (rc) {
free(namedup);
} else {
/* Got info, register DBI in this txn */
uint64_t slot = unused ? unused : txn->mt_numdbs;
txn->mt_dbxs[slot].md_name.mv_data = namedup;
txn->mt_dbxs[slot].md_name.mv_size = len;
txn->mt_dbxs[slot].md_rel = NULL;
txn->mt_dbflags[slot] = dbflag;
/* txn-> and env-> are the same in read txns, use
* tmp variable to avoid undefined assignment
*/
seq = ++txn->mt_env->me_dbiseqs[slot];
txn->mt_dbiseqs[slot] = seq;
memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
*dbi = slot;
mdb_default_cmp(txn, slot);
if (!unused) {
txn->mt_numdbs++;
}
}
return rc;
}
int ESECT
mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
{
if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
return EINVAL;
if (txn->mt_flags & MDB_TXN_BLOCKED)
return MDB_BAD_TXN;
if (txn->mt_dbflags[dbi] & DB_STALE) {
MDB_cursor mc;
MDB_xcursor mx;
/* Stale, must read the DB's root. cursor_init does it for us. */
mdb_cursor_init(&mc, txn, dbi, &mx);
}
return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
}
void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
{
char *ptr;
if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
return;
ptr = (char *) env->me_dbxs[dbi].md_name.mv_data;
/* If there was no name, this was already closed */
if (ptr) {
env->me_dbxs[dbi].md_name.mv_data = NULL;
env->me_dbxs[dbi].md_name.mv_size = 0;
env->me_dbflags[dbi] = 0;
env->me_dbiseqs[dbi]++;
free(ptr);
}
}
int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, uint64_t *flags)
{
/* We could return the flags for the FREE_DBI too but what's the point? */
if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
return EINVAL;
*flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
return MDB_SUCCESS;
}
/** Add all the DB's pages to the free list.
* @param[in] mc Cursor on the DB to free.
* @param[in] subs non-Zero to check for sub-DBs in this DB.
* @return 0 on success, non-zero on failure.
*/
static int
mdb_drop0(MDB_cursor *mc, int subs)
{
int rc;
rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
if (rc == MDB_SUCCESS) {
MDB_txn *txn = mc->mc_txn;
MDB_node *ni;
MDB_cursor mx;
uint64_t i;
/* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
* This also avoids any P_LEAF2 pages, which have no nodes.
* Also if the DB doesn't have sub-DBs and has no overflow
* pages, omit scanning leaves.
*/
if ((mc->mc_flags & C_SUB) ||
(!subs && !mc->mc_db->md_overflow_pages))
mdb_cursor_pop(mc);
mdb_cursor_copy(mc, &mx);
//#ifdef MDB_VL32
// /* bump refcount for mx's pages */
// for (i=0; i<mc->mc_snum; i++)
// mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
//#endif
while (mc->mc_snum > 0) {
MDB_page *mp = mc->mc_pg[mc->mc_top];
unsigned n = NUMKEYS(mp);
if (IS_LEAF(mp)) {
for (i=0; i<n; i++) {
ni = NODEPTR(mp, i);
if (ni->mn_flags & F_BIGDATA) {
MDB_page *omp;
pgno_t pg;
memcpy(&pg, NODEDATA(ni), sizeof(pg));
rc = mdb_page_get(mc, pg, &omp, NULL);
if (rc != 0)
goto done;
mdb_cassert(mc, IS_OVERFLOW(omp));
rc = mdb_midl_append_range(&txn->mt_free_pgs,
pg, omp->mp_pages);
if (rc)
goto done;
mc->mc_db->md_overflow_pages -= omp->mp_pages;
if (!mc->mc_db->md_overflow_pages && !subs)
break;
} else if (subs && (ni->mn_flags & F_SUBDATA)) {
mdb_xcursor_init1(mc, ni);
rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
if (rc)
goto done;
}
}
if (!subs && !mc->mc_db->md_overflow_pages)
goto pop;
} else {
if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
goto done;
for (i=0; i<n; i++) {
pgno_t pg;
ni = NODEPTR(mp, i);
pg = NODEPGNO(ni);
/* free it */
mdb_midl_xappend(txn->mt_free_pgs, pg);
}
}
if (!mc->mc_top)
break;
mc->mc_ki[mc->mc_top] = i;
rc = mdb_cursor_sibling(mc, 1);
if (rc) {
if (rc != MDB_NOTFOUND)
goto done;
/* no more siblings, go back to beginning
* of previous level.
*/
pop:
mdb_cursor_pop(mc);
mc->mc_ki[0] = 0;
for (i=1; i<mc->mc_snum; i++) {
mc->mc_ki[i] = 0;
mc->mc_pg[i] = mx.mc_pg[i];
}
}
}
/* free it */
rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
done:
if (rc)
txn->mt_flags |= MDB_TXN_ERROR;
/* drop refcount for mx's pages */
MDB_CURSOR_UNREF(&mx, 0);
} else if (rc == MDB_NOTFOUND) {
rc = MDB_SUCCESS;
}
mc->mc_flags &= ~C_INITIALIZED;
return rc;
}
int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
{
MDB_cursor *mc, *m2;
int rc;
if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
return EINVAL;
if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
return EACCES;
if (TXN_DBI_CHANGED(txn, dbi))
return MDB_BAD_DBI;
rc = mdb_cursor_open(txn, dbi, &mc);
if (rc)
return rc;
rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
/* Invalidate the dropped DB's cursors */
for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
if (rc)
goto leave;
/* Can't delete the main DB */
if (del && dbi >= CORE_DBS) {
rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
if (!rc) {
txn->mt_dbflags[dbi] = DB_STALE;
mdb_dbi_close(txn->mt_env, dbi);
} else {
txn->mt_flags |= MDB_TXN_ERROR;
}
} else {
/* reset the DB record, mark it dirty */
txn->mt_dbflags[dbi] |= DB_DIRTY;
txn->mt_dbs[dbi].md_depth = 0;
txn->mt_dbs[dbi].md_branch_pages = 0;
txn->mt_dbs[dbi].md_leaf_pages = 0;
txn->mt_dbs[dbi].md_overflow_pages = 0;
txn->mt_dbs[dbi].md_entries = 0;
txn->mt_dbs[dbi].md_root = P_INVALID;
txn->mt_flags |= MDB_TXN_DIRTY;
}
leave:
mdb_cursor_close(mc);
return rc;
}
int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
{
if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
return EINVAL;
txn->mt_dbxs[dbi].md_cmp = cmp;
return MDB_SUCCESS;
}
int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
{
if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
return EINVAL;
txn->mt_dbxs[dbi].md_dcmp = cmp;
return MDB_SUCCESS;
}
int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
{
if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
return EINVAL;
txn->mt_dbxs[dbi].md_rel = rel;
return MDB_SUCCESS;
}
int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
{
if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
return EINVAL;
txn->mt_dbxs[dbi].md_relctx = ctx;
return MDB_SUCCESS;
}
int ESECT
mdb_env_get_maxkeysize(MDB_env *env)
{
return ENV_MAXKEY(env);
}
int ESECT
mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
{
uint64_t i, rdrs;
MDB_reader *mr;
char buf[64];
int rc = 0, first = 1;
if (!env || !func)
return -1;
if (!env->me_txns) {
return func("(no reader locks)\n", ctx);
}
rdrs = env->me_txns->mti_numreaders;
mr = env->me_txns->mti_readers;
for (i=0; i<rdrs; i++) {
if (mr[i].mr_pid) {
txnid_t txnid = mr[i].mr_txnid;
sprintf(buf, txnid == (txnid_t)-1 ?
"%10d %" Z "x -\n" : "%10d %" Z "x %" Yu"\n",
(int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
if (first) {
first = 0;
rc = func(" pid thread txnid\n", ctx);
if (rc < 0)
break;
}
rc = func(buf, ctx);
if (rc < 0)
break;
}
}
if (first) {
rc = func("(no active readers)\n", ctx);
}
return rc;
}
/** Insert pid into list if not already present.
* return -1 if already present.
*/
static int ESECT
mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
{
/* binary search of pid in list */
unsigned base = 0;
unsigned cursor = 1;
int val = 0;
unsigned n = ids[0];
while( 0 < n ) {
unsigned pivot = n >> 1;
cursor = base + pivot + 1;
val = pid - ids[cursor];
if( val < 0 ) {
n = pivot;
} else if ( val > 0 ) {
base = cursor;
n -= pivot + 1;
} else {
/* found, so it's a duplicate */
return -1;
}
}
if( val > 0 ) {
++cursor;
}
ids[0]++;
for (n = ids[0]; n > cursor; n--)
ids[n] = ids[n-1];
ids[n] = pid;
return 0;
}
int ESECT
mdb_reader_check(MDB_env *env, int *dead)
{
if (!env)
return EINVAL;
if (dead)
*dead = 0;
return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
}
/** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
static int ESECT
mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
{
mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
uint64_t i, j, rdrs;
MDB_reader *mr;
MDB_PID_T *pids, pid;
int rc = MDB_SUCCESS, count = 0;
rdrs = env->me_txns->mti_numreaders;
pids = (MDB_PID_T *) malloc((rdrs+1) * sizeof(MDB_PID_T));
if (!pids)
return ENOMEM;
pids[0] = 0;
mr = env->me_txns->mti_readers;
for (i=0; i<rdrs; i++) {
pid = mr[i].mr_pid;
if (pid && pid != env->me_pid) {
if (mdb_pid_insert(pids, pid) == 0) {
if (!mdb_reader_pid(env, Pidcheck, pid)) {
/* Stale reader found */
j = i;
if (rmutex) {
if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
if ((rc = mdb_mutex_failed(env, rmutex, rc)))
break;
rdrs = 0; /* the above checked all readers */
} else {
/* Recheck, a new process may have reused pid */
if (mdb_reader_pid(env, Pidcheck, pid))
j = rdrs;
}
}
for (; j<rdrs; j++)
if (mr[j].mr_pid == pid) {
DPRINTF(("clear stale reader pid %u txn %" Yd,
(unsigned) pid, mr[j].mr_txnid));
mr[j].mr_pid = 0;
count++;
}
if (rmutex)
UNLOCK_MUTEX(rmutex);
}
}
}
}
free(pids);
if (dead)
*dead = count;
return rc;
}
#ifdef MDB_ROBUST_SUPPORTED
/** Handle #LOCK_MUTEX0() failure.
* Try to repair the lock file if the mutex owner died.
* @param[in] env the environment handle
* @param[in] mutex LOCK_MUTEX0() mutex
* @param[in] rc LOCK_MUTEX0() error (nonzero)
* @return 0 on success with the mutex locked, or an error code on failure.
*/
static int ESECT
mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
{
int rlocked, rc2;
MDB_meta *meta;
if (rc == MDB_OWNERDEAD) {
/* We own the mutex. Clean up after dead previous owner. */
rc = MDB_SUCCESS;
rlocked = (mutex == env->me_rmutex);
if (!rlocked) {
/* Keep mti_txnid updated, otherwise next writer can
* overwrite data which latest meta page refers to.
*/
meta = mdb_env_pick_meta(env);
env->me_txns->mti_txnid = meta->mm_txnid;
/* env is hosed if the dead thread was ours */
if (env->me_txn) {
env->me_flags |= MDB_FATAL_ERROR;
env->me_txn = NULL;
rc = MDB_PANIC;
}
}
DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
(rc ? "this process' env is hosed" : "recovering")));
rc2 = mdb_reader_check0(env, rlocked, NULL);
if (rc2 == 0)
rc2 = mdb_mutex_consistent(mutex);
if (rc || (rc = rc2)) {
DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
UNLOCK_MUTEX(mutex);
}
} else {
#ifdef _WIN32
rc = ErrCode();
#endif
DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
}
return rc;
}
#endif /* MDB_ROBUST_SUPPORTED */
#if defined(_WIN32)
/** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
static int ESECT
utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
{
int rc, need = 0;
wchar_t *result = NULL;
for (;;) { /* malloc result, then fill it in */
need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
if (!need) {
rc = ErrCode();
free(result);
return rc;
}
if (!result) {
result = malloc(sizeof(wchar_t) * (need + xtra));
if (!result)
return ENOMEM;
continue;
}
dst->mn_alloced = 1;
dst->mn_len = need - 1;
dst->mn_val = result;
return MDB_SUCCESS;
}
}
#endif /* defined(_WIN32) */
/** @} */
| 28.549727 | 141 | 0.646909 | [
"object"
] |
9bf7abe15cf65e67c9c0321d5c2ca9b03cbaea7e | 17,239 | cpp | C++ | source/code/providers/MySQL_StoredProcedureRow_AsXML_Class_Provider.cpp | Bhaskers-Blu-Org2/MySQL-Provider | 211f79e98e7f34a13c4fb7c01f3aaaefc0dada63 | [
"MIT"
] | 5 | 2019-07-04T17:07:16.000Z | 2021-04-20T15:59:30.000Z | source/code/providers/MySQL_StoredProcedureRow_AsXML_Class_Provider.cpp | microsoft/MySQL-Provider | 211f79e98e7f34a13c4fb7c01f3aaaefc0dada63 | [
"MIT"
] | 5 | 2016-04-12T23:00:45.000Z | 2019-03-28T23:04:57.000Z | source/code/providers/MySQL_StoredProcedureRow_AsXML_Class_Provider.cpp | microsoft/MySQL-Provider | 211f79e98e7f34a13c4fb7c01f3aaaefc0dada63 | [
"MIT"
] | 6 | 2019-09-18T00:11:36.000Z | 2021-11-10T10:07:03.000Z | /* @migen@ */
/*
* --------------------------------- START OF LICENSE ----------------------------
*
* MySQL cimprov ver. 1.0
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* ---------------------------------- END OF LICENSE -----------------------------
*/
#include <scxcorelib/scxcmn.h>
#include <scxcorelib/scxhandle.h>
#include <scxcorelib/scxlog.h>
#include <scxcorelib/scxnameresolver.h>
#include "sqlauth.h"
#include "sqlbinding.h"
#include <algorithm>
#include <string>
#include <MI.h>
#include "MySQL_StoredProcedureRow_AsXML_Class_Provider.h"
using namespace std;
using namespace SCXCoreLib;
//
// Utility functions
//
// Technically, these can be in anonomous namespace, but they're not for unit test purposes
//
/**
Helper to get a value for a specified key in a given query
Given a WQL query like: "select * from foo where param1='value' or param2='foo'",
find the value given a key (param1's value is 'value', param2's value is 'foo')
\param[out] value Value for the key/property specified in the query
\param[in] query WQL query to search
\param[in] key Key or property to search for within the WQL query
\throws MissingValue if the specified key isn't found in query
*/
bool GetValueForKey(string& value, const string& query, const string& key)
{
// Note: We want parameter names in query to be case insensitive (as they are in OMI itself).
// So we find what we care about on a lower-case'd version of the query, but then pull the
// parameter value from the actual query string.
string queryLower(query);
std::transform(queryLower.begin(), queryLower.end(), queryLower.begin(), ::tolower);
string delimiter("\"\'");
string::size_type start(queryLower.find(key)); // Start position of key in query
string::size_type quote(queryLower.find_first_of(delimiter, start)); // Position of first quote after key
// If the key or first quote are not found, return failure
if (start == string::npos || quote == string::npos)
{
return false;
}
string endDelimiter("\\" + queryLower.substr(quote,1));
string::size_type lastPos = quote + 1;
// Find the closing quote character
do
{
string::size_type pos = queryLower.find_first_of(endDelimiter, lastPos);
if ( string::npos == pos )
{
// These substr's won't throw exceptions as quote and 0 are guaranteed to be in bounds
string tail(query.substr(quote + 1 /* " */)); // Tail of query not including first quote
value = tail.substr(0, tail.find_first_of(delimiter)); // Value not including second quote
}
else if ( '\\' == queryLower[pos] )
{
// Skip any quoted character
lastPos = pos + 2;
continue;
}
else
{
// We must have found our closing quote
value = query.substr(quote + 1, pos - quote - 1);
}
break;
} while (true);
return true;
}
/*----------------------------------------------------------------------------*/
/**
Quote an XML string for passage via WS-Man (which is, itself, an XML format).
The following characters are quoted:
" "
' '
< <
> >
& &
All other characters are passed through unmodified.
\param str String quote as XML
\returns Quoted string
*/
string QuoteXMLString(string input)
{
wstring text(StrFromUTF8(input));
wstring delimiters(L"\"'<>&");
stringstream ss;
wstring::size_type lastPos = 0;
do
{
wstring::size_type pos = text.find_first_of(delimiters, lastPos);
if ( wstring::npos == pos )
{
ss << StrToUTF8(text.substr(lastPos));
break;
}
if ( pos > 0 )
{
ss << StrToUTF8(text.substr(lastPos, pos - lastPos));
}
switch ( text[pos] )
{
case L'"':
ss << """;
break;
case L'\'':
ss << "'";
break;
case L'<':
ss << "<";
break;
case L'>':
ss << ">";
break;
case '&':
ss << "&";
}
lastPos = pos + 1;
} while (true);
return ss.str();
}
MI_BEGIN_NAMESPACE
MySQL_StoredProcedureRow_AsXML_Class_Provider::MySQL_StoredProcedureRow_AsXML_Class_Provider(
Module* module) :
m_Module(module)
{
}
MySQL_StoredProcedureRow_AsXML_Class_Provider::~MySQL_StoredProcedureRow_AsXML_Class_Provider()
{
}
void MySQL_StoredProcedureRow_AsXML_Class_Provider::Load(
Context& context)
{
context.Post(MI_RESULT_OK);
}
void MySQL_StoredProcedureRow_AsXML_Class_Provider::Unload(
Context& context)
{
context.Post(MI_RESULT_OK);
}
void MySQL_StoredProcedureRow_AsXML_Class_Provider::EnumerateInstances(
Context& context,
const String& nameSpace,
const PropertySet& propertySet,
bool keysOnly,
const MI_Filter* filter)
{
SCXLogHandle hLog = SCXLogHandleFactory::GetLogHandle(L"mysql.provider.storedprocedurerow_asxml");
CIM_PEX_BEGIN
{
SCX_LOGTRACE(hLog, "Entry: MySQL_StoredProcedureRow_AsXML_Class_Provider::EnumerateInstances");
// This provider's interface is the WQL invocation, which is a SQL-like query
// made by the OMI client to the OMI server. We use this with a query of the
// form:
//
// select * from MySQL_StoredProcedureRow_AsXML
// where DatabaseName = 'dbname' or StoredProcedureName = 'spname'
// or Prameters = 'param1, param2, param3'
//
// In this way, we can indirectly receive input (the database name, the stored
// procedure name, and the parameters) while OMI's processing of the WQL query
// will pass all rows since DatabaseName and StoredProcedureName are always
// returned with all instances.
//
// Since the filter is required, return an error if filter is not specified.
if ( !filter )
{
SCX_LOGINFO(hLog, "Class StoredProcedureRow_AsXML enumerated without XML filter!");
context.Post( MI_RESULT_FAILED );
return;
}
// The MI_Filter pointer (structure defined in MI.h) gives us the expression
// via the function table found on the filter. 'GetExpression' returns the
// query through a C-style reference.
const MI_Char* lang; // String to receive the 'query language', must be "WQL"
const MI_Char* expr; // String to receive the 'query expression', our input
filter->ft->GetExpression(filter, &lang, &expr);
// Sanity check (the query language must be WQL)
{
string language(lang);
if ( language != "WQL" )
{
SCX_LOGERROR(hLog, "Class StoredProcedureRow_AsXML enumerated with query language: " + language);
context.Post( MI_RESULT_FAILED );
return;
}
}
// Get our query and required parameters from the query
string query(expr);
string strPort, database, spName, spParameters;
unsigned int port;
if ( GetValueForKey(strPort, query, "port") )
{
port = StrToUInt(StrFromUTF8(strPort));
}
else
{
// Default to port 3306 if port not specified in query
port = 3306;
}
if ( !GetValueForKey(database, query, "databasename") )
{
SCX_LOGINFO(hLog, "Class StoredProcedureRow_AsXML enumerated with query: " + query + ", couldn't find DatabaseName");
context.Post( MI_RESULT_FAILED );
return;
}
if ( !GetValueForKey(spName, query, "storedprocedurename") )
{
SCX_LOGINFO(hLog, "Class StoredProcedureRow_AsXML enumerated with query: " + query
+ ", couldn't find StoredProcedureName");
context.Post( MI_RESULT_FAILED );
return;
}
GetValueForKey(spParameters, query, "parameters"); // Parameters are optional
SCX_LOGTRACE(hLog, "MySQL_StoredProcedureRow_AsXML_Class_Provider::EnumerateInstances: Query: " + query
+ ", Database: " + database + ", StoredProcName: " + spName);
if ( spParameters.size() )
{
SCX_LOGTRACE(hLog, "MySQL_StoredProcedureRow_AsXML_Class_Provider::EnumerateInstances: Parameters: " + spParameters);
}
else
{
SCX_LOGTRACE(hLog, "MySQL_StoredProcedureRow_AsXML_Class_Provider::EnumerateInstances: (No parameters)");
}
// Contruct parameter list for the query
vector<std::string> parameters;
if ( spParameters.size() )
{
vector<std::wstring> wParameters;
StrTokenize(StrFromUTF8(spParameters), wParameters, L",");
// Convert the std::wstring vector into std::string vector
for (vector<std::wstring>::const_iterator it = wParameters.begin(); it != wParameters.end(); ++it)
{
parameters.push_back( StrToUTF8(*it) );
}
}
//
// Now we're ready to execute the stored procedure
//
util::unique_ptr<MySQL_Binding> pBinding( g_pFactory->GetBinding() );
util::unique_ptr<MySQL_Query_Rows> pQuery(g_pFactory->GetQueryByRow());
util::unique_ptr<MySQL_Authentication> pAuth(g_pFactory->GetAuthentication());
pAuth->Load();
pBinding->AllowStoredProcedures();
if ( !pBinding->AttachUsingStoredCredentials(port, pAuth, database) )
{
std::stringstream ss;
ss << "Failure attaching to MySQL on port: " << port << ", Error "
<< pBinding->GetErrorNum() << ": " << pBinding->GetErrorText();
SCX_LOGINFO(hLog, ss.str());
context.Post(MI_RESULT_FAILED);
return;
}
// Construct the query string (something like 'call `spName` ("p1", "p2", "p3")' based on # of parameters)
string strQuery = "call `" + spName + "` ";
if ( parameters.size() )
{
for (vector<std::string>::const_iterator it = parameters.begin(); it != parameters.end(); ++it)
{
strQuery += ( it == parameters.begin() ? "(\"" : ", \"");
strQuery += pQuery->EscapeQuery(*it) + "\"";
}
strQuery += ");";
}
else
{
strQuery += "();";
}
// The following is only logged in trace mode; check severity for efficiency
if ( eTrace == hLog.GetSeverityThreshold() )
{
SCX_LOGTRACE(hLog, "MySQL generated query: " + strQuery);
string parameterList;
string quote ("\"");
for (vector<std::string>::const_iterator it = parameters.begin(); it != parameters.end(); ++it)
{
parameterList += (it != parameters.begin() ? ", " : "") + quote + *it + quote;
}
SCX_LOGTRACE(hLog, "Parameter substitution list: " + ( parameterList.size() ? parameterList : "<None>") );
}
if ( ! pQuery->ExecuteQuery(strQuery.c_str(), strQuery.size()) )
{
std::stringstream ss;
ss << "Failure executing query to execute stored procedure, error "
<< pQuery->GetErrorNum() << ": " << pQuery->GetErrorText();
SCX_LOGINFO(hLog, ss.str());
context.Post(MI_RESULT_FAILED);
return;
}
// Don't try to get further information if no data was returned from query
if ( pQuery->GetColumnCount() )
{
vector<string> columnNames, columns;
if ( ! pQuery->GetColumnNames(columnNames) )
{
std::stringstream ss;
ss << "Failure collecting column names, error "
<< pQuery->GetErrorNum() << ": " << pQuery->GetErrorText();
SCX_LOGINFO(hLog, ss.str());
context.Post(MI_RESULT_FAILED);
return;
}
// Instance ID should be: hostname:bind-address:port:database:storedProcName:row#
// Build the constant stuff here, once for efficiency
string instanceID;
{
stringstream ss;
NameResolver nr;
string hostname = StrToUTF8(nr.GetHostname());
MySQL_AuthenticationEntry entry;
pAuth->GetEntry(port, entry);
ss << hostname << ":" << entry.binding << ":" << port << ":"
<< database << ":" << spName << ":";
instanceID = ss.str();
}
size_t rowNumber = 0;
while ( pQuery->GetNextRow(columns) )
{
rowNumber++;
MySQL_StoredProcedureRow_AsXML_Class inst;
inst.InstanceID_value( string(instanceID + StrToUTF8(StrFrom(rowNumber))).c_str() );
if ( ! keysOnly )
{
// Construct the result for this row
string rowResult;
rowResult += "<row>";
bool fIsTruncated = false;
for (size_t i = 0; i < pQuery->GetColumnCount(); ++i)
{
std::string columnResult;
columnResult += "<field name=\"" + QuoteXMLString(columnNames[i]) + "\">";
columnResult += QuoteXMLString(columns[i]);
columnResult += "</field>";
// Limit return row length to 60k bytes (OMI instance max is 64k bytes)
if (rowResult.size() + columnResult.size() > 60000)
{
fIsTruncated = true;
break;
}
rowResult += columnResult;
}
rowResult += "</row>";
// Populate remaining columns
inst.Port_value( port );
inst.DatabaseName_value( database.c_str() );
inst.StoredProcedureName_value( spName.c_str() );
// Property "Parameters" will not be returned ...
inst.RowXMLValue_value( rowResult.c_str() );
inst.IsTruncated_value( fIsTruncated );
}
context.Post(inst);
}
}
SCX_LOGTRACE(hLog, "Exit: MySQL_StoredProcedureRow_AsXML_Class_Provider::EnumerateInstances");
context.Post(MI_RESULT_OK);
}
CIM_PEX_END( L"MySQL_StoredProcedureRow_AsXML_Class_Provider::EnumerateInstances", hLog );
}
void MySQL_StoredProcedureRow_AsXML_Class_Provider::GetInstance(
Context& context,
const String& nameSpace,
const MySQL_StoredProcedureRow_AsXML_Class& instanceName,
const PropertySet& propertySet)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void MySQL_StoredProcedureRow_AsXML_Class_Provider::CreateInstance(
Context& context,
const String& nameSpace,
const MySQL_StoredProcedureRow_AsXML_Class& newInstance)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void MySQL_StoredProcedureRow_AsXML_Class_Provider::ModifyInstance(
Context& context,
const String& nameSpace,
const MySQL_StoredProcedureRow_AsXML_Class& modifiedInstance,
const PropertySet& propertySet)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void MySQL_StoredProcedureRow_AsXML_Class_Provider::DeleteInstance(
Context& context,
const String& nameSpace,
const MySQL_StoredProcedureRow_AsXML_Class& instanceName)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
MI_END_NAMESPACE
| 34.478 | 129 | 0.580022 | [
"vector",
"transform"
] |
5003b8c1bd209bc2ad0263f30383603371507206 | 1,086 | cpp | C++ | src/algorithms/implementation/service_lane/service_lane.cpp | kirmani/competitive-programming | c350ca82e0e03c16d2d3b04c90c9a61c5b7bda60 | [
"MIT"
] | null | null | null | src/algorithms/implementation/service_lane/service_lane.cpp | kirmani/competitive-programming | c350ca82e0e03c16d2d3b04c90c9a61c5b7bda60 | [
"MIT"
] | null | null | null | src/algorithms/implementation/service_lane/service_lane.cpp | kirmani/competitive-programming | c350ca82e0e03c16d2d3b04c90c9a61c5b7bda60 | [
"MIT"
] | null | null | null | // service_lane.cpp
// Copyright (C) 2015 Sean Kirmani <sean@kirmani.io>
//
// Distributed under terms of the MIT license.
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int LargestVehicle(vector<int> widths, int start, int end) {
int min = widths[start];
for (int i = start + 1; i <= end; i++) {
int current_width = widths[i];
min = (min > current_width) ? current_width : min;
}
return min;
}
int main() {
int n;
int t;
cin >> n >> t;
vector<int> width(n);
for (int width_i = 0; width_i < n; width_i++) {
cin >> width[width_i];
}
for (int a0 = 0; a0 < t; a0++) {
int i;
int j;
cin >> i >> j;
cout << LargestVehicle(width, i, j) << endl;
}
return 0;
}
| 19.392857 | 60 | 0.632597 | [
"vector"
] |
5007ddcdd69353649fb51a852b00850acc7e11b3 | 12,649 | cpp | C++ | lib/ST_Anything/Everything.cpp | hansaya/GarageDoorOpener | 946b1431143d4c5b1c9493f951f6d8f09a7e52f5 | [
"MIT"
] | 1 | 2020-12-07T22:32:27.000Z | 2020-12-07T22:32:27.000Z | lib/ST_Anything/Everything.cpp | hansaya/GarageDoorOpener | 946b1431143d4c5b1c9493f951f6d8f09a7e52f5 | [
"MIT"
] | null | null | null | lib/ST_Anything/Everything.cpp | hansaya/GarageDoorOpener | 946b1431143d4c5b1c9493f951f6d8f09a7e52f5 | [
"MIT"
] | null | null | null | //******************************************************************************************
// File: Everything.cpp
// Authors: Dan G Ogorchock & Daniel J Ogorchock (Father and Son)
//
// Summary: st::Everything is a generic class which essentially acts as the main() routine.
// All st::Device type objects are managed by st::Everything. It is responsible for
// for calling the correct functions within each object it is responsible for at the
// proper time. It handles all initialization of and use of the SmarThings Shield library.
//
// THere are user-definable settings which will impact the st::Everything class stored in
// Constants.h. Please edit Constants.h to adjust these settings.
//
// In general, this file should not need to be modified.
//
// Change History:
//
// Date Who What
// ---- --- ----
// 2015-01-03 Dan & Daniel Original Creation
// 2015-01-10 Dan Ogorchock Minor improvements to support Door Control Capability
// 2015-03-14 Dan Ogorchock Added public setLED() function to control ThingShield LED
// 2015-03-28 Dan Ogorchock Added throttling capability to sendStrings to improve success rate of ST Cloud getting the data ("SENDSTRINGS_INTERVAL" is in CONSTANTS.H)
// 2017-02-07 Dan Ogorchock Added support for new SmartThings v2.0 library (ThingShield, W5100, ESP8266)
// 2017-02-19 Dan Ogorchock Fixed bug in throttling capability
// 2017-04-26 Dan Ogorchock Allow each communication method to specify unique ST transmission throttling delay
// 2019-02-09 Dan Ogorchock Add update() call to Executors in support of devices like EX_Servo that need a non-blocking mechanism
// 2019-02-24 Dan Ogorchock Added new special callOnMsgRcvd2 callback capability. Allows recvd string to be manipulated in the sketch before being processed by Everything.
//
//******************************************************************************************
//#include <Arduino.h>
//#include <avr/pgmspace.h>
#include "Everything.h"
long freeRam(); //freeRam() function prototype - useful in determining how much SRAM is available on Arduino
#if defined(ARDUINO_ARCH_SAMD)
extern "C" char* sbrk(int incr);
#endif
namespace st
{
//private
void Everything::updateDevices()
{
for(unsigned int index=0; index<m_nSensorCount; ++index)
{
m_Sensors[index]->update();
sendStrings();
}
for (unsigned int i = 0; i<m_nExecutorCount; ++i)
{
m_Executors[i]->update();
sendStrings();
}
}
#if defined(ENABLE_SERIAL)
void Everything::readSerial()
{
String message;
while(Serial.available()>0)
{
char c=Serial.read();
message+=c;
delay(10);
}
if(message.length()>0)
{
receiveSmartString(message);
}
}
#endif
void Everything::sendStrings()
{
unsigned int index;
//Loop through the Return_String buffer and send each "|" delimited string to ST Shield
while(Return_String.length()>=1 && Return_String[0]!='|')
{
index=Return_String.indexOf("|");
if(debug)
{
Serial.print(F("Everything: Sending: "));
Serial.println(Return_String.substring(0, index));
//Serial.print(F("Everything: getTransmitInterval() = "));
//Serial.println(SmartThing->getTransmitInterval());
}
#ifndef DISABLE_SMARTTHINGS
// if (millis() - sendstringsLastMillis < Constants::SENDSTRINGS_INTERVAL)
if (millis() - sendstringsLastMillis < SmartThing->getTransmitInterval())
{
// delay(Constants::SENDSTRINGS_INTERVAL - (millis() - sendstringsLastMillis)); //Added due to slow ST Hub/Cloud Processing. Events were being missed. DGO 2015-03-28
delay(SmartThing->getTransmitInterval() - (millis() - sendstringsLastMillis)); //modified to allow different values for each method of communicating to ST cloud. DGO 2017-04-26
}
SmartThing->send(Return_String.substring(0, index));
sendstringsLastMillis = millis();
#endif
#if defined(ENABLE_SERIAL) && defined(DISABLE_SMARTTHINGS)
Serial.println(Return_String.substring(0, index));
#endif
if(callOnMsgSend!=0)
{
callOnMsgSend(Return_String.substring(0, index));
}
Return_String=Return_String.substring(index+1);
}
Return_String.remove(0); //clear the Return_String buffer
}
void Everything::refreshDevices()
{
for(unsigned int i=0; i<m_nExecutorCount; ++i)
{
m_Executors[i]->refresh();
sendStrings();
}
for (unsigned int i = 0; i<m_nSensorCount; ++i)
{
m_Sensors[i]->refresh();
sendStrings();
}
}
//public
void Everything::init()
{
Serial.begin(Constants::SERIAL_BAUDRATE);
Return_String.reserve(st::Constants::RETURN_STRING_RESERVE); //allocate Return_String buffer one time to prevent Heap Fragmentation. RETURN_STRING_RESERVE is set in Constants.h
if(debug)
{
Serial.println(F("Everything: init started"));
Serial.print(F("Everything: Free RAM = "));
Serial.println(freeRam());
}
#ifndef DISABLE_SMARTTHINGS
SmartThing->init();
#endif
if(debug)
{
Serial.println(F("Everything: init ended"));
Serial.print(F("Everything: Free RAM = "));
Serial.println(freeRam());
}
}
void Everything::initDevices()
{
if(debug)
{
Serial.println(F("Everything: initDevices started"));
Serial.print(F("Everything: Free RAM = "));
Serial.println(freeRam());
}
for(unsigned int index=0; index<m_nSensorCount; ++index)
{
m_Sensors[index]->init();
sendStrings();
}
for(unsigned int index=0; index<m_nExecutorCount; ++index)
{
m_Executors[index]->init();
sendStrings();
}
if(debug)
{
Serial.println(F("Everything: initDevices ended"));
Serial.print(F("Everything: Free RAM = "));
Serial.println(freeRam());
}
refLastMillis = millis(); //avoid immediately refreshing after initialization
}
void Everything::run()
{
updateDevices(); //call each st::Sensor object to refresh data
#ifndef DISABLE_SMARTTHINGS
SmartThing->run(); //call the ST Shield Library to receive any data from the ST Hub
#endif
#if defined(ENABLE_SERIAL)
readSerial(); //read data from the Arduino IDE Serial Monitor window (useful for debugging sometimes)
#endif
sendStrings(); //send any pending updates to ST Cloud
#ifndef DISABLE_REFRESH //Added new check to allow user to disable REFRESH feature - setting is in Constants.h)
if ((bTimersPending == 0) && ((millis() - refLastMillis) >= long(Constants::DEV_REFRESH_INTERVAL) * 1000)) //DEV_REFRESH_INTERVAL is set in Constants.h
{
refLastMillis = millis();
refreshDevices(); //call each st::Device object to refresh data (this is just a safeguard to ensure the state of the Arduino and the ST Cloud stay in synch should an event be missed)
}
#endif
if((debug) && (millis()%60000==0) && (millis()!=lastmillis))
{
lastmillis = millis();
Serial.print(F("Everything: Free Ram = "));
Serial.println(freeRam());
}
}
bool Everything::sendSmartString(String &str)
{
while(str.length()>1 && str[0]=='|') //get rid of leading pipes (messes up sendStrings()'s parsing technique)
{
str=str.substring(1);
}
if((str.length()==1 && str[0]=='|') || str.length()==0)
{
return false;
}
if(Return_String.length()+str.length()>=Constants::RETURN_STRING_RESERVE)
{
if (debug)
{
Serial.print(F("Everything: ERROR: \""));
Serial.print(str);
Serial.println(F("\" would overflow the Return_String 'buffer'"));
}
return false;
}
else
{
Return_String+=str+"|"; //add the new message to the queue to be sent to ST Shield with a "|" delimiter
return true;
}
}
bool Everything::sendSmartStringNow(String &str)
{
if (sendSmartString(str)) sendStrings(); //send any pending updates to ST Cloud immediately
}
Device* Everything::getDeviceByName(const String &str)
{
for(unsigned int index=0; index<m_nSensorCount; ++index)
{
if(m_Sensors[index]->getName()==str)
return (Device*)m_Sensors[index];
}
for(unsigned int index=0; index<m_nExecutorCount; ++index)
{
if(m_Executors[index]->getName()==str)
return (Device*)m_Executors[index];
}
return 0; //null if no such device present
}
bool Everything::addSensor(Sensor *sensor)
{
if(m_nSensorCount>=Constants::MAX_SENSOR_COUNT)
{
if(debug)
{
Serial.print(F("Did not add sensor named "));
Serial.print(sensor->getName());
Serial.println(F("(You've exceeded maximum number of sensors; edit Constants.h)"));
}
return false;
}
else
{
m_Sensors[m_nSensorCount]=sensor;
++m_nSensorCount;
}
if(debug)
{
Serial.print(F("Everything: adding sensor named "));
Serial.println(sensor->getName());
Serial.print(F("Everything: Free RAM = "));
Serial.println(freeRam());
}
return true;
}
bool Everything::addExecutor(Executor *executor)
{
if(m_nExecutorCount>=Constants::MAX_EXECUTOR_COUNT)
{
if(debug)
{
Serial.print(F("Did not add executor named "));
Serial.print(executor->getName());
Serial.println(F("(You've exceeded maximum number of executors; edit Constants.h)"));
}
return false;
}
else
{
m_Executors[m_nExecutorCount]=executor;
++m_nExecutorCount;
}
if(debug)
{
Serial.print(F("Everything: adding executor named "));
Serial.println(executor->getName());
Serial.print(F("Everything: Free RAM = "));
Serial.println(freeRam());
}
return true;
}
//friends!
void receiveSmartString(String message)
{
message.trim();
if(Everything::debug && message.length()>1)
{
Serial.print(F("Everything: Received: "));
Serial.println(message);
}
if (Everything::callOnMsgRcvd2 != 0)
{
Everything::callOnMsgRcvd2(message);
}
if (message == "refresh")
{
Everything::refreshDevices();
}
else if (message.length() > 1) //ignore empty string messages from the ST Hub
{
Device *p = Everything::getDeviceByName(message.substring(0, message.indexOf(' ')));
if (p != 0)
{
p->beSmart(message); //pass the incoming SmartThings Shield message to the correct Device's beSmart() routine
}
}
if(Everything::callOnMsgRcvd!=0)
{
Everything::callOnMsgRcvd(message);
}
}
//initialize static members
st::SmartThings* Everything::SmartThing=0; //initialize pointer to null
String Everything::Return_String;
Sensor* Everything::m_Sensors[Constants::MAX_SENSOR_COUNT];
Executor* Everything::m_Executors[Constants::MAX_EXECUTOR_COUNT];
byte Everything::m_nSensorCount=0;
byte Everything::m_nExecutorCount=0;
unsigned long Everything::lastmillis=0;
unsigned long Everything::refLastMillis=0;
unsigned long Everything::sendstringsLastMillis=0;
bool Everything::debug=false;
byte Everything::bTimersPending=0; //initialize variable
void (*Everything::callOnMsgSend)(const String &msg)=0; //initialize this callback function to null
void (*Everything::callOnMsgRcvd)(const String &msg)=0; //initialize this callback function to null
void(*Everything::callOnMsgRcvd2)(String &msg) = 0; //initialize this callback function to null
//SmartThings static members
//#ifndef DISABLE_SMARTTHINGS
// // Please refer to Constants.h for settings that affect whether a board uses SoftwareSerial or Hardware Serial calls
// #if defined(ST_SOFTWARE_SERIAL) //use Software Serial
// SmartThingsThingShield Everything::SmartThing(Constants::pinRX, Constants::pinTX, receiveSmartString);
// #elif defined(ST_HARDWARE_SERIAL) //use Hardware Serial
// SmartThingsThingShield Everything::SmartThing(Constants::SERIAL_TYPE, receiveSmartString);
// #endif
// SmartThingsNetworkState_t Everything::stNetworkState=(SmartThingsNetworkState_t)99; //bogus value for first pass through Everything::updateNetworkState()
//#endif
}
//freeRam() function - useful in determining how much SRAM is available on Arduino
long freeRam()
{
#if defined(ARDUINO_ARCH_AVR)
extern int __heap_start, *__brkval;
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
#elif defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32)
return ESP.getFreeHeap();
#elif defined(ARDUINO_ARCH_SAMD)
char top;
return &top - reinterpret_cast<char*>(sbrk(0));
#else
return -1;
#endif // !
}
| 31.309406 | 186 | 0.661475 | [
"object"
] |
500e74cee42d46db00208a27bb71d2ac417b3a32 | 5,866 | hh | C++ | RAVL2/OS/DataProc/Governor.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/OS/DataProc/Governor.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/OS/DataProc/Governor.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2001, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
#ifndef RAVL_DPGOVERNOR_HEADER
#define RAVL_DPGOVERNOR_HEADER
///////////////////////////////////////////////////////////
//! rcsid="$Id: Governor.hh 7572 2010-02-19 17:27:34Z cyberplug $"
//! docentry="Ravl.API.Core.Data Processing.Extras"
//! author="Charles Galambos"
//! date="12/10/98"
//! lib=RavlDPMT
//! file="Ravl/OS/DataProc/Governor.hh"
#include "Ravl/DP/StreamOp.hh"
#include "Ravl/OS/Date.hh"
#include "Ravl/Threads/ThreadEvent.hh"
namespace RavlN {
//! userlevel=Develop
//: Governor base body.
class DPGovernorBaseBodyC
: virtual public DPEntityBodyC
{
public:
DPGovernorBaseBodyC(double ndelay,RealT nMinDelay = 0)
: delay(ndelay),
frameCnt(0),
minDelay(nMinDelay),
m_persistBypass(false)
{}
//: Constructor
DPGovernorBaseBodyC(const DPGovernorBaseBodyC &oth)
: delay(oth.delay),
frameCnt(0),
minDelay(0),
m_persistBypass(false)
{}
//: Copy Constructor
UIntT FrameCount() const { return frameCnt; }
//: Access frame count.
RealT Delay() const { return delay; }
//: Access frame count.
RealT &Delay() { return delay; }
//: Access frame count.
RealT MinDelay() const { return minDelay; }
//: Access frame count.
RealT &MinDelay() { return minDelay; }
//: Access frame count.
bool SetDelay(RealT newDelay);
//: Set new delay.
// newDelay must be positive or zero
bool Bypass(bool bypass, bool persist);
//; Bypass the governor
// bypass is cleared after next get, if persist is not true.
protected:
void WaitForTimeup();
//: Wait for timeup.
DateC next;
RealT delay;
UIntT frameCnt; // Frame count,can be used to measure frame rate.
RealT minDelay; // Minimum delay to insert.
ThreadEventC m_bypass; //Bypass the current waiting period
volatile bool m_persistBypass; // bypass until further notice.
};
////////////////////////////////////
//! userlevel=Normal
//: Governor base Handle.
// Stream independant control of frame rate.
class DPGovernorBaseC
: virtual public DPEntityC
{
public:
DPGovernorBaseC()
: DPEntityC(true)
{}
//: Default constructor.
DPGovernorBaseC(DPGovernorBaseBodyC &bod)
: DPEntityC(bod)
{}
//: Body Constructor
DPGovernorBaseC(const DPGovernorBaseC &bod)
: DPEntityC(bod)
{}
//: Copy Constructor
protected:
DPGovernorBaseBodyC &Body()
{ return dynamic_cast<DPGovernorBaseBodyC &>(DPEntityC::Body()); }
//: Access body.
const DPGovernorBaseBodyC &Body() const
{ return dynamic_cast<const DPGovernorBaseBodyC &>(DPEntityC::Body()); }
//: Access body.
public:
UIntT FrameCount() const
{ return Body().FrameCount(); }
//: Access frame count.
RealT Delay() const
{ return Body().Delay(); }
//: Access delay
RealT &Delay()
{ return Body().Delay(); }
//: Access delay
RealT MinDelay() const
{ return Body().MinDelay(); }
//: Access delay
RealT &MinDelay()
{ return Body().MinDelay(); }
//: Access delay
bool SetDelay(RealT newDelay)
{ return Body().SetDelay(newDelay); }
//: Set new delay.
// newDelay must be positive or zero
bool Bypass(bool bypass, bool persist=false)
{ return Body().Bypass(bypass, persist); }
//; Bypass the governor
// bypass is cleared after next get, if persist is not true.
};
///////////////////////////
//! userlevel=Develop
//: Governor body.
template<class DataT>
class DPGovernorBodyC
: public DPIStreamOpBodyC<DataT,DataT>,
public DPGovernorBaseBodyC
{
public:
DPGovernorBodyC(double ndelay,RealT nMinDelay = 0)
: DPGovernorBaseBodyC(ndelay,nMinDelay)
{}
//: Constructor
DPGovernorBodyC(const DPGovernorBodyC<DataT> &oth)
: DPIStreamOpBodyC<DataT,DataT>(oth),
DPGovernorBaseBodyC(oth)
{}
//: Copy Constructor
virtual bool Save(ostream &out) const
{ return DPGovernorBaseBodyC::Save(out); }
//: Save to ostream.
virtual DataT Get() {
DataT ret = this->input.Get();
WaitForTimeup();
return ret;
}
//: Process next piece of data.
virtual bool Get(DataT &outbuff) {
bool ret = this->input.Get(outbuff);
WaitForTimeup();
return ret;
}
//: Process some data.
virtual bool IsGetReady() const {
RavlAssert(this->input.IsValid());
return this->input.IsGetReady();
}
virtual bool IsGetEOS() const {
RavlAssert(this->input.IsValid());
return this->input.IsGetEOS();
}
//: Has the End Of Stream been reached ?
// true = yes.
virtual RCBodyVC &Copy() const
{ return *new DPGovernorBodyC(*this); }
//: Creat a copy of this object.
};
////////////////////////////////////
//! userlevel=Normal
//: Governor Handle.
// This class limits the minimum time between
// get operations. This is used for things
// like control the frame rate of a video
// sequence.
template<class DataT>
class DPGovernorC
: public DPIStreamOpC<DataT,DataT>,
public DPGovernorBaseC
{
public:
DPGovernorC(double ndelay,RealT nminDelay = 0)
: DPEntityC(*new DPGovernorBodyC<DataT>(ndelay,nminDelay))
{}
//: Constructor
bool Save(ostream &out) const
{ return DPGovernorBaseC::Save(out); }
//: Save to ostream.
};
}
#endif
| 25.284483 | 76 | 0.615922 | [
"object"
] |
5027e93f5b815f4cf958d35c680faf15161f06e2 | 823 | cpp | C++ | vision_bridge/src/ros_trainer.cpp | HSRobot/HIROP_ROS-3.0 | 59f97bc139b825247c3e71c3f6f110c4cfda174a | [
"Apache-2.0"
] | null | null | null | vision_bridge/src/ros_trainer.cpp | HSRobot/HIROP_ROS-3.0 | 59f97bc139b825247c3e71c3f6f110c4cfda174a | [
"Apache-2.0"
] | null | null | null | vision_bridge/src/ros_trainer.cpp | HSRobot/HIROP_ROS-3.0 | 59f97bc139b825247c3e71c3f6f110c4cfda174a | [
"Apache-2.0"
] | null | null | null | #include "ros_trainer.h"
TrainService::TrainService(ros::NodeHandle n){
mNodeHandle = n;
mTrainer = new Trainer();
}
int TrainService::start(){
trainServer = mNodeHandle.advertiseService(TRAIN_SERVER_NAME, &TrainService::trainCallback, this);
ROS_INFO("train service start finish");
}
int TrainService::stop(){
}
bool TrainService::trainCallback(hirop_msgs::train::Request &req, hirop_msgs::train::Response &res){
if(req.configPath == ""){
ROS_INFO("the train config file path error");
return false;
}
if(mTrainer->setTrainConfig(req.configPath)){
ROS_INFO("When setting trainer, something was wrong");
return false;
}
if(!mTrainer->train()){
return true;
}
ROS_INFO("When train object, something was wrong");
return false;
}
| 22.861111 | 102 | 0.667072 | [
"object"
] |
df25f454ee974d970a9852bf2784d686b64c0abf | 4,487 | cpp | C++ | hands-on/vectorization/NeuNetNaive.cpp | vvolkl/esc19 | 0e9cb64d0789a1d8cc570337978c16c982b9c547 | [
"CC-BY-4.0"
] | null | null | null | hands-on/vectorization/NeuNetNaive.cpp | vvolkl/esc19 | 0e9cb64d0789a1d8cc570337978c16c982b9c547 | [
"CC-BY-4.0"
] | null | null | null | hands-on/vectorization/NeuNetNaive.cpp | vvolkl/esc19 | 0e9cb64d0789a1d8cc570337978c16c982b9c547 | [
"CC-BY-4.0"
] | null | null | null | #include<cmath>
#include<limits>
#include<array>
#include<vector>
#include<random>
// c++ -Ofast -fopenmp -mavx2 -mfma NeuNetNaive.cpp -fopt-info-vec -ftree-loop-if-convert-stores
// --param max-completely-peel-times=1
#include <omp.h>
// #define SCALAR
#include "approx_vexp.h"
template<typename T>
T sigmoid(T x) {
return T(1)/(T(1)+unsafe_expf<T,5,true>(-x));
// return T(1)/(T(1)+std::exp(-x));
}
template<typename T, int N>
struct Neuron {
std::array<float,N+1> w;
T operator()(std::array<T,N> const & x) const {
input = x;
T res = w[N];
for (int i=0; i<N; ++i) res+=w[i]*x[i];
return result=sigmoid(res);
}
T sum(std::array<T,N> const & x) const {
input = x;
T res = w[N];
for (int i=0; i<N; ++i) res+=w[i]*x[i];
return res;
}
void updateWeight(float learingRate) {
T corr = learingRate*result*(1.f-result)*error;
for (int i=0; i<N; ++i) w[i] += corr*input[i];
w[N] += corr;
}
mutable std::array<T,N> input;
mutable T result;
T error;
};
template<typename T, int N, int M>
struct Layer {
std::array<Neuron<T,N>,M> neurons;
using Output = std::array<T,M>;
Output operator()(std::array<T,N> const & x) const {
Output res;
for (int i=0; i<M; ++i) res[i] = neurons[i](x);
return res;
}
void updateWeight(float learingRate) {
for (auto & n : neurons) n.updateWeight(learingRate);
}
};
template<typename T, int N, int M>
struct NeuNet {
Layer<T,N,M> hidden1;
Layer<T,M,M> hidden2;
Neuron<T,M> output;
T operator()(std::array<T,N> const & x) const {
return output(hidden2(hidden1(x)));
}
void train(std::array<T,N> const & x, T const & target, float learingRate) {
output.error = target - (*this)(x);
for (int i=0; i<M; ++i) hidden2.neurons[i].error = output.w[i]*output.error;
for (int i=0; i<M; ++i) hidden1.neurons[i].error = 0;
for (int j=0; j<M; ++j) for (int i=0; i<M; ++i) hidden1.neurons[j].error += hidden2.neurons[i].w[j]*hidden2.neurons[i].error;
hidden1.updateWeight(learingRate);
hidden2.updateWeight(learingRate);
output.updateWeight(learingRate);
}
};
#include <x86intrin.h>
unsigned int taux=0;
inline unsigned long long rdtscp() {
return __rdtscp(&taux);
}
template<typename Data>
struct Reader {
explicit Reader(long long iread) : toRead(iread){}
long long operator()(std::vector<Data> & buffer) {
auto bufSize = buffer.size();
// random instead of reading
for ( auto & b : buffer) for (auto & e : b) e=rgen(eng); // background
for (auto j=0U; j<bufSize; j+=4) // one out of 4
buffer[j][4] = buffer[j][3] = buffer[j][2] = buffer[j][0]; //signal...
toRead -= bufSize;
return toRead;
}
private:
long long toRead;
std::mt19937 eng;
std::uniform_real_distribution<float> rgen = std::uniform_real_distribution<float>(0.,1.);
};
#include<iostream>
template<int NX, int MNodes>
void go() {
constexpr long long Nentries = 1024*10000;
std::mt19937 eng;
std::uniform_real_distribution<float> rgen(0.,1.);
std::uniform_real_distribution<float> wgen(-1.,1.);
NeuNet<float,NX,MNodes> net;
// random ...
for (auto & w: net.output.w) w=wgen(eng);
for (auto & n: net.hidden2.neurons) for (auto & w: n.w) w=wgen(eng);
for (auto & n: net.hidden1.neurons) for (auto & w: n.w) w=wgen(eng);
// timers
long long tt=0, tc=0;
using Data = std::array<float,NX>; // one row
constexpr unsigned int bufSize=1024;
// "array of struct"
std::vector<Data> buffer(bufSize); // an "array" of rows
// train
Reader<Data> reader1(Nentries/4);
while (reader1(buffer)>=0) {
tt -= rdtscp();
int ll=4;
for (auto & b : buffer) {
float t=0.f;
if (4==ll) { t=1.f; ll=1;} // signal (see reader)
else ++ll;
net.train(b,t,0.02f);
}
tt +=rdtscp();
}
double count=0;
double pass=0;
float cut = 0.5;
Reader<Data> reader2(Nentries);
// classify
while (reader2(buffer)>=0) {
tc -= rdtscp();
for ( auto & b : buffer) {
if (net(b)>cut) ++pass;
++count;
}
tc +=rdtscp();
}
std::cout << "\nInput Size " << NX << " layer size " << MNodes << std::endl;
std::cout << "total time training " << double(tt)*1.e-9 << std::endl;
std::cout << "total time classification " << double(tc)*1.e-9 << std::endl;
std::cout << "final result " << pass/count << std::endl;
}
int main() {
go<10,14>();
go<10,7>();
return 0;
}
| 21.572115 | 129 | 0.595275 | [
"vector"
] |
df2cdd7ffa9bb2fa6096d9d1949f30f502147d77 | 1,059 | cpp | C++ | LeetCodeSolutions/LeetCode_0289.cpp | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | 24 | 2020-03-28T06:10:25.000Z | 2021-11-23T05:01:29.000Z | LeetCodeSolutions/LeetCode_0289.cpp | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | null | null | null | LeetCodeSolutions/LeetCode_0289.cpp | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | 8 | 2020-05-18T02:43:16.000Z | 2021-05-24T18:11:38.000Z | class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int row = board.size();
if (row == 0) return ;
int col = board[0].size();
for(int i = 0; i < row; ++i)
for(int j = 0; j < col; ++j)
trans(board, i, j, row, col);
for(int i = 0; i < row; ++ i)
for(int j = 0; j < col; ++j)
board[i][j] >>= 1;
}
void trans(vector<vector<int> >&board, int i, int j, int& row, int& col){
int cnt = 0;
for(int di = -1; di < 2; ++di)
for(int dj = -1; dj < 2; ++ dj)
{
if(di == 0 && dj == 0) continue;
int ci = i + di, cj = j + dj;
if(ci < 0 || ci >= row) continue;
if(cj < 0 || cj >= col) continue;
cnt += board[ci][cj] & 1;
}
if(board[i][j]){
if(cnt == 2 || cnt == 3) board[i][j] = (1 << 1) + board[i][j];
}
else{
if(cnt == 3) board[i][j] = 1 << 1;
}
}
}; | 29.416667 | 77 | 0.368272 | [
"vector"
] |
df38b07ab1b0b29d6d03ae82ab261fdda5db71a5 | 14,743 | cpp | C++ | OpenSFFeatures/FeatureTracking.cpp | Norman0406/OpenSkeletonFitting | 43a6ba856a629a8b67683605194e90c1a2846300 | [
"DOC"
] | 24 | 2015-04-06T19:00:04.000Z | 2021-01-15T18:16:41.000Z | OpenSFFeatures/FeatureTracking.cpp | solbach/open-skeleton-fitting | 80f53861481eb9998a26993f4a22478e97e3748b | [
"DOC"
] | 5 | 2015-07-08T16:23:36.000Z | 2018-06-23T15:00:20.000Z | OpenSFFeatures/FeatureTracking.cpp | solbach/open-skeleton-fitting | 80f53861481eb9998a26993f4a22478e97e3748b | [
"DOC"
] | 12 | 2015-07-01T14:56:29.000Z | 2021-01-15T18:16:47.000Z | /***********************************************************************
*
* OpenSkeletonFitting
* Skeleton fitting by the use of energy minimization
* Copyright (C) 2012 Norman Link <norman.link@gmx.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
***********************************************************************/
#include "precompiled.h"
#include "../OpenSFitting/Joint.h"
#include "FeatureTracking.h"
#include "FeaturePoint.h"
namespace osf
{
int FeatureTracking::counter = 0; // temp
FeatureTracking::FeatureTracking(std::vector<std::pair<JointType, std::pair<cv::Point3d, cv::Point> > >& features,
const cv::Mat& projMat)
: m_inFeatures(features), m_projMat(projMat)
{
m_maxLabel = 0;
m_searchRadius = 0.3;
m_featureLifespan = 1;
}
FeatureTracking::~FeatureTracking(void)
{
clearFeatures();
}
void FeatureTracking::clearFeatures()
{
m_prevFeatures.clear();
m_curFeatures.clear();
for (std::map<int, FeaturePointAccessor*>::const_iterator it = m_trackedFeaturesAcc.begin();
it != m_trackedFeaturesAcc.end(); it++)
delete it->second;
m_trackedFeaturesAcc.clear();
}
const FeaturePoint* FeatureTracking::getPointByLabel(int label) const
{
if (label < 0) {
WARN << "invalid label: " << label << ENDL;
return 0;
}
// find tracked feature point
std::map<int, FeaturePointAccessor*>::const_iterator it = m_trackedFeaturesAcc.find(label);
if (it == m_trackedFeaturesAcc.end()) {
WARN << "invalid label: " << label << ENDL;
return 0;
}
return it->second;
}
bool FeatureTracking::getPointByLabel(cv::Point3d& point, int label) const
{
const FeaturePoint* ftPoint = getPointByLabel(label);
if (!ftPoint)
return false;
point = ftPoint->getPosition3d();
return true;
}
void FeatureTracking::getLabelList(std::vector<int>& list) const
{
list.clear();
for (std::map<int, FeaturePointAccessor*>::const_iterator it = m_trackedFeaturesAcc.begin();
it != m_trackedFeaturesAcc.end(); it++) {
list.push_back(it->second->getTrackingLabel());
}
}
void FeatureTracking::setSearchRadius(double searchRadius)
{
m_searchRadius = searchRadius;
}
void FeatureTracking::setFeatureLifespan(int lifespan)
{
m_featureLifespan = lifespan;
}
double FeatureTracking::getSearchRadius() const
{
return m_searchRadius;
}
int FeatureTracking::getFeatureLifespan() const
{
return m_featureLifespan;
}
const std::vector<FeaturePoint*>& FeatureTracking::getFeaturePoints() const
{
return m_trackedFeatures;
}
void FeatureTracking::stepLifetime()
{
// add up the lifetime values of every tracked feature point
for (std::map<int, FeaturePointAccessor*>::const_iterator it = m_trackedFeaturesAcc.begin();
it != m_trackedFeaturesAcc.end(); it++) {
it->second->stepLifetime();
}
}
void FeatureTracking::markFeature(int label)
{
std::map<int, FeaturePointAccessor*>::const_iterator it = m_trackedFeaturesAcc.find(label);
if (it == m_trackedFeaturesAcc.end()) {
WARN << "label not found: " << label << ENDL;
return;
}
FeaturePointAccessor* ftPoint = m_trackedFeaturesAcc[label];
// TODO: find a nicer approach for this
// some problems here confusing assignment
if (ftPoint->getJointLabel() == JT_TORSO)
ftPoint->setJointLabel(JT_UNKNOWN);
ftPoint->setConfirmState(FeaturePoint::CS_UNCONFIRMED);
}
void FeatureTracking::track()
{
/*if (counter == 42)
WARN << "warn" << ENDL;*/
// Step 1: try to find a best matching for every previously tracked feature point in
// the list of current feature points
for (std::vector<SimpleTrackingItem>::const_iterator itPrev = m_prevFeatures.begin();
itPrev != m_prevFeatures.end(); itPrev++) {
// skip point that have not been tracked before
if (itPrev->trackingLabel < 0)
continue;
cv::Point3d prevPos = itPrev->relativePos;
typedef std::vector<SimpleTrackingItem>::iterator iter;
std::vector<iter> closestPoints;
// find closest points to the current location
for (std::vector<SimpleTrackingItem>::iterator itCur = m_curFeatures.begin();
itCur != m_curFeatures.end(); itCur++) {
cv::Point3d curPos = itCur->relativePos;
double dist = distanceP3d(curPos, prevPos);
if (dist < m_searchRadius) {
// check if this point has already been assigned and chose whether a reassignment
// is necessary
bool pushToList = true;
if (itCur->trackingLabel >= 0) {
// get the label of the already assigned point
int label = itCur->trackingLabel;
// find the matching point in the list of previous features
cv::Point3d assignedPos(0, 0, 0);
bool found = false;
for (std::vector<SimpleTrackingItem>::const_iterator it = m_prevFeatures.begin();
it != m_prevFeatures.end(); it++) {
if (it->trackingLabel == label) {
assignedPos = it->relativePos;
found = true;
break;
}
}
// should never happen
if (!found) {
WARN << "matching label not found, this should not happen" << ENDL;
break;
}
// if the already assigned distance is smaller, then no assignment necessary
double assignedDist = distanceP3d(curPos, assignedPos);
if (assignedDist < dist)
pushToList = false;
}
// add to list of closest neighboring points
if (pushToList)
closestPoints.push_back(itCur);
}
}
// find nearest point
double minDist = std::numeric_limits<double>::infinity();
int minDistIndex = -1;
for (int i = 0; i < (int)closestPoints.size(); i++) {
double dist = distanceP3d(prevPos, closestPoints[i]->relativePos);
if (dist < minDist) {
minDist = dist;
minDistIndex = i;
}
}
// match with nearest point
if (minDistIndex >= 0) {
// if this point was already assigned a value, remove it first
if (closestPoints[minDistIndex]->trackingLabel >= 0) {
// mark feature "to be removed" and set label to JT_UNKNOWN
markFeature(closestPoints[minDistIndex]->trackingLabel);
}
// assign the same label
closestPoints[minDistIndex]->trackingLabel = itPrev->trackingLabel;
// get feature point and set right values
FeaturePointAccessor* ftPoint = m_trackedFeaturesAcc[itPrev->trackingLabel];
if (!ftPoint || ftPoint->getTrackingLabel() != itPrev->trackingLabel)
throw Exception("feature point invalid");
if (closestPoints[minDistIndex]->listIndex >= 0)
ftPoint->setConfirmState(FeaturePoint::CS_CONFIRMED);
// set label
JointType jLabel = JT_UNKNOWN;
if (closestPoints[minDistIndex]->listIndex >= 0)
jLabel = m_inFeatures[closestPoints[minDistIndex]->listIndex].first;
else
jLabel = ftPoint->getJointLabel();
if (jLabel != JT_UNKNOWN)
ftPoint->setJointLabel(jLabel);
}
else {
// mark feature "to be removed"
markFeature(itPrev->trackingLabel);
}
}
/*if (counter >= 42)
goto step3;*/
// Step 2: assign every not-yet assigned current feature point a valid not-tracked
// feature point in the list of previous features
for (std::vector<SimpleTrackingItem>::iterator itCur = m_curFeatures.begin();
itCur != m_curFeatures.end(); itCur++) {
// skip feature points that are already tracked by previous step
if (itCur->trackingLabel >= 0)
continue;
cv::Point3d curPos = itCur->relativePos;
typedef std::vector<SimpleTrackingItem>::iterator iter;
std::vector<iter> closestPoints;
// find closest points to the current location
for (std::vector<SimpleTrackingItem>::iterator itPrev = m_prevFeatures.begin();
itPrev != m_prevFeatures.end(); itPrev++) {
// skip previous features that are already tracked
if (itPrev->trackingLabel >= 0)
continue;
cv::Point3d prevPos = itPrev->relativePos;
double dist = distanceP3d(curPos, prevPos);
if (dist < m_searchRadius) {
// add to list of closest neighboring points
closestPoints.push_back(itPrev);
}
}
// create new feature point
FeaturePointAccessor* ftPoint = new FeaturePointAccessor(m_maxLabel);
ftPoint->setConfirmState(FeaturePoint::CS_CONFIRMED);
// set label
JointType jLabel = JT_UNKNOWN;
if (itCur->listIndex >= 0)
jLabel = m_inFeatures[itCur->listIndex].first;
if (jLabel != JT_UNKNOWN)
ftPoint->setJointLabel(jLabel);
if (!closestPoints.empty()) {
// find nearest point
double minDist = std::numeric_limits<double>::infinity();
int minDistIndex = -1;
for (int i = 0; i < (int)closestPoints.size(); i++) {
double dist = distanceP3d(curPos, closestPoints[i]->relativePos);
if (dist < minDist) {
minDist = dist;
minDistIndex = i;
}
}
if (minDistIndex >= 0) {
// match with nearest point
closestPoints[minDistIndex]->trackingLabel = m_maxLabel;
}
else {
// should never happen
delete ftPoint;
ftPoint = 0;
}
}
// add feature point to list
if (ftPoint) {
itCur->trackingLabel = m_maxLabel;
m_trackedFeaturesAcc[m_maxLabel] = ftPoint;
m_maxLabel++;
}
}
// Step 3: set data for tracked feature points
for (int i = 0; i < (int)m_curFeatures.size(); i++) {
int label = m_curFeatures[i].trackingLabel;
if (label < 0)
continue;
std::map<int, FeaturePointAccessor*>::const_iterator it = m_trackedFeaturesAcc.find(label);
if (it == m_trackedFeaturesAcc.end())
WARN << "label not found: " << label << ENDL;
else {
// set position
cv::Point2d pos2d(0, 0);
pointXYZ2UV(m_projMat, m_curFeatures[i].globalPos, pos2d);
it->second->setPosition(m_curFeatures[i].globalPos, m_curFeatures[i].relativePos, pos2d);
}
}
counter++;
}
void FeatureTracking::extrapolate()
{
// TODO: create virtual feature points, if tracking was lost.
// There are two types of virtual feature points. When a feature point is obscured, just
// use its last position in relation to the torso position and normal as virtual
// feature point for the next x frames. If tracking was lost and the point is not obscured
// (feature extraction is not working), use nearest neighbor from the point cloud to
// generate the virtual feature point until a valid feature was found again (or for the
// next x frames?).
// TODO: if a previous feature is not found in the list of current features, add
// its position and label to current features again for a limited time and remove
// it, when the time is over (1 - 5 frames)
// remove feature points whose unconfirmed lifetime is too high
for (std::map<int, FeaturePointAccessor*>::iterator it = m_trackedFeaturesAcc.begin();
it != m_trackedFeaturesAcc.end();) {
if (it->second->getLatestUnconfLifetime() > m_featureLifespan) {
// remove entry from m_curFeatures
for (std::vector<SimpleTrackingItem>::iterator it2 = m_curFeatures.begin();
it2 != m_curFeatures.end();) {
if (it2->trackingLabel == it->first) {
it2 = m_curFeatures.erase(it2);
}
else
it2++;
}
// delete and remove feature point
delete it->second;
#ifdef _WIN32
it = m_trackedFeaturesAcc.erase(it);
#elif __APPLE__ & __MACH__
// NOTE: not sure if correct
m_trackedFeaturesAcc.erase(it++);
#endif
}
else
it++;
}
// add unconfirmed feature points that are not yet removed to m_curFeatures. This means, that in the
// next step, they will be added to the list of previous features and tried to be matched against.
for (std::map<int, FeaturePointAccessor*>::const_iterator it = m_trackedFeaturesAcc.begin();
it != m_trackedFeaturesAcc.end(); it++) {
if (!it->second->isConfirmed()) {
cv::Point3d globPos = it->second->getPosition3d();
cv::Point3d relPos = it->second->getRelativePosition();
globPos = relPos + m_curTorsoPos;
cv::Point2d imgPos(0, 0);
pointXYZ2UV(m_projMat, globPos, imgPos);
it->second->setPosition(globPos, relPos, imgPos);
m_curFeatures.push_back(SimpleTrackingItem(globPos, relPos, -1, it->second->getTrackingLabel()));
}
}
}
void FeatureTracking::computeFeatureFeatures()
{
for (std::map<int, FeaturePointAccessor*>::const_iterator it = m_trackedFeaturesAcc.begin();
it != m_trackedFeaturesAcc.end(); it++) {
it->second->computeTemporalFeatures();
// TOOD: when the feature point is not virtual at the moment, compute local
// image features
}
}
void FeatureTracking::process()
{
// get torso position
bool torsoFound = false;
for (std::vector<std::pair<JointType, std::pair<cv::Point3d, cv::Point> > >::const_iterator it =
m_inFeatures.begin(); it != m_inFeatures.end(); it++) {
if (it->first == JT_TORSO) {
m_curTorsoPos = it->second.first;
torsoFound = true;
}
}
// only track if a torso position has been found
if (torsoFound) {
// copy previous current features to previous features
m_prevFeatures.clear();
for (std::vector<SimpleTrackingItem>::const_iterator it = m_curFeatures.begin();
it != m_curFeatures.end(); it++)
m_prevFeatures.push_back(*it);
// copy incoming features to current features
m_curFeatures.clear();
for (int i = 0; i < (int)m_inFeatures.size(); i++) {
m_curFeatures.push_back(SimpleTrackingItem(m_inFeatures[i].second.first,
m_inFeatures[i].second.first - m_curTorsoPos, i));
}
// track
if (!m_prevFeatures.empty()) {
track();
stepLifetime();
computeFeatureFeatures();
extrapolate();
}
// copy previous current input features to previous input features
m_prevInFeatures.clear();
for (std::vector<std::pair<JointType, std::pair<cv::Point3d, cv::Point> > >::const_iterator it =
m_inFeatures.begin(); it != m_inFeatures.end(); it++)
m_prevInFeatures.push_back(*it);
}
else {
m_curTorsoPos = cv::Point3d(0, 0, -1);
clearFeatures();
}
// add to public tracking list
m_trackedFeatures.clear();
for (std::map<int, FeaturePointAccessor*>::const_iterator it = m_trackedFeaturesAcc.begin();
it != m_trackedFeaturesAcc.end(); it++)
m_trackedFeatures.push_back(it->second);
}
}
| 30.650728 | 115 | 0.674218 | [
"vector"
] |
df3cd2a47ce8e900a338cdbe8488c9309dee1f78 | 1,089 | hpp | C++ | include/robot/devices/timer_class.hpp | 1069B/TBD_Code | 624162c66e8d24d04657934081074e91f856ce57 | [
"MIT"
] | null | null | null | include/robot/devices/timer_class.hpp | 1069B/TBD_Code | 624162c66e8d24d04657934081074e91f856ce57 | [
"MIT"
] | null | null | null | include/robot/devices/timer_class.hpp | 1069B/TBD_Code | 624162c66e8d24d04657934081074e91f856ce57 | [
"MIT"
] | null | null | null | #include "robot/robot_main.hpp"
#ifndef TIMER_CLASS_H
#define TIMER_CLASS_H
class Timer{
private:
int m_current_time{0};
int m_reset_time{0};
int m_previous_lap_time{0};
std::vector<int> m_average_lap_vector;
int m_action_flag{INT_MAX};
bool m_stopped{false};
int m_stop_time{0};
public:
/* Constuctors */
Timer();
/* Getting Function */
int get_absolute_time();
int get_elapsed_time();
int get_current_lap_time();
double get_average_lap_time();// Last 10 laps
bool get_preform_action();
/* Setter Function */
void set_timer(int const p_timer){ m_reset_time -= get_absolute_time() - p_timer; };
void set_flag_delay(int const p_delay){ m_action_flag = get_absolute_time() + p_delay; };
void set_flag_absolute_time(int const p_absolute_time_flag){ m_action_flag = p_absolute_time_flag; };
void set_flag_elapsed_time(int const p_elapsed_time_flag){ set_flag_delay(p_elapsed_time_flag - get_elapsed_time()); };
/* Action Functions */
void reset_timer();
void stop_timer();
void resume_timer();
};
#endif // TIMER_CLASS_H
| 21.78 | 121 | 0.730946 | [
"vector"
] |
df4cc8344957f886bef649c6e240de5716ea5957 | 2,370 | cpp | C++ | examples/example_collider.cpp | claby2/valiant | d932574fe1f424c444a09ac99ae53fa2c7c4a9ac | [
"MIT"
] | null | null | null | examples/example_collider.cpp | claby2/valiant | d932574fe1f424c444a09ac99ae53fa2c7c4a9ac | [
"MIT"
] | null | null | null | examples/example_collider.cpp | claby2/valiant | d932574fe1f424c444a09ac99ae53fa2c7c4a9ac | [
"MIT"
] | null | null | null | #include "../valiant/valiant.hpp"
class Player : public valiant::Object,
public valiant::Rectangle,
public valiant::Collider {
public:
Player() : move_speed_(300), w_(false), a_(false), s_(false), d_(false) {}
void start() override {
shape.width = 50;
shape.height = 50;
shape.color.r = 255;
shape.color.g = 0;
shape.color.b = 255;
shape.color.a = 255;
}
void update() override {
if (input.get_key("W")) {
w_ = true;
}
if (input.get_key("A")) {
a_ = true;
}
if (input.get_key("S")) {
s_ = true;
}
if (input.get_key("D")) {
d_ = true;
}
if (input.get_key_up("W")) {
w_ = false;
}
if (input.get_key_up("A")) {
a_ = false;
}
if (input.get_key_up("S")) {
s_ = false;
}
if (input.get_key_up("D")) {
d_ = false;
}
move();
}
void on_collision_stay(const valiant::Collision &collision) override {
shape.color.g = 255;
}
void on_collision_exit(const valiant::Collision &collision) override {
shape.color.g = 0;
}
private:
const float move_speed_;
bool w_;
bool a_;
bool s_;
bool d_;
void move() {
float delta = move_speed_ * time.delta_time;
if (w_) {
transform.position.y -= delta;
}
if (a_) {
transform.position.x -= delta;
}
if (s_) {
transform.position.y += delta;
}
if (d_) {
transform.position.x += delta;
}
}
};
class RectangleObject : public valiant::Object,
public valiant::Rectangle,
public valiant::Collider {
public:
void start() override {
shape.width = 100;
shape.height = 100;
shape.color.r = 255;
shape.color.g = 0;
shape.color.b = 0;
shape.color.a = 255;
transform.position.x = -75;
}
};
int main() {
valiant::Renderer renderer(valiant::ENABLE | valiant::VSYNC);
Player player;
RectangleObject rectangle_object;
renderer.add_object(player);
renderer.add_object(rectangle_object);
renderer.run();
}
| 23.465347 | 78 | 0.494093 | [
"object",
"shape",
"transform"
] |
df4fdeef8218fd45db80fb95fddb4c2ec17c56cc | 1,059 | hpp | C++ | print.hpp | wincentbalin/DDB | c3aa2d4413fb32d5d9fbeef651041206b6ffd462 | [
"MIT"
] | null | null | null | print.hpp | wincentbalin/DDB | c3aa2d4413fb32d5d9fbeef651041206b6ffd462 | [
"MIT"
] | 11 | 2021-02-11T07:24:22.000Z | 2021-02-11T07:27:55.000Z | print.hpp | wincentbalin/DDB | c3aa2d4413fb32d5d9fbeef651041206b6ffd462 | [
"MIT"
] | null | null | null | /**
* print.hpp
*
* Printing include part of Disc Data Base.
*
* Copyright (c) 2010-2011 Wincent Balin
*
* Based upon ddb.pl, created years before and serving faithfully until today.
*
* Uses SQLite database version 3.
*
* Published under MIT license. See LICENSE file for further information.
*/
#ifndef PRINT_HPP
#define PRINT_HPP
#include <string>
#include <vector>
class Print
{
public:
enum Verbosity
{
CRITICAL = 0,
INFO = 1,
VERBOSE = 2,
DEBUG = 3,
VERBOSE_DEBUG = 4
};
Print(enum Verbosity verbosity = CRITICAL);
virtual ~Print();
enum Verbosity get_verbosity(void);
void msg(const char* text, enum Verbosity message_verbosity);
void add_disc(const char* disc_name);
void add_directory(const char* disc_name, const char* directory);
void add_file(const char* disc_name, const char* directory, const char* file);
void output(void);
private:
enum Verbosity specified_verbosity;
std::vector<std::string> results;
};
#endif /* PRINT_HPP */
| 23.021739 | 82 | 0.668555 | [
"vector"
] |
df5104dd9e5be800f22e1da0198631affcbd34d1 | 32,332 | cpp | C++ | src/steadystateproblem.cpp | kristianmeyerr/AMICI | 15f14c24b781daf5ceb3606d79edbbf57155a043 | [
"CC0-1.0"
] | null | null | null | src/steadystateproblem.cpp | kristianmeyerr/AMICI | 15f14c24b781daf5ceb3606d79edbbf57155a043 | [
"CC0-1.0"
] | null | null | null | src/steadystateproblem.cpp | kristianmeyerr/AMICI | 15f14c24b781daf5ceb3606d79edbbf57155a043 | [
"CC0-1.0"
] | null | null | null | #include "amici/steadystateproblem.h"
#include "amici/backwardproblem.h"
#include "amici/defines.h"
#include "amici/edata.h"
#include "amici/forwardproblem.h"
#include "amici/misc.h"
#include "amici/model.h"
#include "amici/newton_solver.h"
#include "amici/solver.h"
#include "amici/solver_cvodes.h"
#include <cmath>
#include <cstring>
#include <ctime>
#include <cvodes/cvodes.h>
#include <memory>
#include <sundials/sundials_dense.h>
constexpr realtype conv_thresh = 1.0;
namespace amici {
SteadystateProblem::SteadystateProblem(const Solver &solver, const Model &model)
: delta_(model.nx_solver), delta_old_(model.nx_solver),
ewt_(model.nx_solver), ewtQB_(model.nplist()),
x_old_(model.nx_solver), xdot_(model.nx_solver),
sdx_(model.nx_solver, model.nplist()), xB_(model.nJ * model.nx_solver),
xQ_(model.nJ * model.nx_solver), xQB_(model.nplist()),
xQBdot_(model.nplist()), max_steps_(solver.getNewtonMaxSteps()),
dJydx_(model.nJ * model.nx_solver * model.nt(), 0.0),
state_({INFINITY, // t
AmiVector(model.nx_solver), // x
AmiVector(model.nx_solver), // dx
AmiVectorArray(model.nx_solver, model.nplist()), // sx
model.getModelState()}), // state
atol_(solver.getAbsoluteToleranceSteadyState()),
rtol_(solver.getRelativeToleranceSteadyState()),
atol_sensi_(solver.getAbsoluteToleranceSteadyStateSensi()),
rtol_sensi_(solver.getRelativeToleranceSteadyStateSensi()),
atol_quad_(solver.getAbsoluteToleranceQuadratures()),
rtol_quad_(solver.getRelativeToleranceQuadratures()),
newton_solver_(NewtonSolver::getSolver(solver, model)),
damping_factor_mode_(solver.getNewtonDampingFactorMode()),
damping_factor_lower_bound_(solver.getNewtonDampingFactorLowerBound()),
newton_step_conv_(solver.getNewtonStepSteadyStateCheck()),
check_sensi_conv_(solver.getSensiSteadyStateCheck()) {
/* Check for compatibility of options */
if (solver.getSensitivityMethod() == SensitivityMethod::forward &&
solver.getSensitivityMethodPreequilibration() ==
SensitivityMethod::adjoint &&
solver.getSensitivityOrder() > SensitivityOrder::none)
throw AmiException("Preequilibration using adjoint sensitivities "
"is not compatible with using forward "
"sensitivities during simulation");
}
void SteadystateProblem::workSteadyStateProblem(const Solver &solver,
Model &model,
int it) {
initializeForwardProblem(it, solver, model);
/* Compute steady state, track computation time */
clock_t starttime = clock();
findSteadyState(solver, model, it);
cpu_time_ = (double)((clock() - starttime) * 1000) / CLOCKS_PER_SEC;
/* Check whether state sensis still need to be computed */
if (getSensitivityFlag(model, solver, it,
SteadyStateContext::newtonSensi)) {
try {
/* this might still fail, if the Jacobian is singular and
simulation did not find a steady state */
newton_solver_->computeNewtonSensis(state_.sx, model, state_);
} catch (NewtonFailure const &) {
throw AmiException(
"Steady state sensitivity computation failed due "
"to unsuccessful factorization of RHS Jacobian");
}
}
}
void SteadystateProblem::workSteadyStateBackwardProblem(
const Solver &solver, Model &model, const BackwardProblem *bwd) {
if (!initializeBackwardProblem(solver, model, bwd))
return;
/* compute quadratures, track computation time */
clock_t starttime = clock();
computeSteadyStateQuadrature(solver, model);
cpu_timeB_ = (double)((clock() - starttime) * 1000) / CLOCKS_PER_SEC;
}
void SteadystateProblem::findSteadyState(const Solver &solver, Model &model,
int it) {
steady_state_status_.resize(3, SteadyStateStatus::not_run);
bool turnOffNewton = model.getSteadyStateSensitivityMode() ==
SteadyStateSensitivityMode::integrationOnly &&
((it == -1 && solver.getSensitivityMethodPreequilibration() ==
SensitivityMethod::forward) || solver.getSensitivityMethod() ==
SensitivityMethod::forward);
/* First, try to run the Newton solver */
if (!turnOffNewton)
findSteadyStateByNewtonsMethod(model, false);
/* Newton solver didn't work, so try to simulate to steady state */
if (!checkSteadyStateSuccess())
findSteadyStateBySimulation(solver, model, it);
/* Simulation didn't work, retry the Newton solver from last sim state. */
if (!turnOffNewton && !checkSteadyStateSuccess())
findSteadyStateByNewtonsMethod(model, true);
/* Nothing worked, throw an as informative error as possible */
if (!checkSteadyStateSuccess())
handleSteadyStateFailure();
}
void SteadystateProblem::findSteadyStateByNewtonsMethod(Model &model,
bool newton_retry) {
int ind = newton_retry ? 2 : 0;
try {
applyNewtonsMethod(model, newton_retry);
steady_state_status_[ind] = SteadyStateStatus::success;
} catch (NewtonFailure const &ex) {
/* nothing to be done */
switch (ex.error_code) {
case AMICI_TOO_MUCH_WORK:
steady_state_status_[ind] = SteadyStateStatus::failed_convergence;
break;
case AMICI_NO_STEADY_STATE:
steady_state_status_[ind] =
SteadyStateStatus::failed_too_long_simulation;
break;
case AMICI_SINGULAR_JACOBIAN:
steady_state_status_[ind] = SteadyStateStatus::failed_factorization;
break;
case AMICI_DAMPING_FACTOR_ERROR:
steady_state_status_[ind] = SteadyStateStatus::failed_damping;
break;
default:
steady_state_status_[ind] = SteadyStateStatus::failed;
break;
}
}
}
void SteadystateProblem::findSteadyStateBySimulation(const Solver &solver,
Model &model, int it) {
try {
if (it < 0) {
/* Preequilibration? -> Create a new solver instance for sim */
bool integrateSensis = getSensitivityFlag(
model, solver, it, SteadyStateContext::solverCreation);
auto newtonSimSolver = createSteadystateSimSolver(
solver, model, integrateSensis, false);
runSteadystateSimulation(*newtonSimSolver, model, false);
} else {
/* Solver was already created, use this one */
runSteadystateSimulation(solver, model, false);
}
steady_state_status_[1] = SteadyStateStatus::success;
} catch (NewtonFailure const &ex) {
switch (ex.error_code) {
case AMICI_TOO_MUCH_WORK:
steady_state_status_[1] = SteadyStateStatus::failed_convergence;
break;
case AMICI_NO_STEADY_STATE:
steady_state_status_[1] =
SteadyStateStatus::failed_too_long_simulation;
break;
default:
model.app->warningF("AMICI:newton",
"AMICI newton method failed: %s\n", ex.what());
steady_state_status_[1] = SteadyStateStatus::failed;
}
} catch (AmiException const &ex) {
model.app->warningF("AMICI:equilibration",
"AMICI equilibration failed: %s\n", ex.what());
steady_state_status_[1] = SteadyStateStatus::failed;
}
}
void SteadystateProblem::initializeForwardProblem(int it, const Solver &solver,
Model &model) {
newton_solver_->reinitialize();
/* process solver handling for pre- or postequilibration */
if (it == -1) {
/* solver was not run before, set up everything */
model.initialize(state_.x, state_.dx, state_.sx, sdx_,
solver.getSensitivityOrder() >=
SensitivityOrder::first);
state_.t = model.t0();
solver.setup(state_.t, &model, state_.x, state_.dx, state_.sx, sdx_);
} else {
/* solver was run before, extract current state from solver */
solver.writeSolution(&state_.t, state_.x, state_.dx, state_.sx, xQ_);
}
/* overwrite starting timepoint */
if (it < 1) /* No previous time point computed, set t = t0 */
state_.t = model.t0();
else /* Carry on simulating from last point */
state_.t = model.getTimepoint(it - 1);
state_.state = model.getModelState();
flagUpdatedState();
}
bool SteadystateProblem::initializeBackwardProblem(const Solver &solver,
Model &model,
const BackwardProblem *bwd) {
newton_solver_->reinitialize();
/* note that state_ is still set from forward run */
if (bwd) {
/* preequilibration */
if (solver.getSensitivityMethodPreequilibration() !=
SensitivityMethod::adjoint)
return false; /* if not adjoint mode, there's nothing to do */
/* If we need to reinitialize solver states, this won't work yet. */
if (model.nx_reinit() > 0)
throw NewtonFailure(
AMICI_NOT_IMPLEMENTED,
"Adjoint preequilibration with reinitialization of "
"non-constant states is not yet implemented. Stopping.");
solver.reInit(state_.t, state_.x, state_.dx);
solver.updateAndReinitStatesAndSensitivities(&model);
xB_.copy(bwd->getAdjointState());
}
/* postequilibration does not need a reInit */
/* initialize quadratures */
xQ_.zero();
xQB_.zero();
xQBdot_.zero();
return true;
}
void SteadystateProblem::computeSteadyStateQuadrature(const Solver &solver,
Model &model) {
/* This routine computes the quadratures:
xQB = Integral[ xB(x(t), t, p) * dxdot/dp(x(t), t, p) | dt ]
As we're in steady state, we have x(t) = x_ss (x_steadystate), hence
xQB = Integral[ xB(x_ss, t, p) | dt ] * dxdot/dp(x_ss, t, p)
We therefore compute the integral over xB first and then do a
matrix-vector multiplication */
auto sensitivityMode = model.getSteadyStateSensitivityMode();
/* Try to compute the analytical solution for quadrature algebraically */
if (sensitivityMode == SteadyStateSensitivityMode::newtonOnly
|| sensitivityMode == SteadyStateSensitivityMode::integrateIfNewtonFails)
getQuadratureByLinSolve(model);
/* Perform simulation */
if (sensitivityMode == SteadyStateSensitivityMode::integrationOnly ||
(sensitivityMode == SteadyStateSensitivityMode::integrateIfNewtonFails
&& !hasQuadrature()))
getQuadratureBySimulation(solver, model);
/* If analytic solution and integration did not work, throw an Exception */
if (!hasQuadrature())
throw AmiException(
"Steady state backward computation failed: Linear "
"system could not be solved (possibly due to singular Jacobian), "
"and numerical integration did not equilibrate within maxsteps");
}
void SteadystateProblem::getQuadratureByLinSolve(Model &model) {
/* Computes the integral over the adjoint state xB:
If the Jacobian has full rank, this has an analytical solution, since
d/dt[ xB(t) ] = JB^T(x(t), p) xB(t) = JB^T(x_ss, p) xB(t)
This linear ODE system with time-constant matrix has the solution
xB(t) = exp( t * JB^T(x_ss, p) ) * xB(0)
This integral xQ over xB is given as the solution of
JB^T(x_ss, p) * xQ = xB(0)
So we first try to solve the linear system, if possible. */
/* copy content of xB into vector with integral */
xQ_.copy(xB_);
/* try to solve the linear system */
try {
/* compute integral over xB and write to xQ */
newton_solver_->prepareLinearSystemB(model, state_);
newton_solver_->solveLinearSystem(xQ_);
/* Compute the quadrature as the inner product xQ * dxdotdp */
computeQBfromQ(model, xQ_, xQB_);
/* set flag that quadratures is available (for processing in rdata) */
hasQuadrature_ = true;
/* Finalize by setting adjoint state to zero (its steady state) */
xB_.zero();
} catch (NewtonFailure const &) {
hasQuadrature_ = false;
}
}
void SteadystateProblem::getQuadratureBySimulation(const Solver &solver,
Model &model) {
/* If the Jacobian is singular, the integral over xB must be computed
by usual integration over time, but simplifications can be applied:
x is not time dependent, no forward trajectory is needed. */
/* set starting timepoint for the simulation solver */
state_.t = model.t0();
/* xQ was written in getQuadratureByLinSolve() -> set to zero */
xQ_.zero();
/* create a new solver object */
auto simSolver = createSteadystateSimSolver(solver, model, false, true);
/* perform integration and quadrature */
try {
runSteadystateSimulation(*simSolver, model, true);
hasQuadrature_ = true;
} catch (NewtonFailure const &) {
hasQuadrature_ = false;
}
}
[[noreturn]] void SteadystateProblem::handleSteadyStateFailure() {
/* Throw error message according to error codes */
std::string errorString = "Steady state computation failed. "
"First run of Newton solver failed";
writeErrorString(&errorString, steady_state_status_[0]);
errorString.append(" Simulation to steady state failed");
writeErrorString(&errorString, steady_state_status_[1]);
errorString.append(" Second run of Newton solver failed");
writeErrorString(&errorString, steady_state_status_[2]);
throw AmiException(errorString.c_str());
}
void SteadystateProblem::writeErrorString(std::string *errorString,
SteadyStateStatus status) const {
/* write error message according to steady state status */
switch (status) {
case SteadyStateStatus::failed_too_long_simulation:
(*errorString)
.append(": System could not be equilibrated via"
" simulating to a late time point.");
break;
case SteadyStateStatus::failed_damping:
(*errorString).append(": Damping factor reached lower bound.");
break;
case SteadyStateStatus::failed_factorization:
(*errorString).append(": RHS could not be factorized.");
break;
case SteadyStateStatus::failed_convergence:
(*errorString).append(": No convergence was achieved.");
break;
case SteadyStateStatus::failed:
(*errorString).append(".");
break;
default:
break;
}
}
bool SteadystateProblem::getSensitivityFlag(const Model &model,
const Solver &solver, int it,
SteadyStateContext context) {
/* We need to check whether we need to compute forward sensitivities.
Depending on the situation (pre-/postequilibration) and the solver
settings, the logic may be involved and is handled here.
Most of these boolean operation could be simplified. However,
clarity is more important than brevity. */
/* Are we running in preequilibration (and hence create)? */
bool preequilibration = (it == -1);
/* Have we maybe already computed forward sensitivities? */
bool forwardSensisAlreadyComputed =
solver.getSensitivityOrder() >= SensitivityOrder::first &&
steady_state_status_[1] == SteadyStateStatus::success &&
(model.getSteadyStateSensitivityMode() ==
SteadyStateSensitivityMode::integrationOnly ||
model.getSteadyStateSensitivityMode() ==
SteadyStateSensitivityMode::integrateIfNewtonFails);
bool simulationStartedInSteadystate =
steady_state_status_[0] == SteadyStateStatus::success &&
numsteps_[0] == 0;
/* Do we need forward sensis for postequilibration? */
bool needForwardSensisPosteq =
!preequilibration && !forwardSensisAlreadyComputed &&
solver.getSensitivityOrder() >= SensitivityOrder::first &&
solver.getSensitivityMethod() == SensitivityMethod::forward;
/* Do we need forward sensis for preequilibration? */
bool needForwardSensisPreeq =
preequilibration && !forwardSensisAlreadyComputed &&
solver.getSensitivityMethodPreequilibration() ==
SensitivityMethod::forward &&
solver.getSensitivityOrder() >= SensitivityOrder::first;
/* Do we need to do the linear system solve to get forward sensitivities? */
bool needForwardSensisNewton =
(needForwardSensisPreeq || needForwardSensisPosteq) &&
!simulationStartedInSteadystate;
/* When we're creating a new solver object */
bool needForwardSensiAtCreation =
needForwardSensisPreeq &&
(model.getSteadyStateSensitivityMode() ==
SteadyStateSensitivityMode::integrationOnly ||
model.getSteadyStateSensitivityMode() ==
SteadyStateSensitivityMode::integrateIfNewtonFails
);
/* Check if we need to store sensis */
switch (context) {
case SteadyStateContext::newtonSensi:
return needForwardSensisNewton;
case SteadyStateContext::sensiStorage:
return needForwardSensisNewton || forwardSensisAlreadyComputed ||
simulationStartedInSteadystate;
case SteadyStateContext::solverCreation:
return needForwardSensiAtCreation;
default:
throw AmiException("Requested invalid context in sensitivity "
"processing during steady state computation");
}
}
realtype SteadystateProblem::getWrmsNorm(const AmiVector &x,
const AmiVector &xdot, realtype atol,
realtype rtol, AmiVector &ewt) const {
/* Depending on what convergence we want to check (xdot, sxdot, xQBdot)
we need to pass ewt[QB], as xdot and xQBdot have different sizes */
/* ewt = x */
N_VAbs(const_cast<N_Vector>(x.getNVector()), ewt.getNVector());
/* ewt *= rtol */
N_VScale(rtol, ewt.getNVector(), ewt.getNVector());
/* ewt += atol */
N_VAddConst(ewt.getNVector(), atol, ewt.getNVector());
/* ewt = 1/ewt (ewt = 1/(rtol*x+atol)) */
N_VInv(ewt.getNVector(), ewt.getNVector());
/* wrms = sqrt(sum((xdot/ewt)**2)/n) where n = size of state vector */
return N_VWrmsNorm(const_cast<N_Vector>(xdot.getNVector()),
ewt.getNVector());
}
realtype SteadystateProblem::getWrms(Model &model,
SensitivityMethod sensi_method) {
realtype wrms = INFINITY;
if (sensi_method == SensitivityMethod::adjoint) {
/* In the adjoint case, only xQB contributes to the gradient, the exact
steadystate is less important, as xB = xQdot may even not converge
to zero at all. So we need xQBdot, hence compute xQB first. */
computeQBfromQ(model, xQ_, xQB_);
computeQBfromQ(model, xB_, xQBdot_);
if (newton_step_conv_)
throw NewtonFailure(
AMICI_NOT_IMPLEMENTED,
"Newton type convergence check is not implemented for adjoint "
"steady state computations. Stopping.");
wrms = getWrmsNorm(xQB_, xQBdot_, atol_quad_, rtol_quad_, ewtQB_);
} else {
/* If we're doing a forward simulation (with or without sensitivities:
Get RHS and compute weighted error norm */
if (newton_step_conv_)
getNewtonStep(model);
else
updateRightHandSide(model);
wrms = getWrmsNorm(state_.x, newton_step_conv_ ? delta_ : xdot_,
atol_, rtol_, ewt_);
}
return wrms;
}
realtype SteadystateProblem::getWrmsFSA(Model &model) {
/* Forward sensitivities: Compute weighted error norm for their RHS */
realtype wrms = 0.0;
/* we don't need to call prepareLinearSystem in this function, since it was
already computed in the preceding getWrms call and both equations have the
same jacobian */
xdot_updated_ = false;
for (int ip = 0; ip < model.nplist(); ++ip) {
model.fsxdot(state_.t, state_.x, state_.dx, ip, state_.sx[ip],
state_.dx, xdot_);
if (newton_step_conv_)
newton_solver_->solveLinearSystem(xdot_);
wrms =
getWrmsNorm(state_.sx[ip], xdot_, atol_sensi_, rtol_sensi_, ewt_);
/* ideally this function would report the maximum of all wrms over
all ip, but for practical purposes we can just report the wrms for
the first ip where we know that the convergence threshold is not
satisfied. */
if (wrms > conv_thresh)
break;
}
/* just report the parameter for the last ip, value doesn't matter it's
only important that all of them satisfy the convergence threshold */
return wrms;
}
bool SteadystateProblem::checkSteadyStateSuccess() const {
/* Did one of the attempts yield s steady state? */
return std::any_of(steady_state_status_.begin(), steady_state_status_.end(),
[](SteadyStateStatus status) {
return status == SteadyStateStatus::success;
});
}
void SteadystateProblem::applyNewtonsMethod(Model &model, bool newton_retry) {
int &i_newtonstep = numsteps_.at(newton_retry ? 2 : 0);
i_newtonstep = 0;
gamma_ = 1.0;
bool update_direction = true;
bool step_successful = false;
if (model.nx_solver == 0)
return;
/* initialize output of linear solver for Newton step */
delta_.zero();
x_old_.copy(state_.x);
bool converged = false;
wrms_ = getWrms(model, SensitivityMethod::none);
converged = newton_retry ? false : wrms_ < conv_thresh;
while (!converged && i_newtonstep < max_steps_) {
/* If Newton steps are necessary, compute the initial search
direction */
if (update_direction) {
getNewtonStep(model);
/* we store delta_ here as later convergence checks may
update it */
delta_old_.copy(delta_);
}
/* Try step with new gamma_/delta_ */
linearSum(1.0, x_old_, gamma_,
update_direction ? delta_ : delta_old_, state_.x);
flagUpdatedState();
/* Compute new xdot and residuals */
realtype wrms_tmp = getWrms(model, SensitivityMethod::none);
step_successful = wrms_tmp < wrms_;
if (step_successful) {
/* If new residuals are smaller than old ones, update state */
wrms_ = wrms_tmp;
/* precheck convergence */
converged = wrms_ < conv_thresh;
if (converged) {
converged = makePositiveAndCheckConvergence(model);
}
/* update x_old_ _after_ positivity was enforced */
x_old_.copy(state_.x);
}
update_direction = updateDampingFactor(step_successful);
/* increase step counter */
i_newtonstep++;
}
if (!converged)
throw NewtonFailure(AMICI_TOO_MUCH_WORK, "applyNewtonsMethod");
}
bool SteadystateProblem::makePositiveAndCheckConvergence(Model &model) {
/* Ensure positivity of the found state and recheck if
the convergence still holds */
auto nonnegative = model.getStateIsNonNegative();
for (int ix = 0; ix < model.nx_solver; ix++) {
if (state_.x[ix] < 0.0 && nonnegative[ix]) {
state_.x[ix] = 0.0;
flagUpdatedState();
}
}
wrms_ = getWrms(model, SensitivityMethod::none);
return wrms_ < conv_thresh;
}
bool SteadystateProblem::updateDampingFactor(bool step_successful) {
if (damping_factor_mode_ != NewtonDampingFactorMode::on)
return true;
if (step_successful)
gamma_ = fmin(1.0, 2.0 * gamma_);
else
gamma_ = gamma_ / 4.0;
if (gamma_ < damping_factor_lower_bound_)
throw NewtonFailure(AMICI_DAMPING_FACTOR_ERROR,
"Newton solver failed: the damping factor "
"reached its lower bound");
return step_successful;
}
void SteadystateProblem::runSteadystateSimulation(const Solver &solver,
Model &model, bool backward) {
if (model.nx_solver == 0)
return;
/* Loop over steps and check for convergence
NB: This function is used for forward and backward simulation, and may
be called by workSteadyStateProblem and workSteadyStateBackwardProblem.
Whether we simulate forward or backward in time is reflected by the
flag "backward". */
/* Do we also have to check for convergence of sensitivities? */
SensitivityMethod sensitivityFlag = SensitivityMethod::none;
if (solver.getSensitivityOrder() > SensitivityOrder::none &&
solver.getSensitivityMethod() == SensitivityMethod::forward)
sensitivityFlag = SensitivityMethod::forward;
/* If flag for forward sensitivity computation by simulation is not set,
disable forward sensitivity integration. Sensitivities will be computed
by newtonsolver.computeNewtonSensis then */
if (model.getSteadyStateSensitivityMode() ==
SteadyStateSensitivityMode::newtonOnly) {
solver.switchForwardSensisOff();
sensitivityFlag = SensitivityMethod::none;
}
if (backward)
sensitivityFlag = SensitivityMethod::adjoint;
/* If run after Newton's method checks again if it converged */
wrms_ = getWrms(model, sensitivityFlag);
int sim_steps = 0;
int convergence_check_frequency = 1;
if (newton_step_conv_)
convergence_check_frequency = 25;
while (true) {
/* One step of ODE integration
reason for tout specification:
max with 1 ensures correct direction (any positive value would do)
multiplication with 10 ensures nonzero difference and should ensure
stable computation value is not important for AMICI_ONE_STEP mode,
only direction w.r.t. current t
*/
solver.step(std::max(state_.t, 1.0) * 10);
if (backward) {
solver.writeSolution(&state_.t, xB_, state_.dx, state_.sx, xQ_);
} else {
solver.writeSolution(&state_.t, state_.x, state_.dx, state_.sx,
xQ_);
flagUpdatedState();
}
try {
/* Check for convergence */
wrms_ = getWrms(model, sensitivityFlag);
/* getWrms needs to be called before getWrmsFSA such that the linear
system is prepared for newton type convergence check */
if (wrms_ < conv_thresh && check_sensi_conv_ &&
sensitivityFlag == SensitivityMethod::forward &&
sim_steps % convergence_check_frequency == 0) {
updateSensiSimulation(solver);
wrms_ = getWrmsFSA(model);
}
} catch (NewtonFailure const &) {
/* linear solves in getWrms failed */
numsteps_.at(1) = sim_steps;
throw;
}
if (wrms_ < conv_thresh)
break; // converged
/* increase counter, check for maxsteps */
sim_steps++;
if (sim_steps >= solver.getMaxSteps()) {
numsteps_.at(1) = sim_steps;
throw NewtonFailure(AMICI_TOO_MUCH_WORK,
"exceeded maximum number of steps");
}
if (state_.t >= 1e200) {
numsteps_.at(1) = sim_steps;
throw NewtonFailure(AMICI_NO_STEADY_STATE,
"simulated to late time"
" point without convergence of RHS");
}
}
// if check_sensi_conv_ is deactivated, we still have to update sensis
if (sensitivityFlag == SensitivityMethod::forward)
updateSensiSimulation(solver);
/* store information about steps and sensitivities, if necessary */
if (backward) {
numstepsB_ = sim_steps;
} else {
numsteps_.at(1) = sim_steps;
}
}
std::unique_ptr<Solver>
SteadystateProblem::createSteadystateSimSolver(const Solver &solver,
Model &model, bool forwardSensis,
bool backward) const {
/* Create new CVode solver object */
auto sim_solver = std::unique_ptr<Solver>(solver.clone());
switch (solver.getLinearSolver()) {
case LinearSolver::dense:
break;
case LinearSolver::KLU:
break;
default:
throw NewtonFailure(AMICI_NOT_IMPLEMENTED,
"invalid solver for steadystate simulation");
}
/* do we need sensitivities? */
if (forwardSensis) {
/* need forward to compute sx0 */
sim_solver->setSensitivityMethod(SensitivityMethod::forward);
} else {
sim_solver->setSensitivityMethod(SensitivityMethod::none);
sim_solver->setSensitivityOrder(SensitivityOrder::none);
}
/* use x and sx as dummies for dx and sdx
(they wont get touched in a CVodeSolver) */
sim_solver->setup(model.t0(), &model, state_.x, state_.dx, state_.sx, sdx_);
if (backward) {
sim_solver->setup(model.t0(), &model, xB_, xB_, state_.sx, sdx_);
sim_solver->setupSteadystate(model.t0(), &model, state_.x, state_.dx,
xB_, xB_, xQ_);
} else {
sim_solver->setup(model.t0(), &model, state_.x, state_.dx, state_.sx,
sdx_);
}
return sim_solver;
}
void SteadystateProblem::computeQBfromQ(Model &model, const AmiVector &yQ,
AmiVector &yQB) const {
/* Compute the quadrature as the inner product: yQB = dxdotdp * yQ */
/* set to zero first, as multiplication adds to existing value */
yQB.zero();
/* multiply */
if (model.pythonGenerated) {
/* fill dxdotdp with current values */
const auto &plist = model.getParameterList();
model.fdxdotdp(state_.t, state_.x, state_.dx);
model.get_dxdotdp_full().multiply(yQB.getNVector(), yQ.getNVector(),
plist, true);
} else {
for (int ip = 0; ip < model.nplist(); ++ip)
yQB[ip] = dotProd(yQ, model.get_dxdotdp()[ip]);
}
}
void SteadystateProblem::getAdjointUpdates(Model &model, const ExpData &edata) {
xB_.zero();
for (int it = 0; it < model.nt(); it++) {
if (std::isinf(model.getTimepoint(it))) {
model.getAdjointStateObservableUpdate(
slice(dJydx_, it, model.nx_solver * model.nJ), it, state_.x,
edata);
for (int ix = 0; ix < model.nxtrue_solver; ix++)
xB_[ix] += dJydx_[ix + it * model.nx_solver];
}
}
}
void SteadystateProblem::flagUpdatedState() {
xdot_updated_ = false;
delta_updated_ = false;
sensis_updated_ = false;
}
void SteadystateProblem::updateSensiSimulation(const Solver &solver) {
if (sensis_updated_)
return;
state_.sx = solver.getStateSensitivity(state_.t);
sensis_updated_ = true;
}
void SteadystateProblem::updateRightHandSide(Model &model) {
if (xdot_updated_)
return;
model.fxdot(state_.t, state_.x, state_.dx, xdot_);
xdot_updated_ = true;
}
void SteadystateProblem::getNewtonStep(Model &model) {
if (delta_updated_)
return;
updateRightHandSide(model);
delta_.copy(xdot_);
newton_solver_->getStep(delta_, model, state_);
delta_updated_ = true;
}
} // namespace amici
| 40.26401 | 81 | 0.626438 | [
"object",
"vector",
"model"
] |
df5f0bc30e5be7a01c69f53c7aa86d936e8240ef | 24,235 | cpp | C++ | src/rpcWiFiGeneric.cpp | aeternam-eng/Seeed_Arduino_rpcWiFi | 23fd20f70cc91959d538b3136dd52a09876af37c | [
"MIT"
] | null | null | null | src/rpcWiFiGeneric.cpp | aeternam-eng/Seeed_Arduino_rpcWiFi | 23fd20f70cc91959d538b3136dd52a09876af37c | [
"MIT"
] | null | null | null | src/rpcWiFiGeneric.cpp | aeternam-eng/Seeed_Arduino_rpcWiFi | 23fd20f70cc91959d538b3136dd52a09876af37c | [
"MIT"
] | null | null | null | /*
ESP8266WiFiGeneric.cpp - rpcWiFi library for esp8266
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "rpcWiFi.h"
#include "rpcWiFiGeneric.h"
extern "C"
{
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include "new_lwip/ip_addr.h"
#include "new_lwip/opt.h"
#include "new_lwip/err.h"
#include "new_lwip/dns.h"
} //extern "C"
#include <vector>
// static xQueueHandle _network_event_queue;
// static TaskHandle_t _network_event_task_handle = NULL;
static EventGroupHandle_t _network_event_group = NULL;
rpc_wifi_mode_t rpcWiFiGenericClass::_wifi_mode = RPC_WIFI_MODE_NULL;
rpc_wifi_power_t rpcWiFiGenericClass::_wifi_power = RPC_WIFI_POWER_19_5dBm;
// static void _network_event_task(void * arg){
// rpc_system_event_t *event = NULL;
// for (;;) {
// if(xQueueReceive(_network_event_queue, &event, portMAX_DELAY) == pdTRUE){
// WiFiGenericClass::_eventCallback(arg, event);
// }
// }
// vTaskDelete(NULL);
// _network_event_task_handle = NULL;
// }
// static esp_err_t _network_event_cb(void *arg, rpc_system_event_t *event){
// if (xQueueSend(_network_event_queue, &event, portMAX_DELAY) != pdPASS) {
// log_w("Network Event Queue Send Failed!");
// return ESP_FAIL;
// }
// return ESP_OK;
// }
// static bool _start_network_event_task(){
// if(!_network_event_group){
// _network_event_group = xEventGroupCreate();
// if(!_network_event_group){
// log_e("Network Event Group Create Failed!");
// return false;
// }
// xEventGroupSetBits(_network_event_group, RPC_WIFI_DNS_IDLE_BIT);
// }
// if(!_network_event_queue){
// _network_event_queue = xQueueCreate(32, sizeof(rpc_system_event_t *));
// if(!_network_event_queue){
// log_e("Network Event Queue Create Failed!");
// return false;
// }
// }
// if(!_network_event_task_handle){
// xTaskCreateUniversal(_network_event_task, "network_event", 4096, NULL, ESP_TASKD_EVENT_PRIO - 1, &_network_event_task_handle, CONFIG_ARDUINO_EVENT_RUNNING_CORE);
// if(!_network_event_task_handle){
// log_e("Network Event Task Start Failed!");
// return false;
// }
// }
// //TODO
// return true;
// //return rpc_esp_event_loop_init(&_network_event_cb, NULL) == ESP_OK;
// }
int htoi(const char *s)
{
int i;
int n = 0;
if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
{
i = 2;
}
else
{
i = 0;
}
for (; (s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z'); ++i)
{
if (tolower(s[i]) > '9')
{
n = 16 * n + (10 + tolower(s[i]) - 'a');
}
else
{
n = 16 * n + (tolower(s[i]) - '0');
}
}
return n;
}
void new_tcpipInit()
{
static bool initialized = false;
if (!initialized)
{
initialized = true;
}
}
static bool lowLevelInitDone = false;
static bool wifiLowLevelInit(bool persistent)
{
if (!lowLevelInitDone)
{
if (!_network_event_group)
{
_network_event_group = xEventGroupCreate();
if (!_network_event_group)
{
log_e("Network Event Group Create Failed!");
return false;
}
xEventGroupSetBits(_network_event_group, RPC_WIFI_DNS_IDLE_BIT);
}
new_tcpip_adapter_init();
system_event_callback_reg(rpcWiFiGenericClass::_eventCallback);
lowLevelInitDone = true;
}
return true;
}
static bool wifiLowLevelDeinit()
{
//deinit not working yet!
wifi_off();
new_tcpip_adapter_stop(RPC_TCPIP_ADAPTER_IF_STA);
new_tcpip_adapter_stop(RPC_TCPIP_ADAPTER_IF_AP);
return true;
}
static bool _esp_wifi_started = false;
static bool espWiFiStart(bool persistent)
{
if (_esp_wifi_started)
{
return true;
}
if (!wifiLowLevelInit(persistent))
{
return false;
}
_esp_wifi_started = true;
rpc_system_event_t event;
event.event_id = RPC_SYSTEM_EVENT_WIFI_READY;
rpcWiFiGenericClass::_eventCallback(nullptr, &event);
return true;
}
static bool espWiFiStop()
{
if (!_esp_wifi_started)
{
return true;
}
_esp_wifi_started = false;
return wifiLowLevelDeinit();
}
// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------- Generic rpcWiFi function -----------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
typedef struct rpcWiFiEventCbList
{
static rpc_wifi_event_id_t current_id;
rpc_wifi_event_id_t id;
rpcWiFiEventCb cb;
rpcWiFiEventFuncCb fcb;
rpcWiFiEventSysCb scb;
rpc_system_event_id_t event;
rpcWiFiEventCbList() : id(current_id++), cb(NULL), fcb(NULL), scb(NULL), event(RPC_SYSTEM_EVENT_WIFI_READY) {}
} rpcWiFiEventCbList_t;
rpc_wifi_event_id_t rpcWiFiEventCbList::current_id = 1;
// arduino dont like std::vectors move static here
static std::vector<rpcWiFiEventCbList_t> cbEventList;
bool rpcWiFiGenericClass::_persistent = true;
rpc_wifi_mode_t rpcWiFiGenericClass::_forceSleepLastMode = RPC_WIFI_MODE_NULL;
rpcWiFiGenericClass::rpcWiFiGenericClass()
{
}
int rpcWiFiGenericClass::setStatusBits(int bits)
{
if (!_network_event_group)
{
return 0;
}
return xEventGroupSetBits(_network_event_group, bits);
}
int rpcWiFiGenericClass::clearStatusBits(int bits)
{
if (!_network_event_group)
{
return 0;
}
return xEventGroupClearBits(_network_event_group, bits);
}
int rpcWiFiGenericClass::getStatusBits()
{
if (!_network_event_group)
{
return 0;
}
return xEventGroupGetBits(_network_event_group);
}
int rpcWiFiGenericClass::waitStatusBits(int bits, uint32_t timeout_ms)
{
if (!_network_event_group)
{
return 0;
}
return xEventGroupWaitBits(
_network_event_group, // The event group being tested.
bits, // The bits within the event group to wait for.
pdFALSE, // BIT_0 and BIT_4 should be cleared before returning.
pdTRUE, // Don't wait for both bits, either bit will do.
timeout_ms / portTICK_PERIOD_MS) &
bits; // Wait a maximum of 100ms for either bit to be set.
}
/**
* set callback function
* @param cbEvent rpcWiFiEventCb
* @param event optional filter (WIFI_EVENT_MAX is all events)
*/
rpc_wifi_event_id_t rpcWiFiGenericClass::onEvent(rpcWiFiEventCb cbEvent, rpc_system_event_id_t event)
{
if (!cbEvent)
{
return 0;
}
rpcWiFiEventCbList_t newEventHandler;
newEventHandler.cb = cbEvent;
newEventHandler.fcb = NULL;
newEventHandler.scb = NULL;
newEventHandler.event = event;
cbEventList.push_back(newEventHandler);
return newEventHandler.id;
}
rpc_wifi_event_id_t rpcWiFiGenericClass::onEvent(rpcWiFiEventFuncCb cbEvent, rpc_system_event_id_t event)
{
if (!cbEvent)
{
return 0;
}
rpcWiFiEventCbList_t newEventHandler;
newEventHandler.cb = NULL;
newEventHandler.fcb = cbEvent;
newEventHandler.scb = NULL;
newEventHandler.event = event;
cbEventList.push_back(newEventHandler);
return newEventHandler.id;
}
rpc_wifi_event_id_t rpcWiFiGenericClass::onEvent(rpcWiFiEventSysCb cbEvent, rpc_system_event_id_t event)
{
if (!cbEvent)
{
return 0;
}
rpcWiFiEventCbList_t newEventHandler;
newEventHandler.cb = NULL;
newEventHandler.fcb = NULL;
newEventHandler.scb = cbEvent;
newEventHandler.event = event;
cbEventList.push_back(newEventHandler);
return newEventHandler.id;
}
/**
* removes a callback form event handler
* @param cbEvent rpcWiFiEventCb
* @param event optional filter (WIFI_EVENT_MAX is all events)
*/
void rpcWiFiGenericClass::removeEvent(rpcWiFiEventCb cbEvent, rpc_system_event_id_t event)
{
if (!cbEvent)
{
return;
}
for (uint32_t i = 0; i < cbEventList.size(); i++)
{
rpcWiFiEventCbList_t entry = cbEventList[i];
if (entry.cb == cbEvent && entry.event == event)
{
cbEventList.erase(cbEventList.begin() + i);
}
}
}
void rpcWiFiGenericClass::removeEvent(rpcWiFiEventSysCb cbEvent, rpc_system_event_id_t event)
{
if (!cbEvent)
{
return;
}
for (uint32_t i = 0; i < cbEventList.size(); i++)
{
rpcWiFiEventCbList_t entry = cbEventList[i];
if (entry.scb == cbEvent && entry.event == event)
{
cbEventList.erase(cbEventList.begin() + i);
}
}
}
void rpcWiFiGenericClass::removeEvent(rpc_wifi_event_id_t id)
{
for (uint32_t i = 0; i < cbEventList.size(); i++)
{
rpcWiFiEventCbList_t entry = cbEventList[i];
if (entry.id == id)
{
cbEventList.erase(cbEventList.begin() + i);
}
}
}
/**
* callback for rpcWiFi events
* @param arg
*/
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
const char *rpc_system_event_names[] = {"WIFI_READY", "SCAN_DONE", "STA_START", "STA_STOP", "STA_CONNECTED", "STA_DISCONNECTED", "STA_AUTHMODE_CHANGE", "STA_GOT_IP", "STA_LOST_IP", "STA_WPS_ER_SUCCESS", "STA_WPS_ER_FAILED", "STA_WPS_ER_TIMEOUT", "STA_WPS_ER_PIN", "STA_WPS_OVERLAP", "AP_START", "AP_STOP", "AP_STACONNECTED", "AP_STADISCONNECTED", "AP_STAIPASSIGNED", "AP_PROBEREQRECVED", "GOT_IP6", "ETH_START", "ETH_STOP", "ETH_CONNECTED", "ETH_DISCONNECTED", "ETH_GOT_IP", "MAX"};
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN
const char *rpc_system_event_reasons[] = {"UNSPECIFIED", "AUTH_EXPIRE", "AUTH_LEAVE", "ASSOC_EXPIRE", "ASSOC_TOOMANY", "NOT_AUTHED", "NOT_ASSOCED", "ASSOC_LEAVE", "ASSOC_NOT_AUTHED", "DISASSOC_PWRCAP_BAD", "DISASSOC_SUPCHAN_BAD", "UNSPECIFIED", "IE_INVALID", "MIC_FAILURE", "4WAY_HANDSHAKE_TIMEOUT", "GROUP_KEY_UPDATE_TIMEOUT", "IE_IN_4WAY_DIFFERS", "GROUP_CIPHER_INVALID", "PAIRWISE_CIPHER_INVALID", "AKMP_INVALID", "UNSUPP_RSN_IE_VERSION", "INVALID_RSN_IE_CAP", "802_1X_AUTH_FAILED", "CIPHER_SUITE_REJECTED", "BEACON_TIMEOUT", "NO_AP_FOUND", "AUTH_FAIL", "ASSOC_FAIL", "HANDSHAKE_TIMEOUT"};
#define reason2str(r) ((r > 176) ? rpc_system_event_reasons[r - 176] : rpc_system_event_reasons[r - 1])
#endif
rpc_esp_err_t rpcWiFiGenericClass::_eventCallback(void *arg, rpc_system_event_t *event)
{
log_d("rpcWiFi Event: %d", event->event_id);
if (event->event_id < 27)
{
log_d("Event: %d - %s", event->event_id, rpc_system_event_names[event->event_id]);
}
if (event->event_id == RPC_SYSTEM_EVENT_SCAN_DONE)
{
rpcWiFiScanClass::_scanDone();
}
else if (event->event_id == RPC_SYSTEM_EVENT_STA_START)
{
rpcWiFiSTAClass::_setStatus(RPC_WL_DISCONNECTED);
setStatusBits(RPC_STA_STARTED_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_STA_STOP)
{
rpcWiFiSTAClass::_setStatus(RPC_WL_NO_SHIELD);
clearStatusBits(RPC_STA_STARTED_BIT | RPC_STA_CONNECTED_BIT | RPC_STA_HAS_IP_BIT | RPC_STA_HAS_IP6_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_STA_CONNECTED)
{
if(rpcWiFiSTAClass::_useStaticIp){
rpcWiFiSTAClass::_setStatus(RPC_WL_CONNECTED);
setStatusBits(RPC_STA_HAS_IP_BIT | RPC_STA_CONNECTED_BIT);
} else {
rpcWiFiSTAClass::_setStatus(RPC_WL_IDLE_STATUS);
setStatusBits(RPC_STA_CONNECTED_BIT);
}
}
else if (event->event_id == RPC_SYSTEM_EVENT_STA_DISCONNECTED)
{
uint8_t reason = event->event_info.disconnected.reason;
// log_w("Reason: %u - %s", reason, reason2str(reason));
if (reason == RPC_WIFI_REASON_NO_AP_FOUND)
{
rpcWiFiSTAClass::_setStatus(RPC_WL_NO_SSID_AVAIL);
}
else if (reason == RPC_WIFI_REASON_AUTH_FAIL || reason == RPC_WIFI_REASON_ASSOC_FAIL)
{
rpcWiFiSTAClass::_setStatus(RPC_WL_CONNECT_FAILED);
}
else if (reason == RPC_WIFI_REASON_BEACON_TIMEOUT || reason == RPC_WIFI_REASON_HANDSHAKE_TIMEOUT)
{
rpcWiFiSTAClass::_setStatus(RPC_WL_CONNECTION_LOST);
}
else if (reason == RPC_WIFI_REASON_AUTH_EXPIRE)
{
}
else
{
rpcWiFiSTAClass::_setStatus(RPC_WL_DISCONNECTED);
}
clearStatusBits(RPC_STA_CONNECTED_BIT | RPC_STA_HAS_IP_BIT | RPC_STA_HAS_IP6_BIT);
if (((reason == RPC_WIFI_REASON_AUTH_EXPIRE) ||
(reason >= RPC_WIFI_REASON_BEACON_TIMEOUT && reason != RPC_WIFI_REASON_AUTH_FAIL)) &&
rpcWiFi.getAutoReconnect())
{
rpcWiFi.disconnect();
rpcWiFi.begin();
}
}
else if (event->event_id == RPC_SYSTEM_EVENT_STA_GOT_IP)
{
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
uint8_t *ip = (uint8_t *)&(event->event_info.got_ip.ip_info.ip.addr);
uint8_t *mask = (uint8_t *)&(event->event_info.got_ip.ip_info.netmask.addr);
uint8_t *gw = (uint8_t *)&(event->event_info.got_ip.ip_info.gw.addr);
log_d("STA IP: %u.%u.%u.%u, MASK: %u.%u.%u.%u, GW: %u.%u.%u.%u",
ip[0], ip[1], ip[2], ip[3],
mask[0], mask[1], mask[2], mask[3],
gw[0], gw[1], gw[2], gw[3]);
#endif
rpcWiFiSTAClass::_setStatus(RPC_WL_CONNECTED);
setStatusBits(RPC_STA_HAS_IP_BIT | RPC_STA_CONNECTED_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_STA_LOST_IP)
{
rpcWiFiSTAClass::_setStatus(RPC_WL_IDLE_STATUS);
clearStatusBits(RPC_STA_HAS_IP_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_AP_START)
{
setStatusBits(RPC_AP_STARTED_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_AP_STOP)
{
clearStatusBits(RPC_AP_STARTED_BIT | RPC_AP_HAS_CLIENT_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_AP_STACONNECTED)
{
setStatusBits(RPC_AP_HAS_CLIENT_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_AP_STADISCONNECTED)
{
//rpc_wifi_sta_list_t clients;
if (rpcWiFi.softAPgetStationNum() == 0)
{
clearStatusBits(RPC_AP_HAS_CLIENT_BIT);
}
}
else if (event->event_id == RPC_SYSTEM_EVENT_ETH_START)
{
setStatusBits(RPC_ETH_STARTED_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_ETH_STOP)
{
clearStatusBits(RPC_ETH_STARTED_BIT | RPC_ETH_CONNECTED_BIT | RPC_ETH_HAS_IP_BIT | RPC_ETH_HAS_IP6_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_ETH_CONNECTED)
{
setStatusBits(RPC_ETH_CONNECTED_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_ETH_DISCONNECTED)
{
clearStatusBits(RPC_ETH_CONNECTED_BIT | RPC_ETH_HAS_IP_BIT | RPC_ETH_HAS_IP6_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_ETH_GOT_IP)
{
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
uint8_t *ip = (uint8_t *)&(event->event_info.got_ip.ip_info.ip.addr);
uint8_t *mask = (uint8_t *)&(event->event_info.got_ip.ip_info.netmask.addr);
uint8_t *gw = (uint8_t *)&(event->event_info.got_ip.ip_info.gw.addr);
log_d("ETH IP: %u.%u.%u.%u, MASK: %u.%u.%u.%u, GW: %u.%u.%u.%u",
ip[0], ip[1], ip[2], ip[3],
mask[0], mask[1], mask[2], mask[3],
gw[0], gw[1], gw[2], gw[3]);
#endif
setStatusBits(RPC_ETH_CONNECTED_BIT | RPC_ETH_HAS_IP_BIT);
}
else if (event->event_id == RPC_SYSTEM_EVENT_GOT_IP6)
{
if (event->event_info.got_ip6.if_index == RPC_TCPIP_ADAPTER_IF_AP)
{
setStatusBits(RPC_AP_HAS_IP6_BIT);
}
else if (event->event_info.got_ip6.if_index == RPC_TCPIP_ADAPTER_IF_STA)
{
setStatusBits(RPC_STA_CONNECTED_BIT | RPC_STA_HAS_IP6_BIT);
}
else if (event->event_info.got_ip6.if_index == RPC_TCPIP_ADAPTER_IF_ETH)
{
setStatusBits(RPC_ETH_CONNECTED_BIT | RPC_ETH_HAS_IP6_BIT);
}
}
for (uint32_t i = 0; i < cbEventList.size(); i++)
{
rpcWiFiEventCbList_t entry = cbEventList[i];
if (entry.cb || entry.fcb || entry.scb)
{
if (entry.event == (rpc_system_event_id_t)event->event_id || entry.event == RPC_SYSTEM_EVENT_MAX)
{
if (entry.cb)
{
entry.cb((rpc_system_event_id_t)event->event_id);
}
else if (entry.fcb)
{
entry.fcb((rpc_system_event_id_t)event->event_id, (rpc_system_event_info_t)event->event_info);
}
else
{
entry.scb(event);
}
}
}
}
return ESP_OK;
}
/**
* Return the current channel associated with the network
* @return channel (1-13)
*/
int32_t rpcWiFiGenericClass::channel(void)
{
//TO DO
int primaryChan = 0;
if (!lowLevelInitDone)
{
return primaryChan;
}
wifi_get_channel(&primaryChan);
return primaryChan;
}
/**
* store rpcWiFi config in SDK flash area
* @param persistent
*/
void rpcWiFiGenericClass::persistent(bool persistent)
{
_persistent = persistent;
}
/**
* set new mode
* @param m rpcWiFiMode_t
*/
bool rpcWiFiGenericClass::mode(rpc_wifi_mode_t m)
{
rpc_wifi_mode_t cm = getMode();
if (cm == m)
{
return true;
}
if (!cm && m)
{
if (!espWiFiStart(_persistent))
{
return false;
}
}
else if (cm && !m)
{
return espWiFiStop();
}
rpc_esp_err_t err;
wifi_off();
vTaskDelay(20);
err = wifi_on(m);
if (err)
{
log_e("Could not set mode! %d", err);
return false;
}
_wifi_mode = m;
return true;
}
/**
* get rpcWiFi mode
* @return WiFiMode
*/
rpc_wifi_mode_t rpcWiFiGenericClass::getMode()
{
if (!_esp_wifi_started)
{
return RPC_WIFI_MODE_NULL;
}
return _wifi_mode;
}
/**
* control STA mode
* @param enable bool
* @return ok
*/
bool rpcWiFiGenericClass::enableSTA(bool enable)
{
rpc_wifi_mode_t currentMode = getMode();
bool isEnabled = ((currentMode & RPC_WIFI_MODE_STA) != 0);
if (isEnabled != enable)
{
if (enable)
{
return mode((rpc_wifi_mode_t)(currentMode | RPC_WIFI_MODE_STA));
}
return mode((rpc_wifi_mode_t)(currentMode & (~RPC_WIFI_MODE_STA)));
}
return true;
}
/**
* control AP mode
* @param enable bool
* @return ok
*/
bool rpcWiFiGenericClass::enableAP(bool enable)
{
rpc_wifi_mode_t currentMode = getMode();
bool isEnabled = ((currentMode & RPC_WIFI_MODE_AP) != 0);
if (isEnabled != enable)
{
if (enable)
{
return mode((rpc_wifi_mode_t)(currentMode | RPC_WIFI_MODE_AP));
}
return mode((rpc_wifi_mode_t)(currentMode & (~RPC_WIFI_MODE_AP)));
}
return true;
}
/**
* control modem sleep when only in STA mode
* @param enable bool
* @return ok
*/
bool rpcWiFiGenericClass::setSleep(bool enable)
{
if ((getMode() & RPC_WIFI_MODE_STA) == 0)
{
log_w("STA has not been started");
return false;
}
return false;
}
/**
* get modem sleep enabled
* @return true if modem sleep is enabled
*/
bool rpcWiFiGenericClass::getSleep()
{
//rpc_wifi_ps_type_t ps;
if ((getMode() & RPC_WIFI_MODE_STA) == 0)
{
log_w("STA has not been started");
return false;
}
return false;
}
/**
* control rpcWiFi tx power
* @param power enum maximum rpcWiFi tx power
* @return ok
*/
bool rpcWiFiGenericClass::setTxPower(rpc_wifi_power_t power)
{
if ((getStatusBits() & (RPC_STA_STARTED_BIT | RPC_AP_STARTED_BIT)) == 0)
{
log_w("Neither AP or STA has been started");
return false;
}
_wifi_power = power;
return true;
}
rpc_wifi_power_t rpcWiFiGenericClass::getTxPower()
{
if ((getStatusBits() & (RPC_STA_STARTED_BIT | RPC_AP_STARTED_BIT)) == 0)
{
log_w("Neither AP or STA has been started");
return RPC_WIFI_POWER_19_5dBm;
}
return _wifi_power;
}
// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------ Generic Network function ---------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
/**
* DNS callback
* @param name
* @param ipaddr
* @param callback_arg
*/
static void wifi_dns_found_callback(const char *name, const new_ip_addr_t *ipaddr, void *callback_arg)
{
if (ipaddr)
{
(*reinterpret_cast<IPAddress *>(callback_arg)) = ipaddr->u_addr.ip4.addr;
}
xEventGroupSetBits(_network_event_group, RPC_WIFI_DNS_DONE_BIT);
}
/**
* Resolve the given hostname to an IP address.
* @param aHostname Name to be resolved
* @param aResult IPAddress structure to store the returned IP address
* @return 1 if aIPAddrString was successfully converted to an IP address,
* else error code
*/
int rpcWiFiGenericClass::hostByName(const char *aHostname, IPAddress &aResult)
{
new_ip_addr_t addr;
aResult = static_cast<uint32_t>(0);
waitStatusBits(RPC_WIFI_DNS_IDLE_BIT, 5000);
clearStatusBits(RPC_WIFI_DNS_IDLE_BIT);
err_t err = new_dns_gethostbyname(aHostname, &addr, &wifi_dns_found_callback, &aResult);
if(err == ERR_OK && addr.u_addr.ip4.addr) {
aResult = addr.u_addr.ip4.addr;
} else if(err == ERR_INPROGRESS) {
waitStatusBits(RPC_WIFI_DNS_DONE_BIT, 4000);
clearStatusBits(RPC_WIFI_DNS_DONE_BIT);
}
setStatusBits(RPC_WIFI_DNS_IDLE_BIT);
if((uint32_t)aResult == 0){
log_e("DNS Failed for %s", aHostname);
}
return (uint32_t)aResult != 0;
}
IPAddress rpcWiFiGenericClass::calculateNetworkID(IPAddress ip, IPAddress subnet)
{
IPAddress networkID;
for (size_t i = 0; i < 4; i++)
networkID[i] = subnet[i] & ip[i];
return networkID;
}
IPAddress rpcWiFiGenericClass::calculateBroadcast(IPAddress ip, IPAddress subnet)
{
IPAddress broadcastIp;
for (int i = 0; i < 4; i++)
broadcastIp[i] = ~subnet[i] | ip[i];
return broadcastIp;
}
uint8_t rpcWiFiGenericClass::calculateSubnetCIDR(IPAddress subnetMask)
{
uint8_t CIDR = 0;
for (uint8_t i = 0; i < 4; i++)
{
if (subnetMask[i] == 0x80) // 128
CIDR += 1;
else if (subnetMask[i] == 0xC0) // 192
CIDR += 2;
else if (subnetMask[i] == 0xE0) // 224
CIDR += 3;
else if (subnetMask[i] == 0xF0) // 242
CIDR += 4;
else if (subnetMask[i] == 0xF8) // 248
CIDR += 5;
else if (subnetMask[i] == 0xFC) // 252
CIDR += 6;
else if (subnetMask[i] == 0xFE) // 254
CIDR += 7;
else if (subnetMask[i] == 0xFF) // 255
CIDR += 8;
}
return CIDR;
}
| 29.627139 | 592 | 0.622529 | [
"vector"
] |
df5f478717ac2117f2b0a863941e1fb80b02db6e | 803 | cpp | C++ | 2021_Aug/11.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | 17 | 2018-08-23T08:53:56.000Z | 2021-04-17T00:06:13.000Z | 2021_Aug/11.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | null | null | null | 2021_Aug/11.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | null | null | null | class Solution {
public:
bool canReorderDoubled(vector<int>& arr) {
sort(arr.begin(), arr.end());
vector<bool> select(arr.size(),false);
int count = 0;
int req = int(arr.size() / 2);
for (int i=0; i < arr.size(); i++) {
if (select[i])
continue;
vector<int>::iterator it_two_times = lower_bound(arr.begin() + i + 1, arr.end(),arr[i]*2);
if (it_two_times != arr.end() && *it_two_times == arr[i]*2 && !select[it_two_times - arr.begin()]){
count += 1;
select[it_two_times - arr.begin()] = true;
}
}
cout << count << endl;
if (count == req)
return true;
else
return false;
}
}; | 30.884615 | 111 | 0.455791 | [
"vector"
] |
df6194c2bc836f0494fd2e1c5389a40ff711e6ed | 6,666 | cpp | C++ | groupRPG/Map_Test.cpp | CIT-237-TeamRed/groupRPG | a1ba42faaebfcc1f7c8a754c9a8b66bea6798609 | [
"MIT"
] | 2 | 2018-10-23T19:51:46.000Z | 2018-10-27T21:43:35.000Z | groupRPG/Map_Test.cpp | CIT-237-TeamRed/groupRPG | a1ba42faaebfcc1f7c8a754c9a8b66bea6798609 | [
"MIT"
] | null | null | null | groupRPG/Map_Test.cpp | CIT-237-TeamRed/groupRPG | a1ba42faaebfcc1f7c8a754c9a8b66bea6798609 | [
"MIT"
] | null | null | null | // Map Test Program
// by Team Red
// Jericho Keyne
// Daniel Richardson
// Karlos Boehlke
// Samuel Silverman
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include "Map.h"
#include "Position.h"
#include "Direction.h"
using namespace std;
void printCommands();
bool checkCreatures(Map map, Position pos);
bool checkTreasures(Map map, Position pos);
void checkCreaturesAndTreasures(Map cMap, Map tMap, Position heroPos);
void saveMap(Map map, string fName);
void savePos(Position pos, string fName);
int main() {
// Setup
system("color 3E");
system("title Map Test - Team Red");
// Declaring constant variables
const int NUM_CREATURES = 5;
const int NUM_TREASURES = 5;
const int MAP_WIDTH = 10;
const int MAP_LENGTH = 10;
//create Position array for treasures
Position treasures[NUM_TREASURES];
//set the values of the positions
Position t1(2, 4);
treasures[0] = t1;
Position t2(8, 5);
treasures[1] = t2;
Position t3(3, 7);
treasures[2] = t3;
Position t4(9, 6);
treasures[3] = t4;
Position t5(7, 2);
treasures[4] = t5;
//create treasure map based on position array
Map treasureMap(treasures);
//create Position array for creatures
Position creatures[NUM_CREATURES];
//set the values of the positions
Position c1(1, 4);
creatures[0] = c1;
Position c2(8, 4);
creatures[1] = c2;
Position c3(3, 8);
creatures[2] = c3;
Position c4(9, 6);
creatures[3] = c4;
Position c5(7, 2);
creatures[4] = c5;
//create creature map based on position array
Map creatureMap(creatures);
//set position of the hero
Position hero(0, 0);
//check if there are files, if so, load that data to overwrite the current maps
ifstream creatureMapFile("creatureMap.dat");
ifstream treasureMapFile("treasureMap.dat");
ifstream heroPosFile("heroPos.txt");
if (creatureMapFile.good() && treasureMapFile.good() && heroPosFile.good()) { //if files exist then ask to load, else continue with program
string input;
cout << "Do you want to load the save data? (y/n) ";
getline(cin, input);
transform(input.begin(), input.end(), input.begin(), ::toupper);
if (input == "Y" || input == "YES") { //if the user says yes, then try and load the maps and hero
try {
creatureMap.readBinaryMap("creatureMap.dat");
} catch (Map::ILLEGAL_WIDTH) {
cout << "creatureMap.dat has an illegal width value\n";
return 1;
} catch (Map::ILLEGAL_HEIGHT) {
cout << "creatureMap.dat has an illegal height value\n";
return 2;
}
try {
treasureMap.readBinaryMap("treasureMap.dat");
} catch (Map::ILLEGAL_WIDTH) {
cout << "treasureMap.dat has an illegal width value\n";
return 3;
} catch (Map::ILLEGAL_HEIGHT) {
cout << "treasureMap.dat has an illegal height value\n";
return 4;
}
loadPos(hero, "heroPos.txt");
}
}
//create direction object assuming that Direction::dir is not public static
Direction direction;
// set input string to be empty before loop
string input = "";
do {
checkCreaturesAndTreasures(creatureMap, treasureMap, hero); //outputs if you are on a square with a creature or treasure
cout << "Enter a command: (type \"HELP\" for a list of commands)" ;
getline(cin, input);
transform(input.begin(), input.end(), input.begin(), ::toupper); // make input upper case
if (input == "") // if the input is empty, do nothing
continue;
if (input == "N" || input == "NE" || input == "E" || input == "SE" || input == "S" || input == "SW" || input == "W" || input == "NW") //update direction from input
hero.update(direction.dir(input));
else if (input == "SAVE") { // save the map and position
creatureMap.writeBinaryMap("creatureMap.dat");
treasureMap.writeBinaryMap("treasureMap.dat");
savePos(hero, "heroPos.txt");
cout << "\nYour game has been saved. Continue playing or enter Quit or Exit to leave the game.\n";
continue;
}
else if (input == "QUIT" || input == "EXIT") { //quit or exit the game
cout << "Are you sure (y/n)? ";
getline(cin, input);
transform(input.begin(), input.end(), input.begin(), ::toupper); //make input upper case
if (input == "Y" || input == "YES") {
creatureMap.writeBinaryMap("creatureMap.dat");
treasureMap.writeBinaryMap("treasureMap.dat");
savePos(hero, "heroPos.txt");
cout << "\nYour game has been saved.\n";
break;
} else
input = ""; // reset the input string so the loop will continue
}
else if (input == "HELP") //display the commands if desired
printCommands();
else { // catch if the user inputs an invalid command
cout << "\'" << input << "\' is not a valid command\n";
continue;
}
} while (input != "QUIT" || input != "EXIT"); //continue the loop if the user does not quit or exit
cout << "\n Game closing...";
system("pause");
return 0;
}
void printCommands(){ //print the commands
cout
<< "\n Available Commands: "
<< "\n N, NE, E, SE, S, SW, W, NW "
<< "\n SAVE, QUIT, EXIT \n\n";
}
void checkCreaturesAndTreasures(Map creatureMap, Map treasureMap, Position hero)) { //outputs based on the positions of treasures and creastures around the hero
bool isCreature = checkCreatures(creatureMap, hero);
bool isTreasure = checkTreasures(treasureMap, hero);
bool isCreatureNearby = creatureMap.nearPosition(hero);
bool isTreasureNearby = treasureMap.nearPosition(hero);
if (isCreature)
cout << "There is a creature at " << hero.toString() <<endl;
if (isTreasure)
cout << "There is a treasure at " << hero.toString() << endl;
if (isCreatureNearby)
cout << "There is an enemy nearby\n";
if (isTreasureNearby)
cout << "There is treasure nearby\n";
if (!isCreature && !isTreasure && !isCreatureNearby && !isTreasureNearby)
cout << "There is nothing nearby\n";
}
bool checkCreatures(Map map, Position pos) { //return true if there is a creature at location
return map.checkPosition(pos);
}
bool checkTreasures(Map map, Position pos) {//return true if there is a treasure at location
return map.checkPosition(pos);
}
void loadPos(Position &pos, string fName) { //load a position file for hero
ifstream inputFile(fName);
if (ifstream.fail()) {
cout << "Failed to open file";
return;
}
int rowPos;
inputFile >> rowPos;
int colPos;
inputFile >> colPos;
pos.setRowPos(rowPos);
pos.setColPos(colPos);
}
void savePos(Position pos, string fName) { //save a position file for hero
ofstream outputFile(fName);
if (ofstream.fail()) {
cout << "Failed to open file\n";
return;
}
outputFile << pos.getColPos() << endl;
outputFile << pos.getRowPos() << endl;
} | 31.443396 | 165 | 0.666367 | [
"object",
"transform"
] |
df666754e65c61637172d781f08b91385c126305 | 1,519 | cpp | C++ | class 20 - solve class/F.cpp | pioneerAlpha/CP_Beginner_B4_Amar_iSchool | 271a851cfaf570e9dbde390574c9b0a419299823 | [
"MIT"
] | 4 | 2020-07-10T06:37:52.000Z | 2022-01-03T17:14:21.000Z | Class 18 - solve class 8/E.cpp | pioneerAlpha/CP_Beginner_B1 | fd743b956188e927ac999e108df2f081d4f5fcb2 | [
"Apache-2.0"
] | null | null | null | Class 18 - solve class 8/E.cpp | pioneerAlpha/CP_Beginner_B1 | fd743b956188e927ac999e108df2f081d4f5fcb2 | [
"Apache-2.0"
] | 4 | 2020-11-23T16:58:45.000Z | 2021-01-06T20:20:57.000Z | #include<bits/stdc++.h>
#define ll long long
#define N ((int)1e5 + 5)
#define MOD ((int)1e9 + 7)
#define MAX ((int)1e9 + 7)
#define MAXL ((ll)1e18 + 7)
#define MAXP ((int)1e3 + 7)
#define thr 1e-8
#define pi acos(-1) /// pi = acos ( -1 )
#define fastio ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
int dis[2][105];
vector < int > vec[105];
void bfs(int src , int idx)
{
dis[idx][src] = 0;
queue < int > que;
que.push(src);
while(!que.empty())
{
int a = que.front();
que.pop();
for(int b:vec[a])
{
if(dis[idx][b] == -1)
{
dis[idx][b] = dis[idx][a] + 1;
que.push(b);
}
}
}
}
int main()
{
fastio;
int t , caseno = 1;
cin>>t;
while(t--)
{
int n, m;
cin>>n>>m;
for(int i = 1 ; i<=n ; i++) vec[i].clear();
while(m--){
int a , b;
cin>>a>>b;
a++;
b++;
vec[a].push_back(b);
vec[b].push_back(a);
}
int src , des;
cin>>src>>des;
src++;
des++;
memset(dis,-1,sizeof dis);
bfs(src,0); /// dis[0][i] = distance of node i from src
bfs(des,1); /// dis[1][i] = distance of node i from des
int ans = 0;
for(int i = 1 ; i<=n ; i++){
ans = max(ans , dis[0][i] + dis[1][i]);
}
cout<<"Case "<<caseno++<<": "<<ans<<endl;
}
return 0;
}
| 19.986842 | 64 | 0.425938 | [
"vector"
] |
df70f3bc614b99627feb84037a2ea8807b82895b | 23,396 | cpp | C++ | src/kernel.cpp | GorePradnyesh/OpenCLOn12 | 42cc428ba366a7d9dbafe9512e4344f8ae899a22 | [
"MIT"
] | null | null | null | src/kernel.cpp | GorePradnyesh/OpenCLOn12 | 42cc428ba366a7d9dbafe9512e4344f8ae899a22 | [
"MIT"
] | null | null | null | src/kernel.cpp | GorePradnyesh/OpenCLOn12 | 42cc428ba366a7d9dbafe9512e4344f8ae899a22 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "kernel.hpp"
#include "sampler.hpp"
#include "clc_compiler.h"
extern CL_API_ENTRY cl_kernel CL_API_CALL
clCreateKernel(cl_program program_,
const char* kernel_name,
cl_int* errcode_ret) CL_API_SUFFIX__VERSION_1_0
{
if (!program_)
{
if (errcode_ret) *errcode_ret = CL_INVALID_PROGRAM;
return nullptr;
}
Program& program = *static_cast<Program*>(program_);
auto ReportError = program.GetContext().GetErrorReporter(errcode_ret);
const clc_dxil_object* kernel = nullptr;
{
std::lock_guard Lock(program.m_Lock);
cl_uint DeviceCountWithProgram = 0, DeviceCountWithKernel = 0;
for (auto& Device : program.m_AssociatedDevices)
{
auto& BuildData = program.m_BuildData[Device.Get()];
if (!BuildData ||
BuildData->m_BuildStatus != CL_BUILD_SUCCESS ||
BuildData->m_BinaryType != CL_PROGRAM_BINARY_TYPE_EXECUTABLE)
{
continue;
}
++DeviceCountWithProgram;
auto iter = BuildData->m_Kernels.find(kernel_name);
if (iter == BuildData->m_Kernels.end())
{
continue;
}
++DeviceCountWithKernel;
if (kernel)
{
if (kernel->kernel->num_args != iter->second->kernel->num_args)
{
return ReportError("Kernel argument count differs between devices.", CL_INVALID_KERNEL_DEFINITION);
}
for (unsigned i = 0; i < kernel->kernel->num_args; ++i)
{
auto& a = kernel->kernel->args[i];
auto& b = iter->second->kernel->args[i];
if (strcmp(a.type_name, b.type_name) != 0 ||
strcmp(a.name, b.name) != 0 ||
a.address_qualifier != b.address_qualifier ||
a.access_qualifier != b.access_qualifier ||
a.type_qualifier != b.type_qualifier)
{
return ReportError("Kernel argument differs between devices.", CL_INVALID_KERNEL_DEFINITION);
}
}
}
kernel = iter->second.get();
}
if (!DeviceCountWithProgram)
{
return ReportError("No executable available for program.", CL_INVALID_PROGRAM_EXECUTABLE);
}
if (!DeviceCountWithKernel)
{
return ReportError("No kernel with that name found.", CL_INVALID_KERNEL_NAME);
}
}
try
{
return new Kernel(program, kernel);
}
catch (std::bad_alloc&) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); }
catch (std::exception & e) { return ReportError(e.what(), CL_OUT_OF_RESOURCES); }
catch (_com_error&) { return ReportError(nullptr, CL_OUT_OF_RESOURCES); }
}
extern CL_API_ENTRY cl_int CL_API_CALL
clCreateKernelsInProgram(cl_program program_,
cl_uint num_kernels,
cl_kernel* kernels,
cl_uint* num_kernels_ret) CL_API_SUFFIX__VERSION_1_0
{
if (!program_)
{
return CL_INVALID_PROGRAM;
}
Program& program = *static_cast<Program*>(program_);
auto ReportError = program.GetContext().GetErrorReporter();
try
{
std::map<std::string, Kernel::ref_ptr> temp;
{
std::lock_guard Lock(program.m_Lock);
for (auto& Device : program.m_AssociatedDevices)
{
auto& BuildData = program.m_BuildData[Device.Get()];
if (!BuildData ||
BuildData->m_BuildStatus != CL_BUILD_SUCCESS ||
BuildData->m_BinaryType != CL_PROGRAM_BINARY_TYPE_EXECUTABLE)
{
continue;
}
for (auto& pair : BuildData->m_Kernels)
{
temp.emplace(pair.first, nullptr);
}
}
if (temp.empty())
{
return ReportError("No executable available for program.", CL_INVALID_PROGRAM_EXECUTABLE);
}
if (num_kernels && num_kernels < temp.size())
{
return ReportError("num_kernels is too small.", CL_INVALID_VALUE);
}
}
if (num_kernels_ret)
{
*num_kernels_ret = (cl_uint)temp.size();
}
if (num_kernels)
{
for (auto& pair : temp)
{
cl_int error = CL_SUCCESS;
pair.second.Attach(static_cast<Kernel*>(clCreateKernel(program_, pair.first.c_str(), &error)));
if (error != CL_SUCCESS)
{
return error;
}
}
for (auto& pair : temp)
{
*kernels = pair.second.Detach();
++kernels;
}
}
}
catch (std::bad_alloc&) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); }
catch (std::exception & e) { return ReportError(e.what(), CL_OUT_OF_RESOURCES); }
catch (_com_error&) { return ReportError(nullptr, CL_OUT_OF_RESOURCES); }
return CL_SUCCESS;
}
extern CL_API_ENTRY cl_int CL_API_CALL
clRetainKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0
{
if (!kernel)
{
return CL_INVALID_KERNEL;
}
static_cast<Kernel*>(kernel)->Retain();
return CL_SUCCESS;
}
extern CL_API_ENTRY cl_int CL_API_CALL
clReleaseKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0
{
if (!kernel)
{
return CL_INVALID_KERNEL;
}
static_cast<Kernel*>(kernel)->Release();
return CL_SUCCESS;
}
extern CL_API_ENTRY cl_int CL_API_CALL
clSetKernelArg(cl_kernel kernel,
cl_uint arg_index,
size_t arg_size,
const void* arg_value) CL_API_SUFFIX__VERSION_1_0
{
if (!kernel)
{
return CL_INVALID_KERNEL;
}
return static_cast<Kernel*>(kernel)->SetArg(arg_index, arg_size, arg_value);
}
static cl_mem_object_type MemObjectTypeFromName(const char* name)
{
if (strcmp(name, "image1d_buffer_t") == 0) return CL_MEM_OBJECT_IMAGE1D_BUFFER;
if (strcmp(name, "image1d_t") == 0) return CL_MEM_OBJECT_IMAGE1D;
if (strcmp(name, "image1d_array_t") == 0) return CL_MEM_OBJECT_IMAGE1D_ARRAY;
if (strcmp(name, "image2d_t") == 0) return CL_MEM_OBJECT_IMAGE2D;
if (strcmp(name, "image2d_array_t") == 0) return CL_MEM_OBJECT_IMAGE2D_ARRAY;
if (strcmp(name, "image3d_t") == 0) return CL_MEM_OBJECT_IMAGE3D;
return 0;
}
static D3D12TranslationLayer::RESOURCE_DIMENSION ResourceDimensionFromMemObjectType(cl_mem_object_type type)
{
switch (type)
{
case CL_MEM_OBJECT_IMAGE1D: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE1D;
case CL_MEM_OBJECT_IMAGE1D_ARRAY: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE1DARRAY;
case CL_MEM_OBJECT_IMAGE1D_BUFFER: return D3D12TranslationLayer::RESOURCE_DIMENSION::BUFFER;
case CL_MEM_OBJECT_IMAGE2D: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE2D;
case CL_MEM_OBJECT_IMAGE2D_ARRAY: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE2DARRAY;
case CL_MEM_OBJECT_IMAGE3D: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE3D;
}
return D3D12TranslationLayer::RESOURCE_DIMENSION::UNKNOWN;
}
static D3D12TranslationLayer::SShaderDecls DeclsFromMetadata(clc_dxil_object const* pDxil)
{
auto& metadata = pDxil->metadata;
D3D12TranslationLayer::SShaderDecls decls = {};
cl_uint KernelArgCBIndex = metadata.kernel_inputs_cbv_id;
cl_uint WorkPropertiesCBIndex = metadata.work_properties_cbv_id;
decls.m_NumCBs = max(KernelArgCBIndex + 1, WorkPropertiesCBIndex + 1);
decls.m_NumSamplers = (UINT)metadata.num_samplers;
decls.m_ResourceDecls.resize(metadata.num_srvs);
decls.m_UAVDecls.resize(metadata.num_uavs);
for (cl_uint i = 0; i < pDxil->kernel->num_args; ++i)
{
auto& arg = pDxil->kernel->args[i];
if (arg.address_qualifier == CLC_KERNEL_ARG_ADDRESS_GLOBAL ||
arg.address_qualifier == CLC_KERNEL_ARG_ADDRESS_CONSTANT)
{
cl_mem_object_type imageType = MemObjectTypeFromName(arg.type_name);
if (imageType != 0)
{
auto dim = ResourceDimensionFromMemObjectType(imageType);
bool uav = (arg.access_qualifier & CLC_KERNEL_ARG_ACCESS_WRITE) != 0;
auto& declVector = uav ? decls.m_UAVDecls : decls.m_ResourceDecls;
for (cl_uint j = 0; j < metadata.args[i].image.num_buf_ids; ++j)
declVector[metadata.args[i].image.buf_ids[j]] = dim;
}
else
{
decls.m_UAVDecls[metadata.args[i].globconstptr.buf_id] =
D3D12TranslationLayer::RESOURCE_DIMENSION::RAW_BUFFER;
}
}
}
return decls;
}
static cl_addressing_mode CLAddressingModeFromSpirv(unsigned addressing_mode)
{
return addressing_mode + CL_ADDRESS_NONE;
}
static unsigned SpirvAddressingModeFromCL(cl_addressing_mode mode)
{
return mode - CL_ADDRESS_NONE;
}
static cl_filter_mode CLFilterModeFromSpirv(unsigned filter_mode)
{
return filter_mode + CL_FILTER_NEAREST;
}
Kernel::Kernel(Program& Parent, clc_dxil_object const* pDxil)
: CLChildBase(Parent)
, m_pDxil(pDxil)
, m_ShaderDecls(DeclsFromMetadata(pDxil))
{
m_UAVs.resize(m_pDxil->metadata.num_uavs);
m_SRVs.resize(m_pDxil->metadata.num_srvs);
m_Samplers.resize(m_pDxil->metadata.num_samplers);
m_ArgMetadataToCompiler.resize(m_pDxil->kernel->num_args);
size_t KernelInputsCbSize = m_pDxil->metadata.kernel_inputs_buf_size;
m_KernelArgsCbData.resize(KernelInputsCbSize);
m_ConstSamplers.resize(m_pDxil->metadata.num_const_samplers);
for (cl_uint i = 0; i < m_pDxil->metadata.num_const_samplers; ++i)
{
auto& samplerMeta = m_pDxil->metadata.const_samplers[i];
Sampler::Desc desc =
{
samplerMeta.normalized_coords,
CLAddressingModeFromSpirv(samplerMeta.addressing_mode),
CLFilterModeFromSpirv(samplerMeta.filter_mode)
};
m_ConstSamplers[i] = new Sampler(m_Parent->GetContext(), desc);
m_Samplers[samplerMeta.sampler_id] = m_ConstSamplers[i].Get();
}
for (cl_uint i = 0; i < m_pDxil->metadata.num_consts; ++i)
{
auto& constMeta = m_pDxil->metadata.consts[i];
auto resource = static_cast<Resource*>(clCreateBuffer(&Parent.GetContext(),
CL_MEM_COPY_HOST_PTR | CL_MEM_READ_ONLY | CL_MEM_HOST_NO_ACCESS,
constMeta.size, constMeta.data,
nullptr));
m_InlineConsts.emplace_back(resource, adopt_ref{});
m_UAVs[constMeta.uav_id] = resource;
}
m_Parent->KernelCreated();
}
Kernel::~Kernel()
{
m_Parent->KernelFreed();
}
cl_int Kernel::SetArg(cl_uint arg_index, size_t arg_size, const void* arg_value)
{
auto ReportError = m_Parent->GetContext().GetErrorReporter();
if (arg_index > m_pDxil->kernel->num_args)
{
return ReportError("Argument index out of bounds", CL_INVALID_ARG_INDEX);
}
auto& arg = m_pDxil->kernel->args[arg_index];
switch (arg.address_qualifier)
{
case CLC_KERNEL_ARG_ADDRESS_GLOBAL:
case CLC_KERNEL_ARG_ADDRESS_CONSTANT:
{
if (arg_size != sizeof(cl_mem))
{
return ReportError("Invalid argument size, must be sizeof(cl_mem) for global and constant arguments", CL_INVALID_ARG_SIZE);
}
cl_mem_object_type imageType = MemObjectTypeFromName(arg.type_name);
cl_mem mem = arg_value ? *reinterpret_cast<cl_mem const*>(arg_value) : nullptr;
Resource* resource = static_cast<Resource*>(mem);
if (imageType != 0)
{
bool validImageType = true;
if (resource)
{
validImageType = resource->m_Desc.image_type == imageType;
}
if (!validImageType)
{
return ReportError("Invalid image type.", CL_INVALID_ARG_VALUE);
}
if (arg.access_qualifier & CLC_KERNEL_ARG_ACCESS_WRITE)
{
if (resource && (resource->m_Flags & CL_MEM_READ_ONLY))
{
return ReportError("Invalid mem object flags, binding read-only image to writable image argument.", CL_INVALID_ARG_VALUE);
}
if ((arg.access_qualifier & CLC_KERNEL_ARG_ACCESS_READ) != 0 &&
resource && (resource->m_Flags & CL_MEM_WRITE_ONLY))
{
return ReportError("Invalid mem object flags, binding write-only image to read-write image argument.", CL_INVALID_ARG_VALUE);
}
for (cl_uint i = 0; i < m_pDxil->metadata.args[arg_index].image.num_buf_ids; ++i)
{
m_UAVs[m_pDxil->metadata.args[arg_index].image.buf_ids[i]] = resource;
}
}
else
{
if (resource && (resource->m_Flags & CL_MEM_WRITE_ONLY))
{
return ReportError("Invalid mem object flags, binding write-only image to read-only image argument.", CL_INVALID_ARG_VALUE);
}
for (cl_uint i = 0; i < m_pDxil->metadata.args[arg_index].image.num_buf_ids; ++i)
{
m_SRVs[m_pDxil->metadata.args[arg_index].image.buf_ids[i]] = resource;
}
}
// Store image format in the kernel args
cl_image_format* ImageFormatInKernelArgs = reinterpret_cast<cl_image_format*>(
m_KernelArgsCbData.data() + m_pDxil->metadata.args[arg_index].offset);
*ImageFormatInKernelArgs = {};
if (resource)
{
*ImageFormatInKernelArgs = resource->m_Format;
// The SPIR-V expects the values coming from the intrinsics to be 0-indexed, and implicitly
// adds the necessary values to put it back into the CL constant range
ImageFormatInKernelArgs->image_channel_data_type -= CL_SNORM_INT8;
ImageFormatInKernelArgs->image_channel_order -= CL_R;
}
}
else
{
if (resource && resource->m_Desc.image_type != CL_MEM_OBJECT_BUFFER)
{
return ReportError("Invalid mem object type, must be buffer.", CL_INVALID_ARG_VALUE);
}
uint64_t *buffer_val = reinterpret_cast<uint64_t*>(m_KernelArgsCbData.data() + m_pDxil->metadata.args[arg_index].offset);
auto buf_id = m_pDxil->metadata.args[arg_index].globconstptr.buf_id;
m_UAVs[buf_id] = resource;
if (resource)
{
*buffer_val = (uint64_t)buf_id << 32ull;
}
else
{
*buffer_val = ~0ull;
}
}
break;
}
case CLC_KERNEL_ARG_ADDRESS_PRIVATE:
if (strcmp(arg.type_name, "sampler_t") == 0)
{
if (arg_size != sizeof(cl_sampler))
{
return ReportError("Invalid argument size, must be sizeof(cl_mem) for global arguments", CL_INVALID_ARG_SIZE);
}
cl_sampler samp = arg_value ? *reinterpret_cast<cl_sampler const*>(arg_value) : nullptr;
Sampler* sampler = static_cast<Sampler*>(samp);
m_Samplers[m_pDxil->metadata.args[arg_index].sampler.sampler_id] = sampler;
m_ArgMetadataToCompiler[arg_index].sampler.normalized_coords = sampler ? sampler->m_Desc.NormalizedCoords : 1u;
m_ArgMetadataToCompiler[arg_index].sampler.addressing_mode = sampler ? SpirvAddressingModeFromCL(sampler->m_Desc.AddressingMode) : 0u;
m_ArgMetadataToCompiler[arg_index].sampler.linear_filtering = sampler ? (sampler->m_Desc.FilterMode == CL_FILTER_LINEAR) : 0u;
}
else
{
if (arg_size != m_pDxil->metadata.args[arg_index].size)
{
return ReportError("Invalid argument size", CL_INVALID_ARG_SIZE);
}
memcpy(m_KernelArgsCbData.data() + m_pDxil->metadata.args[arg_index].offset, arg_value, arg_size);
}
break;
case CLC_KERNEL_ARG_ADDRESS_LOCAL:
if (arg_size == 0)
{
return ReportError("Argument size must be nonzero for local arguments", CL_INVALID_ARG_SIZE);
}
if (arg_value != nullptr)
{
return ReportError("Argument value must be null for local arguments", CL_INVALID_ARG_VALUE);
}
m_ArgMetadataToCompiler[arg_index].localptr.size = (cl_uint)arg_size;
break;
}
return CL_SUCCESS;
}
uint16_t const* Kernel::GetRequiredLocalDims() const
{
if (m_pDxil->metadata.local_size[0] != 0)
return m_pDxil->metadata.local_size;
return nullptr;
}
uint16_t const* Kernel::GetLocalDimsHint() const
{
if (m_pDxil->metadata.local_size_hint[0] != 0)
return m_pDxil->metadata.local_size_hint;
return nullptr;
}
extern CL_API_ENTRY cl_int CL_API_CALL
clGetKernelInfo(cl_kernel kernel_,
cl_kernel_info param_name,
size_t param_value_size,
void* param_value,
size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
if (!kernel_)
{
return CL_INVALID_KERNEL;
}
auto RetValue = [&](auto&& param)
{
return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret);
};
auto& kernel = *static_cast<Kernel*>(kernel_);
switch (param_name)
{
case CL_KERNEL_FUNCTION_NAME: return RetValue(kernel.m_pDxil->kernel->name);
case CL_KERNEL_NUM_ARGS: return RetValue((cl_uint)kernel.m_pDxil->kernel->num_args);
case CL_KERNEL_REFERENCE_COUNT: return RetValue(kernel.GetRefCount());
case CL_KERNEL_CONTEXT: return RetValue((cl_context)&kernel.m_Parent->m_Parent.get());
case CL_KERNEL_PROGRAM: return RetValue((cl_program)&kernel.m_Parent.get());
case CL_KERNEL_ATTRIBUTES: return RetValue("");
}
return kernel.m_Parent->GetContext().GetErrorReporter()("Unknown param_name", CL_INVALID_VALUE);
}
extern CL_API_ENTRY cl_int CL_API_CALL
clGetKernelArgInfo(cl_kernel kernel_,
cl_uint arg_indx,
cl_kernel_arg_info param_name,
size_t param_value_size,
void* param_value,
size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_2
{
if (!kernel_)
{
return CL_INVALID_KERNEL;
}
auto RetValue = [&](auto&& param)
{
return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret);
};
auto& kernel = *static_cast<Kernel*>(kernel_);
if (arg_indx > kernel.m_pDxil->kernel->num_args)
{
return CL_INVALID_ARG_INDEX;
}
auto& arg = kernel.m_pDxil->kernel->args[arg_indx];
switch (param_name)
{
case CL_KERNEL_ARG_ADDRESS_QUALIFIER:
switch (arg.address_qualifier)
{
default:
case CLC_KERNEL_ARG_ADDRESS_PRIVATE: return RetValue(CL_KERNEL_ARG_ADDRESS_PRIVATE);
case CLC_KERNEL_ARG_ADDRESS_CONSTANT: return RetValue(CL_KERNEL_ARG_ADDRESS_CONSTANT);
case CLC_KERNEL_ARG_ADDRESS_LOCAL: return RetValue(CL_KERNEL_ARG_ADDRESS_LOCAL);
case CLC_KERNEL_ARG_ADDRESS_GLOBAL: return RetValue(CL_KERNEL_ARG_ADDRESS_GLOBAL);
}
break;
case CL_KERNEL_ARG_ACCESS_QUALIFIER:
switch (arg.access_qualifier)
{
default: return RetValue(CL_KERNEL_ARG_ACCESS_NONE);
case CLC_KERNEL_ARG_ACCESS_READ: return RetValue(CL_KERNEL_ARG_ACCESS_READ_ONLY);
case CLC_KERNEL_ARG_ACCESS_WRITE: return RetValue(CL_KERNEL_ARG_ACCESS_WRITE_ONLY);
case CLC_KERNEL_ARG_ACCESS_READ | CLC_KERNEL_ARG_ACCESS_WRITE: return RetValue(CL_KERNEL_ARG_ACCESS_READ_WRITE);
}
case CL_KERNEL_ARG_TYPE_NAME: return RetValue(arg.type_name);
case CL_KERNEL_ARG_TYPE_QUALIFIER:
{
cl_kernel_arg_type_qualifier qualifier = CL_KERNEL_ARG_TYPE_NONE;
if ((arg.type_qualifier & CLC_KERNEL_ARG_TYPE_CONST) ||
arg.address_qualifier == CLC_KERNEL_ARG_ADDRESS_CONSTANT) qualifier |= CL_KERNEL_ARG_TYPE_CONST;
if (arg.type_qualifier & CLC_KERNEL_ARG_TYPE_RESTRICT) qualifier |= CL_KERNEL_ARG_TYPE_RESTRICT;
if (arg.type_qualifier & CLC_KERNEL_ARG_TYPE_VOLATILE) qualifier |= CL_KERNEL_ARG_TYPE_VOLATILE;
return RetValue(qualifier);
}
case CL_KERNEL_ARG_NAME:
if (arg.name) return RetValue(arg.name);
return CL_KERNEL_ARG_INFO_NOT_AVAILABLE;
}
return kernel.m_Parent->GetContext().GetErrorReporter()("Unknown param_name", CL_INVALID_VALUE);
}
extern CL_API_ENTRY cl_int CL_API_CALL
clGetKernelWorkGroupInfo(cl_kernel kernel_,
cl_device_id device,
cl_kernel_work_group_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
if (!kernel_)
{
return CL_INVALID_KERNEL;
}
UNREFERENCED_PARAMETER(device);
auto RetValue = [&](auto&& param)
{
return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret);
};
auto& kernel = *static_cast<Kernel*>(kernel_);
switch (param_name)
{
case CL_KERNEL_WORK_GROUP_SIZE: return RetValue((size_t)D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP);
case CL_KERNEL_COMPILE_WORK_GROUP_SIZE:
{
size_t size[3] = {};
auto ReqDims = kernel.GetRequiredLocalDims();
if (ReqDims)
std::copy(ReqDims, ReqDims + 3, size);
return RetValue(size);
}
case CL_KERNEL_LOCAL_MEM_SIZE:
{
size_t size = kernel.m_pDxil->metadata.local_mem_size;
for (cl_uint i = 0; i < kernel.m_pDxil->kernel->num_args; ++i)
{
if (kernel.m_pDxil->kernel->args[i].address_qualifier == CLC_KERNEL_ARG_ADDRESS_LOCAL)
{
size -= 4;
size += kernel.m_ArgMetadataToCompiler[i].localptr.size;
}
}
return RetValue(size);
}
case CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE: return RetValue((size_t)64);
case CL_KERNEL_PRIVATE_MEM_SIZE: return RetValue(kernel.m_pDxil->metadata.priv_mem_size);
}
return CL_INVALID_VALUE;
}
| 38.480263 | 147 | 0.614849 | [
"object"
] |
df761bc3f8883cd3bc41f392610b449ec4196955 | 27,233 | cpp | C++ | emulator/src/lib/netlist/nl_setup.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/lib/netlist/nl_setup.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/lib/netlist/nl_setup.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:GPL-2.0+
// copyright-holders:Couriersud
/*
* nlsetup.c
*
*/
#include "plib/palloc.h"
#include "plib/putil.h"
#include "nl_base.h"
#include "nl_setup.h"
#include "nl_parser.h"
#include "nl_factory.h"
#include "devices/nlid_system.h"
#include "devices/nlid_proxy.h"
#include "analog/nld_twoterm.h"
#include "solver/nld_solver.h"
#include "devices/nlid_truthtable.h"
// ----------------------------------------------------------------------------------------
// setup_t
// ----------------------------------------------------------------------------------------
namespace netlist
{
setup_t::setup_t(netlist_t &netlist)
: m_netlist(netlist)
, m_factory(*this)
, m_proxy_cnt(0)
, m_frontier_cnt(0)
{
devices::initialize_factory(m_factory);
}
setup_t::~setup_t()
{
m_links.clear();
m_alias.clear();
m_params.clear();
m_terminals.clear();
m_param_values.clear();
m_sources.clear();
}
pstring setup_t::build_fqn(const pstring &obj_name) const
{
if (m_namespace_stack.empty())
//return netlist().name() + "." + obj_name;
return obj_name;
else
return m_namespace_stack.top() + "." + obj_name;
}
void setup_t::namespace_push(const pstring &aname)
{
if (m_namespace_stack.empty())
//m_namespace_stack.push(netlist().name() + "." + aname);
m_namespace_stack.push(aname);
else
m_namespace_stack.push(m_namespace_stack.top() + "." + aname);
}
void setup_t::namespace_pop()
{
m_namespace_stack.pop();
}
void setup_t::register_lib_entry(const pstring &name, const pstring &sourcefile)
{
factory().register_device(plib::make_unique_base<factory::element_t, factory::library_element_t>(*this, name, name, "", sourcefile));
}
void setup_t::register_dev(const pstring &classname, const pstring &name)
{
auto f = factory().factory_by_name(classname);
if (f == nullptr)
log().fatal(MF_1_CLASS_1_NOT_FOUND, classname);
/* make sure we parse macro library entries */
f->macro_actions(netlist(), name);
m_device_factory.push_back(std::pair<pstring, factory::element_t *>(build_fqn(name), f));
}
bool setup_t::device_exists(const pstring &name) const
{
for (auto e : m_device_factory)
{
if (e.first == name)
return true;
}
return false;
}
void setup_t::register_model(const pstring &model_in)
{
auto pos = model_in.find(" ");
if (pos == pstring::npos)
log().fatal(MF_1_UNABLE_TO_PARSE_MODEL_1, model_in);
pstring model = model_in.left(pos).trim().ucase();
pstring def = model_in.substr(pos + 1).trim();
if (!m_models.insert({model, def}).second)
log().fatal(MF_1_MODEL_ALREADY_EXISTS_1, model_in);
}
void setup_t::register_alias_nofqn(const pstring &alias, const pstring &out)
{
if (!m_alias.insert({alias, out}).second)
log().fatal(MF_1_ADDING_ALI1_TO_ALIAS_LIST, alias);
}
void setup_t::register_alias(const pstring &alias, const pstring &out)
{
pstring alias_fqn = build_fqn(alias);
pstring out_fqn = build_fqn(out);
register_alias_nofqn(alias_fqn, out_fqn);
}
void setup_t::register_dippins_arr(const pstring &terms)
{
std::vector<pstring> list(plib::psplit(terms,", "));
if (list.size() == 0 || (list.size() % 2) == 1)
log().fatal(MF_1_DIP_PINS_MUST_BE_AN_EQUAL_NUMBER_OF_PINS_1,
build_fqn(""));
std::size_t n = list.size();
for (std::size_t i = 0; i < n / 2; i++)
{
register_alias(plib::pfmt("{1}")(i+1), list[i * 2]);
register_alias(plib::pfmt("{1}")(n-i), list[i * 2 + 1]);
}
}
pstring setup_t::termtype_as_str(detail::core_terminal_t &in) const
{
switch (in.type())
{
case detail::terminal_type::TERMINAL:
return pstring("TERMINAL");
case detail::terminal_type::INPUT:
return pstring("INPUT");
case detail::terminal_type::OUTPUT:
return pstring("OUTPUT");
}
log().fatal(MF_1_UNKNOWN_OBJECT_TYPE_1, static_cast<unsigned>(in.type()));
return pstring("Error");
}
pstring setup_t::get_initial_param_val(const pstring &name, const pstring &def)
{
auto i = m_param_values.find(name);
if (i != m_param_values.end())
return i->second;
else
return def;
}
double setup_t::get_initial_param_val(const pstring &name, const double def)
{
auto i = m_param_values.find(name);
if (i != m_param_values.end())
{
double vald = 0;
if (sscanf(i->second.c_str(), "%lf", &vald) != 1)
log().fatal(MF_2_INVALID_NUMBER_CONVERSION_1_2, name, i->second);
return vald;
}
else
return def;
}
int setup_t::get_initial_param_val(const pstring &name, const int def)
{
auto i = m_param_values.find(name);
if (i != m_param_values.end())
{
double vald = 0;
if (sscanf(i->second.c_str(), "%lf", &vald) != 1)
log().fatal(MF_2_INVALID_NUMBER_CONVERSION_1_2, name, i->second);
return static_cast<int>(vald);
}
else
return def;
}
void setup_t::register_param(const pstring &name, param_t ¶m)
{
if (!m_params.insert({param.name(), param_ref_t(param.name(), param.device(), param)}).second)
log().fatal(MF_1_ADDING_PARAMETER_1_TO_PARAMETER_LIST, name);
}
void setup_t::register_term(detail::core_terminal_t &term)
{
if (!m_terminals.insert({term.name(), &term}).second)
log().fatal(MF_2_ADDING_1_2_TO_TERMINAL_LIST, termtype_as_str(term),
term.name());
log().debug("{1} {2}\n", termtype_as_str(term), term.name());
}
void setup_t::register_link_arr(const pstring &terms)
{
std::vector<pstring> list(plib::psplit(terms,", "));
if (list.size() < 2)
log().fatal(MF_2_NET_C_NEEDS_AT_LEAST_2_TERMINAL);
for (std::size_t i = 1; i < list.size(); i++)
{
register_link(list[0], list[i]);
}
}
void setup_t::register_link_fqn(const pstring &sin, const pstring &sout)
{
link_t temp = link_t(sin, sout);
log().debug("link {1} <== {2}\n", sin, sout);
m_links.push_back(temp);
}
void setup_t::register_link(const pstring &sin, const pstring &sout)
{
register_link_fqn(build_fqn(sin), build_fqn(sout));
}
void setup_t::remove_connections(const pstring &pin)
{
pstring pinfn = build_fqn(pin);
bool found = false;
for (auto link = m_links.begin(); link != m_links.end(); )
{
if ((link->first == pinfn) || (link->second == pinfn))
{
log().verbose("removing connection: {1} <==> {2}\n", link->first, link->second);
link = m_links.erase(link);
found = true;
}
else
link++;
}
if (!found)
log().fatal(MF_1_FOUND_NO_OCCURRENCE_OF_1, pin);
}
void setup_t::register_frontier(const pstring &attach, const double r_IN, const double r_OUT)
{
pstring frontier_name = plib::pfmt("frontier_{1}")(m_frontier_cnt);
m_frontier_cnt++;
register_dev("FRONTIER_DEV", frontier_name);
register_param(frontier_name + ".RIN", r_IN);
register_param(frontier_name + ".ROUT", r_OUT);
register_link(frontier_name + ".G", "GND");
pstring attfn = build_fqn(attach);
pstring front_fqn = build_fqn(frontier_name);
bool found = false;
for (auto & link : m_links)
{
if (link.first == attfn)
{
link.first = front_fqn + ".I";
found = true;
}
else if (link.second == attfn)
{
link.second = front_fqn + ".I";
found = true;
}
}
if (!found)
log().fatal(MF_1_FOUND_NO_OCCURRENCE_OF_1, attach);
register_link(attach, frontier_name + ".Q");
}
void setup_t::register_param(const pstring ¶m, const double value)
{
register_param(param, plib::pfmt("{1:.9}").e(value));
}
void setup_t::register_param(const pstring ¶m, const pstring &value)
{
pstring fqn = build_fqn(param);
auto idx = m_param_values.find(fqn);
if (idx == m_param_values.end())
{
if (!m_param_values.insert({fqn, value}).second)
log().fatal(MF_1_ADDING_PARAMETER_1_TO_PARAMETER_LIST,
param);
}
else
{
log().warning(MW_3_OVERWRITING_PARAM_1_OLD_2_NEW_3, fqn, idx->second,
value);
m_param_values[fqn] = value;
}
}
const pstring setup_t::resolve_alias(const pstring &name) const
{
pstring temp = name;
pstring ret;
/* FIXME: Detect endless loop */
do {
ret = temp;
auto p = m_alias.find(ret);
temp = (p != m_alias.end() ? p->second : "");
} while (temp != "" && temp != ret);
log().debug("{1}==>{2}\n", name, ret);
return ret;
}
detail::core_terminal_t *setup_t::find_terminal(const pstring &terminal_in, bool required)
{
const pstring &tname = resolve_alias(terminal_in);
auto ret = m_terminals.find(tname);
/* look for default */
if (ret == m_terminals.end())
{
/* look for ".Q" std output */
ret = m_terminals.find(tname + ".Q");
}
detail::core_terminal_t *term = (ret == m_terminals.end() ? nullptr : ret->second);
if (term == nullptr && required)
log().fatal(MF_2_TERMINAL_1_2_NOT_FOUND, terminal_in, tname);
if (term != nullptr)
log().debug("Found input {1}\n", tname);
return term;
}
detail::core_terminal_t *setup_t::find_terminal(const pstring &terminal_in,
detail::terminal_type atype, bool required)
{
const pstring &tname = resolve_alias(terminal_in);
auto ret = m_terminals.find(tname);
/* look for default */
if (ret == m_terminals.end() && atype == detail::terminal_type::OUTPUT)
{
/* look for ".Q" std output */
ret = m_terminals.find(tname + ".Q");
}
if (ret == m_terminals.end() && required)
log().fatal(MF_2_TERMINAL_1_2_NOT_FOUND, terminal_in, tname);
detail::core_terminal_t *term = (ret == m_terminals.end() ? nullptr : ret->second);
if (term != nullptr && term->type() != atype)
{
if (required)
log().fatal(MF_2_OBJECT_1_2_WRONG_TYPE, terminal_in, tname);
else
term = nullptr;
}
if (term != nullptr)
log().debug("Found input {1}\n", tname);
return term;
}
param_t *setup_t::find_param(const pstring ¶m_in, bool required) const
{
const pstring param_in_fqn = build_fqn(param_in);
const pstring &outname = resolve_alias(param_in_fqn);
auto ret = m_params.find(outname);
if (ret == m_params.end() && required)
log().fatal(MF_2_PARAMETER_1_2_NOT_FOUND, param_in_fqn, outname);
if (ret != m_params.end())
log().debug("Found parameter {1}\n", outname);
return (ret == m_params.end() ? nullptr : &ret->second.m_param);
}
devices::nld_base_proxy *setup_t::get_d_a_proxy(detail::core_terminal_t &out)
{
nl_assert(out.is_logic());
logic_output_t &out_cast = static_cast<logic_output_t &>(out);
devices::nld_base_proxy *proxy = out_cast.get_proxy();
if (proxy == nullptr)
{
// create a new one ...
pstring x = plib::pfmt("proxy_da_{1}_{2}")(out.name())(m_proxy_cnt);
auto new_proxy =
out_cast.logic_family()->create_d_a_proxy(netlist(), x, &out_cast);
m_proxy_cnt++;
//new_proxy->start_dev();
/* connect all existing terminals to new net */
for (auto & p : out.net().m_core_terms)
{
p->clear_net(); // de-link from all nets ...
if (!connect(new_proxy->proxy_term(), *p))
log().fatal(MF_2_CONNECTING_1_TO_2,
new_proxy->proxy_term().name(), (*p).name());
}
out.net().m_core_terms.clear(); // clear the list
out.net().add_terminal(new_proxy->in());
out_cast.set_proxy(proxy);
proxy = new_proxy.get();
netlist().register_dev(std::move(new_proxy));
}
return proxy;
}
devices::nld_base_proxy *setup_t::get_a_d_proxy(detail::core_terminal_t &inp)
{
nl_assert(inp.is_logic());
logic_input_t &incast = dynamic_cast<logic_input_t &>(inp);
devices::nld_base_proxy *proxy = incast.get_proxy();
if (proxy != nullptr)
return proxy;
else
{
log().debug("connect_terminal_input: connecting proxy\n");
pstring x = plib::pfmt("proxy_ad_{1}_{2}")(inp.name())(m_proxy_cnt);
auto new_proxy = incast.logic_family()->create_a_d_proxy(netlist(), x, &incast);
//auto new_proxy = plib::owned_ptr<devices::nld_a_to_d_proxy>::Create(netlist(), x, &incast);
incast.set_proxy(new_proxy.get());
m_proxy_cnt++;
auto ret = new_proxy.get();
/* connect all existing terminals to new net */
if (inp.has_net())
{
for (auto & p : inp.net().m_core_terms)
{
p->clear_net(); // de-link from all nets ...
if (!connect(ret->proxy_term(), *p))
log().fatal(MF_2_CONNECTING_1_TO_2,
ret->proxy_term().name(), (*p).name());
}
inp.net().m_core_terms.clear(); // clear the list
}
ret->out().net().add_terminal(inp);
netlist().register_dev(std::move(new_proxy));
return ret;
}
}
void setup_t::merge_nets(detail::net_t &thisnet, detail::net_t &othernet)
{
log().debug("merging nets ...\n");
if (&othernet == &thisnet)
{
log().warning(MW_1_CONNECTING_1_TO_ITSELF, thisnet.name());
return; // Nothing to do
}
if (thisnet.isRailNet() && othernet.isRailNet())
log().fatal(MF_2_MERGE_RAIL_NETS_1_AND_2,
thisnet.name(), othernet.name());
if (othernet.isRailNet())
{
log().debug("othernet is railnet\n");
merge_nets(othernet, thisnet);
}
else
{
othernet.move_connections(thisnet);
}
}
void setup_t::connect_input_output(detail::core_terminal_t &in, detail::core_terminal_t &out)
{
if (out.is_analog() && in.is_logic())
{
auto proxy = get_a_d_proxy(in);
out.net().add_terminal(proxy->proxy_term());
}
else if (out.is_logic() && in.is_analog())
{
devices::nld_base_proxy *proxy = get_d_a_proxy(out);
connect_terminals(proxy->proxy_term(), in);
//proxy->out().net().register_con(in);
}
else
{
if (in.has_net())
merge_nets(out.net(), in.net());
else
out.net().add_terminal(in);
}
}
void setup_t::connect_terminal_input(terminal_t &term, detail::core_terminal_t &inp)
{
if (inp.is_analog())
{
connect_terminals(inp, term);
}
else if (inp.is_logic())
{
log().verbose("connect terminal {1} (in, {2}) to {3}\n", inp.name(),
inp.is_analog() ? pstring("analog") : inp.is_logic() ? pstring("logic") : pstring("?"), term.name());
auto proxy = get_a_d_proxy(inp);
//out.net().register_con(proxy->proxy_term());
connect_terminals(term, proxy->proxy_term());
}
else
{
log().fatal(MF_1_OBJECT_INPUT_TYPE_1, inp.name());
}
}
void setup_t::connect_terminal_output(terminal_t &in, detail::core_terminal_t &out)
{
if (out.is_analog())
{
log().debug("connect_terminal_output: {1} {2}\n", in.name(), out.name());
/* no proxy needed, just merge existing terminal net */
if (in.has_net())
merge_nets(out.net(), in.net());
else
out.net().add_terminal(in);
}
else if (out.is_logic())
{
log().debug("connect_terminal_output: connecting proxy\n");
devices::nld_base_proxy *proxy = get_d_a_proxy(out);
connect_terminals(proxy->proxy_term(), in);
}
else
{
log().fatal(MF_1_OBJECT_OUTPUT_TYPE_1, out.name());
}
}
void setup_t::connect_terminals(detail::core_terminal_t &t1, detail::core_terminal_t &t2)
{
if (t1.has_net() && t2.has_net())
{
log().debug("T2 and T1 have net\n");
merge_nets(t1.net(), t2.net());
}
else if (t2.has_net())
{
log().debug("T2 has net\n");
t2.net().add_terminal(t1);
}
else if (t1.has_net())
{
log().debug("T1 has net\n");
t1.net().add_terminal(t2);
}
else
{
log().debug("adding analog net ...\n");
// FIXME: Nets should have a unique name
auto anet = plib::palloc<analog_net_t>(netlist(),"net." + t1.name());
netlist().m_nets.push_back(plib::owned_ptr<analog_net_t>(anet, true));
t1.set_net(anet);
anet->add_terminal(t2);
anet->add_terminal(t1);
}
}
static detail::core_terminal_t &resolve_proxy(detail::core_terminal_t &term)
{
if (term.is_logic())
{
logic_t &out = dynamic_cast<logic_t &>(term);
if (out.has_proxy())
return out.get_proxy()->proxy_term();
}
return term;
}
bool setup_t::connect_input_input(detail::core_terminal_t &t1, detail::core_terminal_t &t2)
{
bool ret = false;
if (t1.has_net())
{
if (t1.net().isRailNet())
ret = connect(t2, t1.net().railterminal());
if (!ret)
{
for (auto & t : t1.net().m_core_terms)
{
if (t->is_type(detail::terminal_type::TERMINAL))
ret = connect(t2, *t);
if (ret)
break;
}
}
}
if (!ret && t2.has_net())
{
if (t2.net().isRailNet())
ret = connect(t1, t2.net().railterminal());
if (!ret)
{
for (auto & t : t2.net().m_core_terms)
{
if (t->is_type(detail::terminal_type::TERMINAL))
ret = connect(t1, *t);
if (ret)
break;
}
}
}
return ret;
}
bool setup_t::connect(detail::core_terminal_t &t1_in, detail::core_terminal_t &t2_in)
{
log().debug("Connecting {1} to {2}\n", t1_in.name(), t2_in.name());
detail::core_terminal_t &t1 = resolve_proxy(t1_in);
detail::core_terminal_t &t2 = resolve_proxy(t2_in);
bool ret = true;
if (t1.is_type(detail::terminal_type::OUTPUT) && t2.is_type(detail::terminal_type::INPUT))
{
if (t2.has_net() && t2.net().isRailNet())
log().fatal(MF_1_INPUT_1_ALREADY_CONNECTED, t2.name());
connect_input_output(t2, t1);
}
else if (t1.is_type(detail::terminal_type::INPUT) && t2.is_type(detail::terminal_type::OUTPUT))
{
if (t1.has_net() && t1.net().isRailNet())
log().fatal(MF_1_INPUT_1_ALREADY_CONNECTED, t1.name());
connect_input_output(t1, t2);
}
else if (t1.is_type(detail::terminal_type::OUTPUT) && t2.is_type(detail::terminal_type::TERMINAL))
{
connect_terminal_output(dynamic_cast<terminal_t &>(t2), t1);
}
else if (t1.is_type(detail::terminal_type::TERMINAL) && t2.is_type(detail::terminal_type::OUTPUT))
{
connect_terminal_output(dynamic_cast<terminal_t &>(t1), t2);
}
else if (t1.is_type(detail::terminal_type::INPUT) && t2.is_type(detail::terminal_type::TERMINAL))
{
connect_terminal_input(dynamic_cast<terminal_t &>(t2), t1);
}
else if (t1.is_type(detail::terminal_type::TERMINAL) && t2.is_type(detail::terminal_type::INPUT))
{
connect_terminal_input(dynamic_cast<terminal_t &>(t1), t2);
}
else if (t1.is_type(detail::terminal_type::TERMINAL) && t2.is_type(detail::terminal_type::TERMINAL))
{
connect_terminals(dynamic_cast<terminal_t &>(t1), dynamic_cast<terminal_t &>(t2));
}
else if (t1.is_type(detail::terminal_type::INPUT) && t2.is_type(detail::terminal_type::INPUT))
{
ret = connect_input_input(t1, t2);
}
else
ret = false;
//netlist().error("Connecting {1} to {2} not supported!\n", t1.name(), t2.name());
return ret;
}
void setup_t::resolve_inputs()
{
log().verbose("Resolving inputs ...");
/* Netlist can directly connect input to input.
* We therefore first park connecting inputs and retry
* after all other terminals were connected.
*/
int tries = NL_MAX_LINK_RESOLVE_LOOPS;
while (m_links.size() > 0 && tries > 0)
{
for (auto li = m_links.begin(); li != m_links.end(); )
{
const pstring t1s = li->first;
const pstring t2s = li->second;
detail::core_terminal_t *t1 = find_terminal(t1s);
detail::core_terminal_t *t2 = find_terminal(t2s);
if (connect(*t1, *t2))
li = m_links.erase(li);
else
li++;
}
tries--;
}
if (tries == 0)
{
for (auto & link : m_links)
log().warning(MF_2_CONNECTING_1_TO_2, link.first, link.second);
log().fatal(MF_0_LINK_TRIES_EXCEEDED);
}
log().verbose("deleting empty nets ...");
// delete empty nets
netlist().m_nets.erase(
std::remove_if(netlist().m_nets.begin(), netlist().m_nets.end(),
[](plib::owned_ptr<detail::net_t> &x)
{
if (x->num_cons() == 0)
{
x->netlist().log().verbose("Deleting net {1} ...", x->name());
return true;
}
else
return false;
}), netlist().m_nets.end());
pstring errstr("");
log().verbose("looking for terminals not connected ...");
for (auto & i : m_terminals)
{
detail::core_terminal_t *term = i.second;
if (!term->has_net() && dynamic_cast< devices::NETLIB_NAME(dummy_input) *>(&term->device()) != nullptr)
log().warning(MW_1_DUMMY_1_WITHOUT_CONNECTIONS, term->name());
else if (!term->has_net())
errstr += plib::pfmt("Found terminal {1} without a net\n")(term->name());
else if (term->net().num_cons() == 0)
log().warning(MW_1_TERMINAL_1_WITHOUT_CONNECTIONS, term->name());
}
//FIXME: error string handling
if (errstr != "")
log().fatal("{1}", errstr);
}
void setup_t::start_devices()
{
pstring env = plib::util::environment("NL_LOGS", "");
if (env != "")
{
log().debug("Creating dynamic logs ...");
std::vector<pstring> loglist(plib::psplit(env, ":"));
for (pstring ll : loglist)
{
pstring name = "log_" + ll;
auto nc = factory().factory_by_name("LOG")->Create(netlist(), name);
register_link(name + ".I", ll);
log().debug(" dynamic link {1}: <{2}>\n",ll, name);
netlist().register_dev(std::move(nc));
}
}
}
plib::plog_base<netlist_t, NL_DEBUG> &setup_t::log()
{
return netlist().log();
}
const plib::plog_base<netlist_t, NL_DEBUG> &setup_t::log() const
{
return netlist().log();
}
// ----------------------------------------------------------------------------------------
// Model
// ----------------------------------------------------------------------------------------
static pstring model_string(detail::model_map_t &map)
{
pstring ret = map["COREMODEL"] + "(";
for (auto & i : map)
ret = ret + i.first + "=" + i.second + " ";
return ret + ")";
}
void setup_t::model_parse(const pstring &model_in, detail::model_map_t &map)
{
pstring model = model_in;
std::size_t pos = 0;
pstring key;
while (true)
{
pos = model.find("(");
if (pos != pstring::npos) break;
key = model.ucase();
auto i = m_models.find(key);
if (i == m_models.end())
log().fatal(MF_1_MODEL_NOT_FOUND, model);
model = i->second;
}
pstring xmodel = model.left(pos);
if (xmodel.equals("_"))
map["COREMODEL"] = key;
else
{
auto i = m_models.find(xmodel);
if (i != m_models.end())
model_parse(xmodel, map);
else
log().fatal(MF_1_MODEL_NOT_FOUND, model_in);
}
pstring remainder = model.substr(pos + 1).trim();
if (!remainder.endsWith(")"))
log().fatal(MF_1_MODEL_ERROR_1, model);
// FIMXE: Not optimal
remainder = remainder.left(remainder.length() - 1);
std::vector<pstring> pairs(plib::psplit(remainder," ", true));
for (pstring &pe : pairs)
{
auto pose = pe.find("=");
if (pose == pstring::npos)
log().fatal(MF_1_MODEL_ERROR_ON_PAIR_1, model);
map[pe.left(pose).ucase()] = pe.substr(pose + 1);
}
}
const pstring setup_t::model_value_str(detail::model_map_t &map, const pstring &entity)
{
pstring ret;
if (entity != entity.ucase())
log().fatal(MF_2_MODEL_PARAMETERS_NOT_UPPERCASE_1_2, entity,
model_string(map));
if (map.find(entity) == map.end())
log().fatal(MF_2_ENTITY_1_NOT_FOUND_IN_MODEL_2, entity, model_string(map));
else
ret = map[entity];
return ret;
}
nl_double setup_t::model_value(detail::model_map_t &map, const pstring &entity)
{
pstring tmp = model_value_str(map, entity);
nl_double factor = NL_FCONST(1.0);
auto p = std::next(tmp.begin(), static_cast<pstring::difference_type>(tmp.length() - 1));
switch (*p)
{
case 'M': factor = 1e6; break;
case 'k': factor = 1e3; break;
case 'm': factor = 1e-3; break;
case 'u': factor = 1e-6; break;
case 'n': factor = 1e-9; break;
case 'p': factor = 1e-12; break;
case 'f': factor = 1e-15; break;
case 'a': factor = 1e-18; break;
default:
if (*p < '0' || *p > '9')
log().fatal(MF_1_UNKNOWN_NUMBER_FACTOR_IN_1, entity);
}
if (factor != NL_FCONST(1.0))
tmp = tmp.left(tmp.length() - 1);
return tmp.as_double() * factor;
}
class logic_family_std_proxy_t : public logic_family_desc_t
{
public:
logic_family_std_proxy_t() { }
virtual plib::owned_ptr<devices::nld_base_d_to_a_proxy> create_d_a_proxy(netlist_t &anetlist,
const pstring &name, logic_output_t *proxied) const override;
virtual plib::owned_ptr<devices::nld_base_a_to_d_proxy> create_a_d_proxy(netlist_t &anetlist, const pstring &name, logic_input_t *proxied) const override;
};
plib::owned_ptr<devices::nld_base_d_to_a_proxy> logic_family_std_proxy_t::create_d_a_proxy(netlist_t &anetlist,
const pstring &name, logic_output_t *proxied) const
{
return plib::owned_ptr<devices::nld_base_d_to_a_proxy>::Create<devices::nld_d_to_a_proxy>(anetlist, name, proxied);
}
plib::owned_ptr<devices::nld_base_a_to_d_proxy> logic_family_std_proxy_t::create_a_d_proxy(netlist_t &anetlist, const pstring &name, logic_input_t *proxied) const
{
return plib::owned_ptr<devices::nld_base_a_to_d_proxy>::Create<devices::nld_a_to_d_proxy>(anetlist, name, proxied);
}
const logic_family_desc_t *setup_t::family_from_model(const pstring &model)
{
detail::model_map_t map;
model_parse(model, map);
if (model_value_str(map, "TYPE") == "TTL")
return family_TTL();
if (model_value_str(map, "TYPE") == "CD4XXX")
return family_CD4XXX();
for (auto & e : netlist().m_family_cache)
if (e.first == model)
return e.second.get();
auto ret = plib::make_unique_base<logic_family_desc_t, logic_family_std_proxy_t>();
ret->m_fixed_V = model_value(map, "FV");
ret->m_low_thresh_PCNT = model_value(map, "IVL");
ret->m_high_thresh_PCNT = model_value(map, "IVH");
ret->m_low_VO = model_value(map, "OVL");
ret->m_high_VO = model_value(map, "OVH");
ret->m_R_low = model_value(map, "ORL");
ret->m_R_high = model_value(map, "ORH");
auto retp = ret.get();
netlist().m_family_cache.emplace_back(model, std::move(ret));
return retp;
}
void setup_t::tt_factory_create(tt_desc &desc, const pstring &sourcefile)
{
devices::tt_factory_create(*this, desc, sourcefile);
}
// ----------------------------------------------------------------------------------------
// Sources
// ----------------------------------------------------------------------------------------
void setup_t::include(const pstring &netlist_name)
{
for (auto &source : m_sources)
{
if (source->parse(netlist_name))
return;
}
log().fatal(MF_1_NOT_FOUND_IN_SOURCE_COLLECTION, netlist_name);
}
std::unique_ptr<plib::pistream> setup_t::get_data_stream(const pstring &name)
{
for (auto &source : m_sources)
{
if (source->type() == source_t::DATA)
{
auto strm = source->stream(name);
if (strm)
return strm;
}
}
log().warning(MW_1_DATA_1_NOT_FOUND, name);
return std::unique_ptr<plib::pistream>(nullptr);
}
bool setup_t::parse_stream(plib::putf8_reader &istrm, const pstring &name)
{
plib::pomemstream ostrm;
plib::putf8_writer owrt(ostrm);
plib::ppreprocessor(&m_defines).process(istrm, owrt);
plib::pimemstream istrm2(ostrm);
plib::putf8_reader reader2(istrm2);
return parser_t(reader2, *this).parse(name);
}
void setup_t::register_define(pstring defstr)
{
auto p = defstr.find("=");
if (p != pstring::npos)
register_define(defstr.left(p), defstr.substr(p+1));
else
register_define(defstr, "1");
}
// ----------------------------------------------------------------------------------------
// base sources
// ----------------------------------------------------------------------------------------
bool source_t::parse(const pstring &name)
{
if (m_type != SOURCE)
return false;
else
{
auto rstream = stream(name);
plib::putf8_reader reader(*rstream);
return m_setup.parse_stream(reader, name);
}
}
std::unique_ptr<plib::pistream> source_string_t::stream(const pstring &name)
{
return plib::make_unique_base<plib::pistream, plib::pimemstream>(m_str.c_str(), m_str.mem_t_size());
}
std::unique_ptr<plib::pistream> source_mem_t::stream(const pstring &name)
{
return plib::make_unique_base<plib::pistream, plib::pimemstream>(m_str.c_str(), m_str.mem_t_size());
}
std::unique_ptr<plib::pistream> source_file_t::stream(const pstring &name)
{
return plib::make_unique_base<plib::pistream, plib::pifilestream>(m_filename);
}
bool source_proc_t::parse(const pstring &name)
{
if (name == m_setup_func_name)
{
m_setup_func(setup());
return true;
}
else
return false;
}
std::unique_ptr<plib::pistream> source_proc_t::stream(const pstring &name)
{
std::unique_ptr<plib::pistream> p(nullptr);
return p;
}
}
| 26.388566 | 162 | 0.663166 | [
"vector",
"model"
] |
df7c60fba74024eed14ef5262cf651bd455178c7 | 182,775 | cpp | C++ | src/dome/DomeCoreXeq.cpp | EricKTCheung/dmlite | 7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d | [
"Apache-2.0"
] | null | null | null | src/dome/DomeCoreXeq.cpp | EricKTCheung/dmlite | 7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d | [
"Apache-2.0"
] | null | null | null | src/dome/DomeCoreXeq.cpp | EricKTCheung/dmlite | 7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 CERN
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/** @file DomeCoreXeq.cpp
* @brief A part of the implementation of DomeCore. Functions implementing commands
* @author Fabrizio Furano
* @date Feb 2016
*/
#include "DomeCore.h"
#include "DomeLog.h"
#include "utils/DomeUtils.h"
#include <sys/vfs.h>
#include <unistd.h>
#include <time.h>
#include <sys/param.h>
#include <stdio.h>
#include <algorithm>
#include <functional>
#include <time.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/optional/optional.hpp>
#include "cpp/authn.h"
#include "cpp/dmlite.h"
#include "cpp/catalog.h"
#include "cpp/utils/urls.h"
#include "utils/checksums.h"
#include "utils/DomeTalker.h"
using namespace dmlite;
/// Creates a new logical file entry, and all its parent directories
DmStatus mkdirminuspandcreate(SecurityContext ctx, DomeMySql &sql,
const std::string& path,
std::string &parentpath,
ExtendedStat &parentstat,
ExtendedStat &statinfo) throw (DmException) {
if (path.empty())
return DmStatus(EINVAL, "mkdirminuspandcreate - Empty path. Internal error ?");
if (path[0] != '/')
return DmStatus(EINVAL, "mkdirminuspandcreate - Paths must be absolute.");
Log(Logger::Lvl4, domelogmask, domelogname, "Entering. Absolute path: '" << path << "'");
std::vector<std::string> components = Url::splitPath(path);
std::vector<std::string> todo;
std::string name;
std::string fname = components.back();
components.pop_back();
// Make sure that all the parent dirs exist
do {
std::string ppath = Url::joinPath(components);
ExtendedStat st;
// Try to get the stat of the parent
DmStatus ret = sql.getStatbyLFN(st, ppath);
if (!ret.ok()) {
// No parent means that we have to create it later
Log(Logger::Lvl4, domelogmask, domelogname, "Path to create: '" << ppath << "'");
name = components.back();
components.pop_back();
todo.push_back(ppath);
}
else {
parentstat = st;
parentpath = ppath;
// This means that we successfully processed at least the parent dir
// that we have to return
break;
}
} while ( !components.empty() );
// Here we have a todo list of directories that we have to create
// .... so we do it
// But first check the permissions
// Need to be able to write to the parent
if (checkPermissions(&ctx, parentstat.acl, parentstat.stat, S_IWRITE) != 0)
return DmStatus(EPERM, SSTR("Need write access on '" << parentpath << "'"));
while (!todo.empty()) {
std::string p = todo.back();
todo.pop_back();
DmStatus ret = sql.makedir(parentstat, p, 0774, ctx.user.getUnsigned("uid"), ctx.user.getUnsigned("gid"));
if (!ret.ok()) {
// If we can't create the dir then this is a serious error, unless it already exists
Err(domelogname, "Cannot create path '" << parentpath << "' token: '" << p << "' err: " << ret.code() << "-" << ret.what());
return ret;
}
// Set proper ownership
//catalog->setOwner(parentpath, parentstat.stat.st_uid, parentstat.stat.st_gid);
// Update the parent for the next round
ret = sql.getStatbyParentFileid(parentstat, parentstat.stat.st_ino, p);
if (!ret.ok()) {
// If we can't create the dir then this is a serious error, unless it already exists
Err(domelogname, "Cannot stat path '" << parentpath << "' token: '" << p << "' err: " << ret.code() << "-" << ret.what());
return ret;
}
}
// If a miracle took us here, we only miss to create the final file
DmStatus ret = sql.createfile(parentstat, fname, 0664, ctx.user.getUnsigned("uid"), ctx.user.getUnsigned("gid"));
if (!ret.ok() && (ret.code() != EEXIST)) {
// If we can't create the dir then this is a serious error, unless it already exists
Err(domelogname, "Cannot create file '" << path << "' err: " << ret.code() << "-" << ret.what());
return ret;
}
// Get the statinfo for the final created file
ret = sql.getStatbyParentFileid(statinfo, parentstat.stat.st_ino, fname);
if (!ret.ok()) {
// If we can't create the dir then this is a serious error, unless it already exists
Err(domelogname, "Cannot stat final file '" << path << "' token: '" << fname << "' parent: " << parentstat.stat.st_ino << " err: " << ret.code() << "-" << ret.what());
return ret;
}
return DmStatus();
}
// pick from the list of appropriate filesystems, given the hints
std::vector<DomeFsInfo> DomeCore::pickFilesystems(const std::string &pool,
const std::string &host,
const std::string &fs) {
std::vector<DomeFsInfo> selected;
boost::unique_lock<boost::recursive_mutex> l(status);
Log(Logger::Lvl2, domelogmask, domelogname, "Picking from a list of " << status.fslist.size() << " filesystems to write into");
for(unsigned int i = 0; i < status.fslist.size(); i++) {
std::string fsname = SSTR(status.fslist[i].server << ":" << status.fslist[i].fs);
Log(Logger::Lvl3, domelogmask, domelogname, "Checking '" << fsname << "' of pool '" << status.fslist[i].poolname << "'");
if(!status.fslist[i].isGoodForWrite()) {
Log(Logger::Lvl3, domelogmask, domelogname, fsname << " ruled out - not good for write");
continue;
}
if(!pool.empty() && status.fslist[i].poolname != pool) {
Log(Logger::Lvl3, domelogmask, domelogname, fsname << " ruled out - does not match pool hint");
continue;
}
if(!host.empty() && status.fslist[i].server != host) {
Log(Logger::Lvl3, domelogmask, domelogname, fsname << " ruled out - does not match host hint");
continue;
}
if(!fs.empty() && status.fslist[i].fs != fs) {
Log(Logger::Lvl3, domelogmask, domelogname, fsname << " ruled out - does not match fs hint");
continue;
}
// fslist[i], you win
Log(Logger::Lvl3, domelogmask, domelogname, fsname << " has become a candidate for writing.");
selected.push_back(status.fslist[i]);
}
return selected;
}
int DomeCore::dome_put(DomeReq &req, FCGX_Request &request, bool &success, struct DomeFsInfo *dest, std::string *destrfn, bool dontsendok) {
success = false;
DomeQuotatoken token;
// fetch the parameters, lfn and placement suggestions
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
std::string addreplica_ = req.bodyfields.get<std::string>("additionalreplica", "");
std::string pool = req.bodyfields.get<std::string>("pool", "");
std::string host = req.bodyfields.get<std::string>("host", "");
std::string fs = req.bodyfields.get<std::string>("fs", "");
bool addreplica = false;
if ( (addreplica_ == "true") || (addreplica_ == "yes") || (addreplica_ == "1") || (addreplica_ == "on") )
addreplica = true;
// Log the parameters, level 1
Log(Logger::Lvl1, domelogmask, domelogname, "Entering. lfn: '" << lfn <<
"' addreplica: " << addreplica << " pool: '" << pool <<
"' host: '" << host << "' fs: '" << fs << "'");
if(status.role == status.roleDisk) {
return DomeReq::SendSimpleResp(request, 500, "dome_put only available on head nodes");
}
// Fill the security context
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
DmStatus ret;
DomeMySql sql;
{
ExtendedStat parent;
std::string parentPath, name;
ret = sql.getParent(parent, lfn, parentPath, name);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat the parent of lfn: '" << lfn << "'"));
ret = sql.traverseBackwards(ctx, parent);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Permission denied on lfn: '" << lfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// Need to be able to read the parent
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Need WRITE access on '" << parentPath << "'"));
}
// if(!req.remoteclientdn.size() || !req.remoteclienthost.size()) {
// return DomeReq::SendSimpleResp(request, 501, SSTR("Invalid remote client or remote host credentials: " << req.remoteclientdn << " - " << req.remoteclienthost));
// }
// Give errors for combinations of the parameters that are obviously wrong
if ( (host != "") && (pool != "") ) {
// Error! Log it as such!, level1
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "The pool hint and the host hint are mutually exclusive.");
}
// default minfreespace is 4GB. Gets overridden by the individual pool's value
int64_t minfreespace_bytes = CFG->GetLong("head.put.minfreespace_mb", 1024*4) * 1024*1024;
// use quotatokens?
// TODO: more than quotatoken may match, they all should be considered
if(pool.empty() && host.empty() && fs.empty()) {
if(!status.whichQuotatokenForLfn(lfn, token)) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "No quotatokens match lfn, and no hints were given.");
}
// Check if the quotatoken admits writes for the groups the client belongs to
// Please note that the clients' groups come through fastcgi,
// instead the groups in the quotatoken are in the form of gids
if(!status.canwriteintoQuotatoken(req, token)) {
// Prepare a complete error message that describes why the user can't write
std::string userfqans, tokengroups, s;
DomeGroupInfo gi;
// Start prettyprinting the groups the user belongs to
for (unsigned int i = 0; i < req.creds.groups.size(); i++) {
userfqans += req.creds.groups[i];
if (status.getGroup(req.creds.groups[i], gi)) {
userfqans += SSTR( "(" << gi.groupid << ")" );
}
else
userfqans += "(<unknown group>)";
if (i < req.creds.groups.size()-1) userfqans += ",";
}
// Then prettyprint the gids of the selected token
for (unsigned int i = 0; i < token.groupsforwrite.size(); i++) {
int g = atoi(token.groupsforwrite[i].c_str());
if (status.getGroup(g, gi)) {
tokengroups += SSTR( gi.groupname << "(" << gi.groupid << ")" );
}
else {
tokengroups += SSTR( "<unknown group>(" << token.groupsforwrite[i] << ")" );
}
if (i < token.groupsforwrite.size()-1) tokengroups += ",";
}
std::string err = SSTR("User '" << req.creds.clientName << " with fqans '" << userfqans <<
"' cannot write to quotatoken '" << token.s_token << "(" << token.u_token <<
")' with gids: '" << tokengroups);
Log(Logger::Lvl1, domelogmask, domelogname, err);
return DomeReq::SendSimpleResp(request, DOME_HTTP_DENIED, err);
}
char pooltype;
// Eventually override the default size
status.getPoolInfo(token.poolname, minfreespace_bytes, pooltype);
if(!status.fitsInQuotatoken(token, minfreespace_bytes)) {
std::string err = SSTR("Unable to complete put for '" << lfn << "' - quotatoken '" << token.u_token << "' has insufficient free space. minfreespace_bytes: " << minfreespace_bytes);
Log(Logger::Lvl1, domelogmask, domelogname, err);
return DomeReq::SendSimpleResp(request, DOME_HTTP_INSUFFICIENT_STORAGE, err);
}
pool = token.poolname;
}
// populate the list of candidate filesystems
std::vector<DomeFsInfo> selectedfss = pickFilesystems(pool, host, fs);
// no filesystems match? return error
if (selectedfss.empty()) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST,
SSTR("No filesystems match the given logical path and placement hints. "
"HINT: make sure that the correct pools are associated to the LFN, and that they are writable and online. "
"Selected pool: '" << pool << "'. Selected host: '" << host << "'. Selected fs: '" << fs << "'"));
}
// If we are replicating an existing file, the new replica must go into a filesystem that
// does not contain it already
try {
if (addreplica) {
// Get the list of the replicas of this lfn
std::vector<Replica> replicas;
ret = sql.getReplicas(replicas, lfn);
if (!ret.ok()) {
if (ret.code() == ENOENT)
return DomeReq::SendSimpleResp(request, 404, SSTR("File not found '" << lfn << "'"));
return DomeReq::SendSimpleResp(request, 500, SSTR("Not accessible '" << lfn << "' err: " <<
ret.code() << ":" << ret.what()));
}
// remove from the fslist the filesystems that match with any replica
for (int i = selectedfss.size()-1; i >= 0; i--) {
bool dropfs = false;
// Loop on the replicas
for(size_t j = 0; j < replicas.size(); j++) {
std::string rfn = replicas[j].rfn;
std::string pfn;
size_t pos = rfn.find(":");
if (pos == std::string::npos) pfn = rfn;
else
pfn = rfn.substr(rfn.find(":")+1, rfn.size());
if (status.PfnMatchesFS(replicas[j].server, pfn, selectedfss[i])) {
dropfs = true;
break;
}
}
if (dropfs) {
Log(Logger::Lvl4, domelogmask, domelogname, "Filesystem: '" << selectedfss[i].server << ":" << selectedfss[i].fs <<
"' already has a replica of '" << lfn << "', skipping");
selectedfss.erase(selectedfss.begin()+i);
}
}
}
} catch (DmException e) {
}
// If no filesystems remain, return error "filesystems full for path ..."
if ( !selectedfss.size() ) {
// Error!
return DomeReq::SendSimpleResp(request, DOME_HTTP_INSUFFICIENT_STORAGE,
SSTR("No filesystems can host an additional replica for lfn:'" << lfn));
}
// Remove the filesystems that have less than the minimum free space available
for (int i = selectedfss.size()-1; i >= 0; i--) {
if ( selectedfss[i].canPullFile(status) ) {
// If the filesystem belongs to a volatile pool then we filter it out
// only if the volume is too small, because we assume that files can be purged
if ( selectedfss[i].physicalsize < minfreespace_bytes ) {
Log(Logger::Lvl2, domelogmask, domelogname, "Filesystem: '" <<
selectedfss[i].server << ":" << selectedfss[i].fs <<
"' is smaller than " << minfreespace_bytes << "bytes");
selectedfss.erase(selectedfss.begin()+i);
}
}
else {
// The filesystem does not belong to a volatile pool, hence we check the free space
if (selectedfss[i].freespace < minfreespace_bytes) {
Log(Logger::Lvl2, domelogmask, domelogname, "Filesystem: '" << selectedfss[i].server << ":" << selectedfss[i].fs <<
"' has less than " << minfreespace_bytes << "bytes free");
selectedfss.erase(selectedfss.begin()+i);
}
}
}
// If no filesystems remain, return error "filesystems full for path ..."
if ( !selectedfss.size() ) {
// Error!
return DomeReq::SendSimpleResp(request, DOME_HTTP_INSUFFICIENT_STORAGE, "All matching filesystems are full.");
}
// Sort the selected filesystems by decreasing free space
std::sort(selectedfss.begin(), selectedfss.end(), DomeFsInfo::pred_decr_freespace());
// Use the free space as weight for a random choice among the filesystems
// Nice algorithm taken from http://stackoverflow.com/questions/1761626/weighted-random-numbers#1761646
long sum_of_weight = 0;
int fspos = 0;
for (unsigned int i = 0; i < selectedfss.size(); i++) {
sum_of_weight += (selectedfss[i].freespace >> 20);
}
// RAND_MAX is sufficiently big for this purpose
int rnd = random() % sum_of_weight;
for(unsigned int i=0; i < selectedfss.size(); i++) {
if(rnd < (selectedfss[i].freespace >> 20)) {
fspos = i;
break;
}
rnd -= (selectedfss[i].freespace >> 20);
}
// We have the fs, build the final pfn for the file
// fs/group/date/basename.r_ordinal.f_ordinal
Log(Logger::Lvl1, domelogmask, domelogname, "Selected fs: '" << selectedfss[fspos].server << ":" << selectedfss[fspos].fs <<
" from " << selectedfss.size() << " matchings for lfn: '" << lfn << "'");
// Fetch the time
time_t rawtimenow = time(0);
struct tm tmstruc;
char timestr[16], suffix[32];
localtime_r(&rawtimenow, &tmstruc);
strftime (timestr, 11, "%F", &tmstruc);
// Parse the lfn and pick the 4th token, likely the one with the VO name
std::vector<std::string> vecurl = dmlite::Url::splitPath(lfn);
sprintf(suffix, ".%ld.%ld", status.getGlobalputcount(), rawtimenow);
if (vecurl.size() < 5) {
std::ostringstream os;
os << "Unable to get vo name from the lfn: " << lfn;
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, DOME_HTTP_UNPROCESSABLE, os);
}
std::string pfn = selectedfss[fspos].fs + "/" + vecurl[4] + "/" + timestr + "/" + *vecurl.rbegin() + suffix;
Log(Logger::Lvl4, domelogmask, domelogname, "lfn: '" << lfn << "' --> '" << selectedfss[fspos].server << ":" << pfn << "'");
// NOTE: differently from the historical dpmd, here we do not create the remote path/file
// of the replica in the disk. We jsut make sure that the LFN exists
// The replica in the catalog instead is created here
// Create the logical catalog entry, if not already present. We also create the parent dirs
// if they are absent
ExtendedStat parentstat, lfnstat;
std::string parentpath;
if (!addreplica) {
ret = mkdirminuspandcreate(ctx, sql, lfn, parentpath, parentstat, lfnstat);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot create logical directories for '" << lfn << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 422, os);
}
}
else
ret = sql.getStatbyLFN(lfnstat, lfn);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot add replica to '" << lfn << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, http_status(ret), os);
}
// Create the replica in the catalog
dmlite::Replica r;
r.fileid = lfnstat.stat.st_ino;
r.replicaid = 0;
r.nbaccesses = 0;
r.atime = r.ptime = r.ltime = time(0);
r.status = dmlite::Replica::kBeingPopulated;
r.type = dmlite::Replica::kPermanent;
r.rfn = selectedfss[fspos].server + ":" + pfn;
r["pool"] = selectedfss[fspos].poolname;
r["filesystem"] = selectedfss[fspos].fs;
r.setname = token.s_token;
r["accountedspacetokenname"] = token.u_token;
ret = sql.addReplica(r);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot create replica '" << r.rfn << "' for '" << lfn << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, http_status(ret), os);
}
// Here we are assuming that some frontend will soon start to write a new replica
// with the name we chose here
// Return the response
// This function may have been invoked to know
// details about the placement without telling the client
if (dest && destrfn) {
*dest = selectedfss[fspos];
*destrfn = r.rfn;
success = true;
Log(Logger::Lvl4, domelogmask, domelogname, "No data to the client will be sent yet - supplying destination to caller. ('" <<
*destrfn << "')");
return 0;
}
Log(Logger::Lvl4, domelogmask, domelogname, "Sending response to client for '" << pfn << "'");
boost::property_tree::ptree jresp;
jresp.put("pool", selectedfss[fspos].poolname);
jresp.put("host", selectedfss[fspos].server);
jresp.put("filesystem", selectedfss[fspos].fs);
jresp.put("pfn", pfn);
int rc = 0;
if (!dontsendok)
return DomeReq::SendSimpleResp(request, 200, jresp);
Log(Logger::Lvl3, domelogmask, domelogname, "Success");
success = true;
return rc;
};
int DomeCore::dome_access(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_access only available on head nodes.");
}
std::string absPath = DomeUtils::trim_trailing_slashes(req.bodyfields.get<std::string>("path", ""));
int mode = req.bodyfields.get<int>("mode", 0);
Log(Logger::Lvl4, domelogmask, domelogname, "Processing: '" << absPath << "' mode: " << mode);
if ( !absPath.size() ) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Empty rfn"));
}
ExtendedStat xstat;
boost::property_tree::ptree jresp;
dmlite::DmStatus ret;
{
DomeMySql sql;
ret = sql.getStatbyLFN(xstat, absPath);
}
if (!ret.ok()) {
if (ret.code() == ENOENT)
return DomeReq::SendSimpleResp(request, 404, SSTR("File not found '" << absPath << "'"));
return DomeReq::SendSimpleResp(request, 500, SSTR("Not accessible '" << absPath << "' err: "<< ret.what()));
}
mode_t perm = 0;
if (mode & R_OK) perm = S_IREAD;
if (mode & W_OK) perm |= S_IWRITE;
if (mode & X_OK) perm |= S_IEXEC;
SecurityContext ctx;
fillSecurityContext(ctx, req);
bool ok = false;
try {
ok = !checkPermissions(&ctx, xstat.acl, xstat.stat, perm);
} catch (DmException e) {}
if (!ok)
return DomeReq::SendSimpleResp(request, 403, SSTR("Not accessible '" << absPath << "' err: "<< ret.what()));
return DomeReq::SendSimpleResp(request, 200, "");
};
int DomeCore::dome_accessreplica(DomeReq &req, FCGX_Request &request)
{
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_accessreplica only available on head nodes.");
}
std::string rfn = req.bodyfields.get<std::string>("rfn", "");
int mode = req.bodyfields.get<int>("mode", 0);
DmStatus ret;
struct dmlite::Replica r;
Log(Logger::Lvl4, domelogmask, domelogname, "Processing: '" << rfn << "' mode: " << mode);
if ( !rfn.size() ) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Empty rfn"));
}
DomeMySql sql;
ret = sql.getReplicabyRFN(r, rfn);
if (ret.code() != DMLITE_SUCCESS) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat rfn: '" << rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
ExtendedStat xstat;
ret = sql.getStatbyFileid(xstat, r.fileid);
if (ret.code() != DMLITE_SUCCESS) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat fileid " << r.fileid << " of rfn: '" << rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
bool replicaAllowed = true;
mode_t perm = 0;
if (mode & R_OK)
perm = S_IREAD;
if (mode & W_OK) {
perm |= S_IWRITE;
replicaAllowed = (r.status == Replica::kBeingPopulated);
}
if (mode & X_OK)
perm |= S_IEXEC;
SecurityContext ctx;
fillSecurityContext(ctx, req);
bool ok = false;
try {
ok = !checkPermissions(&ctx, xstat.acl, xstat.stat, perm);
} catch (DmException e) {}
if (!ok)
return DomeReq::SendSimpleResp(request, 403, SSTR("Not accessible '" << rfn << "'"));
if (!replicaAllowed)
return DomeReq::SendSimpleResp(request, 403, SSTR("Not accessible with replica status " << r.status << " '" << rfn << "'"));
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_addreplica(DomeReq &req, FCGX_Request &request)
{
struct dmlite::Replica r;
r.rfn = req.bodyfields.get<std::string>("rfn", "");
r.fileid = req.bodyfields.get<int64_t>("fileid", 0);
r.status = static_cast<dmlite::Replica::ReplicaStatus>(
req.bodyfields.get<char>("status", (char)dmlite::Replica::kAvailable) );
r.type = static_cast<dmlite::Replica::ReplicaType>(
req.bodyfields.get<char>("type", (char)dmlite::Replica::kPermanent) );
r.setname = req.bodyfields.get<std::string>("setname", "");
r.deserialize(req.bodyfields.get<std::string>("xattr", ""));
SecurityContext ctx;
fillSecurityContext(ctx, req);
DmStatus ret;
Log(Logger::Lvl4, domelogmask, domelogname, "Processing: '" << r.rfn << "' fileid: " << r.fileid);
if ( !r.rfn.size() ) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Empty rfn"));
}
DomeMySql sql;
try {
ExtendedStat xstat;
ret = sql.getStatbyFileid(xstat, r.fileid);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat fileid " << r.fileid << " of rfn: '" << r.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
if (!S_ISREG(xstat.stat.st_mode))
return DomeReq::SendSimpleResp(request, 400, SSTR("Inode " << r.fileid << " is not a regular file"));
// Check perms on the parents
ret = sql.traverseBackwards(ctx, xstat);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Permission denied on fileid " << xstat.stat.st_ino
<< " of rfn: '" << r.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
if (checkPermissions(&ctx, xstat.acl, xstat.stat, S_IWRITE) != 0)
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Cannot modify file " << xstat.stat.st_ino
<< " of rfn: '" << r.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// If server is empty, parse the surl
std::string host;
if (r.server.empty()) {
Url u(r.rfn);
host = u.domain;
}
else {
host = r.server;
}
ret = sql.addReplica(r);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 400, SSTR("Cannot add replica " << xstat.stat.st_ino
<< " of rfn: '" << r.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
} catch (DmException e) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Cannot add replica rfn: '" <<
r.rfn << "' err: " << e.code() << " what: '" << e.what() << "'"));
}
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_create(DomeReq &req, FCGX_Request &request)
{
struct dmlite::ExtendedStat f;
std::string path = req.bodyfields.get<std::string>("path", "");
mode_t mode = req.bodyfields.get<mode_t>("mode", 0);
Log(Logger::Lvl4, domelogmask, domelogname, "Processing: '" << path << "' mode: " << mode);
DomeMySql sql;
ExtendedStat parent;
std::string parentPath, name;
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
if ( !path.size() ) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Empty path"));
}
DmStatus ret = sql.getParent(parent, path, parentPath, name);
// Need to be able to write to the parent
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Need write access on '" << parentPath << "'"));
ExtendedStat fstat;
// Check that the file does not exist, or it has no replicas. The query by parent fileid is faster
ret = sql.getStatbyParentFileid(fstat, parent.stat.st_ino, name);
if(ret.ok()) {
std::vector <Replica> reps;
sql.getReplicas(reps, fstat.stat.st_ino);
if (reps.size() > 0)
DomeReq::SendSimpleResp(request, 403, SSTR("Exists and has replicas. Can not truncate '" << path << "'"));
else if (S_ISDIR(fstat.stat.st_mode))
throw DmException(EISDIR,
"%s is a directory. Can not truncate", path.c_str());
}
else {
if(ret.code() != ENOENT) DomeReq::SendSimpleResp(request, 422, SSTR("Unexpected error on path '" << path <<
"' err: " << ret.code() << "'" << ret.what() << "'"));
}
// Effective gid
gid_t egid;
if (parent.stat.st_mode & S_ISGID) {
egid = parent.stat.st_gid;
mode |= S_ISGID;
}
else {
// We take the gid of the first group of the user
// Note by FF 06/02/2017: this makes little sense, I ported it from Catalog.cpp
// and I don't really know what to do with this sneaky assumption
egid = ctx.groups[0].getUnsigned("gid");
}
// Create new
if (ret.code() == ENOENT) {
ExtendedStat newFile;
newFile.parent = parent.stat.st_ino;
newFile.name = name;
newFile.stat.st_mode = (mode & ~S_IFMT) | S_IFREG;
newFile.stat.st_size = 0;
newFile.stat.st_uid = ctx.user.getUnsigned("uid");
newFile.stat.st_gid = egid;
newFile.status = ExtendedStat::kOnline;
// Generate inherited ACL's if there are defaults
if (parent.acl.has(AclEntry::kDefault | AclEntry::kUserObj))
newFile.acl = Acl(parent.acl,
ctx.user.getUnsigned("uid"),
egid,
mode,
&newFile.stat.st_mode);
ret = sql.create(newFile);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Can't create file '" << path << "'"));
}
// Truncate
else {
if (ctx.user.getUnsigned("uid") != fstat.stat.st_uid &&
checkPermissions(&ctx, fstat.acl, fstat.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Not enough permissions to truncate '" << path << "'"));
sql.setSize(fstat.stat.st_ino, 0);
}
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_putdone_disk(DomeReq &req, FCGX_Request &request) {
// The command takes as input server and pfn, separated
// in order to put some distance from rfio concepts, at least in the api
std::string server = req.bodyfields.get<std::string>("server", "");
std::string pfn = req.bodyfields.get<std::string>("pfn", "");
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
size_t size = req.bodyfields.get<size_t>("size", 0);
std::string chktype = req.bodyfields.get<std::string>("checksumtype", "");
std::string chkval = req.bodyfields.get<std::string>("checksumvalue", "");
Log(Logger::Lvl1, domelogmask, domelogname, " server: '" << server << "' pfn: '" << pfn << "' "
" size: " << size << " cksumt: '" << chktype << "' cksumv: '" << chkval << "'" );
// Check for the mandatory arguments
if ( !pfn.length() ) {
std::ostringstream os;
os << "Invalid pfn: '" << pfn << "'";
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, os);
}
// Please note that the server field can be empty
if ( size < 0 ) {
std::ostringstream os;
os << "Invalid size: " << size << " '" << pfn << "'";
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, os);
}
// Now the optional ones for basic sanity
if ( !(chktype.length() > 0) != !(chkval.length() > 0) ) {
std::ostringstream os;
os << "Invalid checksum hint. type:'" << chktype << "' val: '" << chkval << "'";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, os);
}
if (chktype.length() && !checksums::isChecksumFullName(chktype)) {
std::ostringstream os;
os << "Invalid checksum hint. type:'" << chktype << "' val: '" << chkval << "'";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, os);
}
// We are in the disk server, hence we check only things that reside here
// and then forward the request to the head
// Head node stuff will be checked by the headnode
// We check the stat information of the file.
Log(Logger::Lvl2, domelogmask, domelogname, " Stat-ing pfn: '" << pfn << "' "
" on disk.");
struct stat st;
if ( stat(pfn.c_str(), &st) ) {
std::ostringstream os;
char errbuf[1024];
os << "Cannot stat pfn:'" << pfn << "' err: " << errno << ":" << strerror_r(errno, errbuf, 1023);
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, DOME_HTTP_NOT_FOUND, os);
}
Log(Logger::Lvl2, domelogmask, domelogname, " pfn: '" << pfn << "' "
" disksize: " << st.st_size);
if (size == 0) size = st.st_size;
if ( (off_t)size != st.st_size ) {
std::ostringstream os;
os << "Reported size (" << size << ") does not match with the size of the file (" << st.st_size << ")";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, os);
}
// Now forward the request to the head node
Log(Logger::Lvl1, domelogmask, domelogname, " Forwarding to headnode. server: '" << server << "' pfn: '" << pfn << "' "
" size: " << size << " cksumt: '" << chktype << "' cksumv: '" << chkval << "'" );
std::string domeurl = CFG->GetString("disk.headnode.domeurl", (char *)"(empty url)/");
DomeTalker talker(*davixPool, req.creds, domeurl,
"POST", "dome_putdone");
// Copy the same body fields as the original one, except for some fields,
// where we write this machine's hostname (we are a disk server here) and the validated size
if(server.empty()) {
server = status.myhostname;
}
req.bodyfields.put("server", server);
req.bodyfields.put("size", size);
req.bodyfields.put("lfn", lfn);
if(!talker.execute(req.bodyfields)) {
Err(domelogname, talker.err());
return DomeReq::SendSimpleResp(request, 500, talker.err());
}
return DomeReq::SendSimpleResp(request, DOME_HTTP_OK, talker.response());
}
int DomeCore::dome_putdone_head(DomeReq &req, FCGX_Request &request) {
// The command takes as input server and pfn, separated
// in order to put some distance from rfio concepts, at least in the api
std::string server = req.bodyfields.get<std::string>("server", "");
std::string pfn = req.bodyfields.get<std::string>("pfn", "");
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
size_t size = req.bodyfields.get<size_t>("size", 0);
std::string chktype = req.bodyfields.get<std::string>("checksumtype", "");
std::string chkval = req.bodyfields.get<std::string>("checksumvalue", "");
Log(Logger::Lvl1, domelogmask, domelogname, " server: '" << server << "' pfn: '" << pfn << "' "
" size: " << size << " cksumt: '" << chktype << "' cksumv: '" << chkval << "'" );
// Check for the mandatory arguments
if ( !pfn.length() ) {
std::ostringstream os;
os << "Invalid pfn: '" << pfn << "'";
return DomeReq::SendSimpleResp(request, 422, os);
}
if ( !server.length() ) {
std::ostringstream os;
os << "Invalid server: '" << server << "'";
return DomeReq::SendSimpleResp(request, 422, os);
}
if ( size < 0 ) {
std::ostringstream os;
os << "Invalid size: " << size << " '" << pfn << "'";
return DomeReq::SendSimpleResp(request, 422, os);
}
// Now the optional ones for basic sanity
if ( !(chktype.length() > 0) != !(chkval.length() > 0) ) {
std::ostringstream os;
os << "Invalid checksum hint. type:'" << chktype << "' val: '" << chkval << "'";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 422, os);
}
if (chktype.length() && !checksums::isChecksumFullName(chktype)) {
std::ostringstream os;
os << "Invalid checksum hint. type:'" << chktype << "' val: '" << chkval << "'";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 422, os);
}
// Here unfortunately, for backward compatibility we are forced to
// use the rfio syntax.
std::string rfn = server + ":" + pfn;
DomeMySql sql;
dmlite::Replica rep;
DmStatus ret;
ret = sql.getReplicabyRFN(rep, rfn);
if (!ret.ok()) {
if (ret.code() == ENOENT) {
Err(domelogname, "Replica not found '" << rfn << "'");
return DomeReq::SendSimpleResp(request, 404, SSTR("Replica not found '" << rfn << "'"));
}
Err(domelogname, "Not accessible '" << rfn << "' err: "<< ret.what());
return DomeReq::SendSimpleResp(request, 500, SSTR("Not accessible '" << rfn << "' err: "<< ret.what()));
}
if (rep.status != dmlite::Replica::kBeingPopulated) {
std::ostringstream os;
os << "Invalid status for replica '"<< rfn << "'";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 422, os);
}
dmlite::ExtendedStat st;
ret = sql.getStatbyFileid(st, rep.fileid);
if (!ret.ok()) {
if (ret.code() == ENOENT) {
Err(domelogname, "Cannot fetch logical entry for replica '" << rfn << "'");
return DomeReq::SendSimpleResp(request, 422, SSTR("File not found '" << rfn << "'"));
}
Err(domelogname, "Cannot fetch logical entry for replica '" << rfn << "' err: "<< ret.what());
return DomeReq::SendSimpleResp(request, 500, SSTR("Not accessible '" << rfn << "' err: "<< ret.what()));
}
// We are in the headnode getting a size of zero is fishy and has to be doublechecked, old style
if (size == 0) {
std::string domeurl = SSTR("https://" << server << "/domedisk");
DomeTalker talker(*davixPool, req.creds, domeurl,
"GET", "dome_statpfn");
if(!talker.execute("pfn", pfn)) {
Err(domelogname, talker.err());
return DomeReq::SendSimpleResp(request, 500, talker.err());
}
try {
size = talker.jresp().get<size_t>("size");
}
catch(boost::property_tree::ptree_error &e) {
std::string errmsg = SSTR("Received invalid json when talking to " << domeurl << ":" << e.what() << " '" << talker.response() << "'");
Err("takeJSONbodyfields", errmsg);
return DomeReq::SendSimpleResp(request, 500, errmsg);
}
} // if size == 0
// -------------------------------------------------------
// If a miracle took us here, the size has been confirmed
Log(Logger::Lvl1, domelogmask, domelogname, " Final size: " << size );
// Update the replica values, including the checksum
rep.ptime = rep.ltime = rep.atime = time(0);
rep.status = dmlite::Replica::kAvailable;
if(!chktype.empty()) {
Log(Logger::Lvl4, domelogmask, domelogname, " setting checksum: " << chktype << "," << chkval);
rep[chktype] = chkval;
}
ret = sql.updateReplica(rep);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot update replica '"<< rfn << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 500, os);
}
// If the checksum of the main entry is different, just output a bad warning in the log
std::string ck;
if ( !st.getchecksum(chktype, ck) && (ck != chkval) ) {
Err(domelogname, SSTR("Replica checksum mismatch rfn:'"<< rfn << "' : " << chkval << " fileid: " << rep.fileid << " : " << ck));
}
// Anyway propagate the checksum to the main stat
sql.setChecksum(st.stat.st_ino, chktype, chkval);
sql.setSize(st.stat.st_ino, size);
// Now update the space counters for the parent directories!
// Please note that this substitutes the IOPassthrough plugin in the disk's dmlite stack
if (st.parent <= 0) {
Log(Logger::Lvl4, domelogmask, domelogname, " Looking up parent of inode " << st.stat.st_ino << " " << " main entry for replica: '" << rfn << "'");
ret = sql.getStatbyFileid(st, st.stat.st_ino);
if (!ret.ok())
Err( domelogname , " Cannot retrieve parent for inode:" << st.stat.st_ino << " " << " main entry for replica: '" << rfn << "'");
Log(Logger::Lvl4, domelogmask, domelogname, " Ok. Parent of inode " << st.stat.st_ino << " is " << st.parent);
}
if(!sql.addFilesizeToDirs(st, size).ok()) {
Err(domelogname, SSTR("Unable to add filesize to parent directories of " << st.stat.st_ino << ". Directory sizes will be inconsistent."));
}
// For backward compatibility with the DPM daemon, we also update its
// spacetoken counters, adjusting u_space
{
DomeQuotatoken token;
if (rep.setname.size() > 0) {
Log(Logger::Lvl4, domelogmask, domelogname, " Accounted space token: '" << rep.setname <<
"' rfn: '" << rep.rfn << "'");
DomeMySql sql;
DomeMySqlTrans t(&sql);
// Occupy some space
sql.addtoQuotatokenUspace(rep.setname, -size);
t.Commit();
}
}
int rc = DomeReq::SendSimpleResp(request, 200, SSTR("dome_putdone successful."));
Log(Logger::Lvl3, domelogmask, domelogname, "Result: " << rc);
return rc;
};
std::vector<std::string> list_folders(const std::string &folder) {
std::vector<std::string> ret;
DIR *d;
struct dirent *dir;
d = opendir(folder.c_str());
if(!d) return ret;
while((dir = readdir(d)) != NULL) {
std::string name = dir->d_name;
if(name != "." && name != ".." && dir->d_name && dir->d_type == DT_DIR) {
ret.push_back(folder + "/" + name);
}
}
closedir(d);
std::sort(ret.begin(), ret.end(), std::less<std::string>());
return ret;
}
int DomeCore::makespace(std::string fsplusvo, int size) {
// retrieve the list of folders and iterate over them, starting from the oldest
std::vector<std::string> folders = list_folders(fsplusvo);
size_t folder = 0;
size_t evictions = 0;
int space_cleared = 0;
std::string domeurl = CFG->GetString("disk.headnode.domeurl", (char *)"(empty url)/");
while(size >= space_cleared && folder < folders.size()) {
DIR *d = opendir(folders[folder].c_str());
if(!d) break; // should not happen
while(size >= space_cleared) {
struct dirent *entry = readdir(d);
if(!entry) {
break;
}
if(entry->d_type == DT_REG) {
std::string victim = SSTR(folder << "/" << entry->d_name);
struct stat tmp;
if(stat(victim.c_str(), &tmp) != 0) continue; // should not happen
DomeTalker talker(*davixPool, NULL, domeurl,
"POST", "dome_delreplica");
if(!talker.execute("pfn", victim, "server", status.myhostname)) {
Err(domelogname, talker.err()); // dark data? skip file
continue;
}
Log(Logger::Lvl1, domelogmask, domelogname, "Evicting replica '" << victim << "' of size " << tmp.st_size << "from volatile filesystem to make space");
evictions++;
space_cleared += tmp.st_size;
}
}
closedir(d);
folder++;
}
return space_cleared;
}
// semi-random. Depends in what order the filesystem returns the files, which
// is implementation-defined
std::pair<size_t, std::string> pick_a_file(const std::string &folder) {
DIR *d = opendir(folder.c_str());
while(true) {
struct dirent *entry = readdir(d);
if(!entry) {
closedir(d);
return std::make_pair(-1, "");
}
if(entry->d_type == DT_REG) {
std::string filename = SSTR(folder << "/" << entry->d_name);
struct stat tmp;
if(stat(filename.c_str(), &tmp) != 0) continue; // should not happen
closedir(d);
return std::make_pair(tmp.st_size, filename);
}
}
}
int DomeCore::dome_makespace(DomeReq &req, FCGX_Request &request) {
Log(Logger::Lvl4, domelogmask, domelogname, "Entering");
if(status.role == status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, SSTR("makespace only available on disknodes"));
}
std::string fs = req.bodyfields.get<std::string>("fs", "");
std::string voname = req.bodyfields.get<std::string>("vo", "");
int size = req.bodyfields.get<size_t>("size", 0);
bool ensure_space = DomeUtils::str_to_bool(req.bodyfields.get<std::string>("ensure-space", "true"));
if(fs.empty()) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "fs cannot be empty.");
}
if(voname.empty()) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "vo cannot be empty.");
}
if(size <= 0) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "size is required and must be positive.");
}
// verify fs exists!
{
boost::unique_lock<boost::recursive_mutex> l(status);
bool found = false;
size_t i, selected_fs;
for(i = 0; i < status.fslist.size(); i++) {
if(status.fslist[i].fs == fs) {
found = true;
selected_fs = i;
if(ensure_space) {
size -= status.fslist[i].freespace;
}
break;
}
}
if(!found) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, SSTR("Could not find filesystem '" << fs << "'"));
}
if(size <= 0) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_OK, SSTR("Selected fs " << status.fslist[selected_fs].server << ":" << status.fslist[selected_fs].fs << "' has enough space. (" << status.fslist[i].freespace << ")"));
}
}
// retrieve the list of folders and iterate over them, starting from the oldest
std::vector<std::string> folders = list_folders(fs + "/" + voname);
size_t folder = 0;
size_t evictions = 0;
int space_cleared = 0;
std::string domeurl = CFG->GetString("disk.headnode.domeurl", (char *)"(empty url)/");
std::ostringstream response;
while(size >= space_cleared && folder < folders.size()) {
std::pair<size_t, std::string> victim = pick_a_file(folders[folder]);
if(victim.second.empty()) {
// rmdir is part of POSIX and only removes a directory if empty!
// If for some crazy reason we end up here even though the directory
// has files, the following will not have any effects.
rmdir(folders[folder].c_str());
folder++;
continue;
}
space_cleared += victim.first;
evictions++;
Log(Logger::Lvl1, domelogmask, domelogname, "Evicting replica '" << victim.second << "' from volatile filesystem to make space");
response << "Evicting replica '" << victim.second << "' of size '" << victim.first << "'" << "\r\n";
DomeTalker talker(*davixPool, req.creds, domeurl,
"POST", "dome_delreplica");
if(!talker.execute("pfn", victim.second, "server", status.myhostname)) {
Err(domelogname, talker.err());
return DomeReq::SendSimpleResp(request, 500, talker.err());
}
}
response << "Cleared '" << space_cleared << "' bytes through the removal of " << evictions << " files\r\n";
if(space_cleared < size) {
response << "Error: could not clear up the requested amount of space. " << size << "\r\n";
return DomeReq::SendSimpleResp(request, DOME_HTTP_UNPROCESSABLE, response.str());
}
return DomeReq::SendSimpleResp(request, DOME_HTTP_OK, response.str());
}
int DomeCore::dome_getspaceinfo(DomeReq &req, FCGX_Request &request) {
Log(Logger::Lvl4, domelogmask, domelogname, "Entering");
boost::unique_lock<boost::recursive_mutex> l(status);
boost::property_tree::ptree jresp;
for (unsigned int i = 0; i < status.fslist.size(); i++) {
std::string fsname, poolname;
boost::property_tree::ptree top;
fsname = "fsinfo^" + status.fslist[i].server + "^" + status.fslist[i].fs;
// Add this server if not already there
if (status.role == status.roleHead) { // Only headnodes report about pools
jresp.put(boost::property_tree::ptree::path_type(fsname+"^poolname", '^'), status.fslist[i].poolname);
jresp.put(boost::property_tree::ptree::path_type(fsname+"^fsstatus", '^'), status.fslist[i].status);
}
jresp.put(boost::property_tree::ptree::path_type(fsname+"^freespace", '^'), status.fslist[i].freespace);
jresp.put(boost::property_tree::ptree::path_type(fsname+"^physicalsize", '^'), status.fslist[i].physicalsize);
jresp.put(boost::property_tree::ptree::path_type(fsname+"^activitystatus", '^'), status.fslist[i].activitystatus);
if (status.role == status.roleHead) { //Only headnodes report about pools
poolname = "poolinfo^" + status.fslist[i].poolname;
long long tot, free;
int pool_st;
status.getPoolSpaces(status.fslist[i].poolname, tot, free, pool_st);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^poolstatus", '^'), 0);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^freespace", '^'), free);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^physicalsize", '^'), tot);
try {
jresp.put(boost::property_tree::ptree::path_type(poolname+"^s_type", '^'), status.poolslist[status.fslist[i].poolname].stype);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^defsize", '^'), status.poolslist[status.fslist[i].poolname].defsize);
} catch ( ... ) {};
poolname = "poolinfo^" + status.fslist[i].poolname + "^fsinfo^" + status.fslist[i].server + "^" + status.fslist[i].fs;
jresp.put(boost::property_tree::ptree::path_type(poolname+"^fsstatus", '^'), status.fslist[i].status);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^freespace", '^'), status.fslist[i].freespace);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^physicalsize", '^'), status.fslist[i].physicalsize);
}
}
// For completeness, add also the pools that have no filesystems :-(
for (std::map <std::string, DomePoolInfo>::iterator it = status.poolslist.begin();
it != status.poolslist.end();
it++) {
std::string poolname = "poolinfo^" + it->second.poolname;
jresp.put(boost::property_tree::ptree::path_type(poolname+"^s_type", '^'), it->second.stype);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^defsize", '^'), it->second.defsize);
}
return DomeReq::SendSimpleResp(request, 200, jresp);
};
int DomeCore::calculateChecksum(DomeReq &req, FCGX_Request &request, std::string lfn, Replica replica, std::string checksumtype, bool updateLfnChecksum) {
// create queue entry
GenPrioQueueItem::QStatus qstatus = GenPrioQueueItem::Waiting;
std::string namekey = lfn + "[#]" + replica.rfn + "[#]" + checksumtype;
std::vector<std::string> qualifiers;
qualifiers.push_back(""); // the first qualifier is common for all items,
// so the global limit triggers
qualifiers.push_back(replica.server); // server name as second qualifier, so
// the per-node limit triggers
// necessary information to keep when sending dochksum - order is important
qualifiers.push_back(DomeUtils::bool_to_str(updateLfnChecksum));
qualifiers.push_back(req.creds.clientName);
qualifiers.push_back(req.creds.remoteAddress);
status.checksumq->touchItemOrCreateNew(namekey, qstatus, 0, qualifiers);
status.notifyQueues();
boost::property_tree::ptree jresp;
jresp.put("status", "enqueued");
jresp.put("server", replica.server);
jresp.put("pfn", DomeUtils::pfn_from_rfio_syntax(replica.rfn));
jresp.put("queue-size", status.checksumq->nTotal());
return DomeReq::SendSimpleResp(request, 202, jresp);
}
void DomeCore::touch_pull_queue(DomeReq &req, const std::string &lfn, const std::string &server, const std::string &fs,
const std::string &rfn) {
// create or update queue entry
GenPrioQueueItem::QStatus qstatus = GenPrioQueueItem::Waiting;
std::vector<std::string> qualifiers;
qualifiers.push_back(""); // the first qualifier is common for all items,
// so the global limit triggers
qualifiers.push_back(lfn); // lfn as second qualifier
qualifiers.push_back(server);
qualifiers.push_back(fs);
// necessary information to keep - order is important
qualifiers.push_back(rfn);
qualifiers.push_back(req.creds.clientName);
qualifiers.push_back(req.creds.remoteAddress);
status.filepullq->touchItemOrCreateNew(lfn, qstatus, 0, qualifiers);
}
int DomeCore::enqfilepull(DomeReq &req, FCGX_Request &request, std::string lfn) {
// This simple implementation is like a put
DomeFsInfo destfs;
std::string destrfn;
bool success;
dome_put(req, request, success, &destfs, &destrfn, true);
if (!success)
return 1; // means that a response has already been sent in the context of dome_put, btw it can only be an error
touch_pull_queue(req, lfn, destfs.server, destfs.fs, destrfn);
status.notifyQueues();
// TODO: Here we have to trigger the file pull in the disk server,
// by sending a dome_pull request
return DomeReq::SendSimpleResp(request, 202, SSTR("Enqueued file pull request " << destfs.server
<< ", path " << lfn
<< ", check back later.\r\nTotal pulls in queue right now: "
<< status.filepullq->nTotal()));
}
static Replica pickReplica(std::string lfn, std::string rfn, DomeMySql &sql) {
DmStatus ret;
std::vector<Replica> replicas;
ret = sql.getReplicas(replicas, lfn);
if(replicas.size() == 0) {
throw DmException(DMLITE_CFGERR(ENOENT), "The provided LFN does not have any replicas");
}
if(rfn != "") {
for(std::vector<Replica>::iterator it = replicas.begin(); it != replicas.end(); it++) {
if(it->rfn == rfn) {
return *it;
}
}
throw DmException(DMLITE_CFGERR(ENOENT), "The provided PFN does not correspond to any of LFN's replicas");
}
// no explicit pfn? pick a random replica
int index = rand() % replicas.size();
return replicas[index];
}
int DomeCore::dome_info(DomeReq &req, FCGX_Request &request, int myidx, bool authorized) {
Log(Logger::Lvl4, domelogmask, domelogname, "Entering");
std::ostringstream response;
response << "dome [" << DMLITE_MAJOR << "." << DMLITE_MINOR << "." << DMLITE_PATCH << "] running as ";
if(status.role == status.roleDisk) response << "disk";
else response << "head";
response << "\r\nServer PID: " << getpid() << " - Thread Index: " << myidx << " \r\n";
response << "Your DN: " << req.clientdn << "\r\n\r\n";
if(authorized) {
response << "ACCESS TO DOME GRANTED.\r\n"; // magic string, don't change. The tests look for this string
for (char **envp = request.envp ; *envp; ++envp) {
response << *envp << "\r\n";
}
}
else {
response << "ACCESS TO DOME DENIED.\r\n"; // magic string, don't change
response << "Your client certificate is not authorized to directly access dome. Sorry :-)\r\n";
}
return DomeReq::SendSimpleResp(request, 200, response);
}
int DomeCore::dome_chksum(DomeReq &req, FCGX_Request &request) {
Log(Logger::Lvl4, domelogmask, domelogname, "Entering");
if(status.role == status.roleDisk) {
return DomeReq::SendSimpleResp(request, 500, "chksum only available on head nodes");
}
try {
DomeMySql sql;
std::string chksumtype = req.bodyfields.get<std::string>("checksum-type", "");
chksumtype = DomeUtils::remove_prefix_if_exists(chksumtype, "checksum.");
std::string fullchecksum = "checksum." + chksumtype;
std::string pfn = req.bodyfields.get<std::string>("pfn", "");
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
bool forcerecalc = DomeUtils::str_to_bool(req.bodyfields.get<std::string>("force-recalc", "false"));
bool updateLfnChecksum = (pfn == "");
if(chksumtype == "") {
return DomeReq::SendSimpleResp(request, 422, "checksum-type cannot be empty.");
}
if(chksumtype != "md5" && chksumtype != "crc32" && chksumtype != "adler32") {
return DomeReq::SendSimpleResp(request, 422, SSTR("unknown checksum type " << chksumtype));
}
if(forcerecalc) {
Replica replica = pickReplica(lfn, pfn, sql);
return calculateChecksum(req, request, lfn, replica, chksumtype, updateLfnChecksum);
}
// Not forced to do a recalc - maybe I can find the checksums in the db
std::string lfnchecksum;
std::string pfnchecksum;
Replica replica;
// retrieve lfn checksum
ExtendedStat xstat;
{
DomeMySql sql;
DmStatus st = sql.getStatbyLFN(xstat, lfn);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat lfn: '" << lfn << "'"));
}
if(xstat.hasField(fullchecksum)) {
lfnchecksum = xstat.getString(fullchecksum);
Log(Logger::Lvl3, domelogmask, domelogname, "Found lfn checksum in the db: " << lfnchecksum);
}
else {
Log(Logger::Lvl3, domelogmask, domelogname, "Lfn checksum not in the db");
}
// retrieve pfn checksum
if(pfn != "") {
replica = pickReplica(lfn, pfn, sql);
if(replica.hasField(fullchecksum)) {
pfnchecksum = replica.getString(fullchecksum);
Log(Logger::Lvl3, domelogmask, domelogname, "Found pfn checksum in the db: " << pfnchecksum);
}
}
// can I send a response right now? Of course, sir !
if(lfnchecksum != "" && (pfn == "" || pfnchecksum != "")) {
boost::property_tree::ptree jresp;
jresp.put("status", "found");
jresp.put("checksum", lfnchecksum);
if(pfn != "") {
jresp.put("pfn-checksum", pfnchecksum);
}
return DomeReq::SendSimpleResp(request, 200, jresp);
}
// something is missing, need to calculate
if(pfn == "") {
replica = pickReplica(lfn, pfn, sql);
}
return calculateChecksum(req, request, lfn, replica, chksumtype, updateLfnChecksum);
}
catch(dmlite::DmException& e) {
std::ostringstream os("An error has occured.\r\n");
os << "Dmlite exception: " << e.what();
return DomeReq::SendSimpleResp(request, 404, os);
}
Log(Logger::Lvl1, domelogmask, domelogname, "Error - execution should never reach this point");
return DomeReq::SendSimpleResp(request, 500, "Something went wrong, execution should never reach this point.");
}
int DomeCore::dome_chksumstatus(DomeReq &req, FCGX_Request &request) {
if(status.role == status.roleDisk) {
return DomeReq::SendSimpleResp(request, 500, "chksumstatus only available on head nodes");
}
try {
DomeMySql sql;
DmStatus ret;
std::string chksumtype = req.bodyfields.get<std::string>("checksum-type", "");
chksumtype = DomeUtils::remove_prefix_if_exists(chksumtype, "checksum.");
std::string fullchecksum = "checksum." + chksumtype;
std::string pfn = req.bodyfields.get<std::string>("pfn", "");
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
std::string str_status = req.bodyfields.get<std::string>("status", "");
std::string reason = req.bodyfields.get<std::string>("reason", "");
std::string checksum = req.bodyfields.get<std::string>("checksum", "");
bool updateLfnChecksum = DomeUtils::str_to_bool(req.bodyfields.get<std::string>("update-lfn-checksum", "false"));
if(chksumtype == "") {
return DomeReq::SendSimpleResp(request, 422, "checksum-type cannot be empty.");
}
if(pfn == "") {
return DomeReq::SendSimpleResp(request, 422, "pfn cannot be empty.");
}
GenPrioQueueItem::QStatus qstatus;
if(str_status == "pending") {
qstatus = GenPrioQueueItem::Running;
}
else if(str_status == "done" || str_status == "aborted") {
qstatus = GenPrioQueueItem::Finished;
}
else {
return DomeReq::SendSimpleResp(request, 422, "The status provided is not recognized.");
}
// modify the queue as needed
std::string namekey = lfn + "[#]" + pfn + "[#]" + chksumtype;
std::vector<std::string> qualifiers;
Url u(pfn);
std::string server = u.domain;
qualifiers.push_back("");
qualifiers.push_back(server);
qualifiers.push_back(DomeUtils::bool_to_str(updateLfnChecksum));
status.checksumq->touchItemOrCreateNew(namekey, qstatus, 0, qualifiers);
if(qstatus != GenPrioQueueItem::Running) {
status.notifyQueues();
}
if(str_status == "aborted") {
Log(Logger::Lvl1, domelogmask, domelogname, "Checksum calculation failed. LFN: " << lfn
<< "PFN: " << pfn << ". Reason: " << reason);
return DomeReq::SendSimpleResp(request, 200, "");
}
if(str_status == "pending") {
return DomeReq::SendSimpleResp(request, 200, "");
}
// status is done, checksum should not be empty
if(checksum == "") {
Log(Logger::Lvl2, domelogmask, domelogname, "Received 'done' checksum status without a checksum");
return DomeReq::SendSimpleResp(request, 400, "checksum cannot be empty when status is done.");
}
// replace pfn checksum
Replica replica = pickReplica(lfn, pfn, sql);
replica[fullchecksum] = checksum;
ret = sql.updateReplica(replica);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot update replica rfn: '" << replica.rfn << "'"));
}
// replace lfn checksum?
if(updateLfnChecksum) {
ret = sql.setChecksum(replica.fileid, fullchecksum, checksum);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 500, SSTR("Cannot update checksum on fileid: " << replica.fileid << " rfn: '" << replica.rfn << "'"));
}
// still update if it's empty, though
else {
// retrieve lfn checksum
ExtendedStat xstat;
{
DomeMySql sql;
DmStatus st = sql.getStatbyLFN(xstat, lfn);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat lfn: '" << lfn << "'"));
}
if(!xstat.hasField(fullchecksum)) {
ret = sql.setChecksum(xstat.stat.st_ino, fullchecksum, checksum);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 500, SSTR("Cannot update checksum on fileid: " << xstat.stat.st_ino << " lfn: '" << lfn << "'"));
}
}
return DomeReq::SendSimpleResp(request, 200, "");
}
catch(dmlite::DmException& e) {
std::ostringstream os("An error has occured.\r\n");
os << "Dmlite exception: " << e.what();
return DomeReq::SendSimpleResp(request, 404, os);
}
Log(Logger::Lvl1, domelogmask, domelogname, "Error - execution should never reach this point");
return DomeReq::SendSimpleResp(request, 500, "Something went wrong, execution should never reach this point.");
}
int DomeCore::dome_dochksum(DomeReq &req, FCGX_Request &request) {
if(status.role == status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dochksum only available on disk nodes");
}
try {
std::string chksumtype = req.bodyfields.get<std::string>("checksum-type", "");
std::string pfn = req.bodyfields.get<std::string>("pfn", "");
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
bool updateLfnChecksum = DomeUtils::str_to_bool(req.bodyfields.get<std::string>("update-lfn-checksum", "false"));
if(chksumtype == "") {
return DomeReq::SendSimpleResp(request, 422, "checksum-type cannot be empty.");
}
if(pfn == "") {
return DomeReq::SendSimpleResp(request, 422, "pfn cannot be empty.");
}
if(lfn == "") {
return DomeReq::SendSimpleResp(request, 422, "lfn cannot be empty.");
}
PendingChecksum pending(lfn, status.myhostname, pfn, req.creds, chksumtype, updateLfnChecksum);
std::vector<std::string> params;
params.push_back("/usr/bin/dome-checksum");
params.push_back(chksumtype);
params.push_back(pfn);
int id = this->submitCmd(params);
if(id < 0) {
return DomeReq::SendSimpleResp(request, 500, SSTR("An error occured - unable to initiate checksum calculation"));
}
{
boost::lock_guard<boost::recursive_mutex> l(mtx);
diskPendingChecksums[id] = pending;
}
return DomeReq::SendSimpleResp(request, 202, SSTR("Initiated checksum calculation on " << pfn << ", task executor ID: " << id));
}
catch(dmlite::DmException& e) {
std::ostringstream os("An error has occured.\r\n");
os << "Dmlite exception: " << e.what();
return DomeReq::SendSimpleResp(request, 404, os);
}
return DomeReq::SendSimpleResp(request, 500, SSTR("Not implemented, dude."));
};
static std::string extract_checksum(std::string stdout, std::string &err) {
// were there any errors?
std::string magic = ">>>>> HASH ";
size_t pos = stdout.find(magic);
if(pos == std::string::npos) {
err = "Could not find magic string, unable to extract checksum. ";
return "";
}
size_t pos2 = stdout.find("\n", pos);
if(pos2 == std::string::npos) {
err = "Could not find newline after magic string, unable to extract checksum. ";
return "";
}
return stdout.substr(pos+magic.size(), pos2-pos-magic.size());
}
static int extract_stat(std::string stdout, std::string &err, struct dmlite::ExtendedStat &st) {
// were there any errors?
std::string magic = ">>>>> STAT ";
size_t pos = stdout.find(magic);
if(pos == std::string::npos) {
err = "Could not find magic string, unable to extract stat information. ";
return -1;
}
size_t pos2 = stdout.find("\n", pos);
if(pos2 == std::string::npos) {
err = "Could not find newline after magic string, unable to extract stat information. ";
return -1;
}
std::string s = stdout.substr(pos+magic.size(), pos2-pos-magic.size());
return sscanf(s.c_str(), "%ld %d", &st.stat.st_size, &st.stat.st_mode);
}
void DomeCore::sendFilepullStatus(const PendingPull &pending, const DomeTask &task, bool completed) {
std::string checksum, extract_error;
bool failed = (task.resultcode != 0);
Log(Logger::Lvl4, domelogmask, domelogname, "Entering. Completed: " << completed << " rc: " << task.resultcode);
if(completed) {
checksum = extract_checksum(task.stdout, extract_error);
if( ! extract_error.empty()) {
Log(Logger::Lvl4, domelogmask, domelogname, "File pull did not provide any checksum. err: " << extract_error << task.stdout);
}
Log(Logger::Lvl4, domelogmask, domelogname, "File pull checksum: " << checksum);
}
std::string domeurl = CFG->GetString("disk.headnode.domeurl", (char *)"(empty url)/");
Log(Logger::Lvl4, domelogmask, domelogname, domeurl);
DomeTalker talker(*davixPool, pending.creds, domeurl,
"POST", "dome_pullstatus");
// set chksumstatus params
boost::property_tree::ptree jresp;
jresp.put("lfn", pending.lfn);
jresp.put("pfn", pending.pfn);
jresp.put("server", status.myhostname);
Log(Logger::Lvl4, domelogmask, domelogname, "pfn: " << pending.pfn);
jresp.put("checksum-type", pending.chksumtype);
if(completed) {
if(failed) {
jresp.put("status", "aborted");
jresp.put("reason", SSTR(extract_error << task.stdout));
}
else {
jresp.put("status", "done");
jresp.put("checksum", checksum);
// Let's stat the real file on disk, we are in a disk node
struct stat st;
if ( stat(pending.pfn.c_str(), &st) ) {
std::ostringstream os;
char errbuf[1024];
os << "Cannot stat pfn:'" << pending.pfn << "' err: " << errno << ":" << strerror_r(errno, errbuf, 1023);
Err(domelogname, os.str());
// A successful execution and no file should be aborted!
jresp.put("status", "aborted");
jresp.put("reason", SSTR("disk node could not stat pfn: '" << pending.pfn << "' - " << os ));
}
else {
// If stat was successful then we can get the final filesize
Log(Logger::Lvl1, domelogmask, domelogname, "pfn: " << pending.pfn << " has size: " << st.st_size);
jresp.put("filesize", st.st_size);
}
}
}
else {
jresp.put("status", "pending");
}
if(!talker.execute(jresp)) {
Err(domelogname, talker.err());
}
}
void DomeCore::sendChecksumStatus(const PendingChecksum &pending, const DomeTask &task, bool completed) {
Log(Logger::Lvl4, domelogmask, domelogname, "Entering. Completed: " << completed);
std::string checksum, extract_error;
bool failed = false;
if(completed) {
checksum = extract_checksum(task.stdout, extract_error);
if( ! extract_error.empty()) {
Err(domelogname, extract_error << task.stdout);
failed = true;
}
}
std::string domeurl = CFG->GetString("disk.headnode.domeurl", (char *)"(empty url)/");
Log(Logger::Lvl4, domelogmask, domelogname, domeurl);
std::string rfn = pending.server + ":" + pending.pfn;
DomeTalker talker(*davixPool, pending.creds, domeurl,
"POST", "dome_chksumstatus");
// set chksumstatus params
boost::property_tree::ptree jresp;
jresp.put("lfn", pending.lfn);
jresp.put("pfn", rfn);
Log(Logger::Lvl4, domelogmask, domelogname, "rfn: " << rfn);
jresp.put("checksum-type", pending.chksumtype);
if(completed) {
if(failed) {
jresp.put("status", "aborted");
jresp.put("reason", SSTR(extract_error << task.stdout));
}
else {
jresp.put("status", "done");
jresp.put("checksum", checksum);
jresp.put("update-lfn-checksum", DomeUtils::bool_to_str(pending.updateLfnChecksum));
}
}
else {
jresp.put("status", "pending");
}
if(!talker.execute(jresp)) {
Err(domelogname, talker.err());
}
}
int DomeCore::dome_statpool(DomeReq &req, FCGX_Request &request) {
int rc = 0;
Log(Logger::Lvl4, domelogmask, domelogname, "Entering");
if (status.role == status.roleDisk) { // Only headnodes report about pools
std::ostringstream os;
os << "I am a disk node and don't know what a pool is. Only head nodes know pools.";
return DomeReq::SendSimpleResp(request, 422, os);
}
std::string pn = req.bodyfields.get("poolname", "");
if ( !pn.size() ) {
std::ostringstream os;
os << "Pool '" << pn << "' not found.";
return DomeReq::SendSimpleResp(request, 404, os);
}
long long tot, free;
int poolst;
status.getPoolSpaces(pn, tot, free, poolst);
boost::property_tree::ptree jresp;
for (unsigned int i = 0; i < status.fslist.size(); i++)
if (status.fslist[i].poolname == pn) {
std::string fsname, poolname;
boost::property_tree::ptree top;
poolname = "poolinfo^" + status.fslist[i].poolname;
jresp.put(boost::property_tree::ptree::path_type(poolname+"^poolstatus", '^'), poolst);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^freespace", '^'), free);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^physicalsize", '^'), tot);
poolname = "poolinfo^" + status.fslist[i].poolname + "^fsinfo^" + status.fslist[i].server + "^" + status.fslist[i].fs;
jresp.put(boost::property_tree::ptree::path_type(poolname+"^fsstatus", '^'), status.fslist[i].status);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^freespace", '^'), status.fslist[i].freespace);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^physicalsize", '^'), status.fslist[i].physicalsize);
}
// maybe the pool contains no filesystems..
for (std::map <std::string, DomePoolInfo>::iterator it = status.poolslist.begin();
it != status.poolslist.end();
it++) {
if (it->second.poolname == pn) {
std::string poolname = "poolinfo^" + it->second.poolname;
jresp.put(boost::property_tree::ptree::path_type(poolname+"^s_type", '^'), it->second.stype);
jresp.put(boost::property_tree::ptree::path_type(poolname+"^defsize", '^'), it->second.defsize);
}
}
rc = DomeReq::SendSimpleResp(request, 200, jresp);
Log(Logger::Lvl3, domelogmask, domelogname, "Result: " << rc);
return rc;
};
int DomeCore::dome_getdirspaces(DomeReq &req, FCGX_Request &request) {
// Crawl upwards the directory hierarchy of the given path
// stopping when a matching one is found
// The quota tokens indicate the pools that host the files written into
// this directory subtree
Log(Logger::Lvl4, domelogmask, domelogname, "Entering");
std::string absPath = req.bodyfields.get<std::string>("path", "");
if ( !absPath.size() ) {
std::ostringstream os;
os << "Path '" << absPath << "' is empty.";
return DomeReq::SendSimpleResp(request, 422, os);
}
// Make sure it's an absolute lfn path
if (absPath[0] != '/') {
std::ostringstream os;
os << "Path '" << absPath << "' is not an absolute path.";
return DomeReq::SendSimpleResp(request, 422, os);
}
// Remove any trailing slash
while (absPath[ absPath.size()-1 ] == '/') {
absPath.erase(absPath.size() - 1);
}
Log(Logger::Lvl4, domelogmask, domelogname, "Getting spaces for path: '" << absPath << "'");
long long totspace = 0LL;
long long usedspace = 0LL;
long long quotausedspace = 0LL;
long long poolfree = 0LL;
std::string tkname = "<unknown>";
std::string poolname = "<unknown>";
// Get dir used space before crawling upwards
usedspace = status.getDirUsedSpace(absPath);
// Crawl
{
boost::unique_lock<boost::recursive_mutex> l(status);
while (absPath.length() > 0) {
Log(Logger::Lvl4, domelogmask, domelogname, "Processing: '" << absPath << "'");
// Check if any matching quotatoken exists
std::pair <std::multimap<std::string, DomeQuotatoken>::iterator, std::multimap<std::string, DomeQuotatoken>::iterator> myintv;
myintv = status.quotas.equal_range(absPath);
if (myintv.first != myintv.second) {
for (std::multimap<std::string, DomeQuotatoken>::iterator it = myintv.first; it != myintv.second; ++it) {
totspace += it->second.t_space;
// Now find the free space in the mentioned pool
long long ptot, pfree;
int poolst;
status.getPoolSpaces(it->second.poolname, ptot, pfree, poolst);
poolfree += pfree;
Log(Logger::Lvl1, domelogmask, domelogname, "Quotatoken '" << it->second.u_token << "' of pool: '" <<
it->second.poolname << "' matches path '" << absPath << "' totspace: " << totspace);
tkname = it->second.u_token;
poolname = it->second.poolname;
quotausedspace = status.getQuotatokenUsedSpace(it->second);
}
break;
}
// No match found, look upwards by trimming the last token from absPath
size_t pos = absPath.rfind("/");
absPath.erase(pos);
}
}
// Prepare the response
// NOTE:
// A pool may be assigned to many dir subtrees at the same time, hence
// the best value that we can publish for the pool is how much free space it has
// The quotatotspace is the sum of all the quotatokens assigned to this subtree
// In limit cases the tot quota can be less than the used space, hence it's better
// to publish the tot space rather than the free space in the quota.
// One of these cases could be when the sysadmin (with punitive mood) manually assigns
// a quota that is lower than the occupied space. This would be a legitimate attempt
// to prevent clients from writing there until the space decreases...
boost::property_tree::ptree jresp;
jresp.put("quotatotspace", totspace);
long long sp = (totspace - usedspace);
jresp.put("quotafreespace", (sp < 0 ? 0 : sp));
jresp.put("quotausedspace", quotausedspace);
jresp.put("poolfreespace", poolfree);
jresp.put("dirusedspace", usedspace);
jresp.put("quotatoken", tkname);
jresp.put("poolname", poolname);
int rc = DomeReq::SendSimpleResp(request, 200, jresp);
Log(Logger::Lvl3, domelogmask, domelogname, "Result: " << rc);
return rc;
}
int DomeCore::dome_get(DomeReq &req, FCGX_Request &request) {
// Currently just returns a list of all replicas
Log(Logger::Lvl4, domelogmask, domelogname, "Entering");
DomeFsInfo fs;
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
bool canpull = status.LfnMatchesAnyCanPullFS(lfn, fs);
size_t pending_index = -1;
DmStatus ret;
DomeMySql sql;
std::vector <Replica > replicas;
// Check the perms on the parent folder
{
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
ExtendedStat parent;
std::string parentPath, name;
ret = sql.getParent(parent, lfn, parentPath, name);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat the parent of lfn: '" << lfn << "'"));
ret = sql.traverseBackwards(ctx, parent);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Permission denied on lfn: '" << lfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// Need to be able to read the parent
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IREAD) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Need READ access on '" << parentPath << "'"));
}
// And now get the replicas of the file
ret = sql.getReplicas(replicas, lfn);
// Return immediately on errors that are not 'file not found'
if (!ret.ok() && (ret.code() != ENOENT))
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't get replicas of '" << lfn <<
"' err: " << ret.code() << " what:" << ret.what()) );
if (ret.ok()) {
// We found the file... normal processing of its replicas
Log(Logger::Lvl4, domelogmask, domelogname, "Found " << replicas.size() << " replicas. lfn:'" << lfn << "'");
using boost::property_tree::ptree;
ptree jresp;
bool found = false;
bool foundpending = false;
for(size_t i = 0; i < replicas.size(); i++) {
// give only path as pfn
std::string rfn = replicas[i].rfn;
std::string pfn;
size_t pos = rfn.find(":");
if (pos == std::string::npos) pfn = rfn;
else
pfn = rfn.substr(rfn.find(":")+1, rfn.size());
// Check if the replica makes sense and whether its filesystem is enabled
DomeFsInfo fsinfo;
if (!status.PfnMatchesAnyFS(replicas[i].server, pfn, fsinfo)) {
Err(domelogname, SSTR("Replica '" << rfn << "' in server '" << replicas[i].server << "' cannot be matched to any working filesystem. A configuration check is needed."));
continue;
}
if (!fsinfo.isGoodForRead()) continue;
if (replicas[i].status == Replica::kBeingPopulated) {
foundpending = true;
pending_index = i;
continue;
}
found = true;
jresp.put(ptree::path_type(SSTR(i << "^server"), '^'), replicas[i].server);
jresp.put(ptree::path_type(SSTR(i << "^pfn"), '^'), pfn);
jresp.put(ptree::path_type(SSTR(i << "^filesystem"), '^'), replicas[i].getString("filesystem"));
}
if (found)
return DomeReq::SendSimpleResp(request, 200, jresp);
if(foundpending && canpull) {
std::string fs = replicas[pending_index].getString("filesystem");
touch_pull_queue(req, lfn, replicas[pending_index].server, fs, replicas[pending_index].rfn);
return DomeReq::SendSimpleResp(request, 202, SSTR("Refreshed file pull request for " << replicas[pending_index].server
<< ", path " << lfn
<< ", check back later.\r\nTotal pulls in queue right now: "
<< status.filepullq->nTotal()));
}
if (foundpending)
return DomeReq::SendSimpleResp(request, 500, "Only pending replicas are available.");
}
// The lfn does not seemm to exist ? We may have to pull the file from elsewhere
if (ret.code() == ENOENT) {
Log(Logger::Lvl1, domelogmask, domelogname, "Lfn not found: '" << lfn << "'");
}
else
return DomeReq::SendSimpleResp(request, 500, SSTR("Unable to find replicas for '" << lfn << "'"));
// Here we have to trigger the file pull and tell to the client to come back later
if (canpull) {
Log(Logger::Lvl1, domelogmask, domelogname, "Volatile filesystem detected. Seems we can try pulling the file: '" << lfn << "'");
return enqfilepull(req, request, lfn);
}
return DomeReq::SendSimpleResp(request, 404, SSTR("No available replicas for '" << lfn << "'"));
}
int DomeCore::dome_pullstatus(DomeReq &req, FCGX_Request &request) {
if(status.role == status.roleDisk) {
return DomeReq::SendSimpleResp(request, 500, "pullstatus only available on head nodes");
}
Log(Logger::Lvl4, domelogmask, domelogname, "Entering");
try {
DomeMySql sql;
std::string chksumtype = req.bodyfields.get<std::string>("checksum-type", "");
std::string fullchecksum = "checksum." + chksumtype;
std::string pfn = req.bodyfields.get<std::string>("pfn", "");
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
std::string server = req.bodyfields.get<std::string>("server", "");
std::string str_status = req.bodyfields.get<std::string>("status", "");
std::string reason = req.bodyfields.get<std::string>("reason", "");
std::string checksum = req.bodyfields.get<std::string>("checksum", "");
size_t size = req.bodyfields.get("filesize", 0L);
Log(Logger::Lvl1, domelogmask, domelogname, "lfn: '" << lfn << "' server: '" << server << "' pfn: '" << pfn <<
"' pullstatus: '" << str_status << "' cktype: '" << checksum << "' ck: '" << checksum << "' reason: '" << reason << "'");
if(pfn == "") {
return DomeReq::SendSimpleResp(request, 422, "pfn cannot be empty.");
}
if(lfn == "") {
return DomeReq::SendSimpleResp(request, 422, "lfn cannot be empty.");
}
GenPrioQueueItem::QStatus qstatus;
if(str_status == "pending") {
qstatus = GenPrioQueueItem::Running;
}
else if(str_status == "done" || str_status == "aborted") {
qstatus = GenPrioQueueItem::Finished;
}
else {
return DomeReq::SendSimpleResp(request, 422, "The status provided is not recognized.");
}
// modify the queue as needed
std::string namekey = lfn;
std::vector<std::string> qualifiers;
qualifiers.push_back("");
qualifiers.push_back(server);
status.filepullq->touchItemOrCreateNew(namekey, qstatus, 0, qualifiers);
if(qstatus != GenPrioQueueItem::Running) {
status.notifyQueues();
}
if(str_status == "aborted") {
Log(Logger::Lvl1, domelogmask, domelogname, "File pull failed. LFN: " << lfn
<< "PFN: " << pfn << ". Reason: " << reason);
return DomeReq::SendSimpleResp(request, 200, "");
}
if(str_status == "pending") {
Log(Logger::Lvl2, domelogmask, domelogname, "File pull pending... LFN: " << lfn
<< "PFN: " << pfn << ". Reason: " << reason);
return DomeReq::SendSimpleResp(request, 200, "");
}
// status is done, checksum can be empty
Log(Logger::Lvl2, domelogmask, domelogname, "File pull finished. LFN: " << lfn
<< "PFN: " << pfn << ". Reason: " << reason);
// In practice it's like a putdone request, unfortunately we have to
// apparently duplicate some code
// Here unfortunately, for backward compatibility we are forced to
// use the rfio syntax.
std::string rfn = server + ":" + pfn;
dmlite::Replica rep;
DmStatus ret;
ret = sql.getReplicabyRFN(rep, rfn);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot find replica '"<< rfn << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, http_status(ret), os);
}
if (rep.status != dmlite::Replica::kBeingPopulated) {
std::ostringstream os;
os << "Invalid status for replica '"<< rfn << "'";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 422, os);
}
dmlite::ExtendedStat st;
ret = sql.getStatbyFileid(st, rep.fileid);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot fetch logical entry for replica '"<< rfn << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 422, os);
}
// -------------------------------------------------------
// If a miracle took us here, the size has been confirmed
Log(Logger::Lvl1, domelogmask, domelogname, " Final size: " << size );
ret = sql.setSize(rep.fileid, size);
if (ret.ok()) {
std::ostringstream os;
os << "Cannot update replica '"<< rfn << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 500, os);
}
// Update the replica values, including the checksum, if present
rep.ptime = rep.ltime = rep.atime = time(0);
rep.status = dmlite::Replica::kAvailable;
if (checksum.size() && chksumtype.size())
rep[fullchecksum] = checksum;
ret = sql.updateReplica(rep);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot update replica '"<< rfn << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 500, os);
}
// If the checksum of the main entry is different, just output a bad warning in the log
std::string ck;
if ( !st.getchecksum(fullchecksum, ck) && (ck != checksum) ) {
Err(domelogname, SSTR("Replica checksum mismatch rfn:'"<< rfn << "' : " << checksum << " fileid: " << rep.fileid << " : " << ck));
}
return DomeReq::SendSimpleResp(request, 200, "");
}
catch(dmlite::DmException& e) {
std::ostringstream os("An error has occured.\r\n");
os << "Dmlite exception: " << e.what();
return DomeReq::SendSimpleResp(request, 404, os);
}
Log(Logger::Lvl1, domelogmask, domelogname, "Error - execution should never reach this point");
return DomeReq::SendSimpleResp(request, 500, "Something went wrong, execution should never reach this point.");
};
int DomeCore::dome_pull(DomeReq &req, FCGX_Request &request) {
if(status.role == status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_pull only available on disk nodes");
}
Log(Logger::Lvl4, domelogmask, domelogname, "Entering");
try {
//DmlitePoolHandler stack(status.dmpool);
std::string chksumtype = req.bodyfields.get<std::string>("checksum-type", "");
std::string pfn = req.bodyfields.get<std::string>("pfn", "");
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
int64_t neededspace = req.bodyfields.get<int64_t>("neededspace", 0LL);
// Checksumtype in this case can be empty, as it's just a suggestion...
if(pfn == "") {
return DomeReq::SendSimpleResp(request, 422, "pfn cannot be empty.");
}
DomeFsInfo fsinfo;
if(!status.PfnMatchesAnyFS(status.myhostname, pfn, fsinfo)) {
return DomeReq::SendSimpleResp(request, 422, "pfn does not match any of the filesystems of this server.");
}
if(lfn == "") {
return DomeReq::SendSimpleResp(request, 422, "lfn cannot be empty.");
}
if (!CFG->GetString("disk.filepuller.pullhook", (char *)"").size()) {
return DomeReq::SendSimpleResp(request, 500, "File puller is disabled.");
}
Log(Logger::Lvl4, domelogmask, domelogname, "Request to pull pfn: '" << pfn << "' lfn: '" << lfn << "'");
// Commented out because it's normal that a new file has 0 size until it is pulled
// // We retrieve the size of the remote file
// int64_t filesz = 0LL;
// {
//
// std::string domeurl = CFG->GetString("disk.headnode.domeurl", (char *)"(empty url)/");
//
// DomeTalker talker(*davixPool, req.creds, domeurl,
// "GET", "dome_getstatinfo");
//
// if(!talker.execute(req.bodyfields)) {
// Err(domelogname, talker.err());
// return DomeReq::SendSimpleResp(request, 500, talker.err());
// }
//
// try {
// filesz = talker.jresp().get<size_t>("size");
// }
// catch(boost::property_tree::ptree_error &e) {
// std::string errmsg = SSTR("Received invalid json when talking to " << domeurl << ":" << e.what() << " '" << talker.response() << "'");
// Err("takeJSONbodyfields", errmsg);
// return DomeReq::SendSimpleResp(request, 500, errmsg);
// }
//
// }
//
// Log(Logger::Lvl4, domelogmask, domelogname, "Remote size: " << filesz << " for pfn: '" << pfn << "' lfn: '" << lfn << "'");
//
// if (filesz == 0LL) {
// return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot pull a 0-sized file. lfn: '" << lfn << "'") );
// }
// TODO: Doublecheck that there is a suitable replica in P status for the file that we want to fetch
if (neededspace <= 0LL) {
// Try getting the default space for the pool
int64_t pool_defsize = 0LL;
char pool_stype;
if (!status.getPoolInfo(fsinfo.poolname, pool_defsize, pool_stype)) {
Err("dome_pull", SSTR("Can't get pool for fs: '" << fsinfo.server << ":" << fsinfo.fs));
return DomeReq::SendSimpleResp(request, 500, SSTR("Can't get pool for fs: '" << fsinfo.server << ":" << fsinfo.fs) );
}
neededspace = pool_defsize*2;
}
Log(Logger::Lvl2, domelogmask, domelogname, "Checking if we need to makespace. fsinfo.freespace: " << fsinfo.freespace << ", neededspace: " << neededspace);
// Make sure that there is enough space to fit filesz bytes
if (fsinfo.freespace < neededspace) {
Log(Logger::Lvl1, domelogmask, domelogname, "Filesystem can only accommodate " << fsinfo.freespace << "B, filesize is : " << neededspace << " ... trying to purge volatile files.");
std::vector<std::string> comps = Url::splitPath(pfn);
if (comps.size() < 3)
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid pfn: '" << pfn << "'") );
// Drop the last two tokens, to get the fs+vo prefix
comps.pop_back();
comps.pop_back();
std::string fsvopfx = Url::joinPath(comps);
int freed = makespace(fsvopfx, neededspace);
if (freed < neededspace)
return DomeReq::SendSimpleResp(request, 422, SSTR("Volatile file purging failed. Not enough disk space to pull pfn: '" << pfn << "'") );
}
// TODO: Make sure that the phys file does not already exist
Log(Logger::Lvl1, domelogmask, domelogname, "Starting filepull. Remote size: " << neededspace << " for pfn: '" << pfn << "' lfn: '" << lfn << "'");
// Create the necessary directories, if needed
try {
DomeUtils::mkdirp(pfn);
}
catch(DmException &e) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_INTERNAL_SERVER_ERROR, SSTR("Unable to create physical directories for '" << pfn << "'- internal error: '" << e.what() << "'"));
}
// Let's just execute the external hook, passing the obvious parameters
PendingPull pending(lfn, status.myhostname, pfn, req.creds, chksumtype);
std::vector<std::string> params;
params.push_back(CFG->GetString("disk.filepuller.pullhook", (char *)""));
params.push_back(lfn);
params.push_back(pfn);
params.push_back(SSTR(neededspace));
int id = this->submitCmd(params);
if (id < 0)
return DomeReq::SendSimpleResp(request, 500, "Could not invoke file puller.");
diskPendingPulls[id] = pending;
// Now exit, the file pull is hopefully ongoing
return DomeReq::SendSimpleResp(request, 202, SSTR("Initiated file pull. lfn: '" << lfn << "' pfn: '"<< pfn << "', task executor ID: " << id));
}
catch(dmlite::DmException& e) {
std::ostringstream os("An error has occured.\r\n");
os << "Dmlite exception: " << e.what();
return DomeReq::SendSimpleResp(request, 404, os);
}
};
// returns true if str2 is a strict subdir of str1
// both arguments are assumed not to have trailing slashes
static bool is_subdir(const std::string &str1, const std::string &str2) {
size_t pos = str1.find(str2);
return pos == 0 && str1.length() > str2.length() && str1[str2.length()] == '/';
}
int DomeCore::dome_getquotatoken(DomeReq &req, FCGX_Request &request) {
std::string absPath = DomeUtils::trim_trailing_slashes(req.bodyfields.get<std::string>("path", ""));
Log(Logger::Lvl4, domelogmask, domelogname, "Processing: '" << absPath << "'");
bool getsubdirs = req.bodyfields.get<bool>("getsubdirs", false);
bool getparentdirs = req.bodyfields.get<bool>("getparentdirs", false);
// Get the ones that match the object of the query
boost::property_tree::ptree jresp;
int cnt = 0;
// Make a local copy of the quotas to loop on
std::multimap <std::string, DomeQuotatoken> localquotas;
{
boost::unique_lock<boost::recursive_mutex> l(status);
localquotas = status.quotas;
}
DomeMySql sql;
DmStatus ret;
for (std::multimap<std::string, DomeQuotatoken>::iterator it = localquotas.begin(); it != localquotas.end(); ++it) {
bool match = false;
if(absPath == it->second.path) {
match = true; // perfect match, exact directory we're looking for
}
else if(getparentdirs && is_subdir(absPath, it->second.path)) {
match = true; // parent dir match
}
else if(getsubdirs && is_subdir(it->second.path, absPath)) {
match = true; // subdir match
}
Log(Logger::Lvl4, domelogmask, domelogname, "Checking: '" << it->second.path << "' versus '" << absPath << "' getparentdirs: " << getparentdirs << " getsubdirs: " << getsubdirs << " match: " << match);
if(!match) continue;
// Get the used space for this path
long long pathfree = 0LL;
long long pathused = 0LL;
struct dmlite::ExtendedStat st;
ret = sql.getStatbyLFN(st, it->second.path);
if (!ret.ok()) {
std::ostringstream os;
os << "Found quotatokens for non-existing path '"<< it->second.path << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
continue;
}
pathused = st.stat.st_size;
// Now find the free space in the mentioned pool
long long ptot, pfree;
int poolst;
status.getPoolSpaces(it->second.poolname, ptot, pfree, poolst);
pathfree = ( (it->second.t_space - pathused < ptot - pathused) ? it->second.t_space - pathused : ptot - pathused );
if (pathfree < 0) pathfree = 0;
Log(Logger::Lvl4, domelogmask, domelogname, "Quotatoken '" << it->second.u_token << "' of pool: '" <<
it->second.poolname << "' matches path '" << absPath << "' quotatktotspace: " << it->second.t_space <<
" pooltotspace: " << ptot << " pathusedspace: " << pathused << " pathfreespace: " << pathfree );
boost::property_tree::ptree pt, grps;
pt.put("path", it->second.path);
pt.put("quotatkname", it->second.u_token);
pt.put("quotatkpoolname", it->second.poolname);
pt.put("quotatktotspace", it->second.t_space);
pt.put("pooltotspace", ptot);
pt.put("pathusedspace", pathused);
pt.put("pathfreespace", pathfree);
// Push the groups array into the response
for (unsigned i = 0; i < it->second.groupsforwrite.size(); i++) {
DomeGroupInfo gi;
int thisgid = atoi(it->second.groupsforwrite[i].c_str());
if (!status.getGroup(thisgid, gi))
grps.push_back(std::make_pair(it->second.groupsforwrite[i], "<unknown>"));
else
grps.push_back(std::make_pair(it->second.groupsforwrite[i], gi.groupname));
}
pt.push_back(std::make_pair("groups", grps));
jresp.push_back(std::make_pair(it->second.s_token, pt));
cnt++;
}
if (cnt > 0) {
return DomeReq::SendSimpleResp(request, 200, jresp);
}
return DomeReq::SendSimpleResp(request, 404, SSTR("No quotatokens match path '" << absPath << "'"));
};
template<class T>
static void set_if_field_exists(T& target, const boost::property_tree::ptree &bodyfields, const std::string &key) {
if(bodyfields.count(key) != 0) {
target = bodyfields.get<T>(key);
}
}
static bool translate_group_names(DomeStatus &status, const std::string &groupnames, std::vector<std::string> &ids, std::string &err) {
std::vector<std::string> groupnames_vec = DomeUtils::split(groupnames, ",");
ids.clear();
ids.push_back("0"); // not really sure if necessary
for(size_t i = 0; i < groupnames_vec.size(); i++) {
DomeGroupInfo tmp;
if(status.getGroup(groupnames_vec[i], tmp) == 0) {
err = SSTR("Invalid group name: " << groupnames_vec[i]);
return false;
}
ids.push_back(SSTR(tmp.groupid));
}
return true;
}
int DomeCore::dome_setquotatoken(DomeReq &req, FCGX_Request &request) {
Log(Logger::Lvl4, domelogmask, domelogname, "Entering.");
DomeQuotatoken mytk;
mytk.path = DomeUtils::trim_trailing_slashes(req.bodyfields.get("path", ""));
mytk.poolname = req.bodyfields.get("poolname", "");
if (!status.existsPool(mytk.poolname)) {
std::ostringstream os;
os << "Cannot find pool: '" << mytk.poolname << "'";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 404, os);
}
DomeMySql sql;
DmStatus ret;
struct dmlite::ExtendedStat st;
ret = sql.getStatbyLFN(st, mytk.path);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot find logical path: '" << mytk.path << "'";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 404, os);
}
// We fetch the values that we may have in the internal map, using the keys
if ( status.getQuotatoken(mytk.path, mytk.poolname, mytk) ) {
std::ostringstream os;
Log(Logger::Lvl1, domelogmask, domelogname, "No quotatoken found for pool: '" <<
mytk.poolname << "' path '" << mytk.path << "'. Creating new one.");
// set default values
mytk.t_space = 0LL;
mytk.u_token = "(unnamed)";
mytk.s_token = "";
}
set_if_field_exists(mytk.t_space, req.bodyfields, "quotaspace");
set_if_field_exists(mytk.u_token, req.bodyfields, "description");
set_if_field_exists(mytk.s_token, req.bodyfields, "uniqueid");
if(req.bodyfields.count("groups") != 0) {
std::string err;
if(!translate_group_names(status, req.bodyfields.get("groups", ""), mytk.groupsforwrite, err)) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to write quotatoken - " << err));
}
}
// First we write into the db, if it goes well then we update the internal map
int rc;
{
DomeMySql sql;
DomeMySqlTrans t(&sql);
std::string clientid = req.creds.clientName;
if (clientid.size() == 0) clientid = req.clientdn;
if (clientid.size() == 0) clientid = "(unknown)";
rc = sql.setQuotatoken(mytk, clientid);
if (!rc) t.Commit();
}
if (rc) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot write quotatoken into the DB. poolname: '" << mytk.poolname
<< "' t_space: " << mytk.t_space << " u_token: '" << mytk.u_token << "'"));
return 1;
}
status.loadQuotatokens();
return DomeReq::SendSimpleResp(request, 200, SSTR("Quotatoken written. poolname: '" << mytk.poolname
<< "' t_space: " << mytk.t_space << " u_token: '" << mytk.u_token << "'"));
};
int DomeCore::dome_delquotatoken(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_delquotatoken only available on head nodes.");
}
DomeQuotatoken mytk;
mytk.path = req.bodyfields.get("path", "");
mytk.poolname = req.bodyfields.get("poolname", "");
if (!status.existsPool(mytk.poolname)) {
std::ostringstream os;
os << "Cannot find pool: '" << mytk.poolname << "'";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 404, os);
}
// We fetch the values that we may have in the internal map, using the keys, and remove it
if ( status.delQuotatoken(mytk.path, mytk.poolname, mytk) ) {
std::ostringstream os;
os << "No quotatoken found for pool: '" <<
mytk.poolname << "' path '" << mytk.path << "'.";
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 404, os);
}
// If everything was ok, we delete it from the db too
// First we write into the db, if it goes well then we update the internal map
int rc;
{
DomeMySql sql;
DomeMySqlTrans t(&sql);
std::string clientid = req.creds.clientName;
if (clientid.size() == 0) clientid = req.clientdn;
if (clientid.size() == 0) clientid = "(unknown)";
rc = sql.delQuotatoken(mytk, clientid);
if (!rc) t.Commit();
}
if (rc) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot delete quotatoken from the DB. poolname: '" << mytk.poolname
<< "' t_space: " << mytk.t_space << " u_token: '" << mytk.u_token << "'"));
return 1;
}
// To avoid race conditions without locking, we have to make sure that it's not in memory
status.delQuotatoken(mytk.path, mytk.poolname, mytk);
return DomeReq::SendSimpleResp(request, 200, SSTR("Quotatoken deleted. poolname: '" << mytk.poolname
<< "' t_space: " << mytk.t_space << " u_token: '" << mytk.u_token << "'"));
};
int DomeCore::dome_modquotatoken(DomeReq &req, FCGX_Request &request) {
if(status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_modquotatoken only available on head nodes");
}
std::string tokenid = req.bodyfields.get<std::string>("tokenid", "");
if(tokenid.empty()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("tokenid is empty."));
}
DomeQuotatoken mytk;
if(!status.getQuotatoken(tokenid, mytk)) {
return DomeReq::SendSimpleResp(request, 404, SSTR("No quotatoken with id '" << tokenid << "' could be found"));
}
set_if_field_exists(mytk.t_space, req.bodyfields, "quotaspace");
set_if_field_exists(mytk.u_token, req.bodyfields, "description");
set_if_field_exists(mytk.path, req.bodyfields, "path");
set_if_field_exists(mytk.poolname, req.bodyfields, "poolname");
if(req.bodyfields.count("groups") != 0) {
std::string err;
if(!translate_group_names(status, req.bodyfields.get("groups", ""), mytk.groupsforwrite, err)) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to write quotatoken - " << err));
}
}
// First we write into the db, if it goes well then we update the internal map
int rc;
{
DomeMySql sql;
DomeMySqlTrans t(&sql);
rc = sql.setQuotatokenByStoken(mytk);
if (!rc) t.Commit();
}
if (rc) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot write quotatoken into the DB. poolname: '" << mytk.poolname
<< "' t_space: " << mytk.t_space << " u_token: '" << mytk.u_token << "'"));
return 1;
}
status.loadQuotatokens();
return DomeReq::SendSimpleResp(request, 200, SSTR("Quotatoken written. poolname: '" << mytk.poolname
<< "' t_space: " << mytk.t_space << " u_token: '" << mytk.u_token << "'"));
}
int DomeCore::dome_pfnrm(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleDisk) {
return DomeReq::SendSimpleResp(request, 500, "pfnrm only available on disk nodes");
}
std::string absPath = req.bodyfields.get<std::string>("pfn", "");
if (!absPath.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Path '" << absPath << "' is empty."));
}
if (absPath[0] != '/') {
return DomeReq::SendSimpleResp(request, 404, SSTR("Path '" << absPath << "' is not an absolute path."));
}
// Remove any trailing slash
while (absPath[ absPath.size()-1 ] == '/') {
absPath.erase(absPath.size() - 1);
}
if (!status.PfnMatchesAnyFS(status.myhostname, absPath)) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Path '" << absPath << "' is not a valid pfn."));
}
// OK, remove directly on disk
// This is not a high perf function, so we can afford one stat call
struct stat st;
int rc = stat(absPath.c_str(), &st);
if (rc) {
if (errno == ENOENT) {
return DomeReq::SendSimpleResp(request, 200, SSTR("Rm successful. The file or dir '" << absPath << "' not there anyway."));
}
char errbuf[1024];
return DomeReq::SendSimpleResp(request, 422, SSTR("Rm of '" << absPath << "' failed. err: " << errno << " msg: " << strerror_r(errno, errbuf, sizeof(errbuf))));
}
if (S_ISDIR(st.st_mode)) {
int rc = rmdir(absPath.c_str());
if (rc) {
char errbuf[1024];
return DomeReq::SendSimpleResp(request, 422, SSTR("Rmdir of directory '" << absPath << "' failed. err: " << errno << " msg: " << strerror_r(errno, errbuf, sizeof(errbuf))));
}
}
else {
int rc = unlink(absPath.c_str());
if (rc) {
char errbuf[1024];
return DomeReq::SendSimpleResp(request, 422, SSTR("Rm of file '" << absPath << "' failed. err: " << errno << " msg: " << strerror_r(errno, errbuf, sizeof(errbuf))));
}
}
return DomeReq::SendSimpleResp(request, 200, SSTR("Rm successful."));
}
int DomeCore::dome_delreplica(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_delreplica only available on head nodes.");
}
std::string absPath = req.bodyfields.get<std::string>("pfn", "");
std::string srv = req.bodyfields.get<std::string>("server", "");
Log(Logger::Lvl4, domelogmask, domelogname, " srv: '" << srv << "' pfn: '" << absPath << "' ");
if (!absPath.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Path '" << absPath << "' is empty."));
}
if (!srv.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Server name '" << srv << "' is empty."));
}
if (absPath[0] != '/') {
return DomeReq::SendSimpleResp(request, 404, SSTR("Path '" << absPath << "' is not an absolute path."));
}
// Remove any trailing slash
while (absPath[ absPath.size()-1 ] == '/') {
absPath.erase(absPath.size() - 1);
}
if (!status.PfnMatchesAnyFS(srv, absPath)) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Path '" << absPath << "' is not a valid pfn for server '" << srv << "'"));
}
// Get the replica. Unfortunately to delete it we must first fetch it
std::string rfiopath = srv + ":" + absPath;
Log(Logger::Lvl4, domelogmask, domelogname, "Getting replica: '" << rfiopath);
dmlite::Replica rep;
DomeMySql sql;
DmStatus ret;
ret = sql.getReplicabyRFN(rep, rfiopath);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot find replica '"<< rfiopath << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 404, os);
}
// Now check the perms
SecurityContext ctx;
fillSecurityContext(ctx, req);
ExtendedStat xstat;
ret = sql.getStatbyFileid(xstat, rep.fileid);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat fileid " << rep.fileid << " of rfn: '" << rep.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
if (!S_ISREG(xstat.stat.st_mode))
return DomeReq::SendSimpleResp(request, 400, SSTR("Inode " << rep.fileid << " is not a regular file"));
// Check perms on the parents
ret = sql.traverseBackwards(ctx, xstat);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Permission denied on fileid " << xstat.stat.st_ino
<< " of rfn: '" << rep.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
if (checkPermissions(&ctx, xstat.acl, xstat.stat, S_IWRITE) != 0)
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Cannot modify file " << xstat.stat.st_ino
<< " of rfn: '" << rep.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// We fetched it, which means that many things are fine.
// Now delete the physical file
std::string diskurl = "https://" + srv + "/domedisk/";
Log(Logger::Lvl4, domelogmask, domelogname, "Dispatching deletion of replica '" << absPath << "' to disk node: '" << diskurl);
DomeTalker talker(*davixPool, req.creds, diskurl,
"POST", "dome_pfnrm");
if(!talker.execute(req.bodyfields)) {
Err(domelogname, talker.err());
return DomeReq::SendSimpleResp(request, 500, talker.err());
}
Log(Logger::Lvl4, domelogmask, domelogname, "Removing replica: '" << rep.rfn);
// And now remove the replica
{
DomeMySqlTrans t(&sql);
// Free some space
if(sql.delReplica(rep.fileid, rfiopath) != 0) {
std::ostringstream os;
os << "Cannot delete replica '" << rfiopath;
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 404, os);
}
t.Commit();
}
Log(Logger::Lvl4, domelogmask, domelogname, "Check if we have to remove the logical fileid " << rep.fileid);
// Get the file size :-(
int64_t sz = xstat.stat.st_size;
std::vector<Replica> repls;
ret = sql.getReplicas(repls, rep.fileid);
if (!ret.ok() && ret.code() != DMLITE_NO_SUCH_REPLICA)
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't get replicas of fileid " << rep.fileid <<
" err: " << ret.code() << " what:" << ret.what()) );
if (repls.size() == 0) {
// Delete the logical entry if this was the last replica
ret = sql.unlink(rep.fileid);
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot unlink fileid: '"<< rep.fileid << "' : " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
//return DomeReq::SendSimpleResp(request, 404, os);
}
}
if(!sql.addFilesizeToDirs(xstat, -sz).ok()) {
Err(domelogname, SSTR("Unable to decrease filesize from parent directories of fileid: " << xstat.stat.st_ino ));
}
// For backward compatibility with the DPM daemon, we also update its
// spacetoken counters, adjusting u_space
{
DomeQuotatoken token;
if (rep.setname.size() > 0) {
Log(Logger::Lvl4, domelogmask, domelogname, " Accounted space token: '" << rep.setname <<
"' rfn: '" << rep.rfn << "'");
DomeMySql sql;
DomeMySqlTrans t(&sql);
// Free some space
sql.addtoQuotatokenUspace(rep.setname, sz);
t.Commit();
}
}
return DomeReq::SendSimpleResp(request, 200, SSTR("Deleted '" << absPath << "' in server '" << srv << "'. Have a nice day."));
}
/// Removes a pool and all the related filesystems
int DomeCore::dome_rmpool(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_rmpool only available on head nodes.");
}
std::string poolname = req.bodyfields.get<std::string>("poolname", "");
Log(Logger::Lvl4, domelogmask, domelogname, " poolname: '" << poolname << "'");
if (!poolname.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("poolname '" << poolname << "' is empty."));
}
// First we write into the db, if it goes well then we update the internal map
int rc;
{
DomeMySql sql;
DomeMySqlTrans t(&sql);
rc = sql.rmPool(poolname);
if (!rc) t.Commit();
}
if (rc) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot delete pool: '" << poolname << "'"));
return 1;
}
status.loadFilesystems();
return DomeReq::SendSimpleResp(request, 200, "Pool deleted.");
}
int DomeCore::dome_statpfn(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleDisk) {
return DomeReq::SendSimpleResp(request, 500, "dome_statpfn only available on disk nodes.");
}
std::string pfn = req.bodyfields.get<std::string>("pfn", "");
bool matchesfs = DomeUtils::str_to_bool(req.bodyfields.get<std::string>("matchfs", "true"));
Log(Logger::Lvl4, domelogmask, domelogname, " pfn: '" << pfn << "'");
if (!pfn.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("pfn '" << pfn << "' is empty."));
}
if (matchesfs && !status.PfnMatchesAnyFS(status.myhostname, pfn)) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Path '" << pfn << "' does not match any existing filesystems in disk server '" << status.myhostname << "'"));
}
struct stat st;
if ( stat(pfn.c_str(), &st) ) {
std::ostringstream os;
char errbuf[1024];
os << "Cannot stat pfn:'" << pfn << "' err: " << errno << ":" << strerror_r(errno, errbuf, 1023);
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, 404, os);
}
Log(Logger::Lvl2, domelogmask, domelogname, " pfn: '" << pfn << "' "
" disksize: " << st.st_size << " flags: " << st.st_mode);
boost::property_tree::ptree jresp;
jresp.put("size", st.st_size);
jresp.put("mode", st.st_mode);
jresp.put("isdir", ( S_ISDIR(st.st_mode) ));
return DomeReq::SendSimpleResp(request, 200, jresp);
};
int DomeCore::dome_addpool(DomeReq &req, FCGX_Request &request) {
if(status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_addpool only available on head nodes.");
}
std::string poolname = req.bodyfields.get<std::string>("poolname", "");
long pool_defsize = req.bodyfields.get("pool_defsize", 3L * 1024 * 1024 * 1024);
std::string pool_stype = req.bodyfields.get("pool_stype", "P");
Log(Logger::Lvl4, domelogmask, domelogname, " poolname: '" << poolname << "'");
if (!poolname.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("poolname '" << poolname << "' is empty."));
}
if (pool_defsize < 1024*1024) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid defsize: " << pool_defsize));
}
if(pool_stype != "P" && pool_stype != "V") {
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid pool_stype: " << pool_stype));
}
// make sure it doesn't already exist
{
boost::unique_lock<boost::recursive_mutex> l(status);
for (std::vector<DomeFsInfo>::iterator fs = status.fslist.begin(); fs != status.fslist.end(); fs++) {
if(fs->poolname == poolname) {
return DomeReq::SendSimpleResp(request, 422, SSTR("poolname '" << poolname << "' already exists."));
}
}
if (status.poolslist.find(poolname) != status.poolslist.end()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("poolname '" << poolname << "' already exists in the groups map (may have no filesystems)."));
}
}
int rc;
{
DomeMySql sql;
DomeMySqlTrans t(&sql);
rc = sql.addPool(poolname, pool_defsize, pool_stype[0]);
if (!rc) t.Commit();
}
if (rc) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Could not add new pool - error code: " << rc));
}
status.loadFilesystems();
return DomeReq::SendSimpleResp(request, 200, "Pool was created.");
}
int DomeCore::dome_modifypool(DomeReq &req, FCGX_Request &request) {
if(status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_modifypool only available on head nodes.");
}
std::string poolname = req.bodyfields.get<std::string>("poolname", "");
long pool_defsize = req.bodyfields.get("pool_defsize", 3L * 1024 * 1024 * 1024);
std::string pool_stype = req.bodyfields.get("pool_stype", "P");
Log(Logger::Lvl4, domelogmask, domelogname, " poolname: '" << poolname << "'");
if (!poolname.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("poolname '" << poolname << "' is empty."));
}
if (pool_defsize < 1024*1024) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid defsize: " << pool_defsize));
}
if (!pool_stype.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("pool_stype '" << pool_stype << "' is empty."));
}
// make sure it DOES exist
{
boost::unique_lock<boost::recursive_mutex> l(status);
if (status.poolslist.find(poolname) == status.poolslist.end()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("poolname '" << poolname << "' does not exist, cannot modify it."));
}
}
int rc;
{
DomeMySql sql;
DomeMySqlTrans t(&sql);
rc = sql.addPool(poolname, pool_defsize, pool_stype[0]);
if (!rc) t.Commit();
}
if (rc) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Could not modify pool - error code: " << rc));
}
status.loadFilesystems();
return DomeReq::SendSimpleResp(request, 200, "Pool was modified.");
}
/// Adds a filesystem to a pool
int DomeCore::dome_addfstopool(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_addfstopool only available on head nodes.");
}
std::string poolname = req.bodyfields.get<std::string>("poolname", "");
std::string server = req.bodyfields.get<std::string>("server", "");
std::string newfs = req.bodyfields.get<std::string>("fs", "");
int fsstatus = req.bodyfields.get<int>("status", 0); // DomeFsStatus::FsStaticActive
Log(Logger::Lvl4, domelogmask, domelogname, " poolname: '" << poolname << "'");
if (!poolname.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("poolname '" << poolname << "' is empty."));
}
if ((fsstatus < 0) || (fsstatus > 2))
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid status '" << fsstatus << "'. Should be 0, 1 or 2."));
// Make sure it's not already there or that we are not adding a parent/child of an existing fs
for (std::vector<DomeFsInfo>::iterator fs = status.fslist.begin(); fs != status.fslist.end(); fs++) {
if ( status.PfnMatchesFS(server, newfs, *fs) )
return DomeReq::SendSimpleResp(request, 422, SSTR("Filesystem '" << server << ":" << fs->fs << "' already exists or overlaps an existing filesystem."));
}
// Stat the remote path, to make sure it exists and it makes sense
std::string diskurl = "https://" + server + "/domedisk/";
Log(Logger::Lvl4, domelogmask, domelogname, "Stat-ing new filesystem '" << newfs << "' in disk node: '" << server);
DomeTalker talker(*davixPool, req.creds, diskurl,
"GET", "dome_statpfn");
boost::property_tree::ptree jresp;
jresp.put("pfn", newfs);
jresp.put("matchfs", "false");
jresp.put("server", server);
if(!talker.execute(jresp)) {
Err(domelogname, talker.err());
return DomeReq::SendSimpleResp(request, 500, talker.err());
}
// Everything seems OK here, like UFOs invading Earth. We can start updating values.
// First we write into the db, if it goes well then we update the internal map
int rc;
{
DomeMySql sql;
DomeMySqlTrans t(&sql);
DomeFsInfo fsfs;
fsfs.poolname = poolname;
fsfs.server = server;
fsfs.fs = newfs;
fsfs.status = (DomeFsInfo::DomeFsStatus)fsstatus;
rc = sql.addFs(fsfs);
if (!rc) t.Commit();
}
if (rc) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Could not insert new fs: '" << newfs << "' It likely already exists."));
return 1;
}
status.loadFilesystems();
return DomeReq::SendSimpleResp(request, 200, SSTR("New filesystem added."));
}
/// Modifies an existing filesystem
int DomeCore::dome_modifyfs(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_modifyfs only available on head nodes.");
}
std::string poolname = req.bodyfields.get<std::string>("poolname", "");
std::string server = req.bodyfields.get<std::string>("server", "");
std::string newfs = req.bodyfields.get<std::string>("fs", "");
int fsstatus = req.bodyfields.get<int>("status", 0); // DomeFsStatus::FsStaticActive
Log(Logger::Lvl4, domelogmask, domelogname, " poolname: '" << poolname << "'");
if (!poolname.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("poolname '" << poolname << "' is empty."));
}
if ((fsstatus < 0) || (fsstatus > 2))
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid status '" << fsstatus << "'. Should be 0, 1 or 2."));
// Make sure it is already there exactly
{
// Lock status!
boost::unique_lock<boost::recursive_mutex> l(status);
for (std::vector<DomeFsInfo>::iterator fs = status.fslist.begin(); fs != status.fslist.end(); fs++) {
if ( status.PfnMatchesFS(server, newfs, *fs) ) {
if (fs->fs.length() != newfs.length())
return DomeReq::SendSimpleResp(request, 422, SSTR("Filesystem '" << server << ":" << newfs << "' overlaps the existing filesystem '" << fs->fs << "'"));
}
}
}
// Stat the remote path, to make sure it exists and it makes sense
std::string diskurl = "https://" + server + "/domedisk/";
Log(Logger::Lvl4, domelogmask, domelogname, "Stat-ing new filesystem '" << newfs << "' in disk node: '" << server);
DomeTalker talker(*davixPool, req.creds, diskurl,
"GET", "dome_statpfn");
boost::property_tree::ptree jresp;
jresp.put("pfn", newfs);
jresp.put("matchfs", "false");
jresp.put("server", server);
if(!talker.execute(jresp)) {
Err(domelogname, talker.err());
return DomeReq::SendSimpleResp(request, 500, talker.err());
}
// Everything seems OK here, the technological singularity will come. We can start updating values.
// First we write into the db, if it goes well then we update the internal map
int rc;
{
DomeMySql sql;
DomeMySqlTrans t(&sql);
DomeFsInfo fsfs;
fsfs.poolname = poolname;
fsfs.server = server;
fsfs.fs = newfs;
fsfs.status = (DomeFsInfo::DomeFsStatus)fsstatus;
rc = sql.modifyFs(fsfs);
if (!rc) t.Commit();
}
if (rc) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Could not modify fs: '" << newfs << "'."));
return 1;
}
status.loadFilesystems();
return DomeReq::SendSimpleResp(request, 200, SSTR("Filesystem modified."));
}
/// Removes a filesystem, no matter to which pool it was attached
int DomeCore::dome_rmfs(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_rmfs only available on head nodes.");
}
std::string server = req.bodyfields.get<std::string>("server", "");
std::string newfs = req.bodyfields.get<std::string>("fs", "");
Log(Logger::Lvl4, domelogmask, domelogname, " serrver: '" << server << "' fs: '" << newfs << "'");
int ndel = 0;
bool found = false;
{
// Lock status!
boost::unique_lock<boost::recursive_mutex> l(status);
for (std::vector<DomeFsInfo>::iterator fs = status.fslist.begin(); fs != status.fslist.end(); fs++) {
if(newfs == fs->fs) {
found = true;
break;
}
}
}
if(!found) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_NOT_FOUND, SSTR("Filesystem '" << newfs << "' not found on server '" << server << "'"));
}
int rc;
{
DomeMySql sql;
DomeMySqlTrans t(&sql);
rc = sql.rmFs(server, newfs);
if (!rc) t.Commit();
}
if (rc)
return DomeReq::SendSimpleResp(request, 422, SSTR("Failed deleting filesystem '" << newfs << "' of server '" << server << "'"));
status.loadFilesystems();
return DomeReq::SendSimpleResp(request, 200, SSTR("Deleted " << ndel << "filesystems matching '" << newfs << "' of server '" << server << "'"));
}
static void xstat_to_ptree(const dmlite::ExtendedStat& xstat, boost::property_tree::ptree &ptree) {
ptree.put("fileid", xstat.stat.st_ino);
ptree.put("parentfileid", xstat.parent);
ptree.put("size", xstat.stat.st_size);
ptree.put("mode", xstat.stat.st_mode);
ptree.put("atime", xstat.stat.st_atime);
ptree.put("mtime", xstat.stat.st_mtime);
ptree.put("ctime", xstat.stat.st_ctime);
ptree.put("uid", xstat.stat.st_uid);
ptree.put("gid", xstat.stat.st_gid);
ptree.put("nlink", xstat.stat.st_nlink);
ptree.put("acl", xstat.acl.serialize());
ptree.put("name", xstat.name);
ptree.put("xattrs", xstat.serialize());
}
/// Fecthes logical stat information for an LFN or file ID or a pfn
int DomeCore::dome_getstatinfo(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_getstatinfo only available on head nodes.");
}
std::string server = req.bodyfields.get<std::string>("server", "");
std::string pfn = req.bodyfields.get<std::string>("pfn", "");
std::string rfn = req.bodyfields.get<std::string>("rfn", "");
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
Log(Logger::Lvl4, domelogmask, domelogname, " server: '" << server << "' pfn: '" << pfn << "' rfn: '" << rfn << "' lfn: '" << lfn << "'");
struct dmlite::ExtendedStat st;
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
DmStatus ret;
// If lfn is filled then we stat the logical file
if (lfn.size()) {
{
DomeMySql sql;
ExtendedStat parent;
std::string parentPath, name;
ret = sql.getParent(parent, lfn, parentPath, name);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat the parent of lfn: '" << lfn << "'"));
ret = sql.traverseBackwards(ctx, parent);
if (!ret.ok()) {
if (ret.code() == ENOENT)
return DomeReq::SendSimpleResp(request, 404, SSTR("File not found on the parents of lfn: '" << lfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
return DomeReq::SendSimpleResp(request, 403, SSTR("Permission denied on lfn: '" << lfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// Need to be able to read the parent
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IREAD) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Need READ access on '" << parentPath << "'"));
ret = sql.getStatbyLFN(st, lfn);
}
if (ret.code() == ENOENT) {
// If the lfn maps to a pool that can pull files then we want to invoke
// the external stat hook before concluding that the file is not available
DomeFsInfo fsnfo;
if (status.LfnMatchesAnyCanPullFS(lfn, fsnfo)) {
// problem... for an external file there's no damn inode yet, let's set it to 0
std::string hook = CFG->GetString("head.filepuller.stathook", (char *)"");
if ((hook.size() < 5) || (hook[0] != '/'))
return DomeReq::SendSimpleResp(request, 500, "Invalid stat hook.");
std::vector<std::string> params;
params.push_back(hook);
params.push_back(lfn);
int id = this->submitCmd(params);
if (id < 0)
return DomeReq::SendSimpleResp(request, 500, "Could not invoke stat hook.");
// Now wait for the process to have finished
int taskrc = waitResult(id, CFG->GetLong("head.filepuller.stathooktimeout", 60));
if (taskrc)
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot remotely stat lfn: '" << lfn << "'"));
std::string err;
if (extract_stat(this->getTask(id)->stdout, err, st) <= 0) {
Err(domelogname, "Failed stating lfn: '" << lfn << "' err: '" << err << "'");
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot remotely stat lfn: '" << lfn << "'"));
}
}
else
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat lfn: '" << lfn << "' err: " << ret.code() << " what: '" << ret.what() << "' and no volatile filesystem matches.") );
}
}
else {
DmStatus ret;
// Let's be kind with the client and also accept the rfio syntax
if ( rfn.size() ) {
pfn = DomeUtils::pfn_from_rfio_syntax(rfn);
server = DomeUtils::server_from_rfio_syntax(rfn);
}
// If no stat happened so far, we check if we can stat the pfn
if ( (!server.size() || !pfn.size() ) )
return DomeReq::SendSimpleResp(request, 422, SSTR("Not enough parameters."));
// Else we stat the replica, recomposing the rfioname (sob)
rfn = server + ":" + pfn;
{
DomeMySql sql;
ret = sql.getStatbyRFN(st, rfn);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("File not found on rfn: '" << rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
ret = sql.traverseBackwards(ctx, st);
if (!ret.ok()) {
if (ret.code() == ENOENT)
return DomeReq::SendSimpleResp(request, 404, SSTR("File not found on the parents of rfn: '" << rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
return DomeReq::SendSimpleResp(request, 403, SSTR("Permission denied on rfn: '" << rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// Need to be able to read the parents
if (checkPermissions(&ctx, st.acl, st.stat, S_IREAD) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Need READ access on rfn '" << rfn << "'"));
}
if (ret.code() != DMLITE_SUCCESS) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat server: '" << server << "' pfn: '" << pfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
}
boost::property_tree::ptree jresp;
xstat_to_ptree(st, jresp);
return DomeReq::SendSimpleResp(request, 200, jresp);
}
/// Fecthes replica info from its rfn or its Id
int DomeCore::dome_getreplicainfo(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_getstatinfo only available on head nodes.");
}
std::string rfn = req.bodyfields.get<std::string>("rfn", "");
int64_t replicaid = req.bodyfields.get<int64_t>("replicaid", 0);
Log(Logger::Lvl4, domelogmask, domelogname, " rfn: '" << rfn << "' replicaid: " << replicaid);
struct dmlite::Replica r;
DmStatus ret;
if ( !rfn.size() && !replicaid ) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Need a replica filename or a replicaid"));
}
{
DomeMySql sql;
if (replicaid) {
ret = sql.getReplicabyId(r, replicaid);
if (ret.code() != DMLITE_SUCCESS) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot retrieve replicaid: " << replicaid << " err: " << ret.code() << " what: '" << ret.what() << "'"));
}
}
else {
ret = sql.getReplicabyRFN(r, rfn);
if (ret.code() != DMLITE_SUCCESS) {
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot retrieve rfn: '" << rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
}
}
boost::property_tree::ptree jresp;
jresp.put("replicaid", r.replicaid);
jresp.put("fileid", r.fileid);
jresp.put("nbaccesses", r.nbaccesses);
jresp.put("atime", r.atime);
jresp.put("ptime", r.ptime);
jresp.put("ltime", r.ltime);
jresp.put("status", r.status);
jresp.put("type", r.type);
jresp.put("server", r.server);
jresp.put("rfn", rfn);
jresp.put("setname", r.setname);
jresp.put("xattrs", r.serialize());
return DomeReq::SendSimpleResp(request, 200, jresp);
}
/// Like an HTTP GET on a directory, gets all the content
int DomeCore::dome_getdir(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_getdir only available on head nodes.");
}
std::string path = req.bodyfields.get<std::string>("path", "");
if (!path.size()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot list an empty path"));
}
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
DomeMySql sql;
ExtendedStat parent;
std::string parentPath, name;
DmStatus ret = sql.getParent(parent, path, parentPath, name);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat the parent of lfn: '" << path << "'"));
ret = sql.traverseBackwards(ctx, parent);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Permission denied on lfn: '" << path << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// Need to be able to read the parent
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IREAD | S_IEXEC) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Need READ access on '" << parentPath << "'"));
boost::property_tree::ptree jresp, jresp2;
DomeMySqlDir *d;
ret = sql.opendir(d, path);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 500, SSTR("Cannot open dir: '" << path << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
dmlite::ExtendedStat *st;
while ( (st = sql.readdirx(d)) ) {
boost::property_tree::ptree pt;
pt.put("name", st->name);
checksums::fillChecksumInXattr(*st);
xstat_to_ptree(*st, pt);
jresp2.push_back(std::make_pair("", pt));
}
jresp.push_back(std::make_pair("entries", jresp2));
return DomeReq::SendSimpleResp(request, 200, jresp);
}
/// Get id mapping
int DomeCore::dome_getidmap(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_getidmap only available on head nodes.");
}
using namespace boost::property_tree;
try {
std::string username = req.bodyfields.get<std::string>("username");
std::vector<std::string> groupnames;
boost::optional<ptree&> groups_in = req.bodyfields.get_child_optional("groupnames");
if(groups_in) {
for(ptree::const_iterator it = groups_in->begin(); it != groups_in->end(); it++) {
groupnames.push_back(it->second.get_value<std::string>());
}
}
DomeUserInfo userinfo;
std::vector<DomeGroupInfo> groupinfo;
DmStatus st = status.getIdMap(username, groupnames, userinfo, groupinfo);
if (!st.ok()) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to get id mapping: " << st.code() << " what: '" << st.what() << "'"));
}
ptree resp;
resp.put("uid", userinfo.userid);
resp.put("banned", (int) userinfo.banned);
for(std::vector<DomeGroupInfo>::iterator it = groupinfo.begin(); it != groupinfo.end(); it++) {
resp.put(boost::property_tree::ptree::path_type("groups^" + it->groupname + "^gid", '^'), it->groupid);
resp.put(boost::property_tree::ptree::path_type("groups^" + it->groupname + "^banned", '^'), (int) it->banned);
}
return DomeReq::SendSimpleResp(request, 200, resp);
}
catch(ptree_error e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Error while parsing json body: " << e.what()));
}
}
int DomeCore::dome_updatexattr(DomeReq &req, FCGX_Request &request) {
if(status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_updatexattr only available on head nodes.");
}
using namespace boost::property_tree;
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
ino_t fileid = req.bodyfields.get<ino_t>("fileid", 0);
std::string xattr = req.bodyfields.get<std::string>("xattr", "");
if (!lfn.length() && !fileid)
return DomeReq::SendSimpleResp(request, 422, "No path or fileid specified.");
dmlite::ExtendedStat e;
try {
e.deserialize(xattr);
}
catch (DmException e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid xattr content: '" <<
xattr << "' err: " << e.code() << " what: '" << e.what() << "'"));
}
dmlite::ExtendedStat xstat;
DomeMySql sql;
DmStatus ret;
if (!fileid) {
ret = sql.getStatbyLFN(xstat, lfn);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Unable to stat path '" << lfn <<
"' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
else {
ret = sql.getStatbyFileid(xstat, fileid);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Unable to stat fileid " << fileid <<
"' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// Fill the security context
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
// Need write permissions
if (checkPermissions(&ctx, xstat.acl, xstat.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403,
SSTR("Not enough permissions on fileid '" << xstat.stat.st_ino << "' path: '" << lfn << "'"));
ret = sql.updateExtendedAttributes(xstat.stat.st_ino, e);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to update xattrs on fileid " << fileid <<
"' err: " << ret.code() << " what: '" << ret.what() << "'"));
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_deleteuser(DomeReq &req, FCGX_Request &request) {
if(status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_deleteuser only available on head nodes.");
}
std::string username;
using namespace boost::property_tree;
try {
username = req.bodyfields.get<std::string>("username");
}
catch(ptree_error &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Error while parsing json body: " << e.what()));
}
try {
DomeMySql sql;
if (!sql.deleteUser(username).ok())
return DomeReq::SendSimpleResp(request, 500, SSTR("Can't delete user '" << username << "'"));
return DomeReq::SendSimpleResp(request, 200, "");
}
catch(DmException &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to update xattr: '" << e.code() << " what: '" << e.what()));
}
}
int DomeCore::dome_deletegroup(DomeReq &req, FCGX_Request &request) {
if(status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_deletegroup only available on head nodes.");
}
std::string gname;
using namespace boost::property_tree;
try {
gname = req.bodyfields.get<std::string>("groupname");
}
catch(ptree_error &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Error while parsing json body: " << e.what()));
}
try {
DomeMySql sql;
if (!sql.deleteGroup(gname).ok())
return DomeReq::SendSimpleResp(request, 500, SSTR("Can't delete user '" << gname << "'"));
return DomeReq::SendSimpleResp(request, 200, "");
}
catch(DmException &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to update xattr: '" << e.code() << " what: '" << e.what()));
}
}
/// Get information about a group
int DomeCore::dome_getgroup(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_getgroup only available on head nodes.");
}
std::string groupname = req.bodyfields.get<std::string>("groupname", "");
int gid = req.bodyfields.get<int>("groupid", 0);
if (!groupname.size() && !gid) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Groupname or gid not specified"));
}
boost::property_tree::ptree jresp;
try {
DomeMySql sql;
DmStatus st;
DomeGroupInfo grp;
// If a gid was specified then get it by gid
if (gid) {
st = sql.getGroupbyGid(grp, gid);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find group gid:" << gid));
} else {
st = sql.getGroupbyName(grp, groupname);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find group name:'" << groupname << "'"));
}
boost::property_tree::ptree pt;
pt.put("groupname", grp.groupname);
pt.put("gid", grp.groupid);
pt.put("banned", grp.banned);
pt.put("xattr", grp.xattr);
return DomeReq::SendSimpleResp(request, 200, pt);
}
catch (DmException e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to get group info: '" << groupname << "' err: " << e.code() << " what: '" << e.what()));
}
}
int DomeCore::dome_setcomment(DomeReq &req, FCGX_Request &request) {
if(status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_getcomment only available on head nodes.");
}
std::string fname, comm;
ino_t fid;
using namespace boost::property_tree;
// We allow both fileid and lfn in the parms. Fileid has precedence, if specified.
fname = req.bodyfields.get<std::string>("lfn", "");
fid = req.bodyfields.get<ino_t>("fileid", 0);
comm = req.bodyfields.get<std::string>("comment", "");
if (fname == "" && fid == 0)
return DomeReq::SendSimpleResp(request, 422, "Cannot process empty paths.");
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
try {
DomeMySql sql;
ExtendedStat st;
// Gather the stat info, precedence to the fileid
if (!fid) {
DmStatus ret = sql.getStatbyLFN(st, fname);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find lfn: '" << fname << "'"));
}
else {
DmStatus ret = sql.getStatbyFileid(st, fid);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find fileid: " << fid));
}
// Need write permissions in both origin and destination
if (checkPermissions(&ctx, st.acl, st.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403,
SSTR("Not enough permissions on fileid '" << st.stat.st_ino << "' lfn: '" << fname << "'"));
if (sql.setComment(fid = st.stat.st_ino, comm).ok()) {
boost::property_tree::ptree pt;
pt.put("comment", comm);
return DomeReq::SendSimpleResp(request, 200, pt);
}
else
return DomeReq::SendSimpleResp(request, 400, SSTR("Can't set comment for fileid: " << st.stat.st_ino));
}
catch(DmException &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to update comment: '" << e.code() << " what: '" << e.what()));
}
}
int DomeCore::dome_setmode(DomeReq &req, FCGX_Request &request) {
if(status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_setmode only available on head nodes.");
}
std::string fname;
ino_t fid;
mode_t md;
using namespace boost::property_tree;
// We allow both fileid and lfn in the parms. Fileid has precedence, if specified.
fname = req.bodyfields.get<std::string>("path", "");
fid = req.bodyfields.get<ino_t>("fileid", 0);
md = req.bodyfields.get<mode_t>("mode", 0);
if (fname == "" && fid == 0)
return DomeReq::SendSimpleResp(request, 422, "Cannot process empty path and no fileid");
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
try {
DomeMySql sql;
ExtendedStat st;
// Gather the stat info, precedence to the fileid
if (!fid) {
DmStatus ret = sql.getStatbyLFN(st, fname);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find lfn: '" << fname << "'"));
}
else {
DmStatus ret = sql.getStatbyFileid(st, fid);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find fileid: " << fid));
}
// Need write permissions
if (checkPermissions(&ctx, st.acl, st.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403,
SSTR("Not enough permissions on fileid '" << st.stat.st_ino << "' lfn: '" << fname << "'"));
if (sql.setMode(st.stat.st_ino, st.stat.st_uid, st.stat.st_gid, md, st.acl).ok()) {
return DomeReq::SendSimpleResp(request, 200, "");
}
else
return DomeReq::SendSimpleResp(request, 400, SSTR("Can't set mode for fileid: " << fid));
}
catch(DmException &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable toset mode: '" << e.code() << " what: '" << e.what()));
}
}
int DomeCore::dome_getcomment(DomeReq &req, FCGX_Request &request) {
if(status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, 500, "dome_getcomment only available on head nodes.");
}
std::string fname, comm;
ino_t fid;
using namespace boost::property_tree;
try {
// We allow both fileid and lfn in the parms. Fileid has precedence, if specified.
fname = req.bodyfields.get<std::string>("lfn", "");
fid = req.bodyfields.get<ino_t>("fileid", 0);
}
catch(ptree_error &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Error while parsing json body: " << e.what()));
}
try {
DomeMySql sql;
ExtendedStat st;
// If a fileid was not specified then get it
if (!fid) {
DmStatus ret = sql.getStatbyLFN(st, fname);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find lfn: '" << fname << "'"));
fid = st.stat.st_ino;
}
if (sql.getComment(comm, fid).ok()) {
boost::property_tree::ptree pt;
pt.put("comment", comm);
return DomeReq::SendSimpleResp(request, 200, pt);
}
else
return DomeReq::SendSimpleResp(request, 400, SSTR("Can't find comment for fileid: " << fid));
}
catch(DmException &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to update xattr: '" << e.code() << " what: '" << e.what()));
}
}
int DomeCore::dome_getgroupsvec(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_getgroupsvec only available on head nodes.");
}
boost::property_tree::ptree jresp, jresp2;
try {
DomeMySql sql;
DmStatus st;
std::vector<DomeGroupInfo> groups;
// Get all the groups and build a json array response
st = sql.getGroupsVec(groups);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 400, "Can't get groups.");
for (uint ii = 0; ii < groups.size(); ii++) {
boost::property_tree::ptree pt;
pt.put("groupname", groups[ii].groupname);
pt.put("gid", groups[ii].groupid);
pt.put("banned", groups[ii].banned);
pt.put("xattr", groups[ii].xattr);
jresp2.push_back(std::make_pair("", pt));
}
jresp.push_back(std::make_pair("groups", jresp2));
return DomeReq::SendSimpleResp(request, 200, jresp);
}
catch (DmException e) {
return DomeReq::SendSimpleResp(request, 500, SSTR("Unable to get groups. err:" <<
e.code() << " what: '" << e.what()));
}
}
int DomeCore::dome_getusersvec(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_getusersvec only available on head nodes.");
}
boost::property_tree::ptree jresp, jresp2;
try {
DomeMySql sql;
DmStatus st;
std::vector<DomeUserInfo> users;
// Get all the groups and build a json array response
st = sql.getUsersVec(users);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 500, SSTR("Cannot get users. err:" <<
st.code() << " what: '" << st.what()));
for (uint ii = 0; ii < users.size(); ii++) {
boost::property_tree::ptree pt;
pt.put("username", users[ii].username);
pt.put("userid", users[ii].userid);
pt.put("banned", users[ii].banned);
pt.put("xattr", users[ii].xattr);
jresp2.push_back(std::make_pair("", pt));
}
jresp.push_back(std::make_pair("users", jresp2));
return DomeReq::SendSimpleResp(request, 200, jresp);
}
catch (DmException e) {
return DomeReq::SendSimpleResp(request, 500, SSTR("Unable to get users. err:" <<
e.code() << " what: '" << e.what()));
}
}
int DomeCore::dome_getreplicavec(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_getreplicavec only available on head nodes.");
}
using namespace boost::property_tree;
ino_t fid;
std::string lfn;
try {
fid = req.bodyfields.get<ino_t>("fileid", 0);
lfn = req.bodyfields.get<std::string>("lfn", "");
}
catch(ptree_error &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Error while parsing json body: " << e.what()));
}
boost::property_tree::ptree jresp, jresp2;
std::vector<Replica> reps;
try {
DomeMySql sql;
DmStatus st;
ExtendedStat xst;
if (lfn.size() > 0) {
st = sql.getReplicas(reps, lfn);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 400, SSTR("Can't get replicas of lfn " << lfn <<
" err: " << st.code() << " what:" << st.what()) );
}
else {
st = sql.getReplicas(reps, fid);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 400, SSTR("Can't get replicas of fileid " << fid <<
" err: " << st.code() << " what:" << st.what()) );
}
for (uint ii = 0; ii < reps.size(); ii++) {
boost::property_tree::ptree pt;
pt.put("replicaid", reps[ii].replicaid);
pt.put("fileid", reps[ii].fileid);
pt.put("nbaccesses", reps[ii].nbaccesses);
pt.put("atime", reps[ii].atime);
pt.put("ptime", reps[ii].ptime);
pt.put("ltime", reps[ii].ltime);
pt.put("status", reps[ii].status);
pt.put("type", reps[ii].type);
pt.put("server", reps[ii].server);
pt.put("rfn", reps[ii].rfn);
pt.put("setname", reps[ii].setname);
pt.put("xattrs", reps[ii].serialize());
jresp2.push_back(std::make_pair("", pt));
}
jresp.push_back(std::make_pair("replicas", jresp2));
return DomeReq::SendSimpleResp(request, 200, jresp);
}
catch (DmException e) {
return DomeReq::SendSimpleResp(request, 500, SSTR("Unable to get replicas. err:" <<
e.code() << " what: '" << e.what()));
}
}
int DomeCore::dome_getuser(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_getuser only available on head nodes.");
}
using namespace boost::property_tree;
int uid;
std::string username;
ptree jresp;
try {
uid = req.bodyfields.get<int>("userid", -1);
username = req.bodyfields.get<std::string>("username", "");
}
catch(ptree_error &e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Error while parsing json body: " << e.what()));
}
if ( (uid < 0) && (!username.size()) )
return DomeReq::SendSimpleResp(request, 400, SSTR("It's a hard life without userid or username, dear friend."));
try {
DmStatus st;
DomeUserInfo ui;
// Get the user directly from the internal hashes
{
boost::unique_lock<boost::recursive_mutex> l(status);
if (uid >= 0) {
if (!status.getUser(uid, ui))
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find userid " << uid));
}
else if (!status.getUser(username, ui))
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find username '" << username << "'"));
}
jresp.put("username", ui.username);
jresp.put("userid", ui.userid);
jresp.put("banned", ui.banned);
jresp.put("xattr", ui.xattr);
return DomeReq::SendSimpleResp(request, 200, jresp);
}
catch (DmException e) {
return DomeReq::SendSimpleResp(request, 500, SSTR("Unable to get user. err:" <<
e.code() << " what: '" << e.what()));
}
}
int DomeCore::dome_makedir(DomeReq &req, FCGX_Request &request) {
std::string parentpath, path;
mode_t mode;
path = req.bodyfields.get<std::string>("path", "");
mode = req.bodyfields.get<mode_t>("mode", -1);
Log(Logger::Lvl4, domelogmask, domelogname, "Processing: '" << path << "' mode: " << mode);
if (mode < 0)
return DomeReq::SendSimpleResp(request, 422, SSTR("No mode specified"));
if (path.length() <= 0)
return DomeReq::SendSimpleResp(request, 422, SSTR("No path specified"));
SecurityContext ctx;
fillSecurityContext(ctx, req);
DomeMySql sql;
ExtendedStat parent;
std::string dname;
DmStatus ret = sql.getParent(parent, path, parentpath, dname);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find parent path of '" << path << "'"));
// Need to be able to write to the parent
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Need write access on '" << parentpath << "'"));
ret = sql.makedir(parent, dname, mode, ctx.user.getUnsigned("uid"), ctx.user.getUnsigned("gid"));
if (!ret.ok()) {
std::ostringstream os;
os << "Cannot create dir '" << path << "' - " << ret.code() << "-" << ret.what();
Err(domelogname, os.str());
return DomeReq::SendSimpleResp(request, http_status(ret), os);
}
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_newgroup(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_newgroup only available on head nodes.");
}
std::string grpname = req.bodyfields.get<std::string>("groupname", "");
boost::property_tree::ptree pt;
DomeMySql sql;
DmStatus st;
DomeGroupInfo g;
if ( !grpname.size() ) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Empty groupname"));
}
// Create the damn group
st = sql.newGroup(g, grpname);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 400, SSTR("Can't create group '" << grpname <<
"' err:" << st.code() << " '" << st.what()));
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_newuser(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_newuser only available on head nodes.");
}
std::string usname = req.bodyfields.get<std::string>("username", "");
boost::property_tree::ptree pt;
DomeMySql sql;
DmStatus st;
DomeUserInfo u;
if ( !usname.size() ) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Empty username"));
}
// Get all the groups and build a json array response
st = sql.newUser(u, usname);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 400, SSTR("Can't create user '" << usname <<
"' err:" << st.code() << " '" << st.what()));
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_readlink(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_readlink only available on head nodes.");
}
std::string lfn = req.bodyfields.get<std::string>("lfn", "");
DomeMySql sql;
ExtendedStat xstat;
DmStatus st = sql.getStatbyLFN(xstat, lfn);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat lfn: '" << lfn << "'"));
if (!S_ISLNK(xstat.stat.st_mode))
return DomeReq::SendSimpleResp(request, 400, SSTR("Not a symlink lfn: '" <<
lfn << "'"));
SymLink l;
st = sql.readLink(l, xstat.stat.st_ino);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 400, SSTR("Cannot get link lfn: '" << lfn <<
"' fileid: " << xstat.stat.st_ino));
boost::property_tree::ptree jresp;
jresp.put("target", l.link);
return DomeReq::SendSimpleResp(request, 200, jresp);
}
int DomeCore::dome_removedir(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_removedir only available on head nodes.");
}
std::string path = req.bodyfields.get<std::string>("path", "");
std::string parentPath, name;
DomeMySql sql;
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
// Fail inmediately with '/'
if ((path == "/") || (path == ""))
return DomeReq::SendSimpleResp(request, 422, "Can not remove '/' or empty paths.");
// Get the parent of the new folder
ExtendedStat parent;
DmStatus ret = sql.getParent(parent, path, parentPath, name);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot get parent of path: '" << path << "' err: " << ret.code() << " what: '" << ret.what() << "'") );
// Get the file starting from the parent, and check it is a directory and it is empty
ExtendedStat entry;
ret = sql.getStatbyParentFileid(entry, parent.stat.st_ino, name);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat path '" << path <<
"' err: " << ret.code() << "'" << ret.what() << "'"));
if (!S_ISDIR(entry.stat.st_mode))
return DomeReq::SendSimpleResp(request, 422, SSTR("Not a directory. Can not remove path '" << path << "'"));
if (entry.stat.st_nlink > 0)
return DomeReq::SendSimpleResp(request, 422, SSTR("Not empty. Can not remove path '" << path << "'"));
// Check we can remove it
if ((parent.stat.st_mode & S_ISVTX) == S_ISVTX) {
// Sticky bit set
if ( (ctx.user.getUnsigned("uid") != entry.stat.st_uid) &&
(ctx.user.getUnsigned("uid") != parent.stat.st_uid) &&
checkPermissions(&ctx, entry.acl, entry.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403,
SSTR("Not enough permissions to remove '" << path <<
"' (sticky bit set)") );
}
else {
// No sticky bit
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Not enough permissions to remove " << path));
}
ret = sql.unlink(entry.stat.st_ino);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 500, SSTR("Unable to remove path '" << path <<
"' err: " << ret.code() << "'" << ret.what() << "'"));
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_rename(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_rename only available on head nodes.");
}
std::string oldPath = req.bodyfields.get<std::string>("oldpath", "");
std::string newPath = req.bodyfields.get<std::string>("newpath", "");
std::string oldParentPath, newParentPath;
std::string oldName, newName;
ExtendedStat newF;
// Do not even bother with '/'
if (oldPath == "/" || oldPath == ""|| newPath == "/" || newPath == "")
return DomeReq::SendSimpleResp(request, 422, "Cannot process empty paths or '/'");
DomeMySql sql;
// Get source and destination parent
ExtendedStat oldParent, newParent;
DmStatus ret = sql.getParent(oldParent, oldPath, oldParentPath, oldName);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Can't find parent path of '" << oldPath << "'"));
ret = sql.getParent(newParent, newPath, newParentPath, newName);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Can't find parent path of '" << newPath << "'"));
// Stat source
ExtendedStat old;
ret = sql.getStatbyParentFileid(old, oldParent.stat.st_ino, oldName);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot stat path '" << oldPath <<
"' err: " << ret.code() << "'" << ret.what() << "'"));
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
// Need write permissions in both origin and destination
if (checkPermissions(&ctx, oldParent.acl, oldParent.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403,
SSTR("Not enough permissions on origin path '" << oldParentPath << "'"));
if (checkPermissions(&ctx, newParent.acl, newParent.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403,
SSTR("Not enough permissions on destination path '" << newParentPath << "'"));
// If source is a directory, need write permissions there too
if (S_ISDIR(old.stat.st_mode)) {
if (checkPermissions(&ctx, old.acl, old.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403,
SSTR("Not enough permissions on path '" << oldPath << "'"));
// AND destination can not be a child
ExtendedStat aux = newParent;
while (aux.parent > 0) {
if (aux.stat.st_ino == old.stat.st_ino)
return DomeReq::SendSimpleResp(request, 422, "Destination is descendant of source");
ret = sql.getStatbyFileid(aux, aux.parent);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot stat fileid '" << aux.parent <<
"' err: " << ret.code() << "'" << ret.what() << "'"));
}
}
// Check sticky
if (oldParent.stat.st_mode & S_ISVTX &&
ctx.user.getUnsigned("uid") != oldParent.stat.st_uid &&
ctx.user.getUnsigned("uid") != old.stat.st_uid &&
checkPermissions(&ctx, old.acl, old.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403,
"Sticky bit set on the parent, and not enough permissions");
// If the destination exists...
ret = sql.getStatbyParentFileid(newF, newParent.stat.st_ino, newName);
if ( (!ret.ok()) && (ret.code() != ENOENT) )
return DomeReq::SendSimpleResp(request, 500, SSTR("Cannot stat destination path '" << oldPath <<
"' err: " << ret.code() << "'" << ret.what() << "'"));
if (ret.ok()) { // The file was found
// If it is the same, leave the function
if (newF.stat.st_ino == old.stat.st_ino)
return DomeReq::SendSimpleResp(request, 200,
"Source is the same as destination, that's funny.");
// It does! It has to be the same type
if ((newF.stat.st_mode & S_IFMT) != (old.stat.st_mode & S_IFMT)) {
if (S_ISDIR(old.stat.st_mode))
return DomeReq::SendSimpleResp(request, 422,
"Source is a directory and destination is not.");
else
return DomeReq::SendSimpleResp(request, 422,
"Source is not directory and destination is.");
}
// And it has to be empty. Just call remove or unlink
// and they will fail if it is not
if (S_ISDIR(newF.stat.st_mode)) {
if (newF.stat.st_nlink > 0)
return DomeReq::SendSimpleResp(request, 422,
SSTR("The destination directory '" << newPath << "' is not empty"));
}
else {
// Check there are no replicas
if (!S_ISLNK(newF.stat.st_mode)) {
std::vector<Replica> reps;
ret = sql.getReplicas(reps, newF.stat.st_ino);
if (reps.size() > 0)
return DomeReq::SendSimpleResp(request, 422,
SSTR("The destination file '" << newPath << "' exists and has replicas."));
}
// It's safe to remove it
sql.unlink(newF.stat.st_ino);
}
}
// We are good, so we can move now
{
DomeMySqlTrans t(&sql);
// Change the name if needed
if (newName != oldName) {
ret = sql.rename(old.stat.st_ino, newName);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot rename path '" << oldPath <<
"' err: " << ret.code() << "'" << ret.what() << "'"));
}
DOMECACHE->removeInfo(old.stat.st_ino, old.parent, oldName);
DOMECACHE->removeInfo(old.stat.st_ino, old.parent, newName);
// Change the parent if needed
if (newParent.stat.st_ino != oldParent.stat.st_ino) {
ret = sql.move(old.stat.st_ino, newParent.stat.st_ino);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot move path '" << oldPath <<
"' err: " << ret.code() << "'" << ret.what() << "'"));
DOMECACHE->removeInfo(old.stat.st_ino, newParent.stat.st_ino, oldName);
DOMECACHE->removeInfo(old.stat.st_ino, newParent.stat.st_ino, newName);
}
else {
// Parent is the same, but change its mtime
struct utimbuf utim;
utim.actime = time(NULL);
utim.modtime = utim.actime;
sql.utime(oldParent.stat.st_ino, &utim);
}
t.Commit();
}
// Done!
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_setacl(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_setacl only available on head nodes.");
}
std::string path = req.bodyfields.get<std::string>("path", "");
std::string sacl = req.bodyfields.get<std::string>("acl", "");
// Fail inmediately with ''
if (path == "")
return DomeReq::SendSimpleResp(request, 422, "Empty lfn.");
if (sacl == "")
return DomeReq::SendSimpleResp(request, 422, "Empty acl.");
Acl acl;
try {
Acl acl1(sacl);
acl = acl1;
} catch( ... ) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Incorrect acl: '" << sacl << "'"));
}
DomeMySql sql;
ExtendedStat meta;
DmStatus st = sql.getStatbyLFN(meta, path);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat path: '" << path << "'"));
SecurityContext ctx;
fillSecurityContext(ctx, req);
// Check we can change it
if (ctx.user.getUnsigned("uid") != meta.stat.st_uid &&
ctx.user.getUnsigned("uid") != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Only the owner or root can set the ACL of '" << path << "'"));
Acl aclCopy(acl);
// Make sure the owner and group matches!
for (size_t i = 0; i < aclCopy.size(); ++i) {
if (aclCopy[i].type == AclEntry::kUserObj)
aclCopy[i].id = meta.stat.st_uid;
else if (aclCopy[i].type == AclEntry::kGroupObj)
aclCopy[i].id = meta.stat.st_gid;
else if (aclCopy[i].type & AclEntry::kDefault && !S_ISDIR(meta.stat.st_mode))
return DomeReq::SendSimpleResp(request, 422, "Defaults can be only applied to directories");
}
// Validate the ACL
try {
aclCopy.validate();
} catch( DmException e ) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot validate acl: '" << sacl << "' err:" <<
e.code() << ":" << e.what()));
}
// Update the file mode
for (size_t i = 0; i < aclCopy.size(); ++i) {
switch (aclCopy[i].type) {
case AclEntry::kUserObj:
meta.stat.st_mode = (meta.stat.st_mode & 0177077) |
(aclCopy[i].perm << 6);
break;
case AclEntry::kGroupObj:
meta.stat.st_mode = (meta.stat.st_mode & 0177707) |
(aclCopy[i].perm << 3);
break;
case AclEntry::kMask:
meta.stat.st_mode = (meta.stat.st_mode & ~070) |
(meta.stat.st_mode & aclCopy[i].perm << 3);
break;
case AclEntry::kOther:
meta.stat.st_mode = (meta.stat.st_mode & 0177770) |
(aclCopy[i].perm);
break;
default:
continue;
}
}
// Update the file
st = sql.setMode(meta.stat.st_ino,
meta.stat.st_uid, meta.stat.st_gid,
meta.stat.st_mode,
aclCopy);
if (!st.ok())
return DomeReq::SendSimpleResp(request, 400, SSTR("Can't set acl '" << sacl << "' to lfn: '" << path <<
"' err:" << st.code() << " '" << st.what()));
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_setowner(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_rename only available on head nodes.");
}
uid_t newUid;
gid_t newGid;
std::string path = req.bodyfields.get<std::string>("path", "");
try {
newUid = req.bodyfields.get<uid_t>("uid");
newGid = req.bodyfields.get<gid_t>("gid");
}
catch ( ... ) {
return DomeReq::SendSimpleResp(request, 422, "Can't find uid or gid or path.");
}
bool followSymLink = DomeUtils::str_to_bool(req.bodyfields.get<std::string>("follow", "false"));
if(path == "") {
return DomeReq::SendSimpleResp(request, 422, "Path cannot be empty.");
}
// Check that uid and gid are known
DomeUserInfo ui;
DomeGroupInfo gi;
if (!status.getUser(newUid, ui))
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid uid: " << newUid));
if (!status.getGroup(newGid, gi))
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid gid: " << newGid));
DomeMySql sql;
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
ExtendedStat meta;
DmStatus ret = sql.getStatbyLFN(meta, path, followSymLink);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find lfn: '" << path << "'"));
// If -1, no changes
if (newUid == (uid_t)-1)
newUid = meta.stat.st_uid;
if (newGid == (gid_t)-1)
newGid = meta.stat.st_gid;
// Make sense to do anything?
if (newUid == meta.stat.st_uid && newGid == meta.stat.st_gid)
return DomeReq::SendSimpleResp(request, 200, "");
// If root, skip all checks
if (ctx.user.getUnsigned("uid") != 0) {
// Only root can change the owner
if (meta.stat.st_uid != newUid)
return DomeReq::SendSimpleResp(request, 403, "Only root can set the owner");
// If the group is changing...
if (meta.stat.st_gid != newGid) {
// The user has to be the owner
if (meta.stat.st_uid != ctx.user.getUnsigned("uid"))
return DomeReq::SendSimpleResp(request, 403, "Only root can set the group");
// AND it has to belong to that group
if (!hasGroup(ctx.groups, newGid))
return DomeReq::SendSimpleResp(request, 403,
SSTR("The user does not belong to the group " << newGid <<
" '" << gi.groupname << "'"));
// If it does, the group exists :)
}
}
// Update the ACL's if there is any
if (!meta.acl.empty()) {
for (size_t i = 0; i < meta.acl.size(); ++i) {
if (meta.acl[i].type == AclEntry::kUserObj)
meta.acl[i].id = newUid;
else if (meta.acl[i].type == AclEntry::kGroupObj)
meta.acl[i].id = newGid;
}
}
// Change!
sql.setMode(meta.stat.st_ino,
newUid, newGid, meta.stat.st_mode,
meta.acl);
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_setsize(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_rename only available on head nodes.");
}
std::string path = req.bodyfields.get<std::string>("path", "");
if(path == "") {
return DomeReq::SendSimpleResp(request, 422, "Path cannot be empty.");
}
int64_t newSize = req.bodyfields.get<int64_t>("size", -1);
if (newSize < 0)
return DomeReq::SendSimpleResp(request, 422, "Wrong or missing filesize");
DomeMySql sql;
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
ExtendedStat meta;
DmStatus ret = sql.getStatbyLFN(meta, path);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Can't find lfn: '" << path << "'"));
if (ctx.user.getUnsigned("uid") != meta.stat.st_uid &&
checkPermissions(&ctx, meta.acl, meta.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Can not set the size of '" << path << "'"));
DmStatus dmst = sql.setSize(meta.stat.st_ino, newSize);
if (dmst.ok())
return DomeReq::SendSimpleResp(request, 200, "");
return DomeReq::SendSimpleResp(request, 422, SSTR("Can not set the size of '" << path << "' err:" <<
dmst.code() << ":" << dmst.what()));
}
int DomeCore::dome_symlink(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_rename only available on head nodes.");
}
std::string oldPath = req.bodyfields.get<std::string>("target", "");
std::string newPath = req.bodyfields.get<std::string>("link", "");
std::string parentPath, symName;
// Fail inmediately with ''
if (oldPath == "")
return DomeReq::SendSimpleResp(request, 422, "Empty link target.");
if (newPath == "")
return DomeReq::SendSimpleResp(request, 422, "Empty link name.");
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
// Get the parent of the destination and file
ExtendedStat parent;
DomeMySql sql;
DmStatus ret = sql.getParent(parent, newPath, parentPath, symName);
if (!ret.ok()) return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot get parent of '" <<
newPath << "' : " << ret.code() << "-" << ret.what()));
// Check we have write access for the parent
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IWRITE | S_IEXEC) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Not enough permissions on '" << parentPath << "'"));
// Effective gid
gid_t egid;
mode_t mode = 0777;
if (parent.stat.st_mode & S_ISGID) {
egid = parent.stat.st_gid;
mode |= S_ISGID;
}
else {
egid = ctx.groups[0].getUnsigned("gid");;
}
{
DomeMySqlTrans t(&sql);
// Create file
ExtendedStat newLink;
newLink.parent = parent.stat.st_ino;
newLink.name = symName;
newLink.stat.st_mode = mode | S_IFLNK;
newLink.stat.st_size = 0;
newLink.status = ExtendedStat::kOnline;
newLink.stat.st_uid = ctx.groups[0].getUnsigned("uid");
newLink.stat.st_gid = egid;
ret = sql.create(newLink);
if (!ret.ok()) return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot create link '" <<
newPath << "' : " << ret.code() << "-" << ret.what()));
// Create symlink
ret = sql.symlink(newLink.stat.st_ino, oldPath);
if (!ret.ok()) return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot symlink to '" <<
oldPath << "' : " << ret.code() << "-" << ret.what()));
t.Commit();
}
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_unlink(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_unlink only available on head nodes.");
}
const std::string path = req.bodyfields.get<std::string>("lfn", "");
if (path == "")
return DomeReq::SendSimpleResp(request, 422, "Empty lfn.");
std::string parentPath, name;
dmlite::SecurityContext ctx;
fillSecurityContext(ctx, req);
// Get the parent of the destination and file
ExtendedStat parent;
DomeMySql sql;
DmStatus ret = sql.getParent(parent, path, parentPath, name);
if (!ret.ok()) return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot get parent of '" <<
path << "' : " << ret.code() << "-" << ret.what()));
// Check we have write access for the parent
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IEXEC) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Not enough permissions to list on '" << parentPath << "'"));
ExtendedStat file;
ret = sql.getStatbyParentFileid(file, parent.stat.st_ino, name);
if (!ret.ok()) return DomeReq::SendSimpleResp(request, 404, SSTR("Cannot stat '" <<
path << "' : " << ret.code() << "-" << ret.what()));
// Directories can not be removed with this method!
if (S_ISDIR(file.stat.st_mode))
return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot unlink a directory '" << path << "'"));
// Check we can remove it
if ((parent.stat.st_mode & S_ISVTX) == S_ISVTX) {
// Sticky bit set
if (ctx.user.getUnsigned("uid") != file.stat.st_uid &&
ctx.user.getUnsigned("uid") != parent.stat.st_uid &&
checkPermissions(&ctx, file.acl, file.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR(
"Not enough permissions (sticky bit set) to unlink '" << path <<
"'"));
}
else {
// No sticky bit
if (checkPermissions(&ctx, parent.acl, parent.stat, S_IWRITE) != 0)
return DomeReq::SendSimpleResp(request, 403, SSTR("Not enough permissions to unlink '" <<
path << "'"));
}
// Check there are no replicas
if (!S_ISLNK(file.stat.st_mode)) {
std::vector<Replica> replicas;
ret = sql.getReplicas(replicas, file.stat.st_ino);
if (!ret.ok()) return DomeReq::SendSimpleResp(request, 422, SSTR("Cannot get replicas of '" << path << "' : " << ret.code() << "-" << ret.what()));
// Try to remove replicas first
for (unsigned i = 0; i < replicas.size(); ++i) {
// Abort+error if the replica belongs to an unknown filesystem
DomeFsInfo fsinfo;
std::string pfn = DomeUtils::pfn_from_rfio_syntax(replicas[i].rfn);
std::string server = DomeUtils::server_from_rfio_syntax(replicas[i].rfn);
if (!pfn.length() || !server.length()) {
return DomeReq::SendSimpleResp(request, 500, SSTR("Incorrect replica rfn '" << replicas[i].rfn << "'"));
}
if (!status.PfnMatchesAnyFS(server, pfn, fsinfo)) {
return DomeReq::SendSimpleResp(request, 500, SSTR("No filesystem matches replica '" << replicas[i].rfn << "'"));
}
// Abort+error if the replica belongs to a broken/disabled filesystem
if (fsinfo.activitystatus == DomeFsInfo::FsBroken) {
return DomeReq::SendSimpleResp(request, 500, SSTR("A disabled or broken filesystem is matching replica '" << replicas[i].rfn << "'"));
}
// Now delete the physical file
std::string diskurl = "https://" + server + "/domedisk/";
Log(Logger::Lvl4, domelogmask, domelogname, "Dispatching deletion of replica '" << replicas[i].rfn << "' to disk node: '" << diskurl);
DomeTalker talker(*davixPool, req.creds, diskurl,
"POST", "dome_pfnrm");
if(!talker.execute("pfn", pfn)) {
Err(domelogname, talker.err());
return DomeReq::SendSimpleResp(request, 500, SSTR("Unable to delete physical replica '" << replicas[i].rfn << "' err:" << talker.err()));
}
if(!sql.addFilesizeToDirs(file, -file.stat.st_size).ok()) {
Err(domelogname, SSTR("Unable to decrease filesize from parent directories of fileid: " << file.stat.st_ino ));
}
}
}
ret = sql.unlink(file.stat.st_ino);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 500, SSTR("Cannot unlink fileid " << file.stat.st_ino << " of '" << path <<
"' : " << ret.code() << "-" << ret.what()));
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_updategroup(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_updategroup only available on head nodes.");
}
std::string groupname = req.bodyfields.get<std::string>("groupname", "");
int gid = req.bodyfields.get<int>("groupid", 0);
if((groupname == "") && !gid) {
return DomeReq::SendSimpleResp(request, 422, "No group specified.");
}
std::string xattr = req.bodyfields.get<std::string>("xattr", "");
// Validate the xattr string, to avoid inserting junk into the db
dmlite::Extensible e;
try {
e.deserialize(xattr);
}
catch (DmException e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid xattr content: '" <<
xattr << "' err: " << e.code() << " what: '" << e.what() << "'"));
}
int banned = req.bodyfields.get<int>("banned", 0);
DomeGroupInfo group;
DomeMySql sql;
DmStatus ret;
if (gid) {
ret = sql.getGroupbyGid(group, gid);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to get gid '" << gid <<
"' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
else {
ret = sql.getGroupbyName(group, groupname);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to get group '" << groupname <<
"' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
group.xattr = xattr;
group.banned = (DomeGroupInfo::BannedStatus)banned;
ret = sql.updateGroup(group);
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_updatereplica(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_updatereplica only available on head nodes.");
}
// Get all the parameters
Replica r;
r.rfn = req.bodyfields.get<std::string>("rfn", "");
r.replicaid = req.bodyfields.get<int64_t>("replicaid", 0);
r.status = static_cast<dmlite::Replica::ReplicaStatus>(
req.bodyfields.get<char>("status", (char)dmlite::Replica::kAvailable) );
r.type = static_cast<dmlite::Replica::ReplicaType>(
req.bodyfields.get<char>("type", (char)dmlite::Replica::kPermanent) );
r.setname = req.bodyfields.get<std::string>("setname", "");
r.deserialize(req.bodyfields.get<std::string>("xattr", ""));
DomeMySql sql;
SecurityContext ctx;
fillSecurityContext(ctx, req);
// Can not trust the fileid of replica!
Replica rdata;
ExtendedStat meta;
DmStatus ret;
if (r.replicaid) {
ret = sql.getReplicabyId(rdata, r.replicaid);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Unable to get replicaid " << r.replicaid <<
" err: " << ret.code() << " what: '" << ret.what() << "'"));
}
else {
ret = sql.getReplicabyRFN(rdata, r.rfn);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Unable to get replica '" << r.rfn <<
"' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
ret = sql.getStatbyFileid(meta, rdata.fileid);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 404, SSTR("Unable to get fileid " << rdata.fileid <<
" from replicaid " << r.replicaid <<
" err: " << ret.code() << " what: '" << ret.what() << "'"));
ret = sql.traverseBackwards(ctx, meta);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Permission denied on fileid " << rdata.fileid
<< " of rfn: '" << r.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
if (checkPermissions(&ctx, meta.acl, meta.stat, S_IWRITE) != 0)
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 403, SSTR("Cannot modify fileid " << rdata.fileid
<< " of rfn: '" << r.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// Note, we can't modify the ids
r.fileid = rdata.fileid;
r.replicaid = rdata.replicaid;
ret = sql.updateReplica(r);
if (!ret.ok()) {
return DomeReq::SendSimpleResp(request, 500, SSTR("Cannot modify replica " << rdata.fileid
<< " of rfn: '" << r.rfn << "' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
return DomeReq::SendSimpleResp(request, 200, "");
}
int DomeCore::dome_updateuser(DomeReq &req, FCGX_Request &request) {
if (status.role != status.roleHead) {
return DomeReq::SendSimpleResp(request, DOME_HTTP_BAD_REQUEST, "dome_updateuser only available on head nodes.");
}
std::string username = req.bodyfields.get<std::string>("username", "");
int uid = req.bodyfields.get<int>("uid", 0);
if((username == "") && !uid) {
return DomeReq::SendSimpleResp(request, 422, "No user specified.");
}
std::string xattr = req.bodyfields.get<std::string>("xattr", "");
int banned = req.bodyfields.get<int>("banned", 0);
DomeUserInfo user;
DomeMySql sql;
DmStatus ret;
if (uid) {
ret = sql.getUser(user, uid);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to get uid '" << uid <<
"' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
else {
ret = sql.getUser(user, username);
if (!ret.ok())
return DomeReq::SendSimpleResp(request, 422, SSTR("Unable to get user '" << username <<
"' err: " << ret.code() << " what: '" << ret.what() << "'"));
}
// Validate the xattr string, to avoid inserting junk into the db
dmlite::Extensible e;
try {
e.deserialize(xattr);
}
catch (DmException e) {
return DomeReq::SendSimpleResp(request, 422, SSTR("Invalid xattr content: '" <<
xattr << "' err: " << e.code() << " what: '" << e.what() << "'"));
}
user.xattr = xattr;
user.banned = (DomeUserInfo::BannedStatus)banned;
ret = sql.updateUser(user);
return DomeReq::SendSimpleResp(request, 200, "");
}
| 34.708507 | 221 | 0.625923 | [
"object",
"vector"
] |
df80c4014513756c499524a3cb176f8a9839b52e | 1,773 | hh | C++ | graph/display.hh | CN-TU/remy | 0c0887322b0cbf6e3497e3aeb95c979907f03623 | [
"Apache-2.0"
] | 6 | 2020-03-19T04:16:02.000Z | 2022-03-30T15:41:39.000Z | graph/display.hh | CN-TU/remy | 0c0887322b0cbf6e3497e3aeb95c979907f03623 | [
"Apache-2.0"
] | 1 | 2020-05-20T12:05:49.000Z | 2021-11-14T13:39:23.000Z | graph/display.hh | CN-TU/remy | 0c0887322b0cbf6e3497e3aeb95c979907f03623 | [
"Apache-2.0"
] | null | null | null | #ifndef DISPLAY_HH
#define DISPLAY_HH
#include <deque>
#include <string>
#include "gl_objects.hh"
class Display
{
static const std::string shader_source_scale_from_pixel_coordinates;
static const std::string shader_source_passthrough_texture;
static const std::string shader_source_solid_color;
struct CurrentContextWindow
{
GLFWContext glfw_context_ = {};
Window window_;
CurrentContextWindow( const unsigned int width, const unsigned int height,
const std::string & title );
} current_context_window_;
VertexShader scale_from_pixel_coordinates_ = { shader_source_scale_from_pixel_coordinates };
FragmentShader passthrough_texture_ = { shader_source_passthrough_texture };
FragmentShader solid_color_ = { shader_source_solid_color };
Program texture_shader_program_ = {};
Program solid_color_shader_program_ = {};
Texture texture_;
VertexArrayObject texture_shader_array_object_ = {};
VertexArrayObject solid_color_array_object_ = {};
VertexBufferObject screen_corners_ = {};
VertexBufferObject other_vertices_ = {};
public:
Display( const unsigned int width, const unsigned int height,
const std::string & title );
void draw( const Image & image );
void draw( const float red, const float green, const float blue, const float alpha,
const float width,
const float cutoff,
const std::deque<std::pair<float, float>> & vertices,
const std::function<std::pair<float, float>(const std::pair<float, float> &)> & transform );
void clear( void );
void repaint( void );
void swap( void );
const Window & window( void ) const { return current_context_window_.window_; }
void resize( const std::pair<unsigned int, unsigned int> & target_size );
};
#endif /* DISPLAY_HH */
| 29.065574 | 98 | 0.742809 | [
"transform"
] |
df822ac0b9212a3deb13187754dfc75f47a34230 | 10,338 | cpp | C++ | esphome/components/esp32_ble_server/ble_characteristic.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 249 | 2018-04-07T12:04:11.000Z | 2019-01-25T01:11:34.000Z | esphome/components/esp32_ble_server/ble_characteristic.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 243 | 2018-04-11T16:37:11.000Z | 2019-01-25T16:50:37.000Z | esphome/components/esp32_ble_server/ble_characteristic.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 40 | 2018-04-10T05:50:14.000Z | 2019-01-25T15:20:36.000Z | #include "ble_characteristic.h"
#include "ble_server.h"
#include "ble_service.h"
#include "esphome/core/log.h"
#ifdef USE_ESP32
namespace esphome {
namespace esp32_ble_server {
static const char *const TAG = "esp32_ble_server.characteristic";
BLECharacteristic::BLECharacteristic(const ESPBTUUID uuid, uint32_t properties) : uuid_(uuid) {
this->set_value_lock_ = xSemaphoreCreateBinary();
xSemaphoreGive(this->set_value_lock_);
this->properties_ = (esp_gatt_char_prop_t) 0;
this->set_broadcast_property((properties & PROPERTY_BROADCAST) != 0);
this->set_indicate_property((properties & PROPERTY_INDICATE) != 0);
this->set_notify_property((properties & PROPERTY_NOTIFY) != 0);
this->set_read_property((properties & PROPERTY_READ) != 0);
this->set_write_property((properties & PROPERTY_WRITE) != 0);
this->set_write_no_response_property((properties & PROPERTY_WRITE_NR) != 0);
}
void BLECharacteristic::set_value(std::vector<uint8_t> value) {
xSemaphoreTake(this->set_value_lock_, 0L);
this->value_ = std::move(value);
xSemaphoreGive(this->set_value_lock_);
}
void BLECharacteristic::set_value(const std::string &value) {
this->set_value(std::vector<uint8_t>(value.begin(), value.end()));
}
void BLECharacteristic::set_value(const uint8_t *data, size_t length) {
this->set_value(std::vector<uint8_t>(data, data + length));
}
void BLECharacteristic::set_value(uint8_t &data) {
uint8_t temp[1];
temp[0] = data;
this->set_value(temp, 1);
}
void BLECharacteristic::set_value(uint16_t &data) {
uint8_t temp[2];
temp[0] = data;
temp[1] = data >> 8;
this->set_value(temp, 2);
}
void BLECharacteristic::set_value(uint32_t &data) {
uint8_t temp[4];
temp[0] = data;
temp[1] = data >> 8;
temp[2] = data >> 16;
temp[3] = data >> 24;
this->set_value(temp, 4);
}
void BLECharacteristic::set_value(int &data) {
uint8_t temp[4];
temp[0] = data;
temp[1] = data >> 8;
temp[2] = data >> 16;
temp[3] = data >> 24;
this->set_value(temp, 4);
}
void BLECharacteristic::set_value(float &data) {
float temp = data;
this->set_value((uint8_t *) &temp, 4);
}
void BLECharacteristic::set_value(double &data) {
double temp = data;
this->set_value((uint8_t *) &temp, 8);
}
void BLECharacteristic::set_value(bool &data) {
uint8_t temp[1];
temp[0] = data;
this->set_value(temp, 1);
}
void BLECharacteristic::notify(bool notification) {
if (!notification) {
ESP_LOGW(TAG, "notification=false is not yet supported");
// TODO: Handle when notification=false
}
if (this->service_->get_server()->get_connected_client_count() == 0)
return;
for (auto &client : this->service_->get_server()->get_clients()) {
size_t length = this->value_.size();
esp_err_t err = esp_ble_gatts_send_indicate(this->service_->get_server()->get_gatts_if(), client.first,
this->handle_, length, this->value_.data(), false);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_send_indicate failed %d", err);
return;
}
}
}
void BLECharacteristic::add_descriptor(BLEDescriptor *descriptor) { this->descriptors_.push_back(descriptor); }
void BLECharacteristic::do_create(BLEService *service) {
this->service_ = service;
esp_attr_control_t control;
control.auto_rsp = ESP_GATT_RSP_BY_APP;
ESP_LOGV(TAG, "Creating characteristic - %s", this->uuid_.to_string().c_str());
esp_bt_uuid_t uuid = this->uuid_.get_uuid();
esp_err_t err = esp_ble_gatts_add_char(service->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
this->properties_, nullptr, &control);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_add_char failed: %d", err);
return;
}
this->state_ = CREATING;
}
bool BLECharacteristic::is_created() {
if (this->state_ == CREATED)
return true;
if (this->state_ != CREATING_DEPENDENTS)
return false;
bool created = true;
for (auto *descriptor : this->descriptors_) {
created &= descriptor->is_created();
}
if (created)
this->state_ = CREATED;
return this->state_ == CREATED;
}
bool BLECharacteristic::is_failed() {
if (this->state_ == FAILED)
return true;
bool failed = false;
for (auto *descriptor : this->descriptors_) {
failed |= descriptor->is_failed();
}
if (failed)
this->state_ = FAILED;
return this->state_ == FAILED;
}
void BLECharacteristic::set_broadcast_property(bool value) {
if (value) {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_BROADCAST);
} else {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_BROADCAST);
}
}
void BLECharacteristic::set_indicate_property(bool value) {
if (value) {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_INDICATE);
} else {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_INDICATE);
}
}
void BLECharacteristic::set_notify_property(bool value) {
if (value) {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_NOTIFY);
} else {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_NOTIFY);
}
}
void BLECharacteristic::set_read_property(bool value) {
if (value) {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_READ);
} else {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_READ);
}
}
void BLECharacteristic::set_write_property(bool value) {
if (value) {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_WRITE);
} else {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_WRITE);
}
}
void BLECharacteristic::set_write_no_response_property(bool value) {
if (value) {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_WRITE_NR);
} else {
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_WRITE_NR);
}
}
void BLECharacteristic::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
esp_ble_gatts_cb_param_t *param) {
switch (event) {
case ESP_GATTS_ADD_CHAR_EVT: {
if (this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
this->handle_ = param->add_char.attr_handle;
for (auto *descriptor : this->descriptors_) {
descriptor->do_create(this);
}
this->state_ = CREATING_DEPENDENTS;
}
break;
}
case ESP_GATTS_READ_EVT: {
if (param->read.handle != this->handle_)
break; // Not this characteristic
if (!param->read.need_rsp)
break; // For some reason you can request a read but not want a response
uint16_t max_offset = 22;
esp_gatt_rsp_t response;
if (param->read.is_long) {
if (this->value_.size() - this->value_read_offset_ < max_offset) {
// Last message in the chain
response.attr_value.len = this->value_.size() - this->value_read_offset_;
response.attr_value.offset = this->value_read_offset_;
memcpy(response.attr_value.value, this->value_.data() + response.attr_value.offset, response.attr_value.len);
this->value_read_offset_ = 0;
} else {
response.attr_value.len = max_offset;
response.attr_value.offset = this->value_read_offset_;
memcpy(response.attr_value.value, this->value_.data() + response.attr_value.offset, response.attr_value.len);
this->value_read_offset_ += max_offset;
}
} else {
response.attr_value.offset = 0;
if (this->value_.size() + 1 > max_offset) {
response.attr_value.len = max_offset;
this->value_read_offset_ = max_offset;
} else {
response.attr_value.len = this->value_.size();
}
memcpy(response.attr_value.value, this->value_.data(), response.attr_value.len);
}
response.attr_value.handle = this->handle_;
response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
esp_err_t err =
esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &response);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
}
break;
}
case ESP_GATTS_WRITE_EVT: {
if (this->handle_ != param->write.handle)
return;
if (param->write.is_prep) {
this->value_.insert(this->value_.end(), param->write.value, param->write.value + param->write.len);
this->write_event_ = true;
} else {
this->set_value(param->write.value, param->write.len);
}
if (param->write.need_rsp) {
esp_gatt_rsp_t response;
response.attr_value.len = param->write.len;
response.attr_value.handle = this->handle_;
response.attr_value.offset = param->write.offset;
response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
memcpy(response.attr_value.value, param->write.value, param->write.len);
esp_err_t err =
esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, &response);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
}
}
if (!param->write.is_prep) {
this->on_write_(this->value_);
}
break;
}
case ESP_GATTS_EXEC_WRITE_EVT: {
if (!this->write_event_)
break;
this->write_event_ = false;
if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) {
this->on_write_(this->value_);
}
esp_err_t err =
esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, nullptr);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
}
break;
}
default:
break;
}
for (auto *descriptor : this->descriptors_) {
descriptor->gatts_event_handler(event, gatts_if, param);
}
}
} // namespace esp32_ble_server
} // namespace esphome
#endif
| 33.028754 | 120 | 0.674018 | [
"vector"
] |
df9effe51436ede7f9b578c328e4a31fa3ec5464 | 6,113 | cpp | C++ | src/building.cpp | acdzh/elevator_simulation | 3521c89a111e8e72c6eb1821eb7911394e81341a | [
"WTFPL"
] | 10 | 2019-11-07T11:06:56.000Z | 2020-07-03T17:27:45.000Z | src/building.cpp | acdzh/elevator_simulation | 3521c89a111e8e72c6eb1821eb7911394e81341a | [
"WTFPL"
] | null | null | null | src/building.cpp | acdzh/elevator_simulation | 3521c89a111e8e72c6eb1821eb7911394e81341a | [
"WTFPL"
] | 3 | 2021-05-17T12:26:42.000Z | 2021-06-17T11:41:22.000Z | #include "building.h"
#include "ui_building.h"
building::building(QWidget *parent, std::vector<elevator*> _eles, int _FLOOR_NUM, int _ELE_SELECT_MODE) : QWidget(parent), ui(new Ui::building){
ui->setupUi(this);
eles = _eles;
FLOOR_NUM = _FLOOR_NUM;
ELE_NUM = int(eles.size());
ELE_SELECT_MODE = _ELE_SELECT_MODE;
srand(unsigned (time(nullptr)) );
this->setWindowTitle("控制台 / 当前外部调度算法: " + QString::number(ELE_SELECT_MODE, 10));
//draw elevators
for(int i = 0; i < ELE_NUM; i++){
QLabel *eleNo = new QLabel(ui->groupBox_eles);
eleNo->setGeometry(20 + 40 * i, 30, 20, 20);
eleNo->setAlignment(Qt::AlignHCenter);
eleNo->setText(QString::number(i + 1, 10));
eleNo->show();
QSlider *eleSlider = new QSlider(ui->groupBox_eles);
eleSlider->setGeometry(20 + 40 * i, 50, 20, 220);
eleSlider->setMinimum(1);
eleSlider->setMaximum(FLOOR_NUM);
eleSlider->setSingleStep(1);
eleSlider->setPageStep(1);
eleSlider->show();
eleSliders.push_back(eleSlider);
QLabel *eleCurrent = new QLabel(ui->groupBox_eles);
eleCurrent->setGeometry(20 + 40 * i, 270, 20, 20);
eleCurrent->setAlignment(Qt::AlignHCenter);
eleCurrent->setText("1");
eleCurrent->show();
eleCurrents.push_back(eleCurrent);
}
//draw btns
for(int i = 0; i < FLOOR_NUM; i++){
QLabel *floorNo = new QLabel(ui->groupBox_btns);
floorNo->setGeometry(20 + 40 * (i % 10), 30 + 120 * (i / 10), 30, 30);
floorNo->setAlignment(Qt::AlignHCenter);
floorNo->setText(QString::number(i + 1, 10));
floorNo->show();
QPushButton *floorBtnUp = new QPushButton(ui->groupBox_btns);
floorBtnUp->setGeometry(20 + 40 * (i % 10), 60 + 120 * (i / 10), 30, 30);
floorBtnUp->setText("↑");
floorBtnUp->show();
floorBtnsUp.push_back(floorBtnUp);
connect(floorBtnsUp[unsigned(i)], &QPushButton::clicked, this, [=]{floorBtnsUp[unsigned(i)]->setEnabled(false);});
connect(floorBtnsUp[unsigned(i)], &QPushButton::clicked, this, [=]{ele_select_send(true, i);});
QPushButton *floorBtnDown = new QPushButton(ui->groupBox_btns);
floorBtnDown->setGeometry(20 + 40 * (i % 10), 100 + 120 * (i / 10), 30, 30);
floorBtnDown->setText("↓");
floorBtnDown->show();
floorBtnsDown.push_back(floorBtnDown);
connect(floorBtnsDown[unsigned(i)], &QPushButton::clicked, this, [=]{floorBtnsDown[unsigned(i)]->setEnabled(false);});
connect(floorBtnsDown[unsigned(i)], &QPushButton::clicked, this, [=]{ele_select_send(false, i);});
}
floorBtnsDown[0]->hide();
floorBtnsUp[unsigned(FLOOR_NUM) - 1]->hide();
//set suitable box and window size
ui->groupBox_eles->setGeometry(10, 10, ELE_NUM > 10 ? 20 + 40 * ELE_NUM : 430, 300);
ui->groupBox_btns->setGeometry(10, 320, 430, FLOOR_NUM > 20 ? 20 + 120 * ((FLOOR_NUM) / 10 + 1) : 280);
ui->label_bar->setGeometry(10, FLOOR_NUM > 20 ? 340 + 120 * ((FLOOR_NUM) / 10 + 1) : 600, ELE_NUM > 10 ? 20 + 40 * ELE_NUM : 430, 20);
this->resize(ELE_NUM > 10 ? 40 + 40 * ELE_NUM : 450, FLOOR_NUM > 20 ? 360 + 120 * ((FLOOR_NUM) / 10 + 1) : 620);
//every 100ms, refresh sliders
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &building::timer_building_tick);
timer->start(100);
}
building::~building(){
delete ui;
}
void building::renew_label(unsigned int i){
eleSliders[i]->setValue(eles[i]->currentFloor + 1);
eleCurrents[i]->setText(QString::number(eles[i]->currentFloor + 1));
}
bool building::send_request(bool up, int floor, elevator *ele, bool forceRecive){
return(ele->recive_request(up, floor, forceRecive));
}
int building::ele_rate(bool reqUp, int reqFloor, int eleFloor, int eleStatus){
if(reqFloor == eleFloor) return 10000;
double distanceRating = double(abs(eleFloor - reqFloor)) / double(FLOOR_NUM);
if(eleStatus == 0) distanceRating *= 3;
double statusRating = eleStatus == 0 ? 1.0 : reqUp ? eleStatus == 1 ? eleFloor < reqFloor ? 1.0 : 0.2
: eleFloor < reqFloor ? 0.6 : 0.4
: eleStatus == 2 ? eleFloor > reqFloor ? 1.0 : 0.2
: eleFloor > reqFloor ? 0.6 : 0.4;
return int(100.0 * (distanceRating * 0.6 + statusRating * 0.4));
}
void building::ele_select_send(bool up, int floor){
ui->label_bar->setText("开始处理来自"+ QString::number(floor + 1, 10) +"层的电梯调度请求...");
if(ELE_SELECT_MODE == 1){
eleRatings.clear();
for(int i = 0; i < ELE_NUM; i++)
eleRatings.push_back({i, ele_rate(up, floor, eles[unsigned(i)]->currentFloor, eles[unsigned(i)]->status)});
std::sort(eleRatings.begin(), eleRatings.end(),
[](std::pair<int, int> &a, std::pair<int, int> &b){
return a.second < b.second;
});
bool successSend = false;
for(auto i : eleRatings) {
if(send_request(up, floor, eles[unsigned(i.first)])){
successSend = true;
ui->label_bar->setText("已为来自"+ QString::number(floor + 1, 10) +"层的请求调度" + QString::number(i.first + 1, 10) + "号电梯.");
return;
}else{
ui->label_bar->setText("为来自"+ QString::number(floor + 1, 10) +"层调度" + QString::number(i.first + 1, 10) + "号电梯的请求被拒绝.");
continue;
}
}
if(successSend == false) {
send_request(up, floor, eles[unsigned(eleRatings.begin()->first)], true);
ui->label_bar->setText("已为来自"+ QString::number(floor + 1, 10) +"层的请求强制调度" + QString::number(eleRatings.begin()->first + 1, 10) + "号电梯.");
}
}
else if(ELE_SELECT_MODE == 2) {
int temp = rand() % (ELE_NUM);
send_request(up, floor, eles[unsigned(temp)], true);
ui->label_bar->setText("已为来自"+ QString::number(floor + 1, 10) +"层的请求选择" + QString::number(temp + 1, 10) + "号电梯.");
}
else {
for(auto i : eles){
send_request(up, floor, i, true);
ui->label_bar->setText("已将来自"+ QString::number(floor + 1, 10) +"层的请求发送至所有电梯.");
}
}
}
void building::timer_building_tick(){
for(unsigned int i = 0; i < unsigned(ELE_NUM); i++){
renew_label(i);
if(eles[i]->status == 0){
if(ELE_SELECT_MODE == 3){
ui->label_bar->setText(QString::number(i + 1, 10) +"号电梯到达, 取消其他电梯请求.");
for(auto j : eles) j->cancel_request(eles[i]->currentFloor);
}
floorBtnsUp[unsigned(eles[i]->currentFloor)]->setEnabled(true);
floorBtnsDown[unsigned(eles[i]->currentFloor)]->setEnabled(true);
}
}
}
| 40.483444 | 144 | 0.655325 | [
"vector"
] |
dfa1d793d4012a29235e96a5145bb3541b20466f | 1,395 | cpp | C++ | src/propagation/rungekutta4.cpp | mattstvan/arc | 1e86947ba70bacd718dcbecbe08b5d4242fe8117 | [
"MIT"
] | null | null | null | src/propagation/rungekutta4.cpp | mattstvan/arc | 1e86947ba70bacd718dcbecbe08b5d4242fe8117 | [
"MIT"
] | null | null | null | src/propagation/rungekutta4.cpp | mattstvan/arc | 1e86947ba70bacd718dcbecbe08b5d4242fe8117 | [
"MIT"
] | 1 | 2022-03-31T02:27:33.000Z | 2022-03-31T02:27:33.000Z | #include <rungekutta4.h>
/*
Fourth-order Runge-Kutta methods
*/
// Direct constructor (default settings)
RungeKutta4::RungeKutta4(ICRF initial_state) : NumericalPropagator{ initial_state } {}
// Direct constructor (full settings)
RungeKutta4::RungeKutta4(ICRF initial_state, double step_size, ForceModel force_model) : NumericalPropagator{ initial_state, step_size, force_model } {}
// Step the integration a number of seconds forward/backward
ICRF RungeKutta4::integrate(ICRF &state, double step) {
// Take derivatives
Vector6 k0 {};
Vector6 k1 = derivatives(state, 0.0, k0).scale(step);
Vector6 w_k1 = k1 / 2.0;
Vector6 k2 = derivatives(state, step / 2.0, w_k1).scale(step);
Vector6 w_k2 = k2 / 2.0;
Vector6 k3 = derivatives(state, step / 2.0, w_k2).scale(step);
Vector6 k4 = derivatives(state, step, k3).scale(step);
// Start combined vector and add weighted values
k2 = k2 * 2;
k3 = k3 * 2;
Vector6 total = k1 + k2;
total = total + k3;
total = total + k4;
total = total / 6;
// Combined position/velocity
Vector6 pos_vel {state.position, state.velocity};
// Add the total weighted velocity/acceleration vector
std::array<Vector3, 2> final_vectors = (pos_vel + total).split();
// Build the new state and return
DateTime new_epoch = state.epoch.increment(step);
return ICRF {state.central_body, new_epoch, final_vectors[0], final_vectors[1]};
} | 37.702703 | 152 | 0.71828 | [
"vector"
] |
dfa67db3660dea8037ccf7142765db3ce6c8a935 | 4,628 | cpp | C++ | src/byteBuffer.cpp | Linaname/mtc | 6318a16524a2f898ab553792710261e2dcceadbd | [
"MIT"
] | null | null | null | src/byteBuffer.cpp | Linaname/mtc | 6318a16524a2f898ab553792710261e2dcceadbd | [
"MIT"
] | 1 | 2017-06-09T14:07:48.000Z | 2017-06-09T14:07:48.000Z | src/byteBuffer.cpp | Linaname/mtc | 6318a16524a2f898ab553792710261e2dcceadbd | [
"MIT"
] | 11 | 2017-04-25T15:26:50.000Z | 2022-03-22T12:41:09.000Z | /*
The MIT License (MIT)
Copyright (c) 2000-2016 Андрей Коваленко aka Keva
keva@meta.ua
keva@rambler.ru
skype: big_keva
phone: +7(495)648-4058, +7(916)015-5592
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
=============================================================================
Данная лицензия разрешает лицам, получившим копию данного программного обеспечения
и сопутствующей документации (в дальнейшем именуемыми «Программное Обеспечение»),
безвозмездно использовать Программное Обеспечение без ограничений, включая неограниченное
право на использование, копирование, изменение, слияние, публикацию, распространение,
сублицензирование и/или продажу копий Программного Обеспечения, а также лицам, которым
предоставляется данное Программное Обеспечение, при соблюдении следующих условий:
Указанное выше уведомление об авторском праве и данные условия должны быть включены во
все копии или значимые части данного Программного Обеспечения.
ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ,
ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ ГАРАНТИИ ТОВАРНОЙ ПРИГОДНОСТИ,
СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И ОТСУТСТВИЯ НАРУШЕНИЙ, НО НЕ ОГРАНИЧИВАЯСЬ
ИМИ.
НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО КАКИМ-ЛИБО ИСКАМ,
ЗА УЩЕРБ ИЛИ ПО ИНЫМ ТРЕБОВАНИЯМ, В ТОМ ЧИСЛЕ, ПРИ ДЕЙСТВИИ КОНТРАКТА, ДЕЛИКТЕ ИЛИ ИНОЙ
СИТУАЦИИ, ВОЗНИКШИМ ИЗ-ЗА ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫХ ДЕЙСТВИЙ
С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
*/
# include "../byteBuffer.h"
# include <cstring>
# include <vector>
namespace mtc
{
template <class error>
class ByteBuffer final: public std::vector<char>, public IByteBuffer
{
implement_lifetime_control
public:
virtual const char* GetPtr() const override { return data(); }
virtual word32_t GetLen() const override { return size(); }
virtual int SetBuf( const void* p, word32_t l ) override
{
try
{ return resize( l ), memcpy( data(), p, l ), 0; }
catch ( const std::bad_alloc& x )
{ return error::result( x, ENOMEM ); }
}
virtual int SetLen( word32_t l ) override
{
try
{ return resize( l ), 0; }
catch ( const std::bad_alloc& x )
{ return error::result( x, ENOMEM ); }
}
};
struct throw_error
{
template<class X, class R>
static R result( const X& except, R ) { throw except; }
};
struct nothrow_error
{
template<class X, class R>
static R result( const X&, R result ) { return result; }
};
int CreateByteBuffer( IByteBuffer** ppi )
{
if ( ppi == nullptr )
return EINVAL;
if ( (*ppi = allocate<ByteBuffer<nothrow_error>>()) == nullptr )
return ENOMEM;
return (*ppi)->Attach(), 0;
}
int CreateByteBuffer( IByteBuffer** ppi, const void* memptr, uint32_t length )
{
if ( ppi == nullptr )
return EINVAL;
if ( (*ppi = allocate<ByteBuffer<nothrow_error>>()) == nullptr )
return ENOMEM;
if ( ((ByteBuffer<nothrow_error>*)*ppi)->SetBuf( memptr, length ) != 0 )
return delete (ByteBuffer<nothrow_error>*)*ppi, ENOMEM;
return (*ppi)->Attach(), 0;
}
api<IByteBuffer> CreateByteBuffer( uint32_t cch )
{
auto palloc = api<IByteBuffer>( new ByteBuffer<throw_error>() );
return palloc->SetLen( cch ), palloc.ptr();
}
api<IByteBuffer> CreateByteBuffer( const void* ptr, uint32_t cch )
{
auto palloc = api<IByteBuffer>( new ByteBuffer<throw_error>() );
return palloc->SetBuf( ptr, cch ), palloc.ptr();
}
}
| 34.537313 | 90 | 0.695333 | [
"vector"
] |
dfb463174346998f7ebc2d7a9f5bed9e11bd778b | 1,093 | cpp | C++ | cpp/RestoreIPAddresses.cpp | thinksource/code_interview | 08be992240508b73894eaf6b8c025168fd19df19 | [
"Apache-2.0"
] | 12 | 2015-03-12T03:27:26.000Z | 2021-03-11T09:26:16.000Z | cpp/RestoreIPAddresses.cpp | thinksource/code_interview | 08be992240508b73894eaf6b8c025168fd19df19 | [
"Apache-2.0"
] | null | null | null | cpp/RestoreIPAddresses.cpp | thinksource/code_interview | 08be992240508b73894eaf6b8c025168fd19df19 | [
"Apache-2.0"
] | 11 | 2015-01-28T16:45:40.000Z | 2017-03-28T20:01:38.000Z | class Solution {
public:
bool isValid(string s) {
int n = s.length();
if(n==0 || n>3) {
return false;
}
if(n>1 && s[0]=='0') {
return false;
}
if(stoi(s) <= 255) {
return true;
}
return false;
}
vector<string> restoreIpAddresses(string s) {
vector<string> res;
int n = s.length();
for(int i=1;i<n;i++) {
if(!isValid(s.substr(0,i))){
continue;
}
for(int j=i+1;j<n;j++) {
if(!isValid(s.substr(i,j-i))){
continue;
}
for(int k=j+1;k<n;k++) {
if(!isValid(s.substr(j,k-j))) {
continue;
}
if(!isValid(s.substr(k))) {
continue;
}
res.push_back(s.substr(0,i)+ "." + s.substr(i,j-i) +"." + s.substr(j,k-j) +"." + s.substr(k));
}
}
}
return res;
}
};
| 26.02381 | 114 | 0.343092 | [
"vector"
] |
dfbbfdeb806316bcbcead3e1fb469a024a076f23 | 1,089 | cpp | C++ | example_algo/bin/algo.cpp | julitopower/SagemakerCpp | 3dec305aa831d2e00aaba318349255b46b503487 | [
"MIT"
] | 1 | 2018-01-03T12:03:06.000Z | 2018-01-03T12:03:06.000Z | example_algo/bin/algo.cpp | julitopower/SagemakerCpp | 3dec305aa831d2e00aaba318349255b46b503487 | [
"MIT"
] | null | null | null | example_algo/bin/algo.cpp | julitopower/SagemakerCpp | 3dec305aa831d2e00aaba318349255b46b503487 | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "sagemaker/Config.hpp"
#include "sagemaker/file_utils.hpp"
#include "sagemaker/integration.hpp"
int main(int argc, char** argv)
{
// Print a few of the interesting locations in the input
sm::Config config{};
sm::print_file(config.hp_file_path);
sm::print_file(config.input_data_config_file_path);
sm::print_file(config.resources_file_path);
// For this initial version we assume that a channel called train
// has been passed. Thus, there will be files under
// config.input_data_path/train
std::vector<std::string> files{};
std::string train_data {config.input_data_path};
train_data += "train/";
sm::read_directory(train_data, files);
for(const auto& file : files) {
std::cout << file << std::endl;
}
// Let's read the hyperparameters
auto hp = sm::get_hyperparameters();
std::cout << hp << std::endl;
sm::report_success();
std::stringstream message{};
message << "This is my model message";
sm::write_model("model_file.txt", message);
return 0;
}
| 27.225 | 67 | 0.706152 | [
"vector",
"model"
] |
dfc36158b05b4d85febc63f983c6d1e6eceba792 | 2,693 | cpp | C++ | Sesion15/CaracteresMultiples(clases).cpp | dcabezas98/FP | af9d418e934a99f425e232f31c71c5904e972215 | [
"MIT"
] | null | null | null | Sesion15/CaracteresMultiples(clases).cpp | dcabezas98/FP | af9d418e934a99f425e232f31c71c5904e972215 | [
"MIT"
] | null | null | null | Sesion15/CaracteresMultiples(clases).cpp | dcabezas98/FP | af9d418e934a99f425e232f31c71c5904e972215 | [
"MIT"
] | null | null | null | /* Programa que lee y almacena texto en objetos del tipo
SecuenciaCaracteres, cuenta con clases específicas para operaciones
de E/S. */
#include<iostream>
using namespace std;
const int TAMANIO = 1000;
class SecuenciaCaracteres {
private:
char vector[TAMANIO];
int utilizados;
public:
SecuenciaCaracteres() {
utilizados = 0;
}
void aniade(char caracter) {
if(utilizados < TAMANIO) {
vector[utilizados] = caracter;
utilizados++;
}
}
char elemento(int pos) {
if(pos >= 0 && pos < utilizados) {
return vector[pos];
}
}
int elementos_utilizados() {
return utilizados;
}
};
class ImpresorSecuenciaCaracteres { // Clase para imprimir secuencias
private:
char inicio;
char separador;
char final;
public:
ImpresorSecuenciaCaracteres(char ini, char fin, char sep) {
inicio = ini;
separador = sep;
final = fin;
}
void Imprime(SecuenciaCaracteres a_imprimir) {
int i;
cout << inicio;
for(i = 0; i < a_imprimir.elementos_utilizados()-1; i++) {
cout << a_imprimir.elemento(i) << separador;
}
cout << a_imprimir.elemento(i) << final << "\n";
}
};
class LectorSecuenciaCaracteres { // Clase que crea secuencias que lee desde el teclado
private:
const char TERMINADOR;
public:
LectorSecuenciaCaracteres(char term): TERMINADOR(term) {
}
char Terminador() {
return TERMINADOR;
}
SecuenciaCaracteres Lee() {
SecuenciaCaracteres secuencia;
char caracter;
cin >> caracter;
while(caracter != TERMINADOR) {
secuencia.aniade(caracter);
cin >> caracter;
}
return secuencia;
}
};
class Texto {
private:
int lineas;
int utilizados[TAMANIO] = {};
char matriz[TAMANIO][TAMANIO];
public:
void Aniade(SecuenciaCaracteres linea) {
for(int j = 0; j < linea.elementos_utilizados(); j++) {
matriz[lineas][j] = linea.elemento(j);
utilizados[lineas]++;
}
lineas++;
}
SecuenciaCaracteres Fila(int i) {
SecuenciaCaracteres fila;
for(int j = 0; j < utilizados[i]; j++)
fila.aniade(matriz[i][j]);
return fila;
}
};
int main() {
int lineas;
LectorSecuenciaCaracteres lector('.');
SecuenciaCaracteres frase;
Texto texto;
cout << "Líneas a leer: ";
cin >> lineas;
int i;
cout << "Escriba su secuencia (" << lector.Terminador() << ") para finalizar:\n";
for(i = 0; i < lineas; i++) {
frase = lector.Lee(); // leo cada secuencia
texto.Aniade(frase); // La añado al texto
}
ImpresorSecuenciaCaracteres impresor('[',']','-');
for(i = 0; i < lineas; i++) {
impresor.Imprime(texto.Fila(i)); // Imprimo las secuencias
}
}
| 16.623457 | 87 | 0.632009 | [
"vector"
] |
dfc5a6ce8cc98d0128bafc8f29d7566f90e6d200 | 662 | hpp | C++ | src/ivorium_core/Basics/multiline_ostream.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | 3 | 2021-02-26T02:59:09.000Z | 2022-02-08T16:44:21.000Z | src/ivorium_core/Basics/multiline_ostream.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | src/ivorium_core/Basics/multiline_ostream.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <iostream>
#include <vector>
namespace iv
{
class multiline_ostream_streambuf : public std::streambuf
{
public:
multiline_ostream_streambuf( std::ostream * out );
virtual std::streambuf::int_type overflow( std::streambuf::int_type value ) override;
void multiline_begin();
void multiline_end();
void clear();
private:
std::ostream * out;
size_t pos;
std::vector< size_t > lengths;
};
class multiline_ostream : public std::ostream
{
public:
multiline_ostream( std::ostream * out );
~multiline_ostream();
void multiline_begin();
void multiline_end();
void clear();
};
}
| 17.891892 | 89 | 0.672205 | [
"vector"
] |
dfc62d0af326b39e6033bb33bdc7b566f7dce8fb | 4,364 | cc | C++ | content/shell/test_runner/pixel_dump.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/shell/test_runner/pixel_dump.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/shell/test_runner/pixel_dump.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/test_runner/pixel_dump.h"
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
#include "cc/paint/paint_flags.h"
#include "cc/paint/skia_paint_canvas.h"
#include "content/public/renderer/render_frame.h"
#include "content/shell/test_runner/web_test_runtime_flags.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "printing/metafile_skia.h"
#include "printing/print_settings.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h"
#include "third_party/blink/public/mojom/clipboard/clipboard.mojom.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/web/web_frame.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_page_popup.h"
#include "third_party/blink/public/web/web_print_params.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/public/web/web_widget.h"
#include "ui/gfx/geometry/point.h"
namespace content {
namespace {
void CapturePixelsForPrinting(
blink::WebLocalFrame* web_frame,
base::OnceCallback<void(const SkBitmap&)> callback) {
auto* frame_widget = web_frame->LocalRoot()->FrameWidget();
frame_widget->UpdateAllLifecyclePhases(blink::DocumentUpdateReason::kTest);
blink::WebSize page_size_in_pixels = frame_widget->Size();
int page_count = web_frame->PrintBegin(page_size_in_pixels);
int total_height = page_count * (page_size_in_pixels.height + 1) - 1;
bool is_opaque = false;
SkBitmap bitmap;
if (!bitmap.tryAllocN32Pixels(page_size_in_pixels.width, total_height,
is_opaque)) {
LOG(ERROR) << "Failed to create bitmap width=" << page_size_in_pixels.width
<< " height=" << total_height;
std::move(callback).Run(SkBitmap());
return;
}
printing::MetafileSkia metafile(printing::SkiaDocumentType::MSKP,
printing::PrintSettings::NewCookie());
cc::SkiaPaintCanvas canvas(bitmap);
canvas.SetPrintingMetafile(&metafile);
web_frame->PrintPagesForTesting(&canvas, page_size_in_pixels);
web_frame->PrintEnd();
std::move(callback).Run(bitmap);
}
} // namespace
void PrintFrameAsync(blink::WebLocalFrame* web_frame,
base::OnceCallback<void(const SkBitmap&)> callback) {
DCHECK(web_frame);
DCHECK(callback);
web_frame->GetTaskRunner(blink::TaskType::kInternalTest)
->PostTask(FROM_HERE, base::BindOnce(&CapturePixelsForPrinting,
base::Unretained(web_frame),
std::move(callback)));
}
void CopyImageAtAndCapturePixels(
blink::WebLocalFrame* web_frame,
int x,
int y,
base::OnceCallback<void(const SkBitmap&)> callback) {
mojo::Remote<blink::mojom::ClipboardHost> clipboard;
content::RenderFrame* render_frame =
content::RenderFrame::FromWebFrame(web_frame);
render_frame->GetBrowserInterfaceBroker()->GetInterface(
clipboard.BindNewPipeAndPassReceiver());
uint64_t sequence_number_before = 0;
clipboard->GetSequenceNumber(ui::ClipboardBuffer::kCopyPaste,
&sequence_number_before);
web_frame->CopyImageAtForTesting(gfx::Point(x, y));
uint64_t sequence_number_after = 0;
while (sequence_number_before == sequence_number_after) {
clipboard->GetSequenceNumber(ui::ClipboardBuffer::kCopyPaste,
&sequence_number_after);
}
SkBitmap bitmap;
clipboard->ReadImage(ui::ClipboardBuffer::kCopyPaste, &bitmap);
std::move(callback).Run(bitmap);
}
} // namespace content
| 37.947826 | 96 | 0.732585 | [
"geometry"
] |
dfcfdcb2a20360b11e4dab7afa5859c9fefa7c62 | 1,990 | hh | C++ | lib/utilities.hh | losalamos/NuT | 5c6e03c45a380ae24ea9ee8bc2e68c3748ddd4e0 | [
"BSD-3-Clause"
] | 4 | 2015-01-01T13:47:53.000Z | 2016-03-31T01:56:43.000Z | lib/utilities.hh | losalamos/NuT | 5c6e03c45a380ae24ea9ee8bc2e68c3748ddd4e0 | [
"BSD-3-Clause"
] | 1 | 2019-05-08T16:21:43.000Z | 2019-05-14T17:20:19.000Z | lib/utilities.hh | lanl/NuT | 5c6e03c45a380ae24ea9ee8bc2e68c3748ddd4e0 | [
"BSD-3-Clause"
] | 4 | 2017-06-21T20:26:30.000Z | 2020-03-19T07:05:00.000Z | // utilities.hh
// T. M. Kelley
// Jan 24, 2011
// (c) Copyright 2011 LANSLLC, all rights reserved
#ifndef UTILITIES_HH
#define UTILITIES_HH
#include "Assert.hh"
#include "types.hh"
#include <algorithm>
#include <cmath>
#include <numeric>
/**!\file Useful operators. */
namespace nut {
template <typename fp_t>
struct mult {
fp_t operator()(fp_t const a) const { return a * t; }
fp_t const t;
explicit mult(fp_t const t_) : t(t_) {}
}; // mult
template <typename fp_t, typename int_t>
struct int_mult {
int_t operator()(fp_t const a) const
{
return int_t(std::floor(a * t + 0.5));
}
fp_t const t;
explicit int_mult(fp_t const t_) : t(t_) {}
}; // mult
template <typename fp_t>
struct div_by {
fp_t operator()(fp_t const a) const { return a / d; }
fp_t const d;
explicit div_by(fp_t const d_) : d(d_)
{
Require(d != fp_t(0), "div_by::ctor: divisor may not equal 0");
}
}; // div_by
/*!\brief if divisor is not equal to 0, returns a / b, otherwise
* returns 0. */
template <typename fp_t>
fp_t
div_if_ne0(fp_t const a, size_t const b)
{
return b != 0 ? fp_t(a / b) : fp_t(0);
}
// sum contents of an STL container
template <typename ContT>
typename ContT::value_type
sum(ContT const & v)
{
return std::accumulate(v.begin(), v.end(), typename ContT::value_type{0});
}
/** Add each element of v1 to corr. element v2. */
template <typename T>
inline void
merge_vectors(std::vector<T> const & v1, std::vector<T> & v2)
{
std::transform(v1.begin(), v1.end(), v2.begin(), v2.begin(), std::plus<T>());
}
/** Append the elements of v1 to v2. */
template <typename T>
inline void
append_vector(std::vector<T> const & v1, std::vector<T> & v2)
{
v2.insert(v2.end(), v1.begin(), v1.end());
}
/** Compare arrays element-wise*/
template <typename vector>
bool
arrays_eq(vector const & a1, vector const & a2)
{
return std::equal(a1.begin(), a1.end(), a2.begin());
}
} // namespace nut
#endif // include_guard
// version
// $Id$
// End of file
| 21.170213 | 79 | 0.654774 | [
"vector",
"transform"
] |
2546c7277976e4080ec736b5fad9e88eb846f2fb | 2,468 | cpp | C++ | src/iterator.cpp | mtth/pal | 4326a6d726981e235a16cc7673916c93348ab3e9 | [
"MIT"
] | 1 | 2015-11-16T19:32:08.000Z | 2015-11-16T19:32:08.000Z | src/iterator.cpp | mtth/pal | 4326a6d726981e235a16cc7673916c93348ab3e9 | [
"MIT"
] | null | null | null | src/iterator.cpp | mtth/pal | 4326a6d726981e235a16cc7673916c93348ab3e9 | [
"MIT"
] | null | null | null | #include "iterator.h"
#include "store.h"
namespace pal {
class IteratorWorker : public Nan::AsyncWorker {
public:
IteratorWorker(Nan::Callback *callback, pal_iterator_t *iterator) : AsyncWorker(callback) {
_iterator = iterator;
}
~IteratorWorker() {}
void Execute() {
_nonEmpty = pal_iterator_next(_iterator, &_key, &_keySize, &_value, &_valueSize);
}
void HandleOKCallback() {
Nan::HandleScope scope;
if (_nonEmpty) {
Nan::MaybeLocal<v8::Object> keyBuf = Nan::CopyBuffer(_key, _keySize);
Nan::MaybeLocal<v8::Object> valueBuf = Nan::CopyBuffer(_value, _valueSize);
v8::Local<v8::Value> argv[] = {
Nan::Null(),
keyBuf.ToLocalChecked(),
valueBuf.ToLocalChecked()
};
callback->Call(3, argv);
} else {
v8::Local<v8::Value> argv[] = {Nan::Null()};
callback->Call(1, argv);
}
}
private:
pal_iterator_t *_iterator;
char *_key;
int32_t _keySize;
char *_value;
int64_t _valueSize;
char _nonEmpty;
};
Iterator::Iterator(pal_reader_t *reader) {
pal_iterator_reset(&_iterator, reader);
}
Iterator::~Iterator() {}
// v8 exposed functions.
/**
* JS constructor.
*
*/
void Iterator::New(const Nan::FunctionCallbackInfo<v8::Value> &info) {
if (info.Length() != 1 || !info[0]->IsObject()) {
Nan::ThrowError("invalid arguments");
return;
}
Store *store = ObjectWrap::Unwrap<Store>(info[0]->ToObject());
Iterator *iter = new Iterator(store->_reader);
iter->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
/**
* Advance the iterator.
*
*/
void Iterator::Next(const Nan::FunctionCallbackInfo<v8::Value> &info) {
if (info.Length() != 1 || !info[0]->IsFunction()) {
Nan::ThrowError("invalid arguments");
return;
}
Iterator *iterator = ObjectWrap::Unwrap<Iterator>(info.This());
Nan::Callback *callback = new Nan::Callback(info[0].As<v8::Function>());
IteratorWorker *worker = new IteratorWorker(callback, &iterator->_iterator);
worker->SaveToPersistent("iterator", info.This());
Nan::AsyncQueueWorker(worker);
}
/**
* Initializer, returns the `Iterator` function.
*
*/
v8::Local<v8::FunctionTemplate> Iterator::Init() {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(Iterator::New);
tpl->SetClassName(Nan::New("Iterator").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "next", Iterator::Next);
return tpl;
}
}
| 25.183673 | 93 | 0.660454 | [
"object"
] |
25475111cf8cdb53aeb86aaf30a38693be6a0e5a | 26,033 | cpp | C++ | src/library/tactic/simplifier/simp_lemmas.cpp | soonhokong/lean-windows | 06dff344c8e0e3876b56294c8443a3b17c26dd48 | [
"Apache-2.0"
] | null | null | null | src/library/tactic/simplifier/simp_lemmas.cpp | soonhokong/lean-windows | 06dff344c8e0e3876b56294c8443a3b17c26dd48 | [
"Apache-2.0"
] | null | null | null | src/library/tactic/simplifier/simp_lemmas.cpp | soonhokong/lean-windows | 06dff344c8e0e3876b56294c8443a3b17c26dd48 | [
"Apache-2.0"
] | 1 | 2018-09-22T14:28:09.000Z | 2018-09-22T14:28:09.000Z | /*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <vector>
#include <string>
#include <library/constants.h>
#include "util/priority_queue.h"
#include "util/sstream.h"
#include "util/flet.h"
#include "util/list_fn.h"
#include "util/name_hash_map.h"
#include "kernel/error_msgs.h"
#include "kernel/find_fn.h"
#include "kernel/instantiate.h"
#include "library/trace.h"
#include "library/num.h"
#include "library/cache_helper.h"
#include "library/scoped_ext.h"
#include "library/attribute_manager.h"
#include "library/type_context.h"
#include "library/vm/vm_expr.h"
#include "library/vm/vm_list.h"
#include "library/tactic/tactic_state.h"
#include "library/tactic/simplifier/ceqv.h"
#include "library/tactic/simplifier/simp_lemmas.h"
namespace lean {
/* Caching */
struct simp_lemma_cache {
typedef name_hash_map<simp_lemmas> cache;
environment m_env;
cache m_simp_lemma_cache;
cache m_congr_lemma_cache;
simp_lemma_cache(environment const & env): m_env(env) {}
environment const & env() const { return m_env; }
cache & simp_cache() { return m_simp_lemma_cache; }
cache & congr_cache() { return m_congr_lemma_cache; }
};
typedef cache_compatibility_helper<simp_lemma_cache> simp_lemma_cache_helper;
MK_THREAD_LOCAL_GET_DEF(simp_lemma_cache_helper, get_slch);
simp_lemma_cache & get_simp_lemma_cache_for(type_context const & ctx) {
return get_slch().get_cache_for(ctx);
}
/* Validation */
LEAN_THREAD_VALUE(bool, g_throw_ex, false);
void validate_simp(type_context & tctx, name const & n);
void validate_congr(type_context & tctx, name const & n);
void on_add_simp_lemma(environment const & env, name const & c, bool) {
type_context tctx(env);
validate_simp(tctx, c);
}
void on_add_congr_lemma(environment const & env, name const & c, bool) {
type_context tctx(env);
validate_congr(tctx, c);
}
/* Getters/checkers */
static void report_failure(sstream const & strm) {
if (g_throw_ex){
throw exception(strm);
} else {
lean_trace(name({"simplifier", "failure"}),
tout() << strm.str() << "\n";);
}
}
simp_lemmas add_core(tmp_type_context & tmp_tctx, simp_lemmas const & s,
name const & id, levels const & univ_metas, expr const & e, expr const & h,
unsigned priority) {
list<expr_pair> ceqvs = to_ceqvs(tmp_tctx, e, h);
if (is_nil(ceqvs)) {
report_failure(sstream() << "invalid [simp] lemma '" << id << "' : " << e);
return s;
}
environment const & env = tmp_tctx.tctx().env();
simp_lemmas new_s = s;
for (expr_pair const & p : ceqvs) {
/* We only clear the eassignment since we want to reuse the temporary universe metavariables associated
with the declaration. */
tmp_tctx.clear_eassignment();
expr rule = tmp_tctx.whnf(p.first);
expr proof = tmp_tctx.whnf(p.second);
bool is_perm = is_permutation_ceqv(env, rule);
buffer<expr> emetas;
buffer<bool> instances;
while (is_pi(rule)) {
expr mvar = tmp_tctx.mk_tmp_mvar(binding_domain(rule));
emetas.push_back(mvar);
instances.push_back(binding_info(rule).is_inst_implicit());
rule = tmp_tctx.whnf(instantiate(binding_body(rule), mvar));
proof = mk_app(proof, mvar);
}
expr rel, lhs, rhs;
if (is_simp_relation(env, rule, rel, lhs, rhs) && is_constant(rel)) {
new_s.insert(const_name(rel), simp_lemma(id, univ_metas, reverse_to_list(emetas),
reverse_to_list(instances), lhs, rhs, proof, is_perm, priority));
}
}
return new_s;
}
static simp_lemmas add_core(tmp_type_context & tmp_tctx, simp_lemmas const & s, name const & cname, unsigned priority) {
declaration const & d = tmp_tctx.tctx().env().get(cname);
buffer<level> us;
unsigned num_univs = d.get_num_univ_params();
for (unsigned i = 0; i < num_univs; i++) {
us.push_back(tmp_tctx.mk_tmp_univ_mvar());
}
levels ls = to_list(us);
expr e = tmp_tctx.whnf(instantiate_type_univ_params(d, ls));
expr h = mk_constant(cname, ls);
return add_core(tmp_tctx, s, cname, ls, e, h, priority);
}
// Return true iff lhs is of the form (B (x : ?m1), ?m2) or (B (x : ?m1), ?m2 x),
// where B is lambda or Pi
static bool is_valid_congr_rule_binding_lhs(expr const & lhs, name_set & found_mvars) {
lean_assert(is_binding(lhs));
expr const & d = binding_domain(lhs);
expr const & b = binding_body(lhs);
if (!is_metavar(d))
return false;
if (is_metavar(b) && b != d) {
found_mvars.insert(mlocal_name(b));
found_mvars.insert(mlocal_name(d));
return true;
}
if (is_app(b) && is_metavar(app_fn(b)) && is_var(app_arg(b), 0) && app_fn(b) != d) {
found_mvars.insert(mlocal_name(app_fn(b)));
found_mvars.insert(mlocal_name(d));
return true;
}
return false;
}
// Return true iff all metavariables in e are in found_mvars
static bool only_found_mvars(expr const & e, name_set const & found_mvars) {
return !find(e, [&](expr const & m, unsigned) {
return is_metavar(m) && !found_mvars.contains(mlocal_name(m));
});
}
// Check whether rhs is of the form (mvar l_1 ... l_n) where mvar is a metavariable,
// and l_i's are local constants, and mvar does not occur in found_mvars.
// If it is return true and update found_mvars
static bool is_valid_congr_hyp_rhs(expr const & rhs, name_set & found_mvars) {
buffer<expr> rhs_args;
expr const & rhs_fn = get_app_args(rhs, rhs_args);
if (!is_metavar(rhs_fn) || found_mvars.contains(mlocal_name(rhs_fn)))
return false;
for (expr const & arg : rhs_args)
if (!is_local(arg))
return false;
found_mvars.insert(mlocal_name(rhs_fn));
return true;
}
simp_lemmas add_congr_core(tmp_type_context & tmp_tctx, simp_lemmas const & s, name const & n, unsigned prio) {
declaration const & d = tmp_tctx.tctx().env().get(n);
buffer<level> us;
unsigned num_univs = d.get_num_univ_params();
for (unsigned i = 0; i < num_univs; i++) {
us.push_back(tmp_tctx.mk_tmp_univ_mvar());
}
levels ls = to_list(us);
expr rule = tmp_tctx.whnf(instantiate_type_univ_params(d, ls));
expr proof = mk_constant(n, ls);
buffer<expr> emetas;
buffer<bool> instances, explicits;
while (is_pi(rule)) {
expr mvar = tmp_tctx.mk_tmp_mvar(binding_domain(rule));
emetas.push_back(mvar);
explicits.push_back(is_explicit(binding_info(rule)));
instances.push_back(binding_info(rule).is_inst_implicit());
rule = tmp_tctx.whnf(instantiate(binding_body(rule), mvar));
proof = mk_app(proof, mvar);
}
expr rel, lhs, rhs;
if (!is_simp_relation(tmp_tctx.tctx().env(), rule, rel, lhs, rhs) || !is_constant(rel)) {
report_failure(sstream() << "invalid [congr] lemma, '" << n
<< "' resulting type is not of the form t ~ s, where '~' is a transitive and reflexive relation");
}
name_set found_mvars;
buffer<expr> lhs_args, rhs_args;
expr const & lhs_fn = get_app_args(lhs, lhs_args);
expr const & rhs_fn = get_app_args(rhs, rhs_args);
if (is_constant(lhs_fn)) {
if (!is_constant(rhs_fn) || const_name(lhs_fn) != const_name(rhs_fn) || lhs_args.size() != rhs_args.size()) {
report_failure(sstream() << "invalid [congr] lemma, '" << n
<< "' resulting type is not of the form (" << const_name(lhs_fn) << " ...) "
<< "~ (" << const_name(lhs_fn) << " ...), where ~ is '" << const_name(rel) << "'");
}
for (expr const & lhs_arg : lhs_args) {
if (is_sort(lhs_arg))
continue;
if (!is_metavar(lhs_arg) || found_mvars.contains(mlocal_name(lhs_arg))) {
report_failure(sstream() << "invalid [congr] lemma, '" << n
<< "' the left-hand-side of the congruence resulting type must be of the form ("
<< const_name(lhs_fn) << " x_1 ... x_n), where each x_i is a distinct variable or a sort");
}
found_mvars.insert(mlocal_name(lhs_arg));
}
} else if (is_binding(lhs)) {
if (lhs.kind() != rhs.kind()) {
report_failure(sstream() << "invalid [congr] lemma, '" << n
<< "' kinds of the left-hand-side and right-hand-side of "
<< "the congruence resulting type do not match");
}
if (!is_valid_congr_rule_binding_lhs(lhs, found_mvars)) {
report_failure(sstream() << "invalid [congr] lemma, '" << n
<< "' left-hand-side of the congruence resulting type must "
<< "be of the form (fun/Pi (x : A), B x)");
}
} else {
report_failure(sstream() << "invalid [congr] lemma, '" << n
<< "' left-hand-side is not an application nor a binding");
}
buffer<expr> congr_hyps;
lean_assert(emetas.size() == explicits.size());
for (unsigned i = 0; i < emetas.size(); i++) {
expr const & mvar = emetas[i];
if (explicits[i] && !found_mvars.contains(mlocal_name(mvar))) {
buffer<expr> locals;
expr type = mlocal_type(mvar);
type_context::tmp_locals local_factory(tmp_tctx.tctx());
while (is_pi(type)) {
expr local = local_factory.push_local_from_binding(type);
locals.push_back(local);
type = instantiate(binding_body(type), local);
}
expr h_rel, h_lhs, h_rhs;
if (!is_simp_relation(tmp_tctx.tctx().env(), type, h_rel, h_lhs, h_rhs) || !is_constant(h_rel))
continue;
unsigned j = 0;
for (expr const & local : locals) {
j++;
if (!only_found_mvars(mlocal_type(local), found_mvars)) {
report_failure(sstream() << "invalid [congr] lemma, '" << n
<< "' argument #" << j << " of parameter #" << (i+1) << " contains "
<< "unresolved parameters");
}
}
if (!only_found_mvars(h_lhs, found_mvars)) {
report_failure(sstream() << "invalid [congr] lemma, '" << n
<< "' argument #" << (i+1) << " is not a valid hypothesis, the left-hand-side contains "
<< "unresolved parameters");
}
if (!is_valid_congr_hyp_rhs(h_rhs, found_mvars)) {
report_failure(sstream() << "invalid [congr] lemma, '" << n
<< "' argument #" << (i+1) << " is not a valid hypothesis, the right-hand-side must be "
<< "of the form (m l_1 ... l_n) where m is parameter that was not "
<< "'assigned/resolved' yet and l_i's are locals");
}
found_mvars.insert(mlocal_name(mvar));
congr_hyps.push_back(mvar);
}
}
simp_lemmas new_s = s;
new_s.insert(const_name(rel), user_congr_lemma(n, ls, reverse_to_list(emetas),
reverse_to_list(instances), lhs, rhs, proof, to_list(congr_hyps), prio));
return new_s;
}
simp_lemmas add_poly(type_context & tctx, simp_lemmas const & s, name const & id, unsigned priority) {
tmp_type_context tmp_tctx(tctx);
return add_core(tmp_tctx, s, id, priority);
}
simp_lemmas add(type_context & tctx, simp_lemmas const & s, name const & id, expr const & e, expr const & h, unsigned priority) {
tmp_type_context tmp_tctx(tctx);
return add_core(tmp_tctx, s, id, list<level>(), e, h, priority);
}
simp_lemmas join(simp_lemmas const & s1, simp_lemmas const & s2) {
simp_lemmas new_s1 = s1;
buffer<pair<name const &, simp_lemma const &>> slemmas;
s2.for_each_simp([&](name const & eqv, simp_lemma const & r) {
slemmas.push_back({eqv, r});
});
for (unsigned i = slemmas.size() - 1; i + 1 > 0; --i)
new_s1.insert(slemmas[i].first, slemmas[i].second);
buffer<pair<name const &, user_congr_lemma const &>> clemmas;
s2.for_each_congr([&](name const & eqv, user_congr_lemma const & r) {
clemmas.push_back({eqv, r});
});
for (unsigned i = clemmas.size() - 1; i + 1 > 0; --i)
new_s1.insert(clemmas[i].first, clemmas[i].second);
return new_s1;
}
void validate_simp(type_context & tctx, name const & n) {
simp_lemmas s;
flet<bool> set_ex(g_throw_ex, true);
tmp_type_context tmp_tctx(tctx);
add_core(tmp_tctx, s, n, LEAN_DEFAULT_PRIORITY);
}
void validate_congr(type_context & tctx, name const & n) {
simp_lemmas s;
flet<bool> set_ex(g_throw_ex, true);
tmp_type_context tmp_tctx(tctx);
add_congr_core(tmp_tctx, s, n, LEAN_DEFAULT_PRIORITY);
}
simp_lemma_core::simp_lemma_core(name const & id, levels const & umetas, list<expr> const & emetas,
list<bool> const & instances, expr const & lhs, expr const & rhs, expr const & proof,
unsigned priority):
m_id(id), m_umetas(umetas), m_emetas(emetas), m_instances(instances),
m_lhs(lhs), m_rhs(rhs), m_proof(proof), m_priority(priority) {}
simp_lemma::simp_lemma(name const & id, levels const & umetas, list<expr> const & emetas,
list<bool> const & instances, expr const & lhs, expr const & rhs, expr const & proof,
bool is_perm, unsigned priority):
simp_lemma_core(id, umetas, emetas, instances, lhs, rhs, proof, priority),
m_is_permutation(is_perm) {}
bool operator==(simp_lemma const & r1, simp_lemma const & r2) {
return r1.m_lhs == r2.m_lhs && r1.m_rhs == r2.m_rhs;
}
format simp_lemma::pp(formatter const & fmt) const {
format r;
r += format("[") + format(get_id()) + format("]") + space();
r += format("#") + format(get_num_emeta());
if (m_priority != LEAN_DEFAULT_PRIORITY)
r += space() + paren(format(m_priority));
if (m_is_permutation)
r += space() + format("perm");
format r1 = comma() + space() + fmt(get_lhs());
r1 += space() + format("↦") + pp_indent_expr(fmt, get_rhs());
r += group(r1);
return r;
}
user_congr_lemma::user_congr_lemma(name const & id, levels const & umetas, list<expr> const & emetas,
list<bool> const & instances, expr const & lhs, expr const & rhs, expr const & proof,
list<expr> const & congr_hyps, unsigned priority):
simp_lemma_core(id, umetas, emetas, instances, lhs, rhs, proof, priority),
m_congr_hyps(congr_hyps) {}
bool operator==(user_congr_lemma const & r1, user_congr_lemma const & r2) {
return r1.m_lhs == r2.m_lhs && r1.m_rhs == r2.m_rhs && r1.m_congr_hyps == r2.m_congr_hyps;
}
format user_congr_lemma::pp(formatter const & fmt) const {
format r;
r += format("[") + format(get_id()) + format("]") + space();
r += format("#") + format(get_num_emeta());
if (m_priority != LEAN_DEFAULT_PRIORITY)
r += space() + paren(format(m_priority));
format r1;
for (expr const & h : m_congr_hyps) {
r1 += space() + paren(fmt(mlocal_type(h)));
}
r += group(r1);
r += space() + format(":") + space();
format r2 = paren(fmt(get_lhs()));
r2 += space() + format("↦") + space() + paren(fmt(get_rhs()));
r += group(r2);
return r;
}
simp_lemmas_for::simp_lemmas_for(name const & eqv):
m_eqv(eqv) {}
void simp_lemmas_for::insert(simp_lemma const & r) {
m_simp_set.insert(r.get_lhs(), r);
}
void simp_lemmas_for::erase(simp_lemma const & r) {
m_simp_set.erase(r.get_lhs(), r);
}
void simp_lemmas_for::insert(user_congr_lemma const & r) {
m_congr_set.insert(r.get_lhs(), r);
}
void simp_lemmas_for::erase(user_congr_lemma const & r) {
m_congr_set.erase(r.get_lhs(), r);
}
list<simp_lemma> const * simp_lemmas_for::find_simp(head_index const & h) const {
return m_simp_set.find(h);
}
void simp_lemmas_for::for_each_simp(std::function<void(simp_lemma const &)> const & fn) const {
m_simp_set.for_each_entry([&](head_index const &, simp_lemma const & r) { fn(r); });
}
list<user_congr_lemma> const * simp_lemmas_for::find_congr(head_index const & h) const {
return m_congr_set.find(h);
}
void simp_lemmas_for::for_each_congr(std::function<void(user_congr_lemma const &)> const & fn) const {
m_congr_set.for_each_entry([&](head_index const &, user_congr_lemma const & r) { fn(r); });
}
void simp_lemmas_for::erase_simp(name_set const & ids) {
// This method is not very smart and doesn't use any indexing or caching.
// So, it may be a bottleneck in the future
buffer<simp_lemma> to_delete;
for_each_simp([&](simp_lemma const & r) {
if (ids.contains(r.get_id())) {
to_delete.push_back(r);
}
});
for (simp_lemma const & r : to_delete) {
erase(r);
}
}
void simp_lemmas_for::erase_simp(buffer<name> const & ids) {
erase_simp(to_name_set(ids));
}
template<typename R>
void simp_lemmas::insert_core(name const & eqv, R const & r) {
simp_lemmas_for s(eqv);
if (auto const * curr = m_sets.find(eqv)) {
s = *curr;
}
s.insert(r);
m_sets.insert(eqv, s);
}
template<typename R>
void simp_lemmas::erase_core(name const & eqv, R const & r) {
if (auto const * curr = m_sets.find(eqv)) {
simp_lemmas_for s = *curr;
s.erase(r);
if (s.empty())
m_sets.erase(eqv);
else
m_sets.insert(eqv, s);
}
}
void simp_lemmas::insert(name const & eqv, simp_lemma const & r) {
return insert_core(eqv, r);
}
void simp_lemmas::erase(name const & eqv, simp_lemma const & r) {
return erase_core(eqv, r);
}
void simp_lemmas::insert(name const & eqv, user_congr_lemma const & r) {
return insert_core(eqv, r);
}
void simp_lemmas::erase(name const & eqv, user_congr_lemma const & r) {
return erase_core(eqv, r);
}
void simp_lemmas::get_relations(buffer<name> & rs) const {
m_sets.for_each([&](name const & r, simp_lemmas_for const &) {
rs.push_back(r);
});
}
void simp_lemmas::erase_simp(name_set const & ids) {
name_map<simp_lemmas_for> new_sets;
m_sets.for_each([&](name const & n, simp_lemmas_for const & s) {
simp_lemmas_for new_s = s;
new_s.erase_simp(ids);
new_sets.insert(n, new_s);
});
m_sets = new_sets;
}
void simp_lemmas::erase_simp(buffer<name> const & ids) {
erase_simp(to_name_set(ids));
}
simp_lemmas_for const * simp_lemmas::find(name const & eqv) const {
return m_sets.find(eqv);
}
list<simp_lemma> const * simp_lemmas::find_simp(name const & eqv, head_index const & h) const {
if (auto const * s = m_sets.find(eqv))
return s->find_simp(h);
return nullptr;
}
list<user_congr_lemma> const * simp_lemmas::find_congr(name const & eqv, head_index const & h) const {
if (auto const * s = m_sets.find(eqv))
return s->find_congr(h);
return nullptr;
}
void simp_lemmas::for_each_simp(std::function<void(name const &, simp_lemma const &)> const & fn) const {
m_sets.for_each([&](name const & eqv, simp_lemmas_for const & s) {
s.for_each_simp([&](simp_lemma const & r) {
fn(eqv, r);
});
});
}
void simp_lemmas::for_each_congr(std::function<void(name const &, user_congr_lemma const &)> const & fn) const {
m_sets.for_each([&](name const & eqv, simp_lemmas_for const & s) {
s.for_each_congr([&](user_congr_lemma const & r) {
fn(eqv, r);
});
});
}
format simp_lemmas::pp(formatter const & fmt, format const & header, bool simp, bool congr) const {
format r;
if (simp) {
name prev_eqv;
for_each_simp([&](name const & eqv, simp_lemma const & rw) {
if (prev_eqv != eqv) {
r += format("simplification rules for ") + format(eqv);
r += header;
r += line();
prev_eqv = eqv;
}
r += rw.pp(fmt) + line();
});
}
if (congr) {
name prev_eqv;
for_each_congr([&](name const & eqv, user_congr_lemma const & cr) {
if (prev_eqv != eqv) {
r += format("congruencec rules for ") + format(eqv) + line();
prev_eqv = eqv;
}
r += cr.pp(fmt) + line();
});
}
return r;
}
format simp_lemmas::pp_simp(formatter const & fmt, format const & header) const {
return pp(fmt, header, true, false);
}
format simp_lemmas::pp_simp(formatter const & fmt) const {
return pp(fmt, format(), true, false);
}
format simp_lemmas::pp_congr(formatter const & fmt) const {
return pp(fmt, format(), false, true);
}
format simp_lemmas::pp(formatter const & fmt) const {
return pp(fmt, format(), true, true);
}
simp_lemmas get_simp_lemmas_for_attr(simp_lemma_cache & sl_cache, type_context & tctx, name const & simp_attr) {
auto it = sl_cache.simp_cache().find(simp_attr);
if (it != sl_cache.simp_cache().end())
return it->second;
auto const & attr = get_attribute(tctx.env(), simp_attr);
simp_lemmas r;
buffer<name> simp_lemmas;
attr.get_instances(tctx.env(), simp_lemmas);
unsigned i = simp_lemmas.size();
while (i > 0) {
i--;
name const & id = simp_lemmas[i];
tmp_type_context tmp_tctx(tctx);
r = add_core(tmp_tctx, r, id, attr.get_prio(tctx.env(), id));
}
sl_cache.simp_cache().insert({simp_attr, r});
return r;
}
simp_lemmas get_congr_lemmas_for_attr(simp_lemma_cache & sl_cache, type_context & tctx, name const & congr_attr) {
auto it = sl_cache.congr_cache().find(congr_attr);
if (it != sl_cache.congr_cache().end())
return it->second;
auto const & attr = get_attribute(tctx.env(), congr_attr);
simp_lemmas r;
buffer<name> congr_lemmas;
attr.get_instances(tctx.env(), congr_lemmas);
unsigned i = congr_lemmas.size();
while (i > 0) {
i--;
name const & id = congr_lemmas[i];
tmp_type_context tmp_tctx(tctx);
r = add_congr_core(tmp_tctx, r, id, attr.get_prio(tctx.env(), id));
}
sl_cache.congr_cache().insert({congr_attr, r});
return r;
}
simp_lemmas get_simp_lemmas(type_context & tctx, buffer<name> const & simp_attrs, buffer<name> const & congr_attrs) {
simp_lemma_cache & sl_cache = get_simp_lemma_cache_for(tctx);
simp_lemmas r;
// Optimization for the case when there is only one simp attr
// (we avoid the redundant head_map_prio inserts)
if (simp_attrs.size() > 0)
r = get_simp_lemmas_for_attr(sl_cache, tctx, simp_attrs[0]);
for (unsigned i = 1; i < simp_attrs.size(); ++i)
r = join(r, get_simp_lemmas_for_attr(sl_cache, tctx, simp_attrs[i]));
for (unsigned i = 0; i < congr_attrs.size(); ++i)
r = join(r, get_congr_lemmas_for_attr(sl_cache, tctx, congr_attrs[i]));
return r;
}
struct vm_simp_lemmas : public vm_external {
simp_lemmas m_val;
vm_simp_lemmas(simp_lemmas const & v): m_val(v) {}
virtual void dealloc() override { this->~vm_simp_lemmas(); get_vm_allocator().deallocate(sizeof(vm_simp_lemmas), this); }
};
simp_lemmas const & to_simp_lemmas(vm_obj const & o) {
lean_assert(is_external(o));
lean_assert(dynamic_cast<vm_simp_lemmas*>(to_external(o)));
return static_cast<vm_simp_lemmas*>(to_external(o))->m_val;
}
vm_obj to_obj(simp_lemmas const & idx) {
return mk_vm_external(new (get_vm_allocator().allocate(sizeof(vm_simp_lemmas))) vm_simp_lemmas(idx));
}
vm_obj tactic_mk_simp_lemmas(vm_obj const & m, vm_obj const & sattrs, vm_obj const & cattrs, vm_obj const & s) {
type_context ctx = mk_type_context_for(s, m);
buffer<name> simp_attrs, congr_attrs;
to_buffer(to_list_name(sattrs), simp_attrs);
to_buffer(to_list_name(cattrs), congr_attrs);
return mk_tactic_success(to_obj(get_simp_lemmas(ctx, simp_attrs, congr_attrs)), to_tactic_state(s));
}
vm_obj tactic_mk_empty_simp_lemmas(vm_obj const & s) {
return mk_tactic_success(to_obj(simp_lemmas()), to_tactic_state(s));
}
vm_obj tactic_simp_lemmas_insert(vm_obj const & m, vm_obj const & lemmas, vm_obj const & lemma, vm_obj const & s) {
type_context tctx = mk_type_context_for(s, m);
expr e = to_expr(lemma);
name id;
if (is_constant(e))
id = const_name(e);
else if (is_local(e))
id = local_pp_name(e);
expr e_type = tctx.infer(e);
// TODO(dhs): accept priority as an argument
// Reason for postponing: better plumbing of numerals through the vm
simp_lemmas new_lemmas = add(tctx, to_simp_lemmas(lemmas), id, tctx.infer(e), e, LEAN_DEFAULT_PRIORITY);
return mk_tactic_success(to_obj(new_lemmas), to_tactic_state(s));
}
void initialize_simp_lemmas() {
DECLARE_VM_BUILTIN(name({"tactic", "mk_simp_lemmas_core"}), tactic_mk_simp_lemmas);
DECLARE_VM_BUILTIN(name({"tactic", "mk_empty_simp_lemmas"}), tactic_mk_empty_simp_lemmas);
DECLARE_VM_BUILTIN(name({"tactic", "simp_lemmas_insert_core"}), tactic_simp_lemmas_insert);
register_system_attribute(basic_attribute::with_check("simp", "simplification lemma", on_add_simp_lemma));
register_system_attribute(basic_attribute::with_check("congr", "congruence lemma", on_add_congr_lemma));
}
void finalize_simp_lemmas() {
}
}
| 37.94898 | 129 | 0.619483 | [
"vector"
] |
2550d1e38413da7bad6985e75403bbec0f727bfa | 3,290 | cpp | C++ | Competitive Programming/System Design/Iterator for Combination.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | Competitive Programming/System Design/Iterator for Combination.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | Competitive Programming/System Design/Iterator for Combination.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | /*
https://leetcode.com/problems/iterator-for-combination/
1286. Iterator for Combination
Medium
688
53
Add to List
Share
Design the CombinationIterator class:
CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
next() Returns the next combination of length combinationLength in lexicographical order.
hasNext() Returns true if and only if there exists a next combination.
Example 1:
Input
["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[["abc", 2], [], [], [], [], [], []]
Output
[null, "ab", true, "ac", true, "bc", false]
Explanation
CombinationIterator itr = new CombinationIterator("abc", 2);
itr.next(); // return "ab"
itr.hasNext(); // return True
itr.next(); // return "ac"
itr.hasNext(); // return True
itr.next(); // return "bc"
itr.hasNext(); // return False
Constraints:
1 <= combinationLength <= characters.length <= 15
All the characters of characters are unique.
At most 104 calls will be made to next and hasNext.
It's guaranteed that all calls of the function next are valid.
*/
// Time: O(k), per operation
// Space: O(k)
class CombinationIterator
{
public:
CombinationIterator(string characters, int combinationLength)
: characters_(characters), combinationLength_(combinationLength), last_(prev(characters.cend(), combinationLength), characters.cend()), stk_{bind(&CombinationIterator::divide, this, 0)}
{
}
string next()
{
iterative_backtracking();
return curr_;
}
bool hasNext()
{
return curr_ != last_;
}
private:
void iterative_backtracking()
{
while (!stk_.empty())
{
const auto cb = move(stk_.back());
stk_.pop_back();
if (cb())
{
return;
}
}
}
bool conquer()
{
if (curr_.length() == combinationLength_)
{
return true;
}
return false;
}
bool prev_divide(char c)
{
curr_.push_back(c);
return false;
}
bool divide(int i)
{
if (curr_.length() != combinationLength_)
{
for (int j = int(characters_.length()) - (combinationLength_ - int(curr_.length()) - 1) - 1;
j >= i; --j)
{
stk_.emplace_back(bind(&CombinationIterator::post_divide, this));
stk_.emplace_back(bind(&CombinationIterator::divide, this, j + 1));
stk_.emplace_back(bind(&CombinationIterator::prev_divide, this, characters_[j]));
}
}
stk_.emplace_back(bind(&CombinationIterator::conquer, this));
return false;
}
bool post_divide()
{
curr_.pop_back();
return false;
}
const string characters_;
const int combinationLength_;
string curr_;
string last_;
vector<function<bool()> > stk_;
};
/**
* Your CombinationIterator object will be instantiated and called as such:
* CombinationIterator* obj = new CombinationIterator(characters, combinationLength);
* string param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
| 24.924242 | 199 | 0.622188 | [
"object",
"vector"
] |
255b07960332aad2c48a540652346ac78f039bcd | 1,157 | hpp | C++ | src/sampler.hpp | rvaser/rampler | 4f2d91e4f3ce5ef61d14b319040a7d24f116aedd | [
"MIT"
] | 1 | 2019-08-22T03:54:54.000Z | 2019-08-22T03:54:54.000Z | src/sampler.hpp | rvaser/rampler | 4f2d91e4f3ce5ef61d14b319040a7d24f116aedd | [
"MIT"
] | 4 | 2018-06-09T13:28:50.000Z | 2021-01-19T10:48:07.000Z | src/sampler.hpp | rvaser/rampler | 4f2d91e4f3ce5ef61d14b319040a7d24f116aedd | [
"MIT"
] | 4 | 2020-07-30T03:40:18.000Z | 2021-07-11T14:18:55.000Z | // Copyright (c) 2021 Robert Vaser
#ifndef RAMPLER_SAMPLER_HPP_
#define RAMPLER_SAMPLER_HPP_
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "bioparser/parser.hpp"
#include "biosoup/sequence.hpp"
namespace rampler {
class Sampler;
std::unique_ptr<Sampler> createSampler(const std::string& sequences_path);
class Sampler {
public:
Sampler(
std::unique_ptr<bioparser::Parser<biosoup::Sequence>> sparser,
const std::string& base_name,
const std::string& extension);
Sampler(const Sampler&) = delete;
Sampler& operator=(const Sampler&) = delete;
Sampler(Sampler&&) = delete;
Sampler& operator=(Sampler&&) = delete;
~Sampler() = default;
void Initialize();
void Subsample(
const std::string& out_directory,
std::uint64_t reference_length,
std::uint64_t coverage);
void Split(const std::string& out_directory, std::uint64_t chunk_size);
private:
std::unique_ptr<bioparser::Parser<biosoup::Sequence>> sparser_;
std::uint64_t sequences_length_;
std::string base_name_;
std::string extension_;
};
} // namespace rampler
#endif // RAMPLER_SAMPLER_HPP_
| 21.830189 | 74 | 0.719101 | [
"vector"
] |
255cbdac1ed9af5f5e0e700923fe31b82451445b | 918 | cc | C++ | uva/chapter_5/377.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | uva/chapter_5/377.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | uva/chapter_5/377.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using ii = pair<int,int>;
using ll = long long;
using llu = unsigned long long;
const int INF = numeric_limits<int>::max();
int get_number() {
string s;
cin >> s;
int i = 0;
for (auto c : s) {
i *= 4;
switch (c) {
case 'V': i += 0; break;
case 'U': i += 1; break;
case 'C': i += 2; break;
case 'D': i += 3; break;
}
}
return i;
}
int main() {
int tcc;
cin >> tcc;
printf("COWCULATIONS OUTPUT\n");
while (tcc--) {
int a = get_number();
int b = get_number();
for (int i = 0; i < 3; i++) {
char c;
cin >> c;
switch (c) {
case 'A' : b += a; break;
case 'L': b *= 4; break;
case 'R': b /= 4; break;
}
}
if (get_number() == b) {
printf("YES\n");
} else {
printf("NO\n");
}
}
printf("END OF OUTPUT\n");
}
| 18.36 | 43 | 0.473856 | [
"vector"
] |
25627215e05a826d6f6d3c8b4fa131f984b05722 | 25,730 | cc | C++ | tools/vgm2rsf/vgm2rsf.cc | mehmetcanbudak/garvuino | a962c16ffb9ab23ec0f55cd25cc02412c3bdf262 | [
"Unlicense"
] | 14 | 2018-01-04T17:20:52.000Z | 2021-06-25T00:04:25.000Z | tools/vgm2rsf/vgm2rsf.cc | mehmetcanbudak/garvuino | a962c16ffb9ab23ec0f55cd25cc02412c3bdf262 | [
"Unlicense"
] | 4 | 2019-03-18T22:18:33.000Z | 2019-04-12T19:42:01.000Z | tools/vgm2rsf/vgm2rsf.cc | mehmetcanbudak/garvuino | a962c16ffb9ab23ec0f55cd25cc02412c3bdf262 | [
"Unlicense"
] | 3 | 2019-03-18T20:28:07.000Z | 2021-02-01T12:32:30.000Z | // Copyright Jean Pierre Cimalando 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <zlib.h>
#include <getopt.h>
#include <vector>
#include <string>
#include <memory>
#include <cmath>
#include <cstdio>
#include <cstdint>
#include <cstring>
///
struct FILE_delete { void operator()(FILE *x) const noexcept { fclose(x); } };
typedef std::unique_ptr<FILE, FILE_delete> FILE_u;
struct gzFile_delete { void operator()(gzFile x) const noexcept { gzclose(x); } };
typedef std::unique_ptr<gzFile_s, gzFile_delete> gzFile_u;
///
static uint32_t decode_u32(const uint8_t *data);
static uint16_t decode_u16(const uint8_t *data);
static void encode_u32(uint8_t *data, uint32_t x);
static void encode_u16(uint8_t *data, uint16_t x);
static bool read_u32(gzFile in, uint32_t *dst);
static bool read_u16(gzFile in, uint16_t *dst);
static bool write_u32(FILE *out, uint32_t src);
static bool write_u16(FILE *out, uint16_t src);
static bool write_u8(FILE *out, uint8_t src);
///
static std::string hhmmss(uint32_t sec);
///
struct AY_command { uint32_t delay; uint8_t reg; uint8_t val; };
static bool read_ay_vgm(gzFile in, uint32_t *clock, const char **chip_type, std::vector<AY_command> &ay_cmds);
static void make_vgm_size_table(uint8_t *table, unsigned version);
///
static void write_ay_rsf(FILE *out, const std::vector<AY_command> &in_cmds, uint32_t clock, uint32_t src_sample_rate, uint32_t rsf_frequency);
static uint32_t ay_quant(std::vector<AY_command> &cmds, uint32_t old_rate, uint32_t new_rate);
///
static std::vector<AY_command> convert_from_sn7x(const std::vector<AY_command> &sn_cmds, uint32_t src_clock, uint32_t dst_clock, bool convert_noise_channel);
///
static void show_help()
{
fprintf(stderr,
"Usage: vgm2rsf [-h] [-o <file.rsf>] [-f <frequency>] [-n] <file.vgm>\n"
" -h : show the help\n"
" -o <file.rsf> : output file in RSF3 format\n"
" -f <frequency> : interrupt frequency of result file (default 100 Hz)\n"
" -t <clock> : clock frequency of target chip if a conversion is required (default 2000000 Hz)\n"
" -n : don't convert the SN76489 noise channel using the multiplexing strategy\n"
" <file.vgm> : input file in VGM or VGZ format\n");
}
int main(int argc, char *argv[])
{
const char *file_out = nullptr;
uint16_t rsf_frequency = 100;
uint32_t target_clock = 2000000;
bool convert_noise_channel = true;
if (argc < 2) {
show_help();
return 0;
}
for (int c; (c = getopt(argc, argv, "o:f:t:nh")) != -1;) {
switch (c) {
case 'o':
file_out = optarg;
break;
case 'f': {
int arg = atoi(optarg);
if (arg < 1 || arg > 1000) {
fprintf(stderr, "frequency must be between 1 and 1000 Hz.\n");
return 1;
}
rsf_frequency = arg;
break;
}
case 't': {
int arg = atoi(optarg);
if (arg < 1000000 || arg > 2500000) {
fprintf(stderr, "target clock must be between 1000000 and 2500000 Hz.\n");
return 1;
}
target_clock = arg;
break;
}
case 'n':
convert_noise_channel = false;
break;
case 'h':
show_help();
return 0;
default:
show_help();
return 1;
}
}
if (argc - optind != 1) {
fprintf(stderr, "must specify exactly one input file.\n");
return 1;
}
///
const char *file_in = argv[optind];
gzFile in = gzopen(file_in, "rb");
if (!in) {
fprintf(stderr, "cannot open input file.\n");
return 1;
}
gzFile_u in_cleanup(in);
std::vector<AY_command> ay_cmds;
uint32_t clock;
const char *chip_type;
ay_cmds.reserve(1024);
if (!read_ay_vgm(in, &clock, &chip_type, ay_cmds)) {
fprintf(stderr, "cannot load the VGM file.\n");
return 1;
}
if (ay_cmds.empty()) {
fprintf(stderr, "input does not contain any AY commands.\n");
return 1;
}
uint32_t total_delay = 0;
for (const AY_command &cmd : ay_cmds)
total_delay += cmd.delay;
int vgm_sample_rate = 44100;
fprintf(stderr, "File: %s\n", file_in);
fprintf(stderr, "Output file: %s\n", file_out);
fprintf(stderr, "Chip: %s\n", chip_type);
fprintf(stderr, "Clock: %u\n", clock);
fprintf(stderr, "Sample rate: %u\n", vgm_sample_rate);
fprintf(stderr, "Total samples: %u\n", total_delay);
fprintf(stderr, "Duration: %s\n", hhmmss(total_delay / vgm_sample_rate).c_str());
fprintf(stderr, "Output frequency: %u\n", rsf_frequency);
if (!strncmp(chip_type, "SN7", 3)) {
fprintf(stderr, "[!] Conversion to AY8910 clocked at %u Hz\n", target_clock);
fprintf(stderr, "[!] Conversion of noise channel: %s\n", convert_noise_channel ? "yes" : "no");
ay_cmds = convert_from_sn7x(ay_cmds, clock, target_clock, convert_noise_channel);
clock = target_clock;
}
if (file_out) {
FILE *out = fopen(file_out, "wb");
if (!out) {
fprintf(stderr, "cannot open output file.\n");
return 1;
}
FILE_u out_cleanup(out);
write_ay_rsf(out, ay_cmds, clock, vgm_sample_rate, rsf_frequency);
if (fflush(out) != 0) {
fprintf(stderr, "cannot write output file.\n");
return 1;
}
}
return 0;
}
///
static uint32_t decode_u32(const uint8_t *data)
{
return data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
}
static uint16_t decode_u16(const uint8_t *data)
{
return data[0] | (data[1] << 8);
}
static void encode_u32(uint8_t *data, uint32_t x)
{
for (unsigned i = 0; i < 4; ++i)
data[i] = (x >> (8 * i)) & 0xFF;
}
static void encode_u16(uint8_t *data, uint16_t x)
{
for (unsigned i = 0; i < 2; ++i)
data[i] = (x >> (8 * i)) & 0xFF;
}
static bool read_u32(gzFile in, uint32_t *dst)
{
uint8_t tmp[4];
if (gzread(in, tmp, 4) != 4)
return false;
if (dst)
*dst = decode_u32(tmp);
return true;
}
static bool read_u16(gzFile in, uint16_t *dst)
{
uint8_t tmp[2];
if (gzread(in, tmp, 2) != 2)
return false;
if (dst)
*dst = decode_u16(tmp);
return true;
}
static bool write_u32(FILE *out, uint32_t src)
{
uint8_t tmp[4];
encode_u32(tmp, src);
return fwrite(tmp, 1, 4, out) == 4;
}
static bool write_u16(FILE *out, uint16_t src)
{
uint8_t tmp[2];
encode_u16(tmp, src);
return fwrite(tmp, 1, 2, out) == 2;
}
static bool write_u8(FILE *out, uint8_t src)
{
return fwrite(&src, 1, 1, out) == 1;
}
///
static std::string hhmmss(uint32_t sec)
{
char buf[32];
unsigned ss = sec;
unsigned hh = ss / 3600;
ss -= hh * 3600;
unsigned mm = ss / 60;
ss -= mm * 60;
sprintf(buf, "%02u:%02u:%02u", hh, mm, ss);
return buf;
}
///
static bool read_ay_vgm(gzFile in, uint32_t *clock, const char **chip_type, std::vector<AY_command> &ay_cmds)
{
uint8_t vgm_header[0x100];
uint32_t vgm_header_size;
int gzret = gzread(in, vgm_header, sizeof(vgm_header));
if (gzret == -1)
return false;
vgm_header_size = (uint32_t)gzret;
if (vgm_header_size < 0x40 || memcmp(vgm_header, "Vgm ", 4))
return false;
uint32_t vgm_version = decode_u32(vgm_header + 0x08);
uint8_t vgm_sizetable[0x100];
make_vgm_size_table(vgm_sizetable, vgm_version);
uint32_t data_offset = 0x0C;
if (vgm_version >= 0x150)
data_offset = decode_u32(vgm_header + 0x34);
if (data_offset == 0)
data_offset = 0x0C;
if (gzseek(in, 0x34 + data_offset, SEEK_SET) == -1)
return false;
vgm_header_size = 0x34 + data_offset;
if (vgm_header_size < sizeof(vgm_header))
memset(vgm_header + vgm_header_size, 0, sizeof(vgm_header) - vgm_header_size);
uint32_t clock_AY = 0;
uint32_t clock_YM2608 = 0;
uint32_t clock_YM2610 = 0;
uint32_t clock_YM2203 = 0;
uint32_t clock_SN76489 = 0;
if ((clock_AY = decode_u32(vgm_header + 0x74))) {
switch (vgm_header[0x78]) {
default: *chip_type = "AY unknown"; break;
case 0x00: *chip_type = "AY8910"; break;
case 0x01: *chip_type = "AY8912"; break;
case 0x02: *chip_type = "AY8913"; break;
case 0x03: *chip_type = "AY8930"; break;
case 0x10: *chip_type = "YM2149"; break;
case 0x11: *chip_type = "YM3439"; break;
case 0x12: *chip_type = "YMZ284"; break;
case 0x13: *chip_type = "YMZ294"; break;
}
*clock = clock_AY;
}
else if ((clock_YM2608 = decode_u32(vgm_header + 0x48))) {
*chip_type = "YM2608 PSG";
*clock = clock_YM2608 / 4;
}
else if ((clock_YM2610 = decode_u32(vgm_header + 0x4C))) {
*chip_type = "YM2610 PSG";
*clock = clock_YM2610 / 4;
}
else if ((clock_YM2203 = decode_u32(vgm_header + 0x44))) {
*chip_type = "YM2203 PSG";
*clock = clock_YM2203 / 2;
}
else if ((clock_SN76489 = decode_u32(vgm_header + 0x0C))) {
if (clock_SN76489 & (1u << 31))
return false;
*chip_type = "SN76489 PSG";
*clock = clock_SN76489;
}
else
return false; // no compatible device
// TODO dynamic YM PSG clock
uint32_t wait = 0;
for (bool end = false; !end;) {
uint8_t cmd = 0;
if (gzread(in, &cmd, 1) != 1) // premature end
break;
switch (cmd) {
default: {
uint8_t to_skip = vgm_sizetable[cmd];
if(to_skip != 0xFF) {
if (gzseek(in, to_skip, SEEK_CUR) == -1)
end = true; // premature end
}
else
end = true; // unrecognized command
break;
}
case 0x50: // SN76489
if (clock_SN76489) {
uint8_t sn_data[1];
if (gzread(in, sn_data, 1) != 1) // premature end
break;
AY_command ay;
ay.delay = wait;
ay.reg = sn_data[0];
ay.val = 0;
ay_cmds.push_back(ay);
wait = 0;
}
break;
case 0x61: {
uint16_t delay;
if (!read_u16(in, &delay))
end = true;
else
wait += delay;
break;
}
case 0x62:
wait += 735;
break;
case 0x63:
wait += 882;
break;
case 0x66: // end of sound data
end = true;
break;
case 0x67: // data block
{
uint32_t pcm_offset;
if (gzseek(in, 2, SEEK_CUR) == -1 || !read_u32(in, &pcm_offset) || gzseek(in, pcm_offset, SEEK_CUR) == -1)
end = true;
break;
}
case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77:
case 0x78: case 0x79: case 0x7a: case 0x7b: case 0x7c: case 0x7d: case 0x7e: case 0x7f:
wait += cmd - 0x6f;
break;
case 0xa0: // AY8190
if (clock_AY) {
uint8_t ay_data[2];
if (gzread(in, ay_data, 2) != 2) // premature end
break;
AY_command ay;
ay.delay = wait;
ay.reg = ay_data[0];
ay.val = ay_data[1];
ay_cmds.push_back(ay);
wait = 0;
}
break;
case 0x55: // YM2203
case 0x56: // YM2608 port 0
case 0x58: // YM2610 port 0
if ((clock_YM2203 && cmd == 0x55) || (clock_YM2608 && cmd == 0x56) || (clock_YM2610 && cmd == 0x58)) {
uint8_t ym_data[2];
if (gzread(in, ym_data, 2) != 2) // premature end
break;
if (ym_data[0] < 0x10) {
AY_command ay;
ay.delay = wait;
ay.reg = ym_data[0];
ay.val = ym_data[1];
ay_cmds.push_back(ay);
wait = 0;
}
}
break;
}
}
return true;
}
static void make_vgm_size_table(uint8_t *table, unsigned version)
{
memset(table, 0xFF, 0x100);
table[0x4F] = 1; // Game Gear PSG stereo, write dd to port 0x06
table[0x50] = 1; // PSG (SN76489/SN76496) write value dd
table[0x51] = 2; // YM2413, write value dd to register aa
table[0x52] = 2; // YM2612 port 0, write value dd to register aa
table[0x53] = 2; // YM2612 port 1, write value dd to register aa
table[0x54] = 2; // YM2151, write value dd to register aa
table[0x55] = 2; // YM2203, write value dd to register aa
table[0x56] = 2; // YM2608 port 0, write value dd to register aa
table[0x57] = 2; // YM2608 port 1, write value dd to register aa
table[0x58] = 2; // YM2610 port 0, write value dd to register aa
table[0x59] = 2; // YM2610 port 1, write value dd to register aa
table[0x5A] = 2; // YM3812, write value dd to register aa
table[0x5B] = 2; // YM3526, write value dd to register aa
table[0x5C] = 2; // Y8950, write value dd to register aa
table[0x5D] = 2; // YMZ280B, write value dd to register aa
table[0x5E] = 2; // YMF262 port 0, write value dd to register aa
table[0x5F] = 2; // YMF262 port 1, write value dd to register aa
table[0x61] = 2; // Wait n samples, n can range from 0 to 65535 (approx 1.49 seconds). Longer pauses than this are represented by multiple wait commands.
table[0x62] = 0; // wait 735 samples (60th of a second), a shortcut for 0x61 0xdf 0x02
table[0x63] = 0; // wait 882 samples (50th of a second), a shortcut for 0x61 0x72 0x03
table[0x66] = 0; // end of sound data
table[0x67] = /* variable size */0xFF; // data block: see below
table[0x68] = 11; // PCM RAM write: see below
for(unsigned a = 0x70; a <= 0x7F; ++a)
table[a] = 0; // wait n+1 samples, n can range from 0 to 15.
for(unsigned a = 0x80; a <= 0x8F; ++a)
table[a] = 0; // YM2612 port 0 address 2A write from the data bank, then wait n samples; n can range from 0 to 15. Note that the wait is n, NOT n+1. See also command 0xE0.
table[0x90] = 4; // Setup Stream Control
table[0x91] = 4; // Set Stream Data
table[0x92] = 5; // Set Stream Frequency
table[0x93] = 10; // Start Stream
table[0x94] = 1; // Stop Stream
table[0x95] = 4; // Start Stream (fast call)
table[0xA0] = 2; // AY8910, write value dd to register aa
table[0xB0] = 2; // RF5C68, write value dd to register aa
table[0xB1] = 2; // RF5C164, write value dd to register aa
table[0xB2] = 2; // PWM, write value ddd to register a (d is MSB, dd is LSB)
table[0xB3] = 2; // GameBoy DMG, write value dd to register aa
table[0xB4] = 2; // NES APU, write value dd to register aa
table[0xB5] = 2; // MultiPCM, write value dd to register aa
table[0xB6] = 2; // uPD7759, write value dd to register aa
table[0xB7] = 2; // OKIM6258, write value dd to register aa
table[0xB8] = 2; // OKIM6295, write value dd to register aa
table[0xB9] = 2; // HuC6280, write value dd to register aa
table[0xBA] = 2; // K053260, write value dd to register aa
table[0xBB] = 2; // Pokey, write value dd to register aa
table[0xBC] = 2; // WonderSwan, write value dd to register aa
table[0xBD] = 2; // SAA1099, write value dd to register aa
table[0xBE] = 2; // ES5506, write value dd to register aa
table[0xBF] = 2; // GA20, write value dd to register aa
table[0xC0] = 3; // Sega PCM, write value dd to memory offset aabb
table[0xC1] = 3; // RF5C68, write value dd to memory offset aabb
table[0xC2] = 3; // RF5C164, write value dd to memory offset aabb
table[0xC3] = 3; // MultiPCM, write set bank offset aabb to channel cc
table[0xC4] = 3; // QSound, write value mmll to register rr (mm - data MSB, ll - data LSB)
table[0xC5] = 3; // SCSP, write value dd to memory offset mmll (mm - offset MSB, ll - offset LSB)
table[0xC6] = 3; // WonderSwan, write value dd to memory offset mmll (mm - offset MSB, ll - offset LSB)
table[0xC7] = 3; // VSU, write value dd to memory offset mmll (mm - offset MSB, ll - offset LSB)
table[0xC8] = 3; // X1-010, write value dd to memory offset mmll (mm - offset MSB, ll - offset LSB)
table[0xD0] = 3; // YMF278B, port pp, write value dd to register aa
table[0xD1] = 3; // YMF271, port pp, write value dd to register aa
table[0xD2] = 3; // SCC1, port pp, write value dd to register aa
table[0xD3] = 3; // K054539, write value dd to register ppaa
table[0xD4] = 3; // C140, write value dd to register ppaa
table[0xD5] = 3; // ES5503, write value dd to register ppaa
table[0xD6] = 3; // ES5506, write value aadd to register pp
table[0xE0] = 4; // Seek to offset dddddddd (Intel byte order) in PCM data bank of data block type 0 (YM2612).
table[0xE1] = 4; // C352, write value aadd to register mmll
for(unsigned a = 0x30; a <= 0x3F; ++a)
table[a] = 1; // one operand, reserved for future use
for(unsigned a = 0x40; a <= 0x4E; ++a)
{
if(version >= 0x160)
table[a] = 2; // two operands, reserved for future use
else
table[a] = 1; // was one operand only til v1.60
}
for(unsigned a = 0xA1; a <= 0xAF; ++a)
table[a] = 2; // two operands, reserved for future use
for(unsigned a = 0xC9; a <= 0xCF; ++a)
table[a] = 3; // three operands, reserved for future use
for(unsigned a = 0xD7; a <= 0xDF; ++a)
table[a] = 3; // three operands, reserved for future use
for(unsigned a = 0xE2; a <= 0xFF; ++a)
table[a] = 4; // four operands, reserved for future use
}
static void write_ay_rsf(FILE *out, const std::vector<AY_command> &in_cmds, uint32_t clock, uint32_t src_sample_rate, uint32_t rsf_frequency)
{
std::vector<AY_command> rsf_cmds = in_cmds;
uint32_t frame_count = ay_quant(rsf_cmds, src_sample_rate, rsf_frequency);
off_t pos_begin = ftello(out);
fwrite("RSF\x03", 1, 4, out);
write_u16(out, rsf_frequency);
off_t pos_song_offset = ftello(out);
write_u16(out, 0); // write later: song offset
write_u32(out, frame_count);
write_u32(out, 0); // TODO: loop frame
write_u32(out, clock);
char title[] = "";
char author[] = "";
char comment[] = "";
fwrite(title, 1, strlen(title) + 1, out);
fwrite(author, 1, strlen(author) + 1, out);
fwrite(comment, 1, strlen(comment) + 1, out);
off_t pos_song_begin = ftello(out);
uint8_t ay_regs[16] = {};
for (size_t i = 0, n = rsf_cmds.size(); i < n; ++i) {
const AY_command *cmd = &rsf_cmds[i];
uint32_t delay = cmd->delay;
if (delay > 1) {
--delay;
while (delay > 0) {
uint32_t current = (delay < 0x100) ? delay : 0xFF;
fputc(0xFE, out);
fputc(current, out);
delay -= current;
}
}
uint8_t ay_old_regs[14];
memcpy(ay_old_regs, ay_regs, 14);
if (cmd->reg < 14)
ay_regs[cmd->reg] = cmd->val;
while (i + 1 < n && rsf_cmds[i + 1].delay == 0) {
cmd = &rsf_cmds[++i];
if (cmd->reg < 14)
ay_regs[cmd->reg] = cmd->val;
}
uint16_t reg_mask = 0;
for (unsigned i = 0; i < 14; ++i) {
if (ay_regs[i] != ay_old_regs[i])
reg_mask |= 1 << i;
}
write_u8(out, reg_mask >> 8);
write_u8(out, reg_mask & 0xFF);
for (unsigned i = 0; i < 14; ++i) {
if (reg_mask & (1 << i))
write_u8(out, ay_regs[i]);
}
}
fseeko(out, pos_song_offset, SEEK_SET);
write_u16(out, pos_song_begin - pos_begin);
}
static uint32_t ay_quant(std::vector<AY_command> &cmds, uint32_t old_rate, uint32_t new_rate)
{
uint32_t total_frames = 0;
double acc_delay = 0;
double old_interval = 1.0 / old_rate;
double new_interval = 1.0 / new_rate;
for (AY_command &cmd : cmds) {
acc_delay += cmd.delay * old_interval;
uint32_t frames = acc_delay * new_rate;
acc_delay -= frames * new_interval;
cmd.delay = frames;
total_frames += frames;
}
return total_frames;
}
static std::vector<AY_command> convert_from_sn7x(const std::vector<AY_command> &sn_cmds, uint32_t src_clock, uint32_t dst_clock, bool convert_noise_channel)
{
std::vector<AY_command> ay_cmds;
uint32_t acc_delay = 0;
auto push_command = [&](uint8_t reg, uint8_t val) {
AY_command ay_cmd;
ay_cmd.delay = acc_delay;
ay_cmd.reg = reg;
ay_cmd.val = val;
ay_cmds.push_back(ay_cmd);
acc_delay = 0;
};
auto push_set_frequency = [&](uint8_t channel, double freq) {
unsigned long dst_tone = lround(dst_clock / (16 * freq));
dst_tone = (dst_tone < 0xFFF) ? dst_tone : 0xFFF;
push_command(2 * channel, dst_tone & 0xFF); // fine tone
push_command(2 * channel + 1, dst_tone >> 8); // rough tone
};
unsigned latch_typ = 0; /* 0=volume 1=tone */
unsigned latch_chn = 0; /* 0-3=channel */
uint16_t sn7_volregs[4] = {0,0,0,0}; /* [0-3]=channel, 10-bit register */
uint16_t sn7_toneregs[4] = {0,0,0,0}; /* [0-3]=channel, 10-bit register */
/*
About noise channel:
SN7x can play noise on the 4th channel independently of 3 tone channels.
AY can play 3 channels only, and one of the channels must be toggled to
enter noise mode; it cannot perform on 4 simultaneous channels.
--- Conversion strategy ---
Multiplex the 3rd AY channel: when noise starts, switch the channel C
to noise mode. As soon as noise volume drops to silence, switch channel
back to tone mode and restore volume.
*/
const unsigned multiplex_channel = 2;
enum {
mix_ch3tone = 0x38,
mix_ch3noise = 0x1c,
};
unsigned current_mix = mix_ch3tone;
auto push_set_noise = [&](uint8_t channel, uint8_t noise) {
if (noise & 4) // white noise
push_command(6, 0x1F/*ADJUST-ME*/);
else // periodic noise
push_command(6, 0x0F/*ADJUST-ME*/);
const double rate_table[4] = /*ADJUST-ME*/
{ 50, 100, 500, 1000 /* au hasard :^) */ };
push_set_frequency(multiplex_channel, rate_table[noise & 3]);
};
// disable noise channels
push_command(7, current_mix);
// set noise frequency
if (convert_noise_channel)
push_set_noise(multiplex_channel, 0);
for (const AY_command &sn_cmd : sn_cmds) {
uint16_t *reg;
acc_delay += sn_cmd.delay;
if (sn_cmd.reg & 128) { // latch & set low bits
latch_typ = (sn_cmd.reg >> 4) & 1;
latch_chn = (sn_cmd.reg >> 5) & 3;
reg = latch_typ ? &sn7_volregs[latch_chn] : &sn7_toneregs[latch_chn];
*reg = (*reg & 0x3F0) | (sn_cmd.reg & 0x00F);
}
else { // set high bits
reg = latch_typ ? &sn7_volregs[latch_chn] : &sn7_toneregs[latch_chn];
*reg = (*reg & 0x00F) | ((sn_cmd.reg & 0x3f) << 4);
}
if (latch_typ && latch_chn < 3) { // set volume
push_command(8 + latch_chn, 0xF - (*reg & 0xF));
}
else if (latch_typ) { // set noise volume
if (convert_noise_channel) {
if ((*reg & 0xF) < 0xF) { // noise on
if (current_mix != mix_ch3noise) {
current_mix = mix_ch3noise;
push_command(7, current_mix);
}
push_set_noise(multiplex_channel, sn7_toneregs[3]);
push_command(8 + multiplex_channel, 0xF - (*reg & 0xF));
}
else { // noise off
if (current_mix != mix_ch3tone) {
current_mix = mix_ch3tone;
push_command(7, current_mix);
}
push_command(8 + multiplex_channel, 0xF - (sn7_volregs[multiplex_channel] & 0xF));
double freq = (double)src_clock / (32 * sn7_toneregs[multiplex_channel]);
push_set_frequency(multiplex_channel, freq);
}
}
}
else if (latch_chn < 3) { // set tone
double freq = (double)src_clock / (32 * *reg);
push_set_frequency(latch_chn, freq);
}
else { // set noise tone
if (convert_noise_channel) {
if (current_mix == mix_ch3noise)
push_set_noise(multiplex_channel, *reg);
}
}
}
return ay_cmds;
}
| 35.489655 | 180 | 0.558531 | [
"vector"
] |
256fa559b24ed1b5afbc2545148d67731273f0e4 | 14,316 | cpp | C++ | cpp/G3M/EllipsoidShape.cpp | glob3mobile/g3m | 2b2c6422f05d13e0855b1dbe4e0afed241184193 | [
"BSD-2-Clause"
] | 70 | 2015-02-06T14:39:14.000Z | 2022-01-07T08:32:48.000Z | cpp/G3M/EllipsoidShape.cpp | glob3mobile/g3m | 2b2c6422f05d13e0855b1dbe4e0afed241184193 | [
"BSD-2-Clause"
] | 118 | 2015-01-21T10:18:00.000Z | 2018-10-16T15:00:57.000Z | cpp/G3M/EllipsoidShape.cpp | glob3mobile/g3m | 2b2c6422f05d13e0855b1dbe4e0afed241184193 | [
"BSD-2-Clause"
] | 41 | 2015-01-10T22:29:27.000Z | 2021-06-08T11:56:16.000Z | //
// EllipsoidShape.cpp
// G3M
//
// Created by Agustin Trujillo Pino on 02/13/13.
//
//
#include "EllipsoidShape.hpp"
#include "ShortBufferBuilder.hpp"
#include "IndexedMesh.hpp"
#include "GLConstants.hpp"
#include "CompositeMesh.hpp"
#include "Color.hpp"
#include "FloatBufferBuilderFromGeodetic.hpp"
#include "FloatBufferBuilderFromCartesian2D.hpp"
#include "FloatBufferBuilderFromCartesian3D.hpp"
#include "IDownloader.hpp"
#include "IImageDownloadListener.hpp"
#include "TexturesHandler.hpp"
#include "TexturedMesh.hpp"
#include "Sector.hpp"
#include "MercatorUtils.hpp"
#include "TextureIDReference.hpp"
#include "SimpleTextureMapping.hpp"
#include "G3MRenderContext.hpp"
#include "TimeInterval.hpp"
#include "IImage.hpp"
#include "EllipsoidalPlanet.hpp"
#include "IMathUtils.hpp"
#include "Geodetic3D.hpp"
EllipsoidShape::EllipsoidShape(Geodetic3D* position,
AltitudeMode altitudeMode,
const Vector3D& radius,
short resolution,
float borderWidth,
bool texturedInside,
bool mercator,
const Color& surfaceColor,
Color* borderColor,
bool withNormals) :
AbstractMeshShape(position, altitudeMode),
_radius(radius),
_oneOverRadiiSquared(Vector3D(1.0 / (radius._x * radius._x ),
1.0 / (radius._y * radius._y),
1.0 / (radius._z * radius._z))),
// _quadric(Quadric::fromEllipsoid(_ellipsoid)),
_textureURL(URL("", false)),
_resolution(resolution < 3 ? 3 : resolution),
_borderWidth(borderWidth),
_texturedInside(texturedInside),
_mercator(mercator),
_surfaceColor(new Color(surfaceColor)),
_borderColor(borderColor),
_textureRequested(false),
_textureImage(NULL),
_withNormals(withNormals),
_texID(NULL),
_depthTest(true),
_cullFace(false),
_culledFace(GLCullFace::back())
{
}
EllipsoidShape::EllipsoidShape(Geodetic3D* position,
AltitudeMode altitudeMode,
const Planet* planet,
const URL& textureURL,
const Vector3D& radius,
short resolution,
float borderWidth,
bool texturedInside,
bool mercator,
bool withNormals) :
AbstractMeshShape(position, altitudeMode),
_radius(radius),
_oneOverRadiiSquared(Vector3D(1.0 / (radius._x * radius._x ),
1.0 / (radius._y * radius._y),
1.0 / (radius._z * radius._z))),
_textureURL(textureURL),
_resolution(resolution < 3 ? 3 : resolution),
_borderWidth(borderWidth),
_texturedInside(texturedInside),
_mercator(mercator),
_surfaceColor(NULL),
_borderColor(NULL),
_textureRequested(false),
_textureImage(NULL),
_withNormals(withNormals),
_texID(NULL),
_depthTest(true),
_cullFace(false),
_culledFace(GLCullFace::back())
{
}
void EllipsoidShape::setSurfaceColor(const Color& surfaceColor) {
delete _surfaceColor;
_surfaceColor = new Color(surfaceColor);
cleanMesh();
}
void EllipsoidShape::setDepthTest(bool depthTest) {
if (_depthTest != depthTest) {
_depthTest = depthTest;
cleanMesh();
}
}
void EllipsoidShape::setCullFace(bool cullFace) {
if (_cullFace != cullFace) {
_cullFace = cullFace;
cleanMesh();
}
}
void EllipsoidShape::setCulledFace(int culledFace) {
if (_culledFace != culledFace) {
_culledFace = culledFace;
cleanMesh();
}
}
EllipsoidShape::~EllipsoidShape() {
delete _surfaceColor;
delete _borderColor;
delete _texID; //Releasing texture
#ifdef JAVA_CODE
super.dispose();
#endif
}
const TextureIDReference* EllipsoidShape::getTextureID(const G3MRenderContext* rc) {
if (_texID == NULL) {
if (_textureImage == NULL) {
return NULL;
}
_texID = rc->getTexturesHandler()->getTextureIDReference(_textureImage,
GLFormat::rgba(),
_textureURL._path,
false,
GLTextureParameterValue::clampToEdge(),
GLTextureParameterValue::clampToEdge());
delete _textureImage;
_textureImage = NULL;
}
if (_texID == NULL) {
rc->getLogger()->logError("Can't load texture %s", _textureURL._path.c_str());
}
if (_texID == NULL) {
return NULL;
}
return _texID->createCopy(); //The copy will be handle by the TextureMapping
}
Mesh* EllipsoidShape::createBorderMesh(const G3MRenderContext* rc,
FloatBufferBuilderFromGeodetic* vertices) {
// create border indices for horizontal lines
ShortBufferBuilder indices;
short delta = (short) (2*_resolution - 1);
for (short j=1; j<_resolution-1; j++) {
for (short i=0; i<2*_resolution-2; i++) {
indices.add((short) (i+j*delta));
indices.add((short) (i+1+j*delta));
}
}
// create border indices for vertical lines
for (short i=0; i<2*_resolution-2; i++) {
for (short j=0; j<_resolution-1; j++) {
indices.add((short) (i+j*delta));
indices.add((short) (i+(j+1)*delta));
}
}
Color* borderColor;
if (_borderColor != NULL) {
borderColor = new Color(*_borderColor);
}
else {
if (_surfaceColor != NULL) {
borderColor = new Color(*_surfaceColor);
}
else {
borderColor = Color::newFromRGBA(1, 0, 0, 1);
}
}
return new IndexedMesh(GLPrimitive::lines(),
vertices->getCenter(),
vertices->create(),
true,
indices.create(),
true,
(_borderWidth < 1) ? 1 : _borderWidth,
1,
borderColor);
}
Mesh* EllipsoidShape::createSurfaceMesh(const G3MRenderContext* rc,
FloatBufferBuilderFromGeodetic* vertices,
FloatBufferBuilderFromCartesian2D* texCoords,
FloatBufferBuilderFromCartesian3D* normals) {
// create surface indices
ShortBufferBuilder indices;
short delta = (short) (2*_resolution - 1);
// create indices for textupe mapping depending on the flag _texturedInside
if (!_texturedInside) {
for (short j=0; j<_resolution-1; j++) {
if (j>0) indices.add((short) (j*delta));
for (short i=0; i<2*_resolution-1; i++) {
indices.add((short) (i+j*delta));
indices.add((short) (i+(j+1)*delta));
}
indices.add((short) ((2*_resolution-2)+(j+1)*delta));
}
}
else {
for (short j=0; j<_resolution-1; j++) {
if (j>0) indices.add((short) ((j+1)*delta));
for (short i=0; i<2*_resolution-1; i++) {
indices.add((short) (i+(j+1)*delta));
indices.add((short) (i+j*delta));
}
indices.add((short) ((2*_resolution-2)+j*delta));
}
}
// create mesh
const Color* surfaceColor = (_surfaceColor == NULL) ? NULL : new Color(*_surfaceColor);
Mesh* im = new IndexedMesh(GLPrimitive::triangleStrip(), // const int primitive,
vertices->getCenter(), // const Vector3D& center,
vertices->create(), // IFloatBuffer* vertices,
true, // bool ownsVertices,
indices.create(), // IShortBuffer* indices,
true, // bool ownsIndices,
(_borderWidth < 1) ? 1 : _borderWidth, // float lineWidth = 1,
1, // float pointSize = 1,
surfaceColor, // const Color* flatColor = NULL,
NULL, // IFloatBuffer* colors = NULL,
_depthTest, // bool depthTest = true,
_withNormals ? normals->create() : NULL, // IFloatBuffer* normals = NULL,
false, // bool polygonOffsetFill = false,
0, // float polygonOffsetFactor = 0,
0, // float polygonOffsetUnits = 0,
_cullFace, // bool cullFace = false,
_culledFace // int culledFace = GLCullFace::back()
);
const TextureIDReference* texID = getTextureID(rc);
if (texID == NULL) {
return im;
}
TextureMapping* texMap = new SimpleTextureMapping(texID,
texCoords->create(),
true,
true);
return new TexturedMesh(im, true, texMap, true, true);
}
class EllipsoidShape_IImageDownloadListener : public IImageDownloadListener {
private:
EllipsoidShape* _ellipsoidShape;
public:
EllipsoidShape_IImageDownloadListener(EllipsoidShape* ellipsoidShape) :
_ellipsoidShape(ellipsoidShape)
{
}
void onDownload(const URL& url,
IImage* image,
bool expired) {
_ellipsoidShape->imageDownloaded(image);
}
void onError(const URL& url) {
}
void onCancel(const URL& url) {
}
void onCanceledDownload(const URL& url,
IImage* image,
bool expired) {
}
};
void EllipsoidShape::imageDownloaded(IImage* image) {
_textureImage = image;
cleanMesh();
}
Mesh* EllipsoidShape::createMesh(const G3MRenderContext* rc) {
if (!_textureRequested) {
_textureRequested = true;
if (_textureURL._path.length() != 0) {
rc->getDownloader()->requestImage(_textureURL,
1000000,
TimeInterval::fromDays(30),
true,
new EllipsoidShape_IImageDownloadListener(this),
true);
}
}
const EllipsoidalPlanet ellipsoid(Ellipsoid(Vector3D::ZERO, _radius));
const Sector sector(Sector::FULL_SPHERE);
FloatBufferBuilderFromGeodetic* vertices = FloatBufferBuilderFromGeodetic::builderWithGivenCenter(&ellipsoid, Vector3D::ZERO);
FloatBufferBuilderFromCartesian2D texCoords;
FloatBufferBuilderFromCartesian3D* normals = FloatBufferBuilderFromCartesian3D::builderWithoutCenter();
const short resolution2Minus2 = (short) (2*_resolution-2);
const short resolutionMinus1 = (short) (_resolution-1);
for (int j = 0; j < _resolution; j++) {
for (int i = 0; i < 2*_resolution-1; i++) {
const double u = (double) i / resolution2Minus2;
const double v = (double) j / resolutionMinus1;
const Geodetic2D innerPoint = sector.getInnerPoint(u, v);
vertices->add(innerPoint);
if (_withNormals) {
Vector3D n = ellipsoid.geodeticSurfaceNormal(innerPoint);
normals->add(n);
}
const double vv = _mercator ? MercatorUtils::getMercatorV(innerPoint._latitude) : v;
texCoords.add((float) u, (float) vv);
}
}
Mesh* surfaceMesh = createSurfaceMesh(rc, vertices, &texCoords, normals);
Mesh* resultMesh;
if (_borderWidth > 0) {
CompositeMesh* compositeMesh = new CompositeMesh();
compositeMesh->addMesh(surfaceMesh);
compositeMesh->addMesh(createBorderMesh(rc, vertices));
resultMesh = compositeMesh;
}
else {
resultMesh = surfaceMesh;
}
delete vertices;
delete normals;
return resultMesh;
}
std::vector<double> EllipsoidShape::intersectionsDistances(const Planet* planet,
const Vector3D& origin,
const Vector3D& direction) const {
const Vector3D m = origin.sub( planet->toCartesian(getPosition()) );
std::vector<double> result;
// By laborious algebraic manipulation....
const double a = (direction._x * direction._x * _oneOverRadiiSquared._x +
direction._y * direction._y * _oneOverRadiiSquared._y +
direction._z * direction._z * _oneOverRadiiSquared._z);
const double b = 2.0 * (m._x * direction._x * _oneOverRadiiSquared._x +
m._y * direction._y * _oneOverRadiiSquared._y +
m._z * direction._z * _oneOverRadiiSquared._z);
const double c = (m._x * m._x * _oneOverRadiiSquared._x +
m._y * m._y * _oneOverRadiiSquared._y +
m._z * m._z * _oneOverRadiiSquared._z - 1.0);
// Solve the quadratic equation: ax^2 + bx + c = 0.
// Algorithm is from Wikipedia's "Quadratic equation" topic, and Wikipedia credits
// Numerical Recipes in C, section 5.6: "Quadratic and Cubic Equations"
const double discriminant = b * b - 4 * a * c;
if (discriminant < 0.0) {
// no intersections
}
else if (discriminant == 0.0) {
// one intersection at a tangent point
result.push_back(-0.5 * b / a);
}
else {
const double t = -0.5 * (b + (b > 0.0 ? 1.0 : -1.0) * IMathUtils::instance()->sqrt(discriminant));
const double root1 = t / a;
const double root2 = c / t;
// Two intersections - return the smallest first.
if (root1 < root2) {
result.push_back(root1);
result.push_back(root2);
}
else {
result.push_back(root2);
result.push_back(root1);
}
}
return result;
}
| 32.684932 | 128 | 0.55176 | [
"mesh",
"vector"
] |
25727e7c2985b2a75b34d295b2d0a83295162fac | 26,621 | cpp | C++ | Projects/Lab7-math-tutor/math-tutor-main.cpp | jesushilarioh/DelMarCSi.cpp | 6dd7905daea510452691fd25b0e3b0d2da0b06aa | [
"MIT"
] | 3 | 2019-02-02T16:59:48.000Z | 2019-02-28T14:50:08.000Z | Projects/Lab7-math-tutor/math-tutor-main.cpp | jesushilariohernandez/DelMarCSi.cpp | 6dd7905daea510452691fd25b0e3b0d2da0b06aa | [
"MIT"
] | null | null | null | Projects/Lab7-math-tutor/math-tutor-main.cpp | jesushilariohernandez/DelMarCSi.cpp | 6dd7905daea510452691fd25b0e3b0d2da0b06aa | [
"MIT"
] | 4 | 2020-04-10T17:22:17.000Z | 2021-11-04T14:34:00.000Z | //******************************************************************
//
// JESUS HILARIO HERNANDEZ
// Course: COSC 1436.001 Programming Fundamentals 1
// Lab # 7 Math Tutor
// Due Date: November 6, 2016
// Instructor: Korinne Caruso
//
// PURPOSE: This program functions as a math tutor to students in
// the elementary - middle school range. This program will have
// a menu selection to choose from that will include: addition
// practice, subtraction practice, multiplication practice, division
// practice, calculating the area of a triangle, the area of a circle,
// and the area of a rectangle.
//
// INPUT: Input for calculating the area selections will require the
// user to input information through the cin object. Input will then
// be checked to be sure that valid data is input at the keyboard.
//
// OUTPUT: For the practice selctions, random numbers will be
// displayed, answered, and sent to an exeternal file. For the
// calculation selections the area of an object will be calculated,
// displayed, and then sent to an external file.
//
//******************************************************************
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib> // For rand and srand
#include <ctime> // For the time function
using namespace std;
// Directives for clearing the screen
#ifdef _WIN32
char buffer[4] = "cls";
const char* clearVar = buffer;
#ifdef _WIN64
char buffer[4] = "cls";
const char* clearVar = buffer;
#endif
#else
char buffer[6] = "clear";
const char* clearVar = buffer;
#endif
// Global Constants for menu selection.
const int CHOICE_1 = 1,
CHOICE_2 = 2,
CHOICE_3 = 3,
CHOICE_4 = 4,
CHOICE_5 = 5,
CHOICE_6 = 6,
CHOICE_7 = 7,
CHOICE_8 = 8;
// Function Prototypes
bool inputVal(bool); // Error Checking
int menu(int); // Menu
bool additionPractice(); // Addition Practice
bool subtractionPractice(); // Subtraction Practice
bool multiplicationPractice(); // Multiplication practice
bool divisionPractice(); // Division practice
bool calculateAreaOfRectangle(); // Calculate area of rectangle
bool calculateAreaOfCircle(); // Calculate area of circle
bool calculateAreaOfTriangle(); // Calculate area of triangle
void clearScreen(); // Clear screen
int inputVal(int); // Error Checking
double inputVal(double); // Error Checking
int main()
{
// Get the system time.
unsigned seed = time(0);
// Seed the random number generator.
srand(seed);
// Constant
const string SHUTDOWN = "CarusoShutDown"; // To shutdown program
// Variables
int menuSelection; // Holds Menu Selection
string teacherPass; // Holds Shudown Password
// Do While used to iterate menu
do
{
clearScreen();
// Display Menu, receive user input
menuSelection = menu(menuSelection);
cout << endl << endl;
// Switch used as menu
switch (menuSelection)
{
case CHOICE_1:
additionPractice(); // Calling additionPractice function
break;
case CHOICE_2:
subtractionPractice(); // Calling subtractionPractice function
break;
case CHOICE_3:
multiplicationPractice(); // Calling multiplicationPractice function
break;
case CHOICE_4:
divisionPractice(); // Calling divisionPractice function
break;
case CHOICE_5:
calculateAreaOfRectangle(); // Calling calculateAreaOfRectangle function
break;
case CHOICE_6:
calculateAreaOfCircle(); // Calling acalculateAreaOfCircle function
break;
case CHOICE_7:
calculateAreaOfTriangle(); // Calling calculateAreaOfTriangle function
break;
case CHOICE_8:
// Clear Screen
clearScreen();
// Ask for password, recieve password
cout << "Password please: ";
cin >> teacherPass;
// If statement checks for valid password.
if (teacherPass != SHUTDOWN)
{
int tries = 4;
for (int num = 0; num < 4; num++)
{
cout << "I'm sorry wrong password." << endl
<< "You have " << tries << " more tries: ";
cin >> teacherPass;
tries--;
if (teacherPass == SHUTDOWN)
{
break;
}
}
}
}
} while (!(teacherPass == SHUTDOWN));
// End program valediction
cout << "Ending Program...\n";
cout << "Program ended." << endl << endl;
return 0;
}
//*******************************************************
// The inputVal Function check for valid input. In *
// this case a boolean must be enter as valid input. *
// The user will be promted to enter valid data if *
// they've entered invalid data. *
//*******************************************************
bool inputVal(bool num)
{
while (!(cin >> num))
{
cout << "\nI'm sorry either a 1 or a 0 \n"
<< "must be entered to proceed: ";
cin.clear();
cin.ignore(123, '\n');
}
return num;
}
//*******************************************************************
// Function menu displays the main menu, receives user selection, *
// and checks for valid input. *
//*******************************************************************
int menu(int num)
{
cout << "\t-----------------------------------------------------\n"
<< "\t\t\tWelcome to Math Tutor!\n"
<< "\t-----------------------------------------------------\n\n"
<< "\tChoose from the menu to continue: \n\n"
<< "\t\t1. Practice Addition \n"
<< "\t\t2. Practice Subtraction \n"
<< "\t\t3. Practice Multiplication\n"
<< "\t\t4. Practice Division\n"
<< "\t\t5. Calculate the Area of a Rectangle\n"
<< "\t\t6. Calculate the Area of a Circle\n"
<< "\t\t7. Calculate the Area of a Triangle\n"
<< "\t\t8. Program Shutdown ";
while (!(cin >> num && num <= CHOICE_8 && num >= CHOICE_1))
{
cout << "I'm sorry, choose a number from the menu: ";
cin.clear();
cin.ignore(123, '\n');
}
return num;
}
//***************************************************************
// The additionPractice function shows a random addition *
// problem, asks for user input, and returns a boolean value. *
//***************************************************************
bool additionPractice()
{
// File object
ofstream outputFile;
// Open outputFile
outputFile.open("MathTutorRecord.txt");
//Varable
bool anotherProb;
// Another problem? Do While
do
{
// Constants
const int MIN_VALUE = 0; // Minimum value
const int MAX_VALUE = 9; // Maximum value
// Variables
int num1; // Holds a value
int num2; // Holds a value
int sum, answer;
// Assigning a random number to num1
num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
// Assigning a random number to num2
num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
// Summing random num1 and num2
sum = num1 + num2;
// Clear Screen
clearScreen();
// Display problem
cout << num1 << " + " << num2 << endl;
cout << "\nType in your answer: ";
// Receive answer
answer = inputVal(answer);
// Process answer
do
{
// If right answer
if (answer == sum)
{
cout << "\nGreat work!\n" << endl;
}
// Else wrong answer
else
{
cout << "\nNot correct, hopefully this will help...\n" << endl;
cout << "\tIf I have " << num1 ;
// If num1 is 1, use singular
if (num1 == 1)
{
cout << " pencil";
}
// Else use plural
else
{
cout << " pencils";
}
cout << " and " << num2;
// If num2 is 1 use singular
if (num2 == 1)
{
cout << " pen";
}
// Else use plural
else
{
cout << " pens";
}
cout << endl
// Ask for answer to problem
<< "\thow many pens and pencils do I have altogether? ";
// Error Check answer
answer = inputVal(answer);
// If answer correct
if (answer == sum)
{
cout << "\nGreat work!\n" << endl;
}
}
// End Process answeer Do While
} while (answer != sum);
// Write to outputFile
outputFile << num1 << " + " << num2 << " = " << sum << endl;
// Ask if would like another problem
cout << "\nWould you like another addition problem?\n"
<< "1. Yes.\n"
<< "0. No. Return to main menu ";
// Error Check
anotherProb = inputVal(anotherProb);
cout << endl;
// Clear Screen
clearScreen();
// End of Another problem? Do While
} while (anotherProb == true);
// Close outputfile
outputFile.close();
// Return boolean value either to
// main menu or another problem.
return anotherProb;
}
//***************************************************************
// The subtractionPractice function shows a random subtraction *
// problem, asks for user input, and returns a boolean value. *
//***************************************************************
bool subtractionPractice()
{
// Output file stream object
ofstream outputFile;
// Open outputFile
outputFile.open("MathTutorRecord.txt");
// Variable
bool anotherProb;
// Another problem? Do While
do
{
const int MIN_VALUE = 0; // Minimum value
const int MAX_VALUE = 9; // Maximum value
// Variables
int num1; // Holds a value
int num2; // Holds a value
int sum, answer;
// Assign random value to num1
num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
// Assign random value to num2
num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
// Sum of num1 and num2
sum = num1 - num2;
// Clear Screen
clearScreen();
// Display problem
cout << num1 << " - " << num2 << endl;
// Ask for a receive answer
cout << "\nType in your answer: ";
// Error Check answer
answer = inputVal(answer);
// Process answer
do
{
// If right answer
if (answer == sum)
{
cout << "\nGreat work!\n" << endl;
}
// Else wrong answer
else
{
cout << "\nSorry, hopefully this will help...\n" << endl;
cout << "\tIf I have " << num1 ;
// If num1 is 1, use singular
if (num1 == 1)
{
cout << " pencil";
}
// Else use plural
else
{
cout << " pencils";
}
cout << " and " << num2;
// If num2 is 1, use singular
if (num2 == 1)
{
cout << " pen";
}
// Else use plural
else
{
cout << " pens";
}
// Ask for answer to problem
cout << endl
<< "\tand subtract them from each other,\n"
<< "\thow many do I have? ";
// Error Check answer
answer = inputVal(answer);
// If answer correct
if (answer == sum)
{
cout << "\nGreat work!\n" << endl;
}
}
// End Process answeer Do While
} while (answer != sum);
// Write data to outputFile
outputFile << num1 << " - " << num2 << " = "<< sum << endl;
// Ask if would like another problem
cout << "\nWould you like another subtraction problem?\n"
<< "1. Yes.\n"
<< "0. No. Return to main menu ";
// Error check
anotherProb = inputVal(anotherProb);
cout << endl;
// End of Another problem? Do While
} while (anotherProb == true);
// Close outputFile
outputFile.close();
// Return boolean value either to
// main menu or another problem.
return anotherProb;
}
//***************************************************************
// The multiplicationPractice function shows a random *
// multiplication problem, asks for user input, and returns a *
// boolean value. *
//***************************************************************
bool multiplicationPractice()
{
// Output stream object
ofstream outputFile;
// Open file
outputFile.open("MathTutorRecord.txt");
// Variable
bool anotherProb;
// Another problem? Do While
do
{
// Constants
const int MIN_VALUE = 0; // Minimum value
const int MAX_VALUE = 9; // Maximum value
// Variables
int num1; // Holds a value
int num2; // Holds a value
int sum, answer;
// Assign random number to num1
num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
// Assign random number to num2
num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
// Sum of num1 and num2
sum = num1 * num2;
// Clear screen
clearScreen();
// Display problem and receive answer.
cout << num1 << " * " << num2 << endl;
cout << "\nType in your answer: ";
// Error Check answer
answer = inputVal(answer);
// Process answer
do
{
// If right answer
if (answer == sum)
{
cout << "\nGreat work!\n" << endl;
}
// Else wrong answer
else
{
// Explain how to solve problem and
// ask for new answer.
cout << "\nNot correct, hopefully this will help...\n" << endl;
cout << "\tIf I have " << num1 << " sets of "
<< num2 << " swans, how many do I have "
<< "altogether? ";
// Error check answer
answer = inputVal(answer);
// If answer right
if (answer == sum)
{
cout << "\nGreat work!\n" << endl;
}
}
// End of Processing answer.
} while (answer != sum);
// Write data to outputFile
outputFile << num1 << " x " << num2 << " = " << sum << endl;
// Ask if would like another problem
cout << "\nWould you like another multiplication problem?\n"
<< "1. Yes.\n"
<< "0. No. Return to main menu ";
// Error check anotherProb
anotherProb = inputVal(anotherProb);
cout << endl;
// End of Another problem? Do While
} while(anotherProb == true);
// Close outputFile
outputFile.close();
// Return boolean value either to
// main menu or another problem.
return anotherProb;
}
//***************************************************************
// The divisionPractice function shows a random division *
// problem, asks for user input, and returns a boolean value. *
//***************************************************************
bool divisionPractice()
{
// Output stream object
ofstream outputFile;
// Open file
outputFile.open("MathTutorRecord.txt");
// Variable
bool anotherProb;
// Another Problem?
do
{
// Constants
const int MIN_VALUE = 1; // Minimum value
const int MAX_VALUE = 9; // Maximum value
// Variables
int num1; // Holds a value
int num2; // Holds a value
int sum, answer, remain;
// Assign random number to num1
num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
// Assign random number to num2
num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
// Sum of num1 and num2
sum = num1 / num2;
// Calculate the remainded or num1 and num2
remain = num1 % num2;
// Clear the screen
clearScreen();
// Display problem
cout << num1 << " / " << num2 << endl;
// Ask to press enter to continue
cout << "\nPress [ENTER] to see answer: ";
// Clear previous input
cin.clear();
cin.ignore(123, '\n');
cin.get();
// Discribe now to solve problem
cout << endl << sum << " remainder " << remain << endl;
cout << "\n\tIf I take " << num1 << " and divide it by " << num2
<< ", \n\t" << "I will get " << sum << " with a remainder of "
<< remain << endl;
// Write data to file
outputFile << num1 << " / " << num2 << " = " << sum << " remainder " << remain << endl;
// Ask to press enter to continue
cout << "\nPress [ENTER] twice to continue: ";
// Clear previous input
cin.clear();
cin.ignore(123, '\n');
cin.get();
// Ask if would like another problem
cout << "\nWould you like another addition problem?\n"
<< "1. Yes.\n"
<< "0. No. Return to main menu ";
// Error check anotherProb input
anotherProb = inputVal(anotherProb);
cout << endl;
// End of Another Problem? do while loop
} while(anotherProb == true);
// Close outputFile
outputFile.close();
// Return boolean value either to
// main menu or another problem.
return anotherProb;
}
//***************************************************************
// The calculateAreaOfRectangle function receives the length and*
// width from the user, calculates the area of a rectangle, and *
// prints that calculation to screen. *
//***************************************************************
bool calculateAreaOfRectangle()
{
// Output stream object
ofstream outputFile;
// Open file
outputFile.open("MathTutorRecord.txt");
// Variable
bool anotherCal;
// Another problem? do while loop
do
{
// Variables: Hold length, width, and area.
double area, length, width;
clearScreen();
// Ask for length
cout << "What is the length of the rectangle? ";
length = inputVal(length);
// Get width
cout << "What is the width? ";
width = inputVal(width);
// Calculate and display
area = length * width;
cout << "\nMultiplying the length by the width " << endl
<< "determines the area of a rectangle. \n" << endl;
// Ask to pree enter ton continue
cout << "Type [ENTER] to continue: ";
// Clear previous input
cin.clear();
cin.ignore(123, '\n');
cin.get();
// Discribe how to solve the problem
cout << "\nThe area of the rectangle is " << area << endl << endl;
// Write data to file
outputFile << "The area of the rectangle is " << area << endl;
// Ask if would like another problem.
cout << "\nWould you like to make another calculation?\n"
<< "1. Yes.\n"
<< "0. No. Return to main menu ";
// Error check anotherCal
anotherCal = inputVal(anotherCal);
cout << endl;
// End of Another probelm? do while loop
} while(anotherCal == true);
// CLose outputFile
outputFile.close();
// Return boolean value either to
// main menu or another problem.
return anotherCal;
}
//*******************************************************************
// The calculateAreaOfCircle function receives the radius of a *
// circle from the user, calculates the area, and prints the *
// calculation to screen. *
//*******************************************************************
bool calculateAreaOfCircle()
{
// Output stream object
ofstream outputFile;
// Open file
outputFile.open("MathTutorRecord.txt");
// Variable
bool anotherCal;
// Another problem? do while loop
do
{
// Variables: Hold area, radius, PI.
const double PI = 3.14;
double area, radius, radSquare;
// Clear Screen
clearScreen();
// Ask for radius
cout << "What is the radius of the circle? ";
radius = inputVal(radius);
// Calculate and display
radSquare = (radius * radius);
area = PI * (radius * radius);
// Explain how to solve for area
cout << "\nSquaring the radius and then multiplying" << endl
<< "it's sum by PI determines the area of a circle.\n" << endl;
// Ask to press enter to proceed
cout << "Type [ENTER] to continue: " << endl;
// Clear previous input
cin.clear();
cin.ignore(123, '\n');
cin.get();
// Display area of circle
cout << "The area of the circle is: " << area << endl << endl;
// Write data to file
outputFile << "The area of the circle is: " << area << endl;
// Ask if would like to make another calculation
cout << "\nWould you like to make another calculation?\n"
<< "1. Yes.\n"
<< "0. No. Return to main menu ";
anotherCal = inputVal(anotherCal);
cout << endl;
// End of Another problem? do while loop
} while(anotherCal == true);
// Close outputFile
outputFile.close();
// Return boolean value either to
// main menu or another problem.
return anotherCal;
}
//*******************************************************************
// The calculateAreaOfTriangle function receives the height and base*
// of a triangle from the user, calculates the area, and prints the *
// calculation to screen. *
//*******************************************************************
bool calculateAreaOfTriangle()
{
// Output stream object
ofstream outputFile;
// Open file
outputFile.open("MathTutorRecord.txt");
// Variable
bool anotherCal;
// Another Problem? Do while loop
do
{
// Variables: Hold length, width, and area.
double area, height, base;
clearScreen(); // Explain program, then get length
cout << "What is the height of the triangle? ";
height = inputVal(height);
// Get width
cout << "What is the base? ";
base = inputVal(base);
// Calculate and display
area = (height * base) / 2;
// Explain how to solve for area
cout << "\nMultiplying the base by the height and dividing\n"
<< "their sum by 2 determines the area of a triangle.\n" << endl;
// Ask to press enter to proceed
cout << "Type [ENTER] to continue: " << endl;
// Clear previous input
cin.clear();
cin.ignore(123, '\n');
cin.get();
// Dipslay area
cout << "The area of the triangle is " << area << endl << endl;
// Write data to a file
outputFile << "The area of the triangle is " << area << endl;
// Ask if would like to make another calculation
cout << "\nWould you like to make another calculation?\n"
<< "1. Yes.\n"
<< "0. No. Return to main menu ";
// Error check anotherCal
anotherCal = inputVal(anotherCal);
cout << endl;
// End of Another problem? do while loop
} while(anotherCal == true);
// Close outputFile
outputFile.close();
// Return boolean value either to
// main menu or another problem.
return anotherCal;
}
//***************************************************
// function to clear screen, using variable *
// created in PPD statement *
//***************************************************
void clearScreen()
{
system(clearVar);
}
//***************************************************************
// Function inputVal (int) check for valid input. *
// If the user types in anything other than the int data type, *
// they will be promted to enter the valid input. *
//***************************************************************
int inputVal(int num)
{
while (!(cin >> num))
{
cout << "\n\tI'm sorry a whole number must be entered: ";
cin.clear();
cin.ignore(123, '\n');
}
return num;
}
//***************************************************************
// Function inputVal (double) check for valid input. *
// If the user types in anything other than double data type, *
// they will be promted to enter the valid data type. *
//***************************************************************
double inputVal(double num)
{
while (!(cin >> num))
{
cout << "\n\tI'm sorry a whole number must be entered: ";
cin.clear();
cin.ignore(123, '\n');
}
return num;
}
| 30.354618 | 95 | 0.4815 | [
"object"
] |
25775443053cf480dc30b2ae4511eeea52abfcb2 | 8,396 | cpp | C++ | tests/parse-ranges-request-tests.cpp | amazing-hash/onyx-up | 2b55cb3cbcd89d66dfface81efc26b8edcf2ce60 | [
"MIT"
] | null | null | null | tests/parse-ranges-request-tests.cpp | amazing-hash/onyx-up | 2b55cb3cbcd89d66dfface81efc26b8edcf2ce60 | [
"MIT"
] | null | null | null | tests/parse-ranges-request-tests.cpp | amazing-hash/onyx-up | 2b55cb3cbcd89d66dfface81efc26b8edcf2ce60 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <vector>
#include <iostream>
#include "../sources/server/utils.h"
class ParseRangesRequestTests : public ::testing::Test {
public:
ParseRangesRequestTests() {
}
~ParseRangesRequestTests() {
}
void SetUp() {
}
void TearDown() {
}
};
TEST_F(ParseRangesRequestTests, Test_1) {
std::string src = "bytes=10-";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 1);
}
TEST_F(ParseRangesRequestTests, Test_2) {
std::string src = "bytes=103-";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 1);
ASSERT_EQ(ranges[0].first, 103);
ASSERT_EQ(ranges[0].second, 20000);
}
TEST_F(ParseRangesRequestTests, Test_3) {
std::string src = "bytes=-10";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 1);
}
TEST_F(ParseRangesRequestTests, Test_4) {
std::string src = "bytes=-103";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 1);
ASSERT_EQ(ranges[0].first, 20000 - 103);
ASSERT_EQ(ranges[0].second, 20000);
}
TEST_F(ParseRangesRequestTests, Test_5) {
std::string src = "bytes=10-100";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 1);
}
TEST_F(ParseRangesRequestTests, Test_6) {
std::string src = "bytes=256-1040";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 1);
ASSERT_EQ(ranges[0].first, 256);
ASSERT_EQ(ranges[0].second, 1040);
}
TEST_F(ParseRangesRequestTests, Test_7) {
std::string src = "bytes=10-100, 120-140";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 2);
}
TEST_F(ParseRangesRequestTests, Test_8) {
std::string src = "bytes=10-100, 120-140";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 2);
ASSERT_EQ(ranges[0].first, 10);
ASSERT_EQ(ranges[0].second, 100);
ASSERT_EQ(ranges[1].first, 120);
ASSERT_EQ(ranges[1].second, 140);
}
TEST_F(ParseRangesRequestTests, Test_9) {
std::string src = "bytes=10-100, -140";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 2);
ASSERT_EQ(ranges[0].first, 10);
ASSERT_EQ(ranges[0].second, 100);
ASSERT_EQ(ranges[1].first, 20000 - 140);
ASSERT_EQ(ranges[1].second, 20000);
}
TEST_F(ParseRangesRequestTests, Test_10) {
std::string src = "bytes=100 - 500, -140";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 2);
ASSERT_EQ(ranges[0].first, 100);
ASSERT_EQ(ranges[0].second, 500);
ASSERT_EQ(ranges[1].first, 20000 - 140);
ASSERT_EQ(ranges[1].second, 20000);
}
TEST_F(ParseRangesRequestTests, Test_11) {
std::string src = "bytes=100-130, 140-";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges.size(), 2);
ASSERT_EQ(ranges[0].first, 100);
ASSERT_EQ(ranges[0].second, 130);
ASSERT_EQ(ranges[1].first, 140);
ASSERT_EQ(ranges[1].second, 20000);
}
TEST_F(ParseRangesRequestTests, Test_12) {
std::string src = "bytes=";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_13) {
std::string src = "bytes=100";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_14) {
std::string src = "bytes=-100-";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_15) {
std::string src = "bytes=-aaa";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_16) {
std::string src = "bytes=200-100";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_17) {
std::string src = "bytes=100-100";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges[0].first, 100);
ASSERT_EQ(ranges[0].second, 100);
}
TEST_F(ParseRangesRequestTests, Test_18) {
std::string src = "bytes=-30000";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_19) {
std::string src = "bytes=100-200, 150-250";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_20) {
std::string src = "bytes=-200, -500";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_21) {
std::string src = "bytes=-20000";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges[0].first, 0);
ASSERT_EQ(ranges[0].second, 20000);
}
TEST_F(ParseRangesRequestTests, Test_22) {
std::string src = "bytes=0-";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges[0].first, 0);
ASSERT_EQ(ranges[0].second, 20000);
}
TEST_F(ParseRangesRequestTests, Test_23) {
std::string src = "bytes=100-200, 100-200";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_24) {
std::string src = "bytes=0-20001";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_25) {
std::string src = "bytes=0-0";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 1);
ASSERT_EQ(ranges[0].first, 0);
ASSERT_EQ(ranges[0].second, 0);
}
TEST_F(ParseRangesRequestTests, Test_26) {
std::string src = "bytes=0-0";
try{
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 0);
ASSERT_EQ(true, false);
} catch (onyxup::OnyxupException & ex){
ASSERT_EQ(true, true);
}
}
TEST_F(ParseRangesRequestTests, Test_27) {
std::string src = "bytes=-0";
std::vector<std::pair<size_t , size_t >> ranges = onyxup::utils::parseRangesRequest(src, 20000);
ASSERT_EQ(ranges[0].first, 20000);
ASSERT_EQ(ranges[0].second, 20000);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 33.584 | 104 | 0.653645 | [
"vector"
] |
258b6a0b00cab434bc5df4fda8a0f6fe9b0553ed | 1,357 | cpp | C++ | solutions/560. Subarray Sum Equals K.cpp | xkunwu/leetcode-collection | 7c5dab83c1cf00aa8ce5e3d2b24de3d2cf0f9869 | [
"MIT"
] | null | null | null | solutions/560. Subarray Sum Equals K.cpp | xkunwu/leetcode-collection | 7c5dab83c1cf00aa8ce5e3d2b24de3d2cf0f9869 | [
"MIT"
] | null | null | null | solutions/560. Subarray Sum Equals K.cpp | xkunwu/leetcode-collection | 7c5dab83c1cf00aa8ce5e3d2b24de3d2cf0f9869 | [
"MIT"
] | null | null | null | /** 560. Subarray Sum Equals K
https://leetcode.com/problems/subarray-sum-equals-k/
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
*/
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
std::map<int, int> cumap;
int sum = 0, nc = 0;
cumap.insert(pair<int, int>(0, 1));
for (size_t ii = 0; ii < nums.size(); ++ii) {
sum += nums[ii];
const int comp = sum - k;
if (cumap.end() != cumap.find(comp)) {
nc += cumap[comp];
}
if (cumap.end() == cumap.find(sum))
cumap.insert(std::pair<int, int>(sum, 1));
else cumap[sum] += 1;
}
return nc;
}
};
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int nc = 0;
const size_t nn = nums.size();
std::vector<int> cumsum(nn + 1, 0);
for (size_t ii = 1; ii <= nn; ++ ii) {
cumsum[ii] = cumsum[ii - 1] + nums[ii - 1];
}
for (size_t ii = 0; ii < nn; ++ii) {
for (size_t jj = ii + 1; jj <= nn; ++jj) {
if (cumsum[jj] - cumsum[ii] == k)
++nc;
}
}
return nc;
}
};
| 30.840909 | 127 | 0.460575 | [
"vector"
] |
259135e2e899504a964eaa313d66164a9e908e96 | 184 | hh | C++ | defolib/mesh-geometry.hh | hanwen/artisjokke | 608d76c5fad74ee4214162044c7ea3b781571e44 | [
"MIT"
] | 5 | 2015-06-06T02:25:02.000Z | 2021-06-18T09:49:56.000Z | defolib/mesh-geometry.hh | hanwen/artisjokke | 608d76c5fad74ee4214162044c7ea3b781571e44 | [
"MIT"
] | null | null | null | defolib/mesh-geometry.hh | hanwen/artisjokke | 608d76c5fad74ee4214162044c7ea3b781571e44 | [
"MIT"
] | 2 | 2015-06-05T12:44:25.000Z | 2015-10-28T09:27:59.000Z | #ifndef MESH_GEOMETRY_HH
#define MESH_GEOMETRY_HH
#include "array.hh"
#include "mesh-connectivity.hh"
Array<Real> lumped_volumes (Mesh_connectivity*fem, Deformation_state*);
#endif
| 18.4 | 71 | 0.804348 | [
"mesh"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.