text
stringlengths 5
1.04M
|
|---|
// Copyright (c) 2006-2008 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 <string>
#include "base/string_piece.h"
#include "testing/gtest/include/gtest/gtest.h"
TEST(StringPieceTest, CheckComparisonOperators) {
#define CMP_Y(op, x, y) \
ASSERT_TRUE( (StringPiece((x)) op StringPiece((y)))); \
ASSERT_TRUE( (StringPiece((x)).compare(StringPiece((y))) op 0))
#define CMP_N(op, x, y) \
ASSERT_FALSE(StringPiece((x)) op StringPiece((y))); \
ASSERT_FALSE(StringPiece((x)).compare(StringPiece((y))) op 0)
CMP_Y(==, "", "");
CMP_Y(==, "a", "a");
CMP_Y(==, "aa", "aa");
CMP_N(==, "a", "");
CMP_N(==, "", "a");
CMP_N(==, "a", "b");
CMP_N(==, "a", "aa");
CMP_N(==, "aa", "a");
CMP_N(!=, "", "");
CMP_N(!=, "a", "a");
CMP_N(!=, "aa", "aa");
CMP_Y(!=, "a", "");
CMP_Y(!=, "", "a");
CMP_Y(!=, "a", "b");
CMP_Y(!=, "a", "aa");
CMP_Y(!=, "aa", "a");
CMP_Y(<, "a", "b");
CMP_Y(<, "a", "aa");
CMP_Y(<, "aa", "b");
CMP_Y(<, "aa", "bb");
CMP_N(<, "a", "a");
CMP_N(<, "b", "a");
CMP_N(<, "aa", "a");
CMP_N(<, "b", "aa");
CMP_N(<, "bb", "aa");
CMP_Y(<=, "a", "a");
CMP_Y(<=, "a", "b");
CMP_Y(<=, "a", "aa");
CMP_Y(<=, "aa", "b");
CMP_Y(<=, "aa", "bb");
CMP_N(<=, "b", "a");
CMP_N(<=, "aa", "a");
CMP_N(<=, "b", "aa");
CMP_N(<=, "bb", "aa");
CMP_N(>=, "a", "b");
CMP_N(>=, "a", "aa");
CMP_N(>=, "aa", "b");
CMP_N(>=, "aa", "bb");
CMP_Y(>=, "a", "a");
CMP_Y(>=, "b", "a");
CMP_Y(>=, "aa", "a");
CMP_Y(>=, "b", "aa");
CMP_Y(>=, "bb", "aa");
CMP_N(>, "a", "a");
CMP_N(>, "a", "b");
CMP_N(>, "a", "aa");
CMP_N(>, "aa", "b");
CMP_N(>, "aa", "bb");
CMP_Y(>, "b", "a");
CMP_Y(>, "aa", "a");
CMP_Y(>, "b", "aa");
CMP_Y(>, "bb", "aa");
std::string x;
for (int i = 0; i < 256; i++) {
x += 'a';
std::string y = x;
CMP_Y(==, x, y);
for (int j = 0; j < i; j++) {
std::string z = x;
z[j] = 'b'; // Differs in position 'j'
CMP_N(==, x, z);
}
}
#undef CMP_Y
#undef CMP_N
}
TEST(StringPieceTest, CheckSTL) {
StringPiece a("abcdefghijklmnopqrstuvwxyz");
StringPiece b("abc");
StringPiece c("xyz");
StringPiece d("foobar");
StringPiece e;
std::string temp("123");
temp += '\0';
temp += "456";
StringPiece f(temp);
ASSERT_EQ(a[6], 'g');
ASSERT_EQ(b[0], 'a');
ASSERT_EQ(c[2], 'z');
ASSERT_EQ(f[3], '\0');
ASSERT_EQ(f[5], '5');
ASSERT_EQ(*d.data(), 'f');
ASSERT_EQ(d.data()[5], 'r');
ASSERT_TRUE(e.data() == NULL);
ASSERT_EQ(*a.begin(), 'a');
ASSERT_EQ(*(b.begin() + 2), 'c');
ASSERT_EQ(*(c.end() - 1), 'z');
ASSERT_EQ(*a.rbegin(), 'z');
ASSERT_EQ(*(b.rbegin() + 2), 'a');
ASSERT_EQ(*(c.rend() - 1), 'x');
ASSERT_TRUE(a.rbegin() + 26 == a.rend());
ASSERT_EQ(a.size(), 26U);
ASSERT_EQ(b.size(), 3U);
ASSERT_EQ(c.size(), 3U);
ASSERT_EQ(d.size(), 6U);
ASSERT_EQ(e.size(), 0U);
ASSERT_EQ(f.size(), 7U);
ASSERT_TRUE(!d.empty());
ASSERT_TRUE(d.begin() != d.end());
ASSERT_TRUE(d.begin() + 6 == d.end());
ASSERT_TRUE(e.empty());
ASSERT_TRUE(e.begin() == e.end());
d.clear();
ASSERT_EQ(d.size(), 0U);
ASSERT_TRUE(d.empty());
ASSERT_TRUE(d.data() == NULL);
ASSERT_TRUE(d.begin() == d.end());
ASSERT_GE(a.max_size(), a.capacity());
ASSERT_GE(a.capacity(), a.size());
char buf[4] = { '%', '%', '%', '%' };
ASSERT_EQ(a.copy(buf, 4), 4U);
ASSERT_EQ(buf[0], a[0]);
ASSERT_EQ(buf[1], a[1]);
ASSERT_EQ(buf[2], a[2]);
ASSERT_EQ(buf[3], a[3]);
ASSERT_EQ(a.copy(buf, 3, 7), 3U);
ASSERT_EQ(buf[0], a[7]);
ASSERT_EQ(buf[1], a[8]);
ASSERT_EQ(buf[2], a[9]);
ASSERT_EQ(buf[3], a[3]);
ASSERT_EQ(c.copy(buf, 99), 3U);
ASSERT_EQ(buf[0], c[0]);
ASSERT_EQ(buf[1], c[1]);
ASSERT_EQ(buf[2], c[2]);
ASSERT_EQ(buf[3], a[3]);
ASSERT_EQ(StringPiece::npos, std::string::npos);
ASSERT_EQ(a.find(b), 0U);
ASSERT_EQ(a.find(b, 1), StringPiece::npos);
ASSERT_EQ(a.find(c), 23U);
ASSERT_EQ(a.find(c, 9), 23U);
ASSERT_EQ(a.find(c, StringPiece::npos), StringPiece::npos);
ASSERT_EQ(b.find(c), StringPiece::npos);
ASSERT_EQ(b.find(c, StringPiece::npos), StringPiece::npos);
ASSERT_EQ(a.find(d), 0U);
ASSERT_EQ(a.find(e), 0U);
ASSERT_EQ(a.find(d, 12), 12U);
ASSERT_EQ(a.find(e, 17), 17U);
StringPiece g("xx not found bb");
ASSERT_EQ(a.find(g), StringPiece::npos);
// empty string nonsense
ASSERT_EQ(d.find(b), StringPiece::npos);
ASSERT_EQ(e.find(b), StringPiece::npos);
ASSERT_EQ(d.find(b, 4), StringPiece::npos);
ASSERT_EQ(e.find(b, 7), StringPiece::npos);
size_t empty_search_pos = std::string().find(std::string());
ASSERT_EQ(d.find(d), empty_search_pos);
ASSERT_EQ(d.find(e), empty_search_pos);
ASSERT_EQ(e.find(d), empty_search_pos);
ASSERT_EQ(e.find(e), empty_search_pos);
ASSERT_EQ(d.find(d, 4), std::string().find(std::string(), 4));
ASSERT_EQ(d.find(e, 4), std::string().find(std::string(), 4));
ASSERT_EQ(e.find(d, 4), std::string().find(std::string(), 4));
ASSERT_EQ(e.find(e, 4), std::string().find(std::string(), 4));
ASSERT_EQ(a.find('a'), 0U);
ASSERT_EQ(a.find('c'), 2U);
ASSERT_EQ(a.find('z'), 25U);
ASSERT_EQ(a.find('$'), StringPiece::npos);
ASSERT_EQ(a.find('\0'), StringPiece::npos);
ASSERT_EQ(f.find('\0'), 3U);
ASSERT_EQ(f.find('3'), 2U);
ASSERT_EQ(f.find('5'), 5U);
ASSERT_EQ(g.find('o'), 4U);
ASSERT_EQ(g.find('o', 4), 4U);
ASSERT_EQ(g.find('o', 5), 8U);
ASSERT_EQ(a.find('b', 5), StringPiece::npos);
// empty string nonsense
ASSERT_EQ(d.find('\0'), StringPiece::npos);
ASSERT_EQ(e.find('\0'), StringPiece::npos);
ASSERT_EQ(d.find('\0', 4), StringPiece::npos);
ASSERT_EQ(e.find('\0', 7), StringPiece::npos);
ASSERT_EQ(d.find('x'), StringPiece::npos);
ASSERT_EQ(e.find('x'), StringPiece::npos);
ASSERT_EQ(d.find('x', 4), StringPiece::npos);
ASSERT_EQ(e.find('x', 7), StringPiece::npos);
ASSERT_EQ(a.rfind(b), 0U);
ASSERT_EQ(a.rfind(b, 1), 0U);
ASSERT_EQ(a.rfind(c), 23U);
ASSERT_EQ(a.rfind(c, 22U), StringPiece::npos);
ASSERT_EQ(a.rfind(c, 1U), StringPiece::npos);
ASSERT_EQ(a.rfind(c, 0U), StringPiece::npos);
ASSERT_EQ(b.rfind(c), StringPiece::npos);
ASSERT_EQ(b.rfind(c, 0U), StringPiece::npos);
ASSERT_EQ(a.rfind(d), (size_t) a.as_string().rfind(std::string()));
ASSERT_EQ(a.rfind(e), a.as_string().rfind(std::string()));
ASSERT_EQ(a.rfind(d, 12), 12U);
ASSERT_EQ(a.rfind(e, 17), 17U);
ASSERT_EQ(a.rfind(g), StringPiece::npos);
ASSERT_EQ(d.rfind(b), StringPiece::npos);
ASSERT_EQ(e.rfind(b), StringPiece::npos);
ASSERT_EQ(d.rfind(b, 4), StringPiece::npos);
ASSERT_EQ(e.rfind(b, 7), StringPiece::npos);
// empty string nonsense
ASSERT_EQ(d.rfind(d, 4), std::string().rfind(std::string()));
ASSERT_EQ(e.rfind(d, 7), std::string().rfind(std::string()));
ASSERT_EQ(d.rfind(e, 4), std::string().rfind(std::string()));
ASSERT_EQ(e.rfind(e, 7), std::string().rfind(std::string()));
ASSERT_EQ(d.rfind(d), std::string().rfind(std::string()));
ASSERT_EQ(e.rfind(d), std::string().rfind(std::string()));
ASSERT_EQ(d.rfind(e), std::string().rfind(std::string()));
ASSERT_EQ(e.rfind(e), std::string().rfind(std::string()));
ASSERT_EQ(g.rfind('o'), 8U);
ASSERT_EQ(g.rfind('q'), StringPiece::npos);
ASSERT_EQ(g.rfind('o', 8), 8U);
ASSERT_EQ(g.rfind('o', 7), 4U);
ASSERT_EQ(g.rfind('o', 3), StringPiece::npos);
ASSERT_EQ(f.rfind('\0'), 3U);
ASSERT_EQ(f.rfind('\0', 12), 3U);
ASSERT_EQ(f.rfind('3'), 2U);
ASSERT_EQ(f.rfind('5'), 5U);
// empty string nonsense
ASSERT_EQ(d.rfind('o'), StringPiece::npos);
ASSERT_EQ(e.rfind('o'), StringPiece::npos);
ASSERT_EQ(d.rfind('o', 4), StringPiece::npos);
ASSERT_EQ(e.rfind('o', 7), StringPiece::npos);
ASSERT_EQ(a.find_first_of(b), 0U);
ASSERT_EQ(a.find_first_of(b, 0), 0U);
ASSERT_EQ(a.find_first_of(b, 1), 1U);
ASSERT_EQ(a.find_first_of(b, 2), 2U);
ASSERT_EQ(a.find_first_of(b, 3), StringPiece::npos);
ASSERT_EQ(a.find_first_of(c), 23U);
ASSERT_EQ(a.find_first_of(c, 23), 23U);
ASSERT_EQ(a.find_first_of(c, 24), 24U);
ASSERT_EQ(a.find_first_of(c, 25), 25U);
ASSERT_EQ(a.find_first_of(c, 26), StringPiece::npos);
ASSERT_EQ(g.find_first_of(b), 13U);
ASSERT_EQ(g.find_first_of(c), 0U);
ASSERT_EQ(a.find_first_of(f), StringPiece::npos);
ASSERT_EQ(f.find_first_of(a), StringPiece::npos);
// empty string nonsense
ASSERT_EQ(a.find_first_of(d), StringPiece::npos);
ASSERT_EQ(a.find_first_of(e), StringPiece::npos);
ASSERT_EQ(d.find_first_of(b), StringPiece::npos);
ASSERT_EQ(e.find_first_of(b), StringPiece::npos);
ASSERT_EQ(d.find_first_of(d), StringPiece::npos);
ASSERT_EQ(e.find_first_of(d), StringPiece::npos);
ASSERT_EQ(d.find_first_of(e), StringPiece::npos);
ASSERT_EQ(e.find_first_of(e), StringPiece::npos);
ASSERT_EQ(a.find_first_not_of(b), 3U);
ASSERT_EQ(a.find_first_not_of(c), 0U);
ASSERT_EQ(b.find_first_not_of(a), StringPiece::npos);
ASSERT_EQ(c.find_first_not_of(a), StringPiece::npos);
ASSERT_EQ(f.find_first_not_of(a), 0U);
ASSERT_EQ(a.find_first_not_of(f), 0U);
ASSERT_EQ(a.find_first_not_of(d), 0U);
ASSERT_EQ(a.find_first_not_of(e), 0U);
// empty string nonsense
ASSERT_EQ(d.find_first_not_of(a), StringPiece::npos);
ASSERT_EQ(e.find_first_not_of(a), StringPiece::npos);
ASSERT_EQ(d.find_first_not_of(d), StringPiece::npos);
ASSERT_EQ(e.find_first_not_of(d), StringPiece::npos);
ASSERT_EQ(d.find_first_not_of(e), StringPiece::npos);
ASSERT_EQ(e.find_first_not_of(e), StringPiece::npos);
StringPiece h("====");
ASSERT_EQ(h.find_first_not_of('='), StringPiece::npos);
ASSERT_EQ(h.find_first_not_of('=', 3), StringPiece::npos);
ASSERT_EQ(h.find_first_not_of('\0'), 0U);
ASSERT_EQ(g.find_first_not_of('x'), 2U);
ASSERT_EQ(f.find_first_not_of('\0'), 0U);
ASSERT_EQ(f.find_first_not_of('\0', 3), 4U);
ASSERT_EQ(f.find_first_not_of('\0', 2), 2U);
// empty string nonsense
ASSERT_EQ(d.find_first_not_of('x'), StringPiece::npos);
ASSERT_EQ(e.find_first_not_of('x'), StringPiece::npos);
ASSERT_EQ(d.find_first_not_of('\0'), StringPiece::npos);
ASSERT_EQ(e.find_first_not_of('\0'), StringPiece::npos);
// StringPiece g("xx not found bb");
StringPiece i("56");
ASSERT_EQ(h.find_last_of(a), StringPiece::npos);
ASSERT_EQ(g.find_last_of(a), g.size()-1);
ASSERT_EQ(a.find_last_of(b), 2U);
ASSERT_EQ(a.find_last_of(c), a.size()-1);
ASSERT_EQ(f.find_last_of(i), 6U);
ASSERT_EQ(a.find_last_of('a'), 0U);
ASSERT_EQ(a.find_last_of('b'), 1U);
ASSERT_EQ(a.find_last_of('z'), 25U);
ASSERT_EQ(a.find_last_of('a', 5), 0U);
ASSERT_EQ(a.find_last_of('b', 5), 1U);
ASSERT_EQ(a.find_last_of('b', 0), StringPiece::npos);
ASSERT_EQ(a.find_last_of('z', 25), 25U);
ASSERT_EQ(a.find_last_of('z', 24), StringPiece::npos);
ASSERT_EQ(f.find_last_of(i, 5), 5U);
ASSERT_EQ(f.find_last_of(i, 6), 6U);
ASSERT_EQ(f.find_last_of(a, 4), StringPiece::npos);
// empty string nonsense
ASSERT_EQ(f.find_last_of(d), StringPiece::npos);
ASSERT_EQ(f.find_last_of(e), StringPiece::npos);
ASSERT_EQ(f.find_last_of(d, 4), StringPiece::npos);
ASSERT_EQ(f.find_last_of(e, 4), StringPiece::npos);
ASSERT_EQ(d.find_last_of(d), StringPiece::npos);
ASSERT_EQ(d.find_last_of(e), StringPiece::npos);
ASSERT_EQ(e.find_last_of(d), StringPiece::npos);
ASSERT_EQ(e.find_last_of(e), StringPiece::npos);
ASSERT_EQ(d.find_last_of(f), StringPiece::npos);
ASSERT_EQ(e.find_last_of(f), StringPiece::npos);
ASSERT_EQ(d.find_last_of(d, 4), StringPiece::npos);
ASSERT_EQ(d.find_last_of(e, 4), StringPiece::npos);
ASSERT_EQ(e.find_last_of(d, 4), StringPiece::npos);
ASSERT_EQ(e.find_last_of(e, 4), StringPiece::npos);
ASSERT_EQ(d.find_last_of(f, 4), StringPiece::npos);
ASSERT_EQ(e.find_last_of(f, 4), StringPiece::npos);
ASSERT_EQ(a.find_last_not_of(b), a.size()-1);
ASSERT_EQ(a.find_last_not_of(c), 22U);
ASSERT_EQ(b.find_last_not_of(a), StringPiece::npos);
ASSERT_EQ(b.find_last_not_of(b), StringPiece::npos);
ASSERT_EQ(f.find_last_not_of(i), 4U);
ASSERT_EQ(a.find_last_not_of(c, 24), 22U);
ASSERT_EQ(a.find_last_not_of(b, 3), 3U);
ASSERT_EQ(a.find_last_not_of(b, 2), StringPiece::npos);
// empty string nonsense
ASSERT_EQ(f.find_last_not_of(d), f.size()-1);
ASSERT_EQ(f.find_last_not_of(e), f.size()-1);
ASSERT_EQ(f.find_last_not_of(d, 4), 4U);
ASSERT_EQ(f.find_last_not_of(e, 4), 4U);
ASSERT_EQ(d.find_last_not_of(d), StringPiece::npos);
ASSERT_EQ(d.find_last_not_of(e), StringPiece::npos);
ASSERT_EQ(e.find_last_not_of(d), StringPiece::npos);
ASSERT_EQ(e.find_last_not_of(e), StringPiece::npos);
ASSERT_EQ(d.find_last_not_of(f), StringPiece::npos);
ASSERT_EQ(e.find_last_not_of(f), StringPiece::npos);
ASSERT_EQ(d.find_last_not_of(d, 4), StringPiece::npos);
ASSERT_EQ(d.find_last_not_of(e, 4), StringPiece::npos);
ASSERT_EQ(e.find_last_not_of(d, 4), StringPiece::npos);
ASSERT_EQ(e.find_last_not_of(e, 4), StringPiece::npos);
ASSERT_EQ(d.find_last_not_of(f, 4), StringPiece::npos);
ASSERT_EQ(e.find_last_not_of(f, 4), StringPiece::npos);
ASSERT_EQ(h.find_last_not_of('x'), h.size() - 1);
ASSERT_EQ(h.find_last_not_of('='), StringPiece::npos);
ASSERT_EQ(b.find_last_not_of('c'), 1U);
ASSERT_EQ(h.find_last_not_of('x', 2), 2U);
ASSERT_EQ(h.find_last_not_of('=', 2), StringPiece::npos);
ASSERT_EQ(b.find_last_not_of('b', 1), 0U);
// empty string nonsense
ASSERT_EQ(d.find_last_not_of('x'), StringPiece::npos);
ASSERT_EQ(e.find_last_not_of('x'), StringPiece::npos);
ASSERT_EQ(d.find_last_not_of('\0'), StringPiece::npos);
ASSERT_EQ(e.find_last_not_of('\0'), StringPiece::npos);
ASSERT_EQ(a.substr(0, 3), b);
ASSERT_EQ(a.substr(23), c);
ASSERT_EQ(a.substr(23, 3), c);
ASSERT_EQ(a.substr(23, 99), c);
ASSERT_EQ(a.substr(0), a);
ASSERT_EQ(a.substr(3, 2), "de");
// empty string nonsense
ASSERT_EQ(a.substr(99, 2), e);
ASSERT_EQ(d.substr(99), e);
ASSERT_EQ(d.substr(0, 99), e);
ASSERT_EQ(d.substr(99, 99), e);
}
TEST(StringPieceTest, CheckCustom) {
StringPiece a("foobar");
std::string s1("123");
s1 += '\0';
s1 += "456";
StringPiece b(s1);
StringPiece e;
std::string s2;
// CopyToString
a.CopyToString(&s2);
ASSERT_EQ(s2.size(), 6U);
ASSERT_EQ(s2, "foobar");
b.CopyToString(&s2);
ASSERT_EQ(s2.size(), 7U);
ASSERT_EQ(s1, s2);
e.CopyToString(&s2);
ASSERT_TRUE(s2.empty());
// AppendToString
s2.erase();
a.AppendToString(&s2);
ASSERT_EQ(s2.size(), 6U);
ASSERT_EQ(s2, "foobar");
a.AppendToString(&s2);
ASSERT_EQ(s2.size(), 12U);
ASSERT_EQ(s2, "foobarfoobar");
// starts_with
ASSERT_TRUE(a.starts_with(a));
ASSERT_TRUE(a.starts_with("foo"));
ASSERT_TRUE(a.starts_with(e));
ASSERT_TRUE(b.starts_with(s1));
ASSERT_TRUE(b.starts_with(b));
ASSERT_TRUE(b.starts_with(e));
ASSERT_TRUE(e.starts_with(""));
ASSERT_TRUE(!a.starts_with(b));
ASSERT_TRUE(!b.starts_with(a));
ASSERT_TRUE(!e.starts_with(a));
// ends with
ASSERT_TRUE(a.ends_with(a));
ASSERT_TRUE(a.ends_with("bar"));
ASSERT_TRUE(a.ends_with(e));
ASSERT_TRUE(b.ends_with(s1));
ASSERT_TRUE(b.ends_with(b));
ASSERT_TRUE(b.ends_with(e));
ASSERT_TRUE(e.ends_with(""));
ASSERT_TRUE(!a.ends_with(b));
ASSERT_TRUE(!b.ends_with(a));
ASSERT_TRUE(!e.ends_with(a));
// remove_prefix
StringPiece c(a);
c.remove_prefix(3);
ASSERT_EQ(c, "bar");
c = a;
c.remove_prefix(0);
ASSERT_EQ(c, a);
c.remove_prefix(c.size());
ASSERT_EQ(c, e);
// remove_suffix
c = a;
c.remove_suffix(3);
ASSERT_EQ(c, "foo");
c = a;
c.remove_suffix(0);
ASSERT_EQ(c, a);
c.remove_suffix(c.size());
ASSERT_EQ(c, e);
// set
c.set("foobar", 6);
ASSERT_EQ(c, a);
c.set("foobar", 0);
ASSERT_EQ(c, e);
c.set("foobar", 7);
ASSERT_NE(c, a);
c.set("foobar");
ASSERT_EQ(c, a);
c.set(static_cast<const void*>("foobar"), 6);
ASSERT_EQ(c, a);
c.set(static_cast<const void*>("foobar"), 0);
ASSERT_EQ(c, e);
c.set(static_cast<const void*>("foobar"), 7);
ASSERT_NE(c, a);
// as_string
std::string s3(a.as_string().c_str(), 7);
ASSERT_EQ(c, s3);
std::string s4(e.as_string());
ASSERT_TRUE(s4.empty());
}
TEST(StringPieceTest, CheckNULL) {
// we used to crash here, but now we don't.
StringPiece s(NULL);
ASSERT_EQ(s.data(), (const char*)NULL);
ASSERT_EQ(s.size(), 0U);
s.set(NULL);
ASSERT_EQ(s.data(), (const char*)NULL);
ASSERT_EQ(s.size(), 0U);
}
TEST(StringPieceTest, CheckComparisons2) {
StringPiece abc("abcdefghijklmnopqrstuvwxyz");
// check comparison operations on strings longer than 4 bytes.
ASSERT_TRUE(abc == StringPiece("abcdefghijklmnopqrstuvwxyz"));
ASSERT_TRUE(abc.compare(StringPiece("abcdefghijklmnopqrstuvwxyz")) == 0);
ASSERT_TRUE(abc < StringPiece("abcdefghijklmnopqrstuvwxzz"));
ASSERT_TRUE(abc.compare(StringPiece("abcdefghijklmnopqrstuvwxzz")) < 0);
ASSERT_TRUE(abc > StringPiece("abcdefghijklmnopqrstuvwxyy"));
ASSERT_TRUE(abc.compare(StringPiece("abcdefghijklmnopqrstuvwxyy")) > 0);
// starts_with
ASSERT_TRUE(abc.starts_with(abc));
ASSERT_TRUE(abc.starts_with("abcdefghijklm"));
ASSERT_TRUE(!abc.starts_with("abcdefguvwxyz"));
// ends_with
ASSERT_TRUE(abc.ends_with(abc));
ASSERT_TRUE(!abc.ends_with("abcdefguvwxyz"));
ASSERT_TRUE(abc.ends_with("nopqrstuvwxyz"));
}
TEST(StringPieceTest, StringCompareNotAmbiguous) {
ASSERT_TRUE("hello" == std::string("hello"));
ASSERT_TRUE("hello" < std::string("world"));
}
TEST(StringPieceTest, HeterogenousStringPieceEquals) {
ASSERT_TRUE(StringPiece("hello") == std::string("hello"));
ASSERT_TRUE("hello" == StringPiece("hello"));
}
|
#include "vistor.h"
void CEOVisitor::visit(Engineer *engineer) {
cout << "工程师: "<< engineer->name<< ", KPI: "<< engineer->kpi << endl;
}
void CEOVisitor::visit(Manager *manager) {
cout << "经理: " << manager->name << ", KPI: " << manager->kpi<<", 新产品数量: " << manager->getProducts() << endl;
}
void CTOVisitor::visit(Engineer *engineer) {
cout << "工程师: "<< engineer->name<< ", 代码行数: "<< engineer->getCodeLines() << endl;
}
void CTOVisitor::visit(Manager *manager) {
cout << "经理: "<< manager->name<< ", 产品数量: "<< manager->getProducts() << endl;
}
|
/*
* ServoControl.cpp
*
* Created on: Sep 14, 2013
* Author: sk
*/
#include "ServoControl.h"
void ServoControl::setSerial(ofSerial *serial) {
this->serial = serial;
}
void ServoControl::setNumber(unsigned char number) {
this->number = number;
}
bool ServoControl::sendTarget(ofSerial *serial) {
uint32_t target_value = (uint32_t) (target.get());
serial->flush();
serial->writeByte(0xAA); //start byte
serial->writeByte(0x0C); //device id
serial->writeByte(0x04); //command number
serial->writeByte(number); //servo number
serial->writeByte(target_value & 0x7F);
serial->writeByte((target_value >> 7) & 0x7F);
}
int ServoControl::getTargetCommand(ofSerial *serial) {
return 0;
}
unsigned char ServoControl::getErrorCommand(ofSerial *serial) {
return 0;
}
void ServoControl::updateTarget(int &placeholder) {
cout << (int)number << " updateTarget " << target.get() << endl;
sendTarget(serial);
}
void ServoControl::getTarget() {
int target = getTargetCommand(serial);
cout << (int)number << " getTarget " << target << endl;
}
void ServoControl::getError() {
unsigned char error = getErrorCommand(serial);
cout << (int)number << " getError " << (int)error << endl;
}
void ServoControl::resetRange() {
set_min.set(default_min);
set_max.set(default_max);
if (target.get() < default_min) {
target.set(default_min);
}
if (target.get() > default_max) {
target.set(default_max);
}
}
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (C) 2008-2016 Ryo Suzuki
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "String.hpp"
# pragma warning (disable: 4127)
# include "../ThirdParty/cppformat/format.h"
# pragma warning (default: 4127)
namespace s3d
{
/// <summary>
/// Python 風フォーマットのためのタグ
/// </summary>
constexpr struct fmt_tag {} PyFmt;
struct PyFmtString
{
PyFmtString() = default;
PyFmtString(const wchar_t *str, size_t len)
: string(str, len) {}
PyFmtString(const std::wstring& str)
: string(str) {}
PyFmtString(std::wstring&& str)
: string(std::move(str)) {}
PyFmtString(const String& str)
: string(str.str()) {}
std::wstring string;
};
namespace literals
{
inline namespace formatting_literals
{
inline PyFmtString operator "" _fmt(const wchar_t *str, size_t len)
{
return PyFmtString(str, len);
}
}
}
/// <summary>
/// 一連の引数を Python 風フォーマットで文字列に変換します。
/// </summary>
/// <param name="args">
/// 変換する値、第二引数は変換指定文字列
/// </param>
/// <returns>
/// 引数を文字列に変換して連結した文字列
/// </returns>
template <class ... Args>
inline String Format(fmt_tag, const Args& ... args)
{
return fmt::format(args...);
}
/// <summary>
/// 一連の引数を Python 風フォーマットで文字列に変換します。
/// </summary>
/// <param name="args">
/// 変換する値、第二引数は変換指定文字列
/// </param>
/// <returns>
/// 引数を文字列に変換して連結した文字列
/// </returns>
template <class ... Args>
inline String Format(const PyFmtString& py, const Args& ... args)
{
return fmt::format(py.string, args...);
}
}
|
#include "refill/system_models/system_model_base.h"
using std::size_t;
namespace refill {
/**
* Use this constructor if your system does not have an input.
* The constructor clones the system noise, so it can be used again.
*
* @param state_dim The systems state dimension.
* @param system_noise The system noise.
*/
SystemModelBase::SystemModelBase(const size_t& state_dim,
const DistributionInterface& system_noise)
: SystemModelBase(state_dim, system_noise, 0u) {}
/**
* Use this constructor if your system model does have an input.
* The constructor clones the system noise, so it can be used again.
*
* @param state_dim The systems state dimension.
* @param system_noise The system noise.
* @param input_dim The systems input dimension.
*/
SystemModelBase::SystemModelBase(const size_t& state_dim,
const DistributionInterface& system_noise,
const size_t& input_dim)
: state_dim_(state_dim),
input_dim_(input_dim),
system_noise_(system_noise.clone()) {}
/**
* @f$ N_s @f$ / @f$ N_n @f$ denotes state and noise dimensions respectively.
*
* @f$ M_s @f$ / @f$ M_n @f$ user defined number of state/noise samples.
*
* @param sampled_state is a @f$ N_s \times M_s @f$ Matrix.
* @param input is the input to the system function.
* @param sampled_noise is a @f$ N_n \times M_n @f$ Matrix.
* @return an @f$ N_s \times (M_s \cdot M_n) @f$ Matrix.
*/
Eigen::MatrixXd SystemModelBase::propagateVectorized(
const Eigen::MatrixXd& sampled_state, const Eigen::VectorXd& input,
const Eigen::MatrixXd& sampled_noise) const {
const size_t kStateDim = getStateDim();
const size_t kInputDim = getInputDim();
const size_t kNoiseDim = getNoiseDim();
const size_t kStateSampleCount = sampled_state.cols();
const size_t kNoiseSampleCount = sampled_noise.cols();
CHECK_EQ(kStateDim, sampled_state.rows());
CHECK_EQ(kNoiseDim, sampled_noise.rows());
if (kInputDim != 0) {
CHECK_EQ(kInputDim, input.rows());
}
Eigen::MatrixXd result(kStateDim, kStateSampleCount * kNoiseSampleCount);
// Evaluate the propagate function for each combination of state / noise
// samples.
for (size_t i = 0u; i < kStateSampleCount; ++i) {
for (size_t j = 0u; j < kNoiseSampleCount; ++j) {
result.col(i * kNoiseSampleCount + j) = propagate(sampled_state.col(i),
input,
sampled_noise.col(j));
}
}
return result;
}
/**
* Use this function if your system does not have an input.
* The function clones the system noise, so it can be used again.
*
* @param state_dim The systems state dimension.
* @param system_noise The system noise.
*/
void SystemModelBase::setSystemModelBaseParameters(
const std::size_t& state_dim, const DistributionInterface& system_noise) {
this->setSystemModelBaseParameters(state_dim, system_noise, 0);
}
/**
* Use this function if your system model does have an input.
* The function clones the system noise, so it can be used again.
*
* @param state_dim The systems state dimension.
* @param system_noise The system noise.
* @param input_dim The systems input dimension.
*/
void SystemModelBase::setSystemModelBaseParameters(
const std::size_t& state_dim, const DistributionInterface& system_noise,
const std::size_t& input_dim) {
state_dim_ = state_dim;
system_noise_.reset(system_noise.clone());
input_dim_ = input_dim;
}
/** @return the state dimension. */
size_t SystemModelBase::getStateDim() const {
return state_dim_;
}
/** @return the input dimension. */
size_t SystemModelBase::getInputDim() const {
return input_dim_;
}
/** @return the noise dimension. */
size_t SystemModelBase::getNoiseDim() const {
CHECK(system_noise_) << "System noise has not been set.";
return system_noise_->mean().size();
}
/** @return a pointer to the system noise distribution. */
DistributionInterface* SystemModelBase::getNoise() const {
CHECK(system_noise_) << "System noise has not been set.";
return system_noise_.get();
}
} // namespace refill
|
/* $Id: edit_label.hpp 48877 2011-03-13 07:49:35Z mordante $ */
/*
Copyright (C) 2010 - 2011 by Ignacio Riquelme Morelle <shadowm2006@gmail.com>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
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 2 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.
See the COPYING file for more details.
*/
#ifndef GUI_DIALOGS_EDIT_LABEL_HPP_INCLUDED
#define GUI_DIALOGS_EDIT_LABEL_HPP_INCLUDED
#include "gui/dialogs/dialog.hpp"
namespace gui2 {
class tedit_label : public tdialog
{
public:
/**
* Constructor.
*
* @param label [in] The initial value of the label.
* @param label [out] The label text the user entered if the dialog
* returns @ref twindow::OK undefined otherise.
* @param team_only [in] The initial value of the team only toggle.
* @param team_only [out] The final value of the team only toggle if the
* dialog returns @ref twindow::OK undefined
* otherise.
*/
tedit_label(std::string& label, bool& team_only);
/** The excute function see @ref tdialog for more information. */
static bool execute(std::string& label, bool& team_only, CVideo& video)
{
return tedit_label(label, team_only).show(video);
}
private:
/** Inherited from tdialog, implemented by REGISTER_DIALOG. */
virtual const std::string& window_id() const;
};
}
#endif /* ! GUI_DIALOGS_EDIT_LABEL_INCLUDED */
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "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 COPYRIGHT
// OWNER OR CONTRIBUTORS 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.
// Implements the DescriptorPool, which collects all descriptors.
#include <Python.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/descriptor_database.h>
#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/message.h>
#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#include <google/protobuf/stubs/hash.h>
#if PY_MAJOR_VERSION >= 3
#define PyString_FromStringAndSize PyUnicode_FromStringAndSize
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#endif
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
? -1 \
: 0) \
: PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#endif
namespace google {
namespace protobuf {
namespace python {
// A map to cache Python Pools per C++ pointer.
// Pointers are not owned here, and belong to the PyDescriptorPool.
static hash_map<const DescriptorPool*, PyDescriptorPool*> descriptor_pool_map;
namespace cdescriptor_pool {
// Create a Python DescriptorPool object, but does not fill the "pool"
// attribute.
static PyDescriptorPool* _CreateDescriptorPool() {
PyDescriptorPool* cpool = PyObject_New(
PyDescriptorPool, &PyDescriptorPool_Type);
if (cpool == NULL) {
return NULL;
}
cpool->underlay = NULL;
cpool->database = NULL;
cpool->descriptor_options =
new hash_map<const void*, PyObject *>();
cpool->py_message_factory = message_factory::NewMessageFactory(
&PyMessageFactory_Type, cpool);
if (cpool->py_message_factory == NULL) {
Py_DECREF(cpool);
return NULL;
}
return cpool;
}
// Create a Python DescriptorPool, using the given pool as an underlay:
// new messages will be added to a custom pool, not to the underlay.
//
// Ownership of the underlay is not transferred, its pointer should
// stay alive.
static PyDescriptorPool* PyDescriptorPool_NewWithUnderlay(
const DescriptorPool* underlay) {
PyDescriptorPool* cpool = _CreateDescriptorPool();
if (cpool == NULL) {
return NULL;
}
cpool->pool = new DescriptorPool(underlay);
cpool->underlay = underlay;
if (!descriptor_pool_map.insert(
std::make_pair(cpool->pool, cpool)).second) {
// Should never happen -- would indicate an internal error / bug.
PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered");
return NULL;
}
return cpool;
}
static PyDescriptorPool* PyDescriptorPool_NewWithDatabase(
DescriptorDatabase* database) {
PyDescriptorPool* cpool = _CreateDescriptorPool();
if (cpool == NULL) {
return NULL;
}
if (database != NULL) {
cpool->pool = new DescriptorPool(database);
cpool->database = database;
} else {
cpool->pool = new DescriptorPool();
}
if (!descriptor_pool_map.insert(std::make_pair(cpool->pool, cpool)).second) {
// Should never happen -- would indicate an internal error / bug.
PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered");
return NULL;
}
return cpool;
}
// The public DescriptorPool constructor.
static PyObject* New(PyTypeObject* type,
PyObject* args, PyObject* kwargs) {
static const char* kwlist[] = {"descriptor_db", 0};
PyObject* py_database = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", const_cast<char**>(kwlist), &py_database)) {
return NULL;
}
DescriptorDatabase* database = NULL;
if (py_database && py_database != Py_None) {
database = new PyDescriptorDatabase(py_database);
}
return reinterpret_cast<PyObject*>(
PyDescriptorPool_NewWithDatabase(database));
}
static void Dealloc(PyObject* object) {
PyDescriptorPool* self = reinterpret_cast<PyDescriptorPool*>(object);
descriptor_pool_map.erase(self->pool);
Py_CLEAR(self->py_message_factory);
for (hash_map<const void*, PyObject*>::iterator it =
self->descriptor_options->begin();
it != self->descriptor_options->end(); ++it) {
Py_DECREF(it->second);
}
delete self->descriptor_options;
delete self->database;
delete self->pool;
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
PyObject* FindMessageByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
}
const Descriptor* message_descriptor =
self->pool->FindMessageTypeByName(string(name, name_size));
if (message_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find message %.200s", name);
return NULL;
}
return PyMessageDescriptor_FromDescriptor(message_descriptor);
}
PyObject* FindFileByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
}
const FileDescriptor* file_descriptor =
self->pool->FindFileByName(string(name, name_size));
if (file_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find file %.200s", name);
return NULL;
}
return PyFileDescriptor_FromDescriptor(file_descriptor);
}
PyObject* FindFieldByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
}
const FieldDescriptor* field_descriptor =
self->pool->FindFieldByName(string(name, name_size));
if (field_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find field %.200s",
name);
return NULL;
}
return PyFieldDescriptor_FromDescriptor(field_descriptor);
}
PyObject* FindExtensionByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
}
const FieldDescriptor* field_descriptor =
self->pool->FindExtensionByName(string(name, name_size));
if (field_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find extension field %.200s", name);
return NULL;
}
return PyFieldDescriptor_FromDescriptor(field_descriptor);
}
PyObject* FindEnumTypeByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
}
const EnumDescriptor* enum_descriptor =
self->pool->FindEnumTypeByName(string(name, name_size));
if (enum_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find enum %.200s", name);
return NULL;
}
return PyEnumDescriptor_FromDescriptor(enum_descriptor);
}
PyObject* FindOneofByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
}
const OneofDescriptor* oneof_descriptor =
self->pool->FindOneofByName(string(name, name_size));
if (oneof_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find oneof %.200s", name);
return NULL;
}
return PyOneofDescriptor_FromDescriptor(oneof_descriptor);
}
PyObject* FindServiceByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
}
const ServiceDescriptor* service_descriptor =
self->pool->FindServiceByName(string(name, name_size));
if (service_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find service %.200s", name);
return NULL;
}
return PyServiceDescriptor_FromDescriptor(service_descriptor);
}
PyObject* FindMethodByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
}
const MethodDescriptor* method_descriptor =
self->pool->FindMethodByName(string(name, name_size));
if (method_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find method %.200s", name);
return NULL;
}
return PyMethodDescriptor_FromDescriptor(method_descriptor);
}
PyObject* FindFileContainingSymbol(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
}
const FileDescriptor* file_descriptor =
self->pool->FindFileContainingSymbol(string(name, name_size));
if (file_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find symbol %.200s", name);
return NULL;
}
return PyFileDescriptor_FromDescriptor(file_descriptor);
}
PyObject* FindExtensionByNumber(PyDescriptorPool* self, PyObject* args) {
PyObject* message_descriptor;
int number;
if (!PyArg_ParseTuple(args, "Oi", &message_descriptor, &number)) {
return NULL;
}
const Descriptor* descriptor = PyMessageDescriptor_AsDescriptor(
message_descriptor);
if (descriptor == NULL) {
return NULL;
}
const FieldDescriptor* extension_descriptor =
self->pool->FindExtensionByNumber(descriptor, number);
if (extension_descriptor == NULL) {
PyErr_Format(PyExc_KeyError, "Couldn't find extension %d", number);
return NULL;
}
return PyFieldDescriptor_FromDescriptor(extension_descriptor);
}
PyObject* FindAllExtensions(PyDescriptorPool* self, PyObject* arg) {
const Descriptor* descriptor = PyMessageDescriptor_AsDescriptor(arg);
if (descriptor == NULL) {
return NULL;
}
std::vector<const FieldDescriptor*> extensions;
self->pool->FindAllExtensions(descriptor, &extensions);
ScopedPyObjectPtr result(PyList_New(extensions.size()));
if (result == NULL) {
return NULL;
}
for (int i = 0; i < extensions.size(); i++) {
PyObject* extension = PyFieldDescriptor_FromDescriptor(extensions[i]);
if (extension == NULL) {
return NULL;
}
PyList_SET_ITEM(result.get(), i, extension); // Steals the reference.
}
return result.release();
}
// These functions should not exist -- the only valid way to create
// descriptors is to call Add() or AddSerializedFile().
// But these AddDescriptor() functions were created in Python and some people
// call them, so we support them for now for compatibility.
// However we do check that the existing descriptor already exists in the pool,
// which appears to always be true for existing calls -- but then why do people
// call a function that will just be a no-op?
// TODO(amauryfa): Need to investigate further.
PyObject* AddFileDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
const FileDescriptor* file_descriptor =
PyFileDescriptor_AsDescriptor(descriptor);
if (!file_descriptor) {
return NULL;
}
if (file_descriptor !=
self->pool->FindFileByName(file_descriptor->name())) {
PyErr_Format(PyExc_ValueError,
"The file descriptor %s does not belong to this pool",
file_descriptor->name().c_str());
return NULL;
}
Py_RETURN_NONE;
}
PyObject* AddDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
const Descriptor* message_descriptor =
PyMessageDescriptor_AsDescriptor(descriptor);
if (!message_descriptor) {
return NULL;
}
if (message_descriptor !=
self->pool->FindMessageTypeByName(message_descriptor->full_name())) {
PyErr_Format(PyExc_ValueError,
"The message descriptor %s does not belong to this pool",
message_descriptor->full_name().c_str());
return NULL;
}
Py_RETURN_NONE;
}
PyObject* AddEnumDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
const EnumDescriptor* enum_descriptor =
PyEnumDescriptor_AsDescriptor(descriptor);
if (!enum_descriptor) {
return NULL;
}
if (enum_descriptor !=
self->pool->FindEnumTypeByName(enum_descriptor->full_name())) {
PyErr_Format(PyExc_ValueError,
"The enum descriptor %s does not belong to this pool",
enum_descriptor->full_name().c_str());
return NULL;
}
Py_RETURN_NONE;
}
PyObject* AddExtensionDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
const FieldDescriptor* extension_descriptor =
PyFieldDescriptor_AsDescriptor(descriptor);
if (!extension_descriptor) {
return NULL;
}
if (extension_descriptor !=
self->pool->FindExtensionByName(extension_descriptor->full_name())) {
PyErr_Format(PyExc_ValueError,
"The extension descriptor %s does not belong to this pool",
extension_descriptor->full_name().c_str());
return NULL;
}
Py_RETURN_NONE;
}
PyObject* AddServiceDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
const ServiceDescriptor* service_descriptor =
PyServiceDescriptor_AsDescriptor(descriptor);
if (!service_descriptor) {
return NULL;
}
if (service_descriptor !=
self->pool->FindServiceByName(service_descriptor->full_name())) {
PyErr_Format(PyExc_ValueError,
"The service descriptor %s does not belong to this pool",
service_descriptor->full_name().c_str());
return NULL;
}
Py_RETURN_NONE;
}
// The code below loads new Descriptors from a serialized FileDescriptorProto.
// Collects errors that occur during proto file building to allow them to be
// propagated in the python exception instead of only living in ERROR logs.
class BuildFileErrorCollector : public DescriptorPool::ErrorCollector {
public:
BuildFileErrorCollector() : error_message(""), had_errors(false) {}
void AddError(const string& filename, const string& element_name,
const Message* descriptor, ErrorLocation location,
const string& message) {
// Replicates the logging behavior that happens in the C++ implementation
// when an error collector is not passed in.
if (!had_errors) {
error_message +=
("Invalid proto descriptor for file \"" + filename + "\":\n");
had_errors = true;
}
// As this only happens on failure and will result in the program not
// running at all, no effort is made to optimize this string manipulation.
error_message += (" " + element_name + ": " + message + "\n");
}
string error_message;
bool had_errors;
};
PyObject* AddSerializedFile(PyDescriptorPool* self, PyObject* serialized_pb) {
char* message_type;
Py_ssize_t message_len;
if (self->database != NULL) {
PyErr_SetString(
PyExc_ValueError,
"Cannot call Add on a DescriptorPool that uses a DescriptorDatabase. "
"Add your file to the underlying database.");
return NULL;
}
if (PyBytes_AsStringAndSize(serialized_pb, &message_type, &message_len) < 0) {
return NULL;
}
FileDescriptorProto file_proto;
if (!file_proto.ParseFromArray(message_type, message_len)) {
PyErr_SetString(PyExc_TypeError, "Couldn't parse file content!");
return NULL;
}
// If the file was already part of a C++ library, all its descriptors are in
// the underlying pool. No need to do anything else.
const FileDescriptor* generated_file = NULL;
if (self->underlay) {
generated_file = self->underlay->FindFileByName(file_proto.name());
}
if (generated_file != NULL) {
return PyFileDescriptor_FromDescriptorWithSerializedPb(
generated_file, serialized_pb);
}
BuildFileErrorCollector error_collector;
const FileDescriptor* descriptor =
self->pool->BuildFileCollectingErrors(file_proto,
&error_collector);
if (descriptor == NULL) {
PyErr_Format(PyExc_TypeError,
"Couldn't build proto file into descriptor pool!\n%s",
error_collector.error_message.c_str());
return NULL;
}
return PyFileDescriptor_FromDescriptorWithSerializedPb(
descriptor, serialized_pb);
}
PyObject* Add(PyDescriptorPool* self, PyObject* file_descriptor_proto) {
ScopedPyObjectPtr serialized_pb(
PyObject_CallMethod(file_descriptor_proto, "SerializeToString", NULL));
if (serialized_pb == NULL) {
return NULL;
}
return AddSerializedFile(self, serialized_pb.get());
}
static PyMethodDef Methods[] = {
{ "Add", (PyCFunction)Add, METH_O,
"Adds the FileDescriptorProto and its types to this pool." },
{ "AddSerializedFile", (PyCFunction)AddSerializedFile, METH_O,
"Adds a serialized FileDescriptorProto to this pool." },
// TODO(amauryfa): Understand why the Python implementation differs from
// this one, ask users to use another API and deprecate these functions.
{ "AddFileDescriptor", (PyCFunction)AddFileDescriptor, METH_O,
"No-op. Add() must have been called before." },
{ "AddDescriptor", (PyCFunction)AddDescriptor, METH_O,
"No-op. Add() must have been called before." },
{ "AddEnumDescriptor", (PyCFunction)AddEnumDescriptor, METH_O,
"No-op. Add() must have been called before." },
{ "AddExtensionDescriptor", (PyCFunction)AddExtensionDescriptor, METH_O,
"No-op. Add() must have been called before." },
{ "AddServiceDescriptor", (PyCFunction)AddServiceDescriptor, METH_O,
"No-op. Add() must have been called before." },
{ "FindFileByName", (PyCFunction)FindFileByName, METH_O,
"Searches for a file descriptor by its .proto name." },
{ "FindMessageTypeByName", (PyCFunction)FindMessageByName, METH_O,
"Searches for a message descriptor by full name." },
{ "FindFieldByName", (PyCFunction)FindFieldByName, METH_O,
"Searches for a field descriptor by full name." },
{ "FindExtensionByName", (PyCFunction)FindExtensionByName, METH_O,
"Searches for extension descriptor by full name." },
{ "FindEnumTypeByName", (PyCFunction)FindEnumTypeByName, METH_O,
"Searches for enum type descriptor by full name." },
{ "FindOneofByName", (PyCFunction)FindOneofByName, METH_O,
"Searches for oneof descriptor by full name." },
{ "FindServiceByName", (PyCFunction)FindServiceByName, METH_O,
"Searches for service descriptor by full name." },
{ "FindMethodByName", (PyCFunction)FindMethodByName, METH_O,
"Searches for method descriptor by full name." },
{ "FindFileContainingSymbol", (PyCFunction)FindFileContainingSymbol, METH_O,
"Gets the FileDescriptor containing the specified symbol." },
{ "FindExtensionByNumber", (PyCFunction)FindExtensionByNumber, METH_VARARGS,
"Gets the extension descriptor for the given number." },
{ "FindAllExtensions", (PyCFunction)FindAllExtensions, METH_O,
"Gets all known extensions of the given message descriptor." },
{NULL}
};
} // namespace cdescriptor_pool
PyTypeObject PyDescriptorPool_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
FULL_MODULE_NAME ".DescriptorPool", // tp_name
sizeof(PyDescriptorPool), // tp_basicsize
0, // tp_itemsize
(destructor)cdescriptor_pool::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"A Descriptor Pool", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
cdescriptor_pool::Methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
cdescriptor_pool::New, // tp_new
PyObject_Del, // tp_free
};
// This is the DescriptorPool which contains all the definitions from the
// generated _pb2.py modules.
static PyDescriptorPool* python_generated_pool = NULL;
bool InitDescriptorPool() {
if (PyType_Ready(&PyDescriptorPool_Type) < 0)
return false;
// The Pool of messages declared in Python libraries.
// generated_pool() contains all messages already linked in C++ libraries, and
// is used as underlay.
python_generated_pool = cdescriptor_pool::PyDescriptorPool_NewWithUnderlay(
DescriptorPool::generated_pool());
if (python_generated_pool == NULL) {
return false;
}
// Register this pool to be found for C++-generated descriptors.
descriptor_pool_map.insert(
std::make_pair(DescriptorPool::generated_pool(),
python_generated_pool));
return true;
}
// The default DescriptorPool used everywhere in this module.
// Today it's the python_generated_pool.
// TODO(amauryfa): Remove all usages of this function: the pool should be
// derived from the context.
PyDescriptorPool* GetDefaultDescriptorPool() {
return python_generated_pool;
}
PyDescriptorPool* GetDescriptorPool_FromPool(const DescriptorPool* pool) {
// Fast path for standard descriptors.
if (pool == python_generated_pool->pool ||
pool == DescriptorPool::generated_pool()) {
return python_generated_pool;
}
hash_map<const DescriptorPool*, PyDescriptorPool*>::iterator it =
descriptor_pool_map.find(pool);
if (it == descriptor_pool_map.end()) {
PyErr_SetString(PyExc_KeyError, "Unknown descriptor pool");
return NULL;
}
return it->second;
}
} // namespace python
} // namespace protobuf
} // namespace google
|
/*
Source File : PDFParsingOptions.h
Copyright 2011 Gal Kahana PDFWriter
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.
*/
#include "PDFParsingOptions.h"
const PDFParsingOptions& PDFParsingOptions::DefaultPDFParsingOptions(){
static PDFParsingOptions pdf_parsing_options("");
return pdf_parsing_options;
}
|
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "media/engine/internalencoderfactory.h"
#include "media/engine/simulcast_encoder_adapter.h"
#include "modules/rtp_rtcp/source/rtp_format.h"
#include "modules/video_coding/codecs/vp9/include/vp9.h"
#include "rtc_base/numerics/safe_conversions.h"
#include "rtc_base/numerics/sequence_number_util.h"
#include "test/call_test.h"
namespace webrtc {
namespace {
const int kFrameMaxWidth = 1280;
const int kFrameMaxHeight = 720;
const int kFrameRate = 30;
const int kMaxSecondsLost = 5;
const int kMaxFramesLost = kFrameRate * kMaxSecondsLost;
const int kMinPacketsToObserve = 10;
const int kEncoderBitrateBps = 300000;
const uint32_t kPictureIdWraparound = (1 << 15);
const size_t kNumTemporalLayers[] = {1, 2, 3};
RtpVideoCodecTypes PayloadNameToRtpVideoCodecType(
const std::string& payload_name) {
if (payload_name == "VP8") {
return kRtpVideoVp8;
} else if (payload_name == "VP9") {
return kRtpVideoVp9;
} else {
RTC_NOTREACHED();
return kRtpVideoNone;
}
}
} // namespace
class PictureIdObserver : public test::RtpRtcpObserver {
public:
explicit PictureIdObserver(RtpVideoCodecTypes codec_type)
: test::RtpRtcpObserver(test::CallTest::kDefaultTimeoutMs),
codec_type_(codec_type),
max_expected_picture_id_gap_(0),
max_expected_tl0_idx_gap_(0),
num_ssrcs_to_observe_(1) {}
void SetExpectedSsrcs(size_t num_expected_ssrcs) {
rtc::CritScope lock(&crit_);
num_ssrcs_to_observe_ = num_expected_ssrcs;
}
void ResetObservedSsrcs() {
rtc::CritScope lock(&crit_);
// Do not clear the timestamp and picture_id, to ensure that we check
// consistency between reinits and recreations.
num_packets_sent_.clear();
observed_ssrcs_.clear();
}
void SetMaxExpectedPictureIdGap(int max_expected_picture_id_gap) {
rtc::CritScope lock(&crit_);
max_expected_picture_id_gap_ = max_expected_picture_id_gap;
// Expect smaller gap for |tl0_pic_idx| (running index for temporal_idx 0).
max_expected_tl0_idx_gap_ = max_expected_picture_id_gap_ / 2;
}
private:
struct ParsedPacket {
uint32_t timestamp;
uint32_t ssrc;
int16_t picture_id;
int16_t tl0_pic_idx;
uint8_t temporal_idx;
FrameType frame_type;
};
bool ParsePayload(const uint8_t* packet,
size_t length,
ParsedPacket* parsed) const {
RTPHeader header;
EXPECT_TRUE(parser_->Parse(packet, length, &header));
EXPECT_TRUE(header.ssrc == test::CallTest::kVideoSendSsrcs[0] ||
header.ssrc == test::CallTest::kVideoSendSsrcs[1] ||
header.ssrc == test::CallTest::kVideoSendSsrcs[2])
<< "Unknown SSRC sent.";
EXPECT_GE(length, header.headerLength + header.paddingLength);
size_t payload_length = length - header.headerLength - header.paddingLength;
if (payload_length == 0) {
return false; // Padding packet.
}
parsed->timestamp = header.timestamp;
parsed->ssrc = header.ssrc;
std::unique_ptr<RtpDepacketizer> depacketizer(
RtpDepacketizer::Create(codec_type_));
RtpDepacketizer::ParsedPayload parsed_payload;
EXPECT_TRUE(depacketizer->Parse(
&parsed_payload, &packet[header.headerLength], payload_length));
switch (codec_type_) {
case kRtpVideoVp8:
parsed->picture_id =
parsed_payload.type.Video.codecHeader.VP8.pictureId;
parsed->tl0_pic_idx =
parsed_payload.type.Video.codecHeader.VP8.tl0PicIdx;
parsed->temporal_idx =
parsed_payload.type.Video.codecHeader.VP8.temporalIdx;
break;
case kRtpVideoVp9:
parsed->picture_id =
parsed_payload.type.Video.codecHeader.VP9.picture_id;
parsed->tl0_pic_idx =
parsed_payload.type.Video.codecHeader.VP9.tl0_pic_idx;
parsed->temporal_idx =
parsed_payload.type.Video.codecHeader.VP9.temporal_idx;
break;
default:
RTC_NOTREACHED();
break;
}
parsed->frame_type = parsed_payload.frame_type;
return true;
}
// Verify continuity and monotonicity of picture_id sequence.
void VerifyPictureId(const ParsedPacket& current,
const ParsedPacket& last) const
RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
if (current.timestamp == last.timestamp) {
EXPECT_EQ(last.picture_id, current.picture_id);
return; // Same frame.
}
// Packet belongs to a new frame.
// Picture id should be increasing.
EXPECT_TRUE((AheadOf<uint16_t, kPictureIdWraparound>(current.picture_id,
last.picture_id)));
// Expect continuously increasing picture id.
int diff = ForwardDiff<uint16_t, kPictureIdWraparound>(last.picture_id,
current.picture_id);
if (diff > 1) {
// If the VideoSendStream is destroyed, any frames still in queue is lost.
// Gaps only possible for first frame after a recreation, i.e. key frames.
EXPECT_EQ(kVideoFrameKey, current.frame_type);
EXPECT_LE(diff - 1, max_expected_picture_id_gap_);
}
}
void VerifyTl0Idx(const ParsedPacket& current, const ParsedPacket& last) const
RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
if (current.tl0_pic_idx == kNoTl0PicIdx ||
current.temporal_idx == kNoTemporalIdx) {
return; // No temporal layers.
}
if (current.timestamp == last.timestamp || current.temporal_idx != 0) {
EXPECT_EQ(last.tl0_pic_idx, current.tl0_pic_idx);
return;
}
// New frame with |temporal_idx| 0.
// |tl0_pic_idx| should be increasing.
EXPECT_TRUE(AheadOf<uint8_t>(current.tl0_pic_idx, last.tl0_pic_idx));
// Expect continuously increasing idx.
int diff = ForwardDiff<uint8_t>(last.tl0_pic_idx, current.tl0_pic_idx);
if (diff > 1) {
// If the VideoSendStream is destroyed, any frames still in queue is lost.
// Gaps only possible for first frame after a recreation, i.e. key frames.
EXPECT_EQ(kVideoFrameKey, current.frame_type);
EXPECT_LE(diff - 1, max_expected_tl0_idx_gap_);
}
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
rtc::CritScope lock(&crit_);
ParsedPacket parsed;
if (!ParsePayload(packet, length, &parsed))
return SEND_PACKET;
uint32_t ssrc = parsed.ssrc;
if (last_observed_packet_.find(ssrc) != last_observed_packet_.end()) {
// Compare to last packet.
VerifyPictureId(parsed, last_observed_packet_[ssrc]);
VerifyTl0Idx(parsed, last_observed_packet_[ssrc]);
}
last_observed_packet_[ssrc] = parsed;
// Pass the test when enough media packets have been received on all
// streams.
if (++num_packets_sent_[ssrc] >= kMinPacketsToObserve &&
observed_ssrcs_.find(ssrc) == observed_ssrcs_.end()) {
observed_ssrcs_.insert(ssrc);
if (observed_ssrcs_.size() == num_ssrcs_to_observe_) {
observation_complete_.Set();
}
}
return SEND_PACKET;
}
rtc::CriticalSection crit_;
const RtpVideoCodecTypes codec_type_;
std::map<uint32_t, ParsedPacket> last_observed_packet_ RTC_GUARDED_BY(crit_);
std::map<uint32_t, size_t> num_packets_sent_ RTC_GUARDED_BY(crit_);
int max_expected_picture_id_gap_ RTC_GUARDED_BY(crit_);
int max_expected_tl0_idx_gap_ RTC_GUARDED_BY(crit_);
size_t num_ssrcs_to_observe_ RTC_GUARDED_BY(crit_);
std::set<uint32_t> observed_ssrcs_ RTC_GUARDED_BY(crit_);
};
class PictureIdTest : public test::CallTest,
public ::testing::WithParamInterface<size_t> {
public:
PictureIdTest() : num_temporal_layers_(GetParam()) {}
virtual ~PictureIdTest() {
EXPECT_EQ(nullptr, video_send_stream_);
EXPECT_TRUE(video_receive_streams_.empty());
task_queue_.SendTask([this]() {
send_transport_.reset();
receive_transport_.reset();
DestroyCalls();
});
}
void SetupEncoder(VideoEncoder* encoder, const std::string& payload_name);
void TestPictureIdContinuousAfterReconfigure(
const std::vector<int>& ssrc_counts);
void TestPictureIdIncreaseAfterRecreateStreams(
const std::vector<int>& ssrc_counts);
private:
const size_t num_temporal_layers_;
std::unique_ptr<PictureIdObserver> observer_;
};
INSTANTIATE_TEST_CASE_P(TemporalLayers,
PictureIdTest,
::testing::ValuesIn(kNumTemporalLayers));
// Use a special stream factory to ensure that all simulcast streams are being
// sent.
class VideoStreamFactory
: public VideoEncoderConfig::VideoStreamFactoryInterface {
public:
explicit VideoStreamFactory(size_t num_temporal_layers)
: num_of_temporal_layers_(num_temporal_layers) {}
private:
std::vector<VideoStream> CreateEncoderStreams(
int width,
int height,
const VideoEncoderConfig& encoder_config) override {
std::vector<VideoStream> streams =
test::CreateVideoStreams(width, height, encoder_config);
// Use the same total bitrates when sending a single stream to avoid
// lowering the bitrate estimate and requiring a subsequent rampup.
const int encoder_stream_bps = kEncoderBitrateBps / rtc::checked_cast<int>(
encoder_config.number_of_streams);
for (size_t i = 0; i < encoder_config.number_of_streams; ++i) {
streams[i].min_bitrate_bps = encoder_stream_bps;
streams[i].target_bitrate_bps = encoder_stream_bps;
streams[i].max_bitrate_bps = encoder_stream_bps;
streams[i].num_temporal_layers = num_of_temporal_layers_;
// test::CreateVideoStreams does not return frame sizes for the lower
// streams that are accepted by VP8Impl::InitEncode.
// TODO(brandtr): Fix the problem in test::CreateVideoStreams, rather
// than overriding the values here.
streams[i].width =
width / (1 << (encoder_config.number_of_streams - 1 - i));
streams[i].height =
height / (1 << (encoder_config.number_of_streams - 1 - i));
}
return streams;
}
const size_t num_of_temporal_layers_;
};
void PictureIdTest::SetupEncoder(VideoEncoder* encoder,
const std::string& payload_name) {
observer_.reset(
new PictureIdObserver(PayloadNameToRtpVideoCodecType(payload_name)));
task_queue_.SendTask([this, &encoder, payload_name]() {
Call::Config config(event_log_.get());
CreateCalls(config, config);
send_transport_.reset(new test::PacketTransport(
&task_queue_, sender_call_.get(), observer_.get(),
test::PacketTransport::kSender, payload_type_map_,
FakeNetworkPipe::Config()));
CreateSendConfig(kNumSimulcastStreams, 0, 0, send_transport_.get());
video_send_config_.encoder_settings.encoder = encoder;
video_send_config_.rtp.payload_name = payload_name;
video_encoder_config_.codec_type = PayloadStringToCodecType(payload_name);
video_encoder_config_.video_stream_factory =
new rtc::RefCountedObject<VideoStreamFactory>(num_temporal_layers_);
video_encoder_config_.number_of_streams = 1;
});
}
void PictureIdTest::TestPictureIdContinuousAfterReconfigure(
const std::vector<int>& ssrc_counts) {
task_queue_.SendTask([this]() {
CreateVideoStreams();
CreateFrameGeneratorCapturer(kFrameRate, kFrameMaxWidth, kFrameMaxHeight);
// Initial test with a single stream.
Start();
});
EXPECT_TRUE(observer_->Wait()) << "Timed out waiting for packets.";
// Reconfigure VideoEncoder and test picture id increase.
// Expect continuously increasing picture id, equivalent to no gaps.
observer_->SetMaxExpectedPictureIdGap(0);
for (int ssrc_count : ssrc_counts) {
video_encoder_config_.number_of_streams = ssrc_count;
observer_->SetExpectedSsrcs(ssrc_count);
observer_->ResetObservedSsrcs();
// Make sure the picture_id sequence is continuous on reinit and recreate.
task_queue_.SendTask([this]() {
video_send_stream_->ReconfigureVideoEncoder(video_encoder_config_.Copy());
});
EXPECT_TRUE(observer_->Wait()) << "Timed out waiting for packets.";
}
task_queue_.SendTask([this]() {
Stop();
DestroyStreams();
});
}
void PictureIdTest::TestPictureIdIncreaseAfterRecreateStreams(
const std::vector<int>& ssrc_counts) {
task_queue_.SendTask([this]() {
CreateVideoStreams();
CreateFrameGeneratorCapturer(kFrameRate, kFrameMaxWidth, kFrameMaxHeight);
// Initial test with a single stream.
Start();
});
EXPECT_TRUE(observer_->Wait()) << "Timed out waiting for packets.";
// Recreate VideoSendStream and test picture id increase.
// When the VideoSendStream is destroyed, any frames still in queue is lost
// with it, therefore it is expected that some frames might be lost.
observer_->SetMaxExpectedPictureIdGap(kMaxFramesLost);
for (int ssrc_count : ssrc_counts) {
task_queue_.SendTask([this, &ssrc_count]() {
frame_generator_capturer_->Stop();
sender_call_->DestroyVideoSendStream(video_send_stream_);
video_encoder_config_.number_of_streams = ssrc_count;
observer_->SetExpectedSsrcs(ssrc_count);
observer_->ResetObservedSsrcs();
video_send_stream_ = sender_call_->CreateVideoSendStream(
video_send_config_.Copy(), video_encoder_config_.Copy());
video_send_stream_->Start();
CreateFrameGeneratorCapturer(kFrameRate, kFrameMaxWidth, kFrameMaxHeight);
frame_generator_capturer_->Start();
});
EXPECT_TRUE(observer_->Wait()) << "Timed out waiting for packets.";
}
task_queue_.SendTask([this]() {
Stop();
DestroyStreams();
});
}
TEST_P(PictureIdTest, ContinuousAfterReconfigureVp8) {
std::unique_ptr<VideoEncoder> encoder(VP8Encoder::Create());
SetupEncoder(encoder.get(), "VP8");
TestPictureIdContinuousAfterReconfigure({1, 3, 3, 1, 1});
}
TEST_P(PictureIdTest, IncreasingAfterRecreateStreamVp8) {
std::unique_ptr<VideoEncoder> encoder(VP8Encoder::Create());
SetupEncoder(encoder.get(), "VP8");
TestPictureIdIncreaseAfterRecreateStreams({1, 3, 3, 1, 1});
}
TEST_P(PictureIdTest, ContinuousAfterStreamCountChangeVp8) {
std::unique_ptr<VideoEncoder> encoder(VP8Encoder::Create());
// Make sure that the picture id is not reset if the stream count goes
// down and then up.
SetupEncoder(encoder.get(), "VP8");
TestPictureIdContinuousAfterReconfigure({3, 1, 3});
}
TEST_P(PictureIdTest, ContinuousAfterReconfigureSimulcastEncoderAdapter) {
InternalEncoderFactory internal_encoder_factory;
SimulcastEncoderAdapter simulcast_encoder_adapter(&internal_encoder_factory);
SetupEncoder(&simulcast_encoder_adapter, "VP8");
TestPictureIdContinuousAfterReconfigure({1, 3, 3, 1, 1});
}
TEST_P(PictureIdTest, IncreasingAfterRecreateStreamSimulcastEncoderAdapter) {
InternalEncoderFactory internal_encoder_factory;
SimulcastEncoderAdapter simulcast_encoder_adapter(&internal_encoder_factory);
SetupEncoder(&simulcast_encoder_adapter, "VP8");
TestPictureIdIncreaseAfterRecreateStreams({1, 3, 3, 1, 1});
}
TEST_P(PictureIdTest, ContinuousAfterStreamCountChangeSimulcastEncoderAdapter) {
InternalEncoderFactory internal_encoder_factory;
SimulcastEncoderAdapter simulcast_encoder_adapter(&internal_encoder_factory);
// Make sure that the picture id is not reset if the stream count goes
// down and then up.
SetupEncoder(&simulcast_encoder_adapter, "VP8");
TestPictureIdContinuousAfterReconfigure({3, 1, 3});
}
TEST_P(PictureIdTest, IncreasingAfterRecreateStreamVp9) {
std::unique_ptr<VideoEncoder> encoder(VP9Encoder::Create());
SetupEncoder(encoder.get(), "VP9");
TestPictureIdIncreaseAfterRecreateStreams({1, 1});
}
} // namespace webrtc
|
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved.
#include <ivp_physics.hxx>
#if !defined(SUN) && !defined(SUN4)
# include <string.h>
#endif
#include <ivu_types.hxx>
// WIN32 ---------------------------------------------------------------------
static int IVP_RAND_SEED = 1;
// returns 0 .. 1.0
IVP_FLOAT ivp_rand() {
IVP_RAND_SEED *= 75;
IVP_FLOAT res = (IVP_RAND_SEED & 0xffff) / (float) 0x10000;
return res;
}
void ivp_srand(int seed) {
if (seed == 0) seed = 1;
IVP_RAND_SEED = seed;
}
int ivp_srand_read(void) {
return IVP_RAND_SEED;
}
extern void *p_malloc(unsigned int size);
#if 0
FILE *p_glob_fp;
void p_init_glob_fp()
{
#ifdef WIN32
p_glob_fp=fopen(ERRORFILEPATH,"a");
#else
p_glob_fp=stdout;
#endif
}
#endif
|
//
// native_encoder.cc
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// 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.
//
#include "native_glue.hh"
#include "fleece/Fleece.hh"
#include "com_couchbase_litecore_fleece_Encoder.h"
using namespace fleece;
using namespace litecore::jni;
// ----------------------------------------------------------------------------
// Encoder
// ----------------------------------------------------------------------------
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: init
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_couchbase_litecore_fleece_Encoder_init(JNIEnv *env, jclass clazz) {
return (jlong) new Encoder();
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: initWithFLEncoder
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL
Java_com_couchbase_litecore_fleece_Encoder_initWithFLEncoder(JNIEnv *env, jclass clazz,
jlong jflenc) {
return (jlong) new Encoder((FLEncoder) jflenc);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: free
* Signature: (J)V
*/
JNIEXPORT void JNICALL
Java_com_couchbase_litecore_fleece_Encoder_free(JNIEnv *env, jclass clazz, jlong jenc) {
delete (Encoder *) jenc;
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: release
* Signature: (J)V
*/
JNIEXPORT void JNICALL
Java_com_couchbase_litecore_fleece_Encoder_release(JNIEnv *env, jclass clazz, jlong jenc) {
Encoder *enc = (Encoder *) jenc;
enc->detach();
delete enc;
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: getFLEncoder
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL
Java_com_couchbase_litecore_fleece_Encoder_getFLEncoder(JNIEnv *env, jclass clazz, jlong jenc) {
Encoder *enc = (Encoder *) jenc;
FLEncoder flenc = (FLEncoder) *enc;
return (jlong) flenc;
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: writeNull
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_writeNull(JNIEnv *env, jclass clazz, jlong jenc) {
return ((Encoder *) jenc)->writeNull();
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: writeBool
* Signature: (JZ)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_writeBool(JNIEnv *env, jclass clazz, jlong jenc,
jboolean jvalue) {
return ((Encoder *) jenc)->writeBool((bool) jvalue);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: writeInt
* Signature: (JJ)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_writeInt(JNIEnv *env, jclass clazz, jlong jenc,
jlong jvalue) {
return ((Encoder *) jenc)->writeInt((int64_t) jvalue);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: writeFloat
* Signature: (JF)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_writeFloat(JNIEnv *env, jclass clazz, jlong jenc,
jfloat jvalue) {
return ((Encoder *) jenc)->writeFloat((float) jvalue);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: writeDouble
* Signature: (JD)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_writeDouble(JNIEnv *env, jclass clazz, jlong jenc,
jdouble jvalue) {
return ((Encoder *) jenc)->writeDouble((double) jvalue);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: writeString
* Signature: (JLjava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_writeString(JNIEnv *env, jclass clazz, jlong jenc,
jstring jvalue) {
jstringSlice value(env, jvalue);
slice s = value;
return ((Encoder *) jenc)->writeString(s);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: writeData
* Signature: (J[B)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_writeData(JNIEnv *env, jclass clazz, jlong jenc,
jbyteArray jvalue) {
jbyteArraySlice value(env, jvalue, true);
slice s = value;
return ((Encoder *) jenc)->writeData(s);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: writeValue
* Signature: (JJ)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_writeValue(JNIEnv *env, jclass clazz, jlong jenc,
jlong jvalue) {
return ((Encoder *) jenc)->writeValue((FLValue) jvalue);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: beginArray
* Signature: (JJ)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_beginArray(JNIEnv *env, jclass clazz, jlong jenc,
jlong jreserve) {
return ((Encoder *) jenc)->beginArray((size_t) jreserve);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: endArray
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_endArray(JNIEnv *env, jclass clazz, jlong jenc) {
return ((Encoder *) jenc)->endArray();
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: beginDict
* Signature: (JJ)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_beginDict(JNIEnv *env, jclass clazz, jlong jenc,
jlong jreserve) {
return ((Encoder *) jenc)->beginDict((size_t) jreserve);
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: writeKey
* Signature: (JLjava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_writeKey(JNIEnv *env, jclass clazz, jlong jenc,
jstring jkey) {
if (jkey == NULL) return false;
jstringSlice key(env, jkey);
slice s = key;
return ((Encoder *) jenc)->writeKey({s.buf, s.size});
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: endDict
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_couchbase_litecore_fleece_Encoder_endDict(JNIEnv *env, jclass clazz, jlong jenc) {
return ((Encoder *) jenc)->endDict();
}
/*
* Class: com_couchbase_litecore_fleece_Encoder
* Method: finish
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL
Java_com_couchbase_litecore_fleece_Encoder_finish(JNIEnv *env, jclass clazz, jlong jenc) {
FLError error = kFLNoError;
alloc_slice result = ((Encoder *) jenc)->finish(&error);
if (error != kFLNoError)
throwError(env, {FleeceDomain, error});
return (jlong) new alloc_slice(result);
}
|
#include <Processors/Transforms/WindowTransform.h>
#include <AggregateFunctions/AggregateFunctionFactory.h>
#include <Common/Arena.h>
#include <Common/FieldVisitorsAccurateComparison.h>
#include <common/arithmeticOverflow.h>
#include <Columns/ColumnConst.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/getLeastSupertype.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/convertFieldToType.h>
namespace DB
{
struct Settings;
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int NOT_IMPLEMENTED;
}
// Interface for true window functions. It's not much of an interface, they just
// accept the guts of WindowTransform and do 'something'. Given a small number of
// true window functions, and the fact that the WindowTransform internals are
// pretty much well defined in domain terms (e.g. frame boundaries), this is
// somewhat acceptable.
class IWindowFunction
{
public:
virtual ~IWindowFunction() = default;
// Must insert the result for current_row.
virtual void windowInsertResultInto(const WindowTransform * transform,
size_t function_index) = 0;
};
// Compares ORDER BY column values at given rows to find the boundaries of frame:
// [compared] with [reference] +/- offset. Return value is -1/0/+1, like in
// sorting predicates -- -1 means [compared] is less than [reference] +/- offset.
template <typename ColumnType>
static int compareValuesWithOffset(const IColumn * _compared_column,
size_t compared_row, const IColumn * _reference_column,
size_t reference_row,
const Field & _offset,
bool offset_is_preceding)
{
// Casting the columns to the known type here makes it faster, probably
// because the getData call can be devirtualized.
const auto * compared_column = assert_cast<const ColumnType *>(
_compared_column);
const auto * reference_column = assert_cast<const ColumnType *>(
_reference_column);
// Note that the storage type of offset returned by get<> is different, so
// we need to specify the type explicitly.
const typename ColumnType::ValueType offset
= _offset.get<typename ColumnType::ValueType>();
assert(offset >= 0);
const auto compared_value_data = compared_column->getDataAt(compared_row);
assert(compared_value_data.size == sizeof(typename ColumnType::ValueType));
auto compared_value = unalignedLoad<typename ColumnType::ValueType>(
compared_value_data.data);
const auto reference_value_data = reference_column->getDataAt(reference_row);
assert(reference_value_data.size == sizeof(typename ColumnType::ValueType));
auto reference_value = unalignedLoad<typename ColumnType::ValueType>(
reference_value_data.data);
bool is_overflow;
if (offset_is_preceding)
is_overflow = common::subOverflow(reference_value, offset, reference_value);
else
is_overflow = common::addOverflow(reference_value, offset, reference_value);
// fmt::print(stderr,
// "compared [{}] = {}, old ref {}, shifted ref [{}] = {}, offset {} preceding {} overflow {} to negative {}\n",
// compared_row, toString(compared_value),
// // fmt doesn't like char8_t.
// static_cast<Int64>(unalignedLoad<typename ColumnType::ValueType>(reference_value_data.data)),
// reference_row, toString(reference_value),
// toString(offset), offset_is_preceding,
// is_overflow, offset_is_preceding);
if (is_overflow)
{
if (offset_is_preceding)
{
// Overflow to the negative, [compared] must be greater.
// We know that because offset is >= 0.
return 1;
}
else
{
// Overflow to the positive, [compared] must be less.
return -1;
}
}
else
{
// No overflow, compare normally.
return compared_value < reference_value ? -1
: compared_value == reference_value ? 0 : 1;
}
}
// A specialization of compareValuesWithOffset for floats.
template <typename ColumnType>
static int compareValuesWithOffsetFloat(const IColumn * _compared_column,
size_t compared_row, const IColumn * _reference_column,
size_t reference_row,
const Field & _offset,
bool offset_is_preceding)
{
// Casting the columns to the known type here makes it faster, probably
// because the getData call can be devirtualized.
const auto * compared_column = assert_cast<const ColumnType *>(
_compared_column);
const auto * reference_column = assert_cast<const ColumnType *>(
_reference_column);
const auto offset = _offset.get<typename ColumnType::ValueType>();
assert(offset >= 0);
const auto compared_value_data = compared_column->getDataAt(compared_row);
assert(compared_value_data.size == sizeof(typename ColumnType::ValueType));
auto compared_value = unalignedLoad<typename ColumnType::ValueType>(
compared_value_data.data);
const auto reference_value_data = reference_column->getDataAt(reference_row);
assert(reference_value_data.size == sizeof(typename ColumnType::ValueType));
auto reference_value = unalignedLoad<typename ColumnType::ValueType>(
reference_value_data.data);
// Floats overflow to Inf and the comparison will work normally, so we don't
// have to do anything.
if (offset_is_preceding)
{
reference_value -= offset;
}
else
{
reference_value += offset;
}
const auto result = compared_value < reference_value ? -1
: compared_value == reference_value ? 0 : 1;
// fmt::print(stderr, "compared {}, offset {}, reference {}, result {}\n",
// compared_value, offset, reference_value, result);
return result;
}
// Helper macros to dispatch on type of the ORDER BY column
#define APPLY_FOR_ONE_TYPE(FUNCTION, TYPE) \
else if (typeid_cast<const TYPE *>(column)) \
{ \
/* clang-tidy you're dumb, I can't put FUNCTION in braces here. */ \
compare_values_with_offset = FUNCTION<TYPE>; /* NOLINT */ \
}
#define APPLY_FOR_TYPES(FUNCTION) \
if (false) /* NOLINT */ \
{ \
/* Do nothing, a starter condition. */ \
} \
APPLY_FOR_ONE_TYPE(FUNCTION, ColumnVector<UInt8>) \
APPLY_FOR_ONE_TYPE(FUNCTION, ColumnVector<UInt16>) \
APPLY_FOR_ONE_TYPE(FUNCTION, ColumnVector<UInt32>) \
APPLY_FOR_ONE_TYPE(FUNCTION, ColumnVector<UInt64>) \
\
APPLY_FOR_ONE_TYPE(FUNCTION, ColumnVector<Int8>) \
APPLY_FOR_ONE_TYPE(FUNCTION, ColumnVector<Int16>) \
APPLY_FOR_ONE_TYPE(FUNCTION, ColumnVector<Int32>) \
APPLY_FOR_ONE_TYPE(FUNCTION, ColumnVector<Int64>) \
APPLY_FOR_ONE_TYPE(FUNCTION, ColumnVector<Int128>) \
\
APPLY_FOR_ONE_TYPE(FUNCTION##Float, ColumnVector<Float32>) \
APPLY_FOR_ONE_TYPE(FUNCTION##Float, ColumnVector<Float64>) \
\
else \
{ \
throw Exception(ErrorCodes::NOT_IMPLEMENTED, \
"The RANGE OFFSET frame for '{}' ORDER BY column is not implemented", \
demangle(typeid(*column).name())); \
}
WindowTransform::WindowTransform(const Block & input_header_,
const Block & output_header_,
const WindowDescription & window_description_,
const std::vector<WindowFunctionDescription> & functions)
: IProcessor({input_header_}, {output_header_})
, input(inputs.front())
, output(outputs.front())
, input_header(input_header_)
, window_description(window_description_)
{
// Materialize all columns in header, because we materialize all columns
// in chunks and it's convenient if they match.
auto input_columns = input_header.getColumns();
for (auto & column : input_columns)
{
column = std::move(column)->convertToFullColumnIfConst();
}
input_header.setColumns(std::move(input_columns));
// Initialize window function workspaces.
workspaces.reserve(functions.size());
for (const auto & f : functions)
{
WindowFunctionWorkspace workspace;
workspace.aggregate_function = f.aggregate_function;
const auto & aggregate_function = workspace.aggregate_function;
if (!arena && aggregate_function->allocatesMemoryInArena())
{
arena = std::make_unique<Arena>();
}
workspace.argument_column_indices.reserve(f.argument_names.size());
for (const auto & argument_name : f.argument_names)
{
workspace.argument_column_indices.push_back(
input_header.getPositionByName(argument_name));
}
workspace.argument_columns.assign(f.argument_names.size(), nullptr);
/// Currently we have slightly wrong mixup of the interfaces of Window and Aggregate functions.
workspace.window_function_impl = dynamic_cast<IWindowFunction *>(const_cast<IAggregateFunction *>(aggregate_function.get()));
if (!workspace.window_function_impl)
{
workspace.aggregate_function_state.reset(
aggregate_function->sizeOfData(),
aggregate_function->alignOfData());
aggregate_function->create(workspace.aggregate_function_state.data());
}
workspaces.push_back(std::move(workspace));
}
partition_by_indices.reserve(window_description.partition_by.size());
for (const auto & column : window_description.partition_by)
{
partition_by_indices.push_back(
input_header.getPositionByName(column.column_name));
}
order_by_indices.reserve(window_description.order_by.size());
for (const auto & column : window_description.order_by)
{
order_by_indices.push_back(
input_header.getPositionByName(column.column_name));
}
// Choose a row comparison function for RANGE OFFSET frame based on the
// type of the ORDER BY column.
if (window_description.frame.type == WindowFrame::FrameType::Range
&& (window_description.frame.begin_type
== WindowFrame::BoundaryType::Offset
|| window_description.frame.end_type
== WindowFrame::BoundaryType::Offset))
{
assert(order_by_indices.size() == 1);
const auto & entry = input_header.getByPosition(order_by_indices[0]);
const IColumn * column = entry.column.get();
APPLY_FOR_TYPES(compareValuesWithOffset)
// Convert the offsets to the ORDER BY column type. We can't just check
// that the type matches, because e.g. the int literals are always
// (U)Int64, but the column might be Int8 and so on.
if (window_description.frame.begin_type
== WindowFrame::BoundaryType::Offset)
{
window_description.frame.begin_offset = convertFieldToTypeOrThrow(
window_description.frame.begin_offset,
*entry.type);
if (applyVisitor(FieldVisitorAccurateLess{},
window_description.frame.begin_offset, Field(0)))
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Window frame start offset must be nonnegative, {} given",
window_description.frame.begin_offset);
}
}
if (window_description.frame.end_type
== WindowFrame::BoundaryType::Offset)
{
window_description.frame.end_offset = convertFieldToTypeOrThrow(
window_description.frame.end_offset,
*entry.type);
if (applyVisitor(FieldVisitorAccurateLess{},
window_description.frame.end_offset, Field(0)))
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Window frame start offset must be nonnegative, {} given",
window_description.frame.end_offset);
}
}
}
}
WindowTransform::~WindowTransform()
{
// Some states may be not created yet if the creation failed.
for (auto & ws : workspaces)
{
if (!ws.window_function_impl)
{
ws.aggregate_function->destroy(
ws.aggregate_function_state.data());
}
}
}
void WindowTransform::advancePartitionEnd()
{
if (partition_ended)
{
return;
}
const RowNumber end = blocksEnd();
// fmt::print(stderr, "end {}, partition_end {}\n", end, partition_end);
// If we're at the total end of data, we must end the partition. This is one
// of the few places in calculations where we need special handling for end
// of data, other places will work as usual based on
// `partition_ended` = true, because end of data is logically the same as
// any other end of partition.
// We must check this first, because other calculations might not be valid
// when we're at the end of data.
if (input_is_finished)
{
partition_ended = true;
// We receive empty chunk at the end of data, so the partition_end must
// be already at the end of data.
assert(partition_end == end);
return;
}
// If we got to the end of the block already, but we are going to get more
// input data, wait for it.
if (partition_end == end)
{
return;
}
// We process one block at a time, but we can process each block many times,
// if it contains multiple partitions. The `partition_end` is a
// past-the-end pointer, so it must be already in the "next" block we haven't
// processed yet. This is also the last block we have.
// The exception to this rule is end of data, for which we checked above.
assert(end.block == partition_end.block + 1);
// Try to advance the partition end pointer.
const size_t partition_by_columns = partition_by_indices.size();
if (partition_by_columns == 0)
{
// No PARTITION BY. All input is one partition, which will end when the
// input ends.
partition_end = end;
return;
}
// Check for partition end.
// The partition ends when the PARTITION BY columns change. We need
// some reference columns for comparison. We might have already
// dropped the blocks where the partition starts, but any other row in the
// partition will do. We can't use frame_start or frame_end or current_row (the next row
// for which we are calculating the window functions), because they all might be
// past the end of the partition. prev_frame_start is suitable, because it
// is a pointer to the first row of the previous frame that must have been
// valid, or to the first row of the partition, and we make sure not to drop
// its block.
assert(partition_start <= prev_frame_start);
// The frame start should be inside the prospective partition, except the
// case when it still has no rows.
assert(prev_frame_start < partition_end || partition_start == partition_end);
assert(first_block_number <= prev_frame_start.block);
const auto block_rows = blockRowsNumber(partition_end);
for (; partition_end.row < block_rows; ++partition_end.row)
{
// fmt::print(stderr, "compare reference '{}' to compared '{}'\n",
// prev_frame_start, partition_end);
size_t i = 0;
for (; i < partition_by_columns; i++)
{
const auto * reference_column
= inputAt(prev_frame_start)[partition_by_indices[i]].get();
const auto * compared_column
= inputAt(partition_end)[partition_by_indices[i]].get();
// fmt::print(stderr, "reference '{}', compared '{}'\n",
// (*reference_column)[prev_frame_start.row],
// (*compared_column)[partition_end.row]);
if (compared_column->compareAt(partition_end.row,
prev_frame_start.row, *reference_column,
1 /* nan_direction_hint */) != 0)
{
break;
}
}
if (i < partition_by_columns)
{
partition_ended = true;
return;
}
}
// Went until the end of block, go to the next.
assert(partition_end.row == block_rows);
++partition_end.block;
partition_end.row = 0;
// Went until the end of data and didn't find the new partition.
assert(!partition_ended && partition_end == blocksEnd());
}
auto WindowTransform::moveRowNumberNoCheck(const RowNumber & _x, int64_t offset) const
{
RowNumber x = _x;
if (offset > 0)
{
for (;;)
{
assertValid(x);
assert(offset >= 0);
const auto block_rows = blockRowsNumber(x);
x.row += offset;
if (x.row >= block_rows)
{
offset = x.row - block_rows;
x.row = 0;
x.block++;
if (x == blocksEnd())
{
break;
}
}
else
{
offset = 0;
break;
}
}
}
else if (offset < 0)
{
for (;;)
{
assertValid(x);
assert(offset <= 0);
// abs(offset) is less than INT64_MAX, as checked in the parser, so
// this negation should always work.
assert(offset >= -INT64_MAX);
if (x.row >= static_cast<uint64_t>(-offset))
{
x.row -= -offset;
offset = 0;
break;
}
// Move to the first row in current block. Note that the offset is
// negative.
offset += x.row;
x.row = 0;
// Move to the last row of the previous block, if we are not at the
// first one. Offset also is incremented by one, because we pass over
// the first row of this block.
if (x.block == first_block_number)
{
break;
}
--x.block;
offset += 1;
x.row = blockRowsNumber(x) - 1;
}
}
return std::tuple{x, offset};
}
auto WindowTransform::moveRowNumber(const RowNumber & _x, int64_t offset) const
{
auto [x, o] = moveRowNumberNoCheck(_x, offset);
#ifndef NDEBUG
// Check that it was reversible.
auto [xx, oo] = moveRowNumberNoCheck(x, -(offset - o));
// fmt::print(stderr, "{} -> {}, result {}, {}, new offset {}, twice {}, {}\n",
// _x, offset, x, o, -(offset - o), xx, oo);
assert(xx == _x);
assert(oo == 0);
#endif
return std::tuple{x, o};
}
void WindowTransform::advanceFrameStartRowsOffset()
{
// Just recalculate it each time by walking blocks.
const auto [moved_row, offset_left] = moveRowNumber(current_row,
window_description.frame.begin_offset.get<UInt64>()
* (window_description.frame.begin_preceding ? -1 : 1));
frame_start = moved_row;
assertValid(frame_start);
// fmt::print(stderr, "frame start {} left {} partition start {}\n",
// frame_start, offset_left, partition_start);
if (frame_start <= partition_start)
{
// Got to the beginning of partition and can't go further back.
frame_start = partition_start;
frame_started = true;
return;
}
if (partition_end <= frame_start)
{
// A FOLLOWING frame start ran into the end of partition.
frame_start = partition_end;
frame_started = partition_ended;
return;
}
// Handled the equality case above. Now the frame start is inside the
// partition, if we walked all the offset, it's final.
assert(partition_start < frame_start);
frame_started = offset_left == 0;
// If we ran into the start of data (offset left is negative), we won't be
// able to make progress. Should have handled this case above.
assert(offset_left >= 0);
}
void WindowTransform::advanceFrameStartRangeOffset()
{
// See the comment for advanceFrameEndRangeOffset().
const int direction = window_description.order_by[0].direction;
const bool preceding = window_description.frame.begin_preceding
== (direction > 0);
const auto * reference_column
= inputAt(current_row)[order_by_indices[0]].get();
for (; frame_start < partition_end; advanceRowNumber(frame_start))
{
// The first frame value is [current_row] with offset, so we advance
// while [frames_start] < [current_row] with offset.
const auto * compared_column
= inputAt(frame_start)[order_by_indices[0]].get();
if (compare_values_with_offset(compared_column, frame_start.row,
reference_column, current_row.row,
window_description.frame.begin_offset,
preceding)
* direction >= 0)
{
frame_started = true;
return;
}
}
frame_started = partition_ended;
}
void WindowTransform::advanceFrameStart()
{
if (frame_started)
{
return;
}
const auto frame_start_before = frame_start;
switch (window_description.frame.begin_type)
{
case WindowFrame::BoundaryType::Unbounded:
// UNBOUNDED PRECEDING, just mark it valid. It is initialized when
// the new partition starts.
frame_started = true;
break;
case WindowFrame::BoundaryType::Current:
// CURRENT ROW differs between frame types only in how the peer
// groups are accounted.
assert(partition_start <= peer_group_start);
assert(peer_group_start < partition_end);
assert(peer_group_start <= current_row);
frame_start = peer_group_start;
frame_started = true;
break;
case WindowFrame::BoundaryType::Offset:
switch (window_description.frame.type)
{
case WindowFrame::FrameType::Rows:
advanceFrameStartRowsOffset();
break;
case WindowFrame::FrameType::Range:
advanceFrameStartRangeOffset();
break;
default:
throw Exception(ErrorCodes::NOT_IMPLEMENTED,
"Frame start type '{}' for frame '{}' is not implemented",
window_description.frame.begin_type,
window_description.frame.type);
}
break;
}
assert(frame_start_before <= frame_start);
if (frame_start == frame_start_before)
{
// If the frame start didn't move, this means we validated that the frame
// starts at the point we reached earlier but were unable to validate.
// This probably only happens in degenerate cases where the frame start
// is further than the end of partition, and the partition ends at the
// last row of the block, but we can only tell for sure after a new
// block arrives. We still have to update the state of aggregate
// functions when the frame start becomes valid, so we continue.
assert(frame_started);
}
assert(partition_start <= frame_start);
assert(frame_start <= partition_end);
if (partition_ended && frame_start == partition_end)
{
// Check that if the start of frame (e.g. FOLLOWING) runs into the end
// of partition, it is marked as valid -- we can't advance it any
// further.
assert(frame_started);
}
}
bool WindowTransform::arePeers(const RowNumber & x, const RowNumber & y) const
{
if (x == y)
{
// For convenience, a row is always its own peer.
return true;
}
if (window_description.frame.type == WindowFrame::FrameType::Rows)
{
// For ROWS frame, row is only peers with itself (checked above);
return false;
}
// For RANGE and GROUPS frames, rows that compare equal w/ORDER BY are peers.
assert(window_description.frame.type == WindowFrame::FrameType::Range);
const size_t n = order_by_indices.size();
if (n == 0)
{
// No ORDER BY, so all rows are peers.
return true;
}
size_t i = 0;
for (; i < n; i++)
{
const auto * column_x = inputAt(x)[order_by_indices[i]].get();
const auto * column_y = inputAt(y)[order_by_indices[i]].get();
if (column_x->compareAt(x.row, y.row, *column_y,
1 /* nan_direction_hint */) != 0)
{
return false;
}
}
return true;
}
void WindowTransform::advanceFrameEndCurrentRow()
{
// fmt::print(stderr, "starting from frame_end {}\n", frame_end);
// We only process one block here, and frame_end must be already in it: if
// we didn't find the end in the previous block, frame_end is now the first
// row of the current block. We need this knowledge to write a simpler loop
// (only loop over rows and not over blocks), that should hopefully be more
// efficient.
// partition_end is either in this new block or past-the-end.
assert(frame_end.block == partition_end.block
|| frame_end.block + 1 == partition_end.block);
if (frame_end == partition_end)
{
// The case when we get a new block and find out that the partition has
// ended.
assert(partition_ended);
frame_ended = partition_ended;
return;
}
// We advance until the partition end. It's either in the current block or
// in the next one, which is also the past-the-end block. Figure out how
// many rows we have to process.
uint64_t rows_end;
if (partition_end.row == 0)
{
assert(partition_end == blocksEnd());
rows_end = blockRowsNumber(frame_end);
}
else
{
assert(frame_end.block == partition_end.block);
rows_end = partition_end.row;
}
// Equality would mean "no data to process", for which we checked above.
assert(frame_end.row < rows_end);
// fmt::print(stderr, "first row {} last {}\n", frame_end.row, rows_end);
// Advance frame_end while it is still peers with the current row.
for (; frame_end.row < rows_end; ++frame_end.row)
{
if (!arePeers(current_row, frame_end))
{
// fmt::print(stderr, "{} and {} don't match\n", reference, frame_end);
frame_ended = true;
return;
}
}
// Might have gotten to the end of the current block, have to properly
// update the row number.
if (frame_end.row == blockRowsNumber(frame_end))
{
++frame_end.block;
frame_end.row = 0;
}
// Got to the end of partition (frame ended as well then) or end of data.
assert(frame_end == partition_end);
frame_ended = partition_ended;
}
void WindowTransform::advanceFrameEndUnbounded()
{
// The UNBOUNDED FOLLOWING frame ends when the partition ends.
frame_end = partition_end;
frame_ended = partition_ended;
}
void WindowTransform::advanceFrameEndRowsOffset()
{
// Walk the specified offset from the current row. The "+1" is needed
// because the frame_end is a past-the-end pointer.
const auto [moved_row, offset_left] = moveRowNumber(current_row,
window_description.frame.end_offset.get<UInt64>()
* (window_description.frame.end_preceding ? -1 : 1)
+ 1);
if (partition_end <= moved_row)
{
// Clamp to the end of partition. It might not have ended yet, in which
// case wait for more data.
frame_end = partition_end;
frame_ended = partition_ended;
return;
}
if (moved_row <= partition_start)
{
// Clamp to the start of partition.
frame_end = partition_start;
frame_ended = true;
return;
}
// Frame end inside partition, if we walked all the offset, it's final.
frame_end = moved_row;
frame_ended = offset_left == 0;
// If we ran into the start of data (offset left is negative), we won't be
// able to make progress. Should have handled this case above.
assert(offset_left >= 0);
}
void WindowTransform::advanceFrameEndRangeOffset()
{
// PRECEDING/FOLLOWING change direction for DESC order.
// See CD 9075-2:201?(E) 7.14 <window clause> p. 429.
const int direction = window_description.order_by[0].direction;
const bool preceding = window_description.frame.end_preceding
== (direction > 0);
const auto * reference_column
= inputAt(current_row)[order_by_indices[0]].get();
for (; frame_end < partition_end; advanceRowNumber(frame_end))
{
// The last frame value is current_row with offset, and we need a
// past-the-end pointer, so we advance while
// [frame_end] <= [current_row] with offset.
const auto * compared_column
= inputAt(frame_end)[order_by_indices[0]].get();
if (compare_values_with_offset(compared_column, frame_end.row,
reference_column, current_row.row,
window_description.frame.end_offset,
preceding)
* direction > 0)
{
frame_ended = true;
return;
}
}
frame_ended = partition_ended;
}
void WindowTransform::advanceFrameEnd()
{
// No reason for this function to be called again after it succeeded.
assert(!frame_ended);
const auto frame_end_before = frame_end;
switch (window_description.frame.end_type)
{
case WindowFrame::BoundaryType::Current:
advanceFrameEndCurrentRow();
break;
case WindowFrame::BoundaryType::Unbounded:
advanceFrameEndUnbounded();
break;
case WindowFrame::BoundaryType::Offset:
switch (window_description.frame.type)
{
case WindowFrame::FrameType::Rows:
advanceFrameEndRowsOffset();
break;
case WindowFrame::FrameType::Range:
advanceFrameEndRangeOffset();
break;
default:
throw Exception(ErrorCodes::NOT_IMPLEMENTED,
"The frame end type '{}' is not implemented",
window_description.frame.end_type);
}
break;
}
// fmt::print(stderr, "frame_end {} -> {}\n", frame_end_before, frame_end);
// We might not have advanced the frame end if we found out we reached the
// end of input or the partition, or if we still don't know the frame start.
if (frame_end_before == frame_end)
{
return;
}
}
// Update the aggregation states after the frame has changed.
void WindowTransform::updateAggregationState()
{
// fmt::print(stderr, "update agg states [{}, {}) -> [{}, {})\n",
// prev_frame_start, prev_frame_end, frame_start, frame_end);
// Assert that the frame boundaries are known, have proper order wrt each
// other, and have not gone back wrt the previous frame.
assert(frame_started);
assert(frame_ended);
assert(frame_start <= frame_end);
assert(prev_frame_start <= prev_frame_end);
assert(prev_frame_start <= frame_start);
assert(prev_frame_end <= frame_end);
assert(partition_start <= frame_start);
assert(frame_end <= partition_end);
// We might have to reset aggregation state and/or add some rows to it.
// Figure out what to do.
bool reset_aggregation = false;
RowNumber rows_to_add_start;
RowNumber rows_to_add_end;
if (frame_start == prev_frame_start)
{
// The frame start didn't change, add the tail rows.
reset_aggregation = false;
rows_to_add_start = prev_frame_end;
rows_to_add_end = frame_end;
}
else
{
// The frame start changed, reset the state and aggregate over the
// entire frame. This can be made per-function after we learn to
// subtract rows from some types of aggregation states, but for now we
// always have to reset when the frame start changes.
reset_aggregation = true;
rows_to_add_start = frame_start;
rows_to_add_end = frame_end;
}
for (auto & ws : workspaces)
{
if (ws.window_function_impl)
{
// No need to do anything for true window functions.
continue;
}
const auto * a = ws.aggregate_function.get();
auto * buf = ws.aggregate_function_state.data();
if (reset_aggregation)
{
// fmt::print(stderr, "(2) reset aggregation\n");
a->destroy(buf);
a->create(buf);
}
// To achieve better performance, we will have to loop over blocks and
// rows manually, instead of using advanceRowNumber().
// For this purpose, the past-the-end block can be different than the
// block of the past-the-end row (it's usually the next block).
const auto past_the_end_block = rows_to_add_end.row == 0
? rows_to_add_end.block
: rows_to_add_end.block + 1;
for (auto block_number = rows_to_add_start.block;
block_number < past_the_end_block;
++block_number)
{
auto & block = blockAt(block_number);
if (ws.cached_block_number != block_number)
{
for (size_t i = 0; i < ws.argument_column_indices.size(); ++i)
{
ws.argument_columns[i] = block.input_columns[
ws.argument_column_indices[i]].get();
}
ws.cached_block_number = block_number;
}
// First and last blocks may be processed partially, and other blocks
// are processed in full.
const auto first_row = block_number == rows_to_add_start.block
? rows_to_add_start.row : 0;
const auto past_the_end_row = block_number == rows_to_add_end.block
? rows_to_add_end.row : block.rows;
// We should add an addBatch analog that can accept a starting offset.
// For now, add the values one by one.
auto * columns = ws.argument_columns.data();
// Removing arena.get() from the loop makes it faster somehow...
auto * arena_ptr = arena.get();
for (auto row = first_row; row < past_the_end_row; ++row)
{
a->add(buf, columns, row, arena_ptr);
}
}
}
prev_frame_start = frame_start;
prev_frame_end = frame_end;
}
void WindowTransform::writeOutCurrentRow()
{
assert(current_row < partition_end);
assert(current_row.block >= first_block_number);
const auto & block = blockAt(current_row);
for (size_t wi = 0; wi < workspaces.size(); ++wi)
{
auto & ws = workspaces[wi];
if (ws.window_function_impl)
{
ws.window_function_impl->windowInsertResultInto(this, wi);
}
else
{
IColumn * result_column = block.output_columns[wi].get();
const auto * a = ws.aggregate_function.get();
auto * buf = ws.aggregate_function_state.data();
// FIXME does it also allocate the result on the arena?
// We'll have to pass it out with blocks then...
a->insertResultInto(buf, *result_column, arena.get());
}
}
// fmt::print(stderr, "wrote out aggregation state for current row '{}'\n",
// current_row);
}
static void assertSameColumns(const Columns & left_all,
const Columns & right_all)
{
assert(left_all.size() == right_all.size());
for (size_t i = 0; i < left_all.size(); ++i)
{
const auto * left_column = left_all[i].get();
const auto * right_column = right_all[i].get();
assert(left_column);
assert(right_column);
assert(typeid(*left_column).hash_code()
== typeid(*right_column).hash_code());
if (isColumnConst(*left_column))
{
Field left_value = assert_cast<const ColumnConst &>(*left_column).getField();
Field right_value = assert_cast<const ColumnConst &>(*right_column).getField();
assert(left_value == right_value);
}
}
}
void WindowTransform::appendChunk(Chunk & chunk)
{
// fmt::print(stderr, "new chunk, {} rows, finished={}\n", chunk.getNumRows(),
// input_is_finished);
// fmt::print(stderr, "chunk structure '{}'\n", chunk.dumpStructure());
// First, prepare the new input block and add it to the queue. We might not
// have it if it's end of data, though.
if (!input_is_finished)
{
if (!chunk.hasRows())
{
// Joins may generate empty input chunks when it's not yet end of
// input. Just ignore them. They probably shouldn't be sending empty
// chunks up the pipeline, but oh well.
return;
}
blocks.push_back({});
auto & block = blocks.back();
// Use the number of rows from the Chunk, because it is correct even in
// the case where the Chunk has no columns. Not sure if this actually
// happens, because even in the case of `count() over ()` we have a dummy
// input column.
block.rows = chunk.getNumRows();
// If we have a (logically) constant column, some Chunks will have a
// Const column for it, and some -- materialized. Such difference is
// generated by e.g. MergingSortedAlgorithm, which mostly materializes
// the constant ORDER BY columns, but in some obscure cases passes them
// through, unmaterialized. This mix is a pain to work with in Window
// Transform, because we have to compare columns across blocks, when e.g.
// searching for peer group boundaries, and each of the four combinations
// of const and materialized requires different code.
// Another problem with Const columns is that the aggregate functions
// can't work with them, so we have to materialize them like the
// Aggregator does.
// Just materialize everything.
auto columns = chunk.detachColumns();
for (auto & column : columns)
column = std::move(column)->convertToFullColumnIfConst();
block.input_columns = std::move(columns);
// Initialize output columns.
for (auto & ws : workspaces)
{
block.output_columns.push_back(ws.aggregate_function->getReturnType()
->createColumn());
block.output_columns.back()->reserve(block.rows);
}
// As a debugging aid, assert that all chunks have the same C++ type of
// columns, that also matches the input header, because we often have to
// work across chunks.
assertSameColumns(input_header.getColumns(), block.input_columns);
}
// Start the calculations. First, advance the partition end.
for (;;)
{
advancePartitionEnd();
// fmt::print(stderr, "partition [{}, {}), {}\n",
// partition_start, partition_end, partition_ended);
// Either we ran out of data or we found the end of partition (maybe
// both, but this only happens at the total end of data).
assert(partition_ended || partition_end == blocksEnd());
if (partition_ended && partition_end == blocksEnd())
{
assert(input_is_finished);
}
// After that, try to calculate window functions for each next row.
// We can continue until the end of partition or current end of data,
// which is precisely the definition of `partition_end`.
while (current_row < partition_end)
{
// fmt::print(stderr, "(1) row {} frame [{}, {}) {}, {}\n",
// current_row, frame_start, frame_end,
// frame_started, frame_ended);
// We now know that the current row is valid, so we can update the
// peer group start.
if (!arePeers(peer_group_start, current_row))
{
peer_group_start = current_row;
peer_group_start_row_number = current_row_number;
++peer_group_number;
}
// Advance the frame start.
advanceFrameStart();
if (!frame_started)
{
// Wait for more input data to find the start of frame.
assert(!input_is_finished);
assert(!partition_ended);
return;
}
// frame_end must be greater or equal than frame_start, so if the
// frame_start is already past the current frame_end, we can start
// from it to save us some work.
if (frame_end < frame_start)
{
frame_end = frame_start;
}
// Advance the frame end.
advanceFrameEnd();
if (!frame_ended)
{
// Wait for more input data to find the end of frame.
assert(!input_is_finished);
assert(!partition_ended);
return;
}
// fmt::print(stderr, "(2) row {} frame [{}, {}) {}, {}\n",
// current_row, frame_start, frame_end,
// frame_started, frame_ended);
// The frame can be empty sometimes, e.g. the boundaries coincide
// or the start is after the partition end. But hopefully start is
// not after end.
assert(frame_started);
assert(frame_ended);
assert(frame_start <= frame_end);
// Now that we know the new frame boundaries, update the aggregation
// states. Theoretically we could do this simultaneously with moving
// the frame boundaries, but it would require some care not to
// perform unnecessary work while we are still looking for the frame
// start, so do it the simple way for now.
updateAggregationState();
// Write out the aggregation results.
writeOutCurrentRow();
if (isCancelled())
{
// Good time to check if the query is cancelled. Checking once
// per block might not be enough in severe quadratic cases.
// Just leave the work halfway through and return, the 'prepare'
// method will figure out what to do. Note that this doesn't
// handle 'max_execution_time' and other limits, because these
// limits are only updated between blocks. Eventually we should
// start updating them in background and canceling the processor,
// like we do for Ctrl+C handling.
//
// This class is final, so the check should hopefully be
// devirtualized and become a single never-taken branch that is
// basically free.
return;
}
// Move to the next row. The frame will have to be recalculated.
// The peer group start is updated at the beginning of the loop,
// because current_row might now be past-the-end.
advanceRowNumber(current_row);
++current_row_number;
first_not_ready_row = current_row;
frame_ended = false;
frame_started = false;
}
if (input_is_finished)
{
// We finalized the last partition in the above loop, and don't have
// to do anything else.
return;
}
if (!partition_ended)
{
// Wait for more input data to find the end of partition.
// Assert that we processed all the data we currently have, and that
// we are going to receive more data.
assert(partition_end == blocksEnd());
assert(!input_is_finished);
break;
}
// Start the next partition.
partition_start = partition_end;
advanceRowNumber(partition_end);
partition_ended = false;
// We have to reset the frame and other pointers when the new partition
// starts.
frame_start = partition_start;
frame_end = partition_start;
prev_frame_start = partition_start;
prev_frame_end = partition_start;
assert(current_row == partition_start);
current_row_number = 1;
peer_group_start = partition_start;
peer_group_start_row_number = 1;
peer_group_number = 1;
// fmt::print(stderr, "reinitialize agg data at start of {}\n",
// partition_start);
// Reinitialize the aggregate function states because the new partition
// has started.
for (auto & ws : workspaces)
{
if (ws.window_function_impl)
{
continue;
}
const auto * a = ws.aggregate_function.get();
auto * buf = ws.aggregate_function_state.data();
a->destroy(buf);
}
// Release the arena we use for aggregate function states, so that it
// doesn't grow without limit. Not sure if it's actually correct, maybe
// it allocates the return values in the Arena as well...
if (arena)
{
arena = std::make_unique<Arena>();
}
for (auto & ws : workspaces)
{
if (ws.window_function_impl)
{
continue;
}
const auto * a = ws.aggregate_function.get();
auto * buf = ws.aggregate_function_state.data();
a->create(buf);
}
}
}
IProcessor::Status WindowTransform::prepare()
{
// fmt::print(stderr, "prepare, next output {}, not ready row {}, first block {}, hold {} blocks\n",
// next_output_block_number, first_not_ready_row, first_block_number,
// blocks.size());
if (output.isFinished() || isCancelled())
{
// The consumer asked us not to continue (or we decided it ourselves),
// so we abort. Not sure what the difference between the two conditions
// is, but it seemed that output.isFinished() is not enough to cancel on
// Ctrl+C. Test manually if you change it.
input.close();
return Status::Finished;
}
if (output_data.exception)
{
// An exception occurred during processing.
output.pushData(std::move(output_data));
output.finish();
input.close();
return Status::Finished;
}
assert(first_not_ready_row.block >= first_block_number);
// The first_not_ready_row might be past-the-end if we have already
// calculated the window functions for all input rows. That's why the
// equality is also valid here.
assert(first_not_ready_row.block <= first_block_number + blocks.size());
assert(next_output_block_number >= first_block_number);
// Output the ready data prepared by work().
// We inspect the calculation state and create the output chunk right here,
// because this is pretty lightweight.
if (next_output_block_number < first_not_ready_row.block)
{
if (output.canPush())
{
// Output the ready block.
const auto i = next_output_block_number - first_block_number;
auto & block = blocks[i];
auto columns = block.input_columns;
for (auto & res : block.output_columns)
{
columns.push_back(ColumnPtr(std::move(res)));
}
output_data.chunk.setColumns(columns, block.rows);
// fmt::print(stderr, "output block {} as chunk '{}'\n",
// next_output_block_number,
// output_data.chunk.dumpStructure());
++next_output_block_number;
output.pushData(std::move(output_data));
}
// We don't need input.setNotNeeded() here, because we already pull with
// the set_not_needed flag.
return Status::PortFull;
}
if (input_is_finished)
{
// The input data ended at the previous prepare() + work() cycle,
// and we don't have ready output data (checked above). We must be
// finished.
assert(next_output_block_number == first_block_number + blocks.size());
assert(first_not_ready_row == blocksEnd());
// FIXME do we really have to do this?
output.finish();
return Status::Finished;
}
// Consume input data if we have any ready.
if (!has_input && input.hasData())
{
// Pulling with set_not_needed = true and using an explicit setNeeded()
// later is somewhat more efficient, because after the setNeeded(), the
// required input block will be generated in the same thread and passed
// to our prepare() + work() methods in the same thread right away, so
// hopefully we will work on hot (cached) data.
input_data = input.pullData(true /* set_not_needed */);
// If we got an exception from input, just return it and mark that we're
// finished.
if (input_data.exception)
{
output.pushData(std::move(input_data));
output.finish();
return Status::PortFull;
}
has_input = true;
// Now we have new input and can try to generate more output in work().
return Status::Ready;
}
// We 1) don't have any ready output (checked above),
// 2) don't have any more input (also checked above).
// Will we get any more input?
if (input.isFinished())
{
// We won't, time to finalize the calculation in work(). We should only
// do this once.
assert(!input_is_finished);
input_is_finished = true;
return Status::Ready;
}
// We have to wait for more input.
input.setNeeded();
return Status::NeedData;
}
void WindowTransform::work()
{
// Exceptions should be skipped in prepare().
assert(!input_data.exception);
assert(has_input || input_is_finished);
try
{
has_input = false;
appendChunk(input_data.chunk);
}
catch (DB::Exception &)
{
output_data.exception = std::current_exception();
has_input = false;
return;
}
// We don't really have to keep the entire partition, and it can be big, so
// we want to drop the starting blocks to save memory. We can drop the old
// blocks if we already returned them as output, and the frame and the
// current row are already past them. We also need to keep the previous
// frame start because we use it as the partition etalon. It is always less
// than the current frame start, so we don't have to check the latter. Note
// that the frame start can be further than current row for some frame specs
// (e.g. EXCLUDE CURRENT ROW), so we have to check both.
assert(prev_frame_start <= frame_start);
const auto first_used_block = std::min(next_output_block_number,
std::min(prev_frame_start.block, current_row.block));
if (first_block_number < first_used_block)
{
// fmt::print(stderr, "will drop blocks from {} to {}\n", first_block_number,
// first_used_block);
blocks.erase(blocks.begin(),
blocks.begin() + (first_used_block - first_block_number));
first_block_number = first_used_block;
assert(next_output_block_number >= first_block_number);
assert(frame_start.block >= first_block_number);
assert(prev_frame_start.block >= first_block_number);
assert(current_row.block >= first_block_number);
assert(peer_group_start.block >= first_block_number);
}
}
// A basic implementation for a true window function. It pretends to be an
// aggregate function, but refuses to work as such.
struct WindowFunction
: public IAggregateFunctionHelper<WindowFunction>
, public IWindowFunction
{
std::string name;
WindowFunction(const std::string & name_, const DataTypes & argument_types_, const Array & parameters_)
: IAggregateFunctionHelper<WindowFunction>(argument_types_, parameters_)
, name(name_)
{}
bool isOnlyWindowFunction() const override { return true; }
[[noreturn]] void fail() const
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"The function '{}' can only be used as a window function, not as an aggregate function",
getName());
}
String getName() const override { return name; }
void create(AggregateDataPtr __restrict) const override { fail(); }
void destroy(AggregateDataPtr __restrict) const noexcept override {}
bool hasTrivialDestructor() const override { return true; }
size_t sizeOfData() const override { return 0; }
size_t alignOfData() const override { return 1; }
void add(AggregateDataPtr __restrict, const IColumn **, size_t, Arena *) const override { fail(); }
void merge(AggregateDataPtr __restrict, ConstAggregateDataPtr, Arena *) const override { fail(); }
void serialize(ConstAggregateDataPtr __restrict, WriteBuffer &) const override { fail(); }
void deserialize(AggregateDataPtr __restrict, ReadBuffer &, Arena *) const override { fail(); }
void insertResultInto(AggregateDataPtr __restrict, IColumn &, Arena *) const override { fail(); }
};
struct WindowFunctionRank final : public WindowFunction
{
WindowFunctionRank(const std::string & name_,
const DataTypes & argument_types_, const Array & parameters_)
: WindowFunction(name_, argument_types_, parameters_)
{}
DataTypePtr getReturnType() const override
{ return std::make_shared<DataTypeUInt64>(); }
bool allocatesMemoryInArena() const override { return false; }
void windowInsertResultInto(const WindowTransform * transform,
size_t function_index) override
{
IColumn & to = *transform->blockAt(transform->current_row)
.output_columns[function_index];
assert_cast<ColumnUInt64 &>(to).getData().push_back(
transform->peer_group_start_row_number);
}
};
struct WindowFunctionDenseRank final : public WindowFunction
{
WindowFunctionDenseRank(const std::string & name_,
const DataTypes & argument_types_, const Array & parameters_)
: WindowFunction(name_, argument_types_, parameters_)
{}
DataTypePtr getReturnType() const override
{ return std::make_shared<DataTypeUInt64>(); }
bool allocatesMemoryInArena() const override { return false; }
void windowInsertResultInto(const WindowTransform * transform,
size_t function_index) override
{
IColumn & to = *transform->blockAt(transform->current_row)
.output_columns[function_index];
assert_cast<ColumnUInt64 &>(to).getData().push_back(
transform->peer_group_number);
}
};
struct WindowFunctionRowNumber final : public WindowFunction
{
WindowFunctionRowNumber(const std::string & name_,
const DataTypes & argument_types_, const Array & parameters_)
: WindowFunction(name_, argument_types_, parameters_)
{}
DataTypePtr getReturnType() const override
{ return std::make_shared<DataTypeUInt64>(); }
bool allocatesMemoryInArena() const override { return false; }
void windowInsertResultInto(const WindowTransform * transform,
size_t function_index) override
{
IColumn & to = *transform->blockAt(transform->current_row)
.output_columns[function_index];
assert_cast<ColumnUInt64 &>(to).getData().push_back(
transform->current_row_number);
}
};
// ClickHouse-specific variant of lag/lead that respects the window frame.
template <bool is_lead>
struct WindowFunctionLagLeadInFrame final : public WindowFunction
{
WindowFunctionLagLeadInFrame(const std::string & name_,
const DataTypes & argument_types_, const Array & parameters_)
: WindowFunction(name_, argument_types_, parameters_)
{
if (!parameters.empty())
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Function {} cannot be parameterized", name_);
}
if (argument_types.empty())
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Function {} takes at least one argument", name_);
}
if (argument_types.size() == 1)
{
return;
}
if (!isInt64OrUInt64FieldType(argument_types[1]->getDefault().getType()))
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Offset must be an integer, '{}' given",
argument_types[1]->getName());
}
if (argument_types.size() == 2)
{
return;
}
const auto supertype = getLeastSupertype({argument_types[0], argument_types[2]});
if (!supertype)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"There is no supertype for the argument type '{}' and the default value type '{}'",
argument_types[0]->getName(),
argument_types[2]->getName());
}
if (!argument_types[0]->equals(*supertype))
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"The supertype '{}' for the argument type '{}' and the default value type '{}' is not the same as the argument type",
supertype->getName(),
argument_types[0]->getName(),
argument_types[2]->getName());
}
if (argument_types.size() > 3)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Function '{}' accepts at most 3 arguments, {} given",
name, argument_types.size());
}
}
DataTypePtr getReturnType() const override { return argument_types[0]; }
bool allocatesMemoryInArena() const override { return false; }
void windowInsertResultInto(const WindowTransform * transform,
size_t function_index) override
{
const auto & current_block = transform->blockAt(transform->current_row);
IColumn & to = *current_block.output_columns[function_index];
const auto & workspace = transform->workspaces[function_index];
int64_t offset = 1;
if (argument_types.size() > 1)
{
offset = (*current_block.input_columns[
workspace.argument_column_indices[1]])[
transform->current_row.row].get<Int64>();
/// Either overflow or really negative value, both is not acceptable.
if (offset < 0)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"The offset for function {} must be in (0, {}], {} given",
getName(), INT64_MAX, offset);
}
}
const auto [target_row, offset_left] = transform->moveRowNumber(
transform->current_row, offset * (is_lead ? 1 : -1));
if (offset_left != 0
|| target_row < transform->frame_start
|| transform->frame_end <= target_row)
{
// Offset is outside the frame.
if (argument_types.size() > 2)
{
// Column with default values is specified.
// The conversion through Field is inefficient, but we accept
// subtypes of the argument type as a default value (for convenience),
// and it's a pain to write conversion that respects ColumnNothing
// and ColumnConst and so on.
const IColumn & default_column = *current_block.input_columns[
workspace.argument_column_indices[2]].get();
to.insert(default_column[transform->current_row.row]);
}
else
{
to.insertDefault();
}
}
else
{
// Offset is inside the frame.
to.insertFrom(*transform->blockAt(target_row).input_columns[
workspace.argument_column_indices[0]],
target_row.row);
}
}
};
void registerWindowFunctions(AggregateFunctionFactory & factory)
{
// Why didn't I implement lag/lead yet? Because they are a mess. I imagine
// they are from the older generation of window functions, when the concept
// of frame was not yet invented, so they ignore the frame and use the
// partition instead. This means we have to track a separate frame for
// these functions, which would make the window transform completely
// impenetrable to human mind. We can't just get away with materializing
// the whole partition like Postgres does, because using a linear amount
// of additional memory is not an option when we have a lot of data. We must
// be able to process at least the lag/lead in streaming fashion.
// A partial solution for constant offsets is rewriting, say `lag(value, offset)
// to `any(value) over (rows between offset preceding and offset preceding)`.
// We also implement non-standard functions `lag/leadInFrame`, that are
// analogous to `lag/lead`, but respect the frame.
// Functions like cume_dist() do require materializing the entire
// partition, but it's probably also simpler to implement them by rewriting
// to a (rows between unbounded preceding and unbounded following) frame,
// instead of adding separate logic for them.
const AggregateFunctionProperties properties = {
// By default, if an aggregate function has a null argument, it will be
// replaced with AggregateFunctionNothing. We don't need this behavior
// e.g. for lagInFrame(number, 1, null).
.returns_default_when_only_null = true,
// This probably doesn't make any difference for window functions because
// it is an Aggregator-specific setting.
.is_order_dependent = true };
factory.registerFunction("rank", {[](const std::string & name,
const DataTypes & argument_types, const Array & parameters, const Settings *)
{
return std::make_shared<WindowFunctionRank>(name, argument_types,
parameters);
}, properties}, AggregateFunctionFactory::CaseInsensitive);
factory.registerFunction("dense_rank", {[](const std::string & name,
const DataTypes & argument_types, const Array & parameters, const Settings *)
{
return std::make_shared<WindowFunctionDenseRank>(name, argument_types,
parameters);
}, properties}, AggregateFunctionFactory::CaseInsensitive);
factory.registerFunction("row_number", {[](const std::string & name,
const DataTypes & argument_types, const Array & parameters, const Settings *)
{
return std::make_shared<WindowFunctionRowNumber>(name, argument_types,
parameters);
}, properties}, AggregateFunctionFactory::CaseInsensitive);
factory.registerFunction("lagInFrame", {[](const std::string & name,
const DataTypes & argument_types, const Array & parameters, const Settings *)
{
return std::make_shared<WindowFunctionLagLeadInFrame<false>>(
name, argument_types, parameters);
}, properties});
factory.registerFunction("leadInFrame", {[](const std::string & name,
const DataTypes & argument_types, const Array & parameters, const Settings *)
{
return std::make_shared<WindowFunctionLagLeadInFrame<true>>(
name, argument_types, parameters);
}, properties});
}
}
|
/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Accept connections from Bitcoin nodes on port 8333.
*/
#include <bitcoin/bitcoin.hpp>
using namespace bc;
using std::placeholders::_1;
using std::placeholders::_2;
// Listening has started.
// Wait to accept a connection.
void listening_started(const std::error_code& ec, acceptor_ptr accept);
// Connection to another Bitcoin node has been established.
// Wait for version message.
void accepted_connection(const std::error_code& ec, channel_ptr node,
acceptor_ptr accept);
// Version message received.
// Display the user agent.
void version_received(const std::error_code& ec, const version_type& version,
channel_ptr node);
void node_stopped(const std::error_code& ec);
void listening_started(const std::error_code& ec, acceptor_ptr accept)
{
if (ec)
{
log_error() << "Listen: " << ec.message();
return;
}
// Accept first connection.
accept->accept(
std::bind(accepted_connection, _1, _2, accept));
}
void accepted_connection(const std::error_code& ec, channel_ptr node,
acceptor_ptr accept)
{
if (ec)
{
log_error() << "Accept: " << ec.message();
return;
}
log_info() << "Accepted connection!";
node->subscribe_stop(node_stopped);
// Now we need to keep it alive otherwise the connection is closed.
node->subscribe_version(
std::bind(version_received, _1, _2, node));
// Keep accepting more connections.
accept->accept(
std::bind(accepted_connection, _1, _2, accept));
}
void version_received(const std::error_code& ec, const version_type& version,
channel_ptr node)
{
// error::service_stopped means the connection was closed.
if (ec == error::service_stopped)
return;
else if (ec)
{
log_error() << "Version message: " << ec.message();
return;
}
log_info() << "User agent: " << version.user_agent;
}
void node_stopped(const std::error_code& ec)
{
if (ec == error::service_stopped)
log_info() << "Connection closed.";
else if (ec)
log_error() << "Connection closed: " << ec.message();
}
int main()
{
threadpool pool(4);
network net(pool);
net.listen(8333, listening_started);
std::cin.get();
pool.stop();
pool.join();
return 0;
}
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2016-2021 Inviwo Foundation
* All rights reserved.
*
* 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
*
*********************************************************************************/
#include <modules/animation/datastructures/keyframe.h>
namespace inviwo {
namespace animation {
bool operator<(const Keyframe& a, const Keyframe& b) { return a.getTime() < b.getTime(); }
bool operator>(const Keyframe& a, const Keyframe& b) { return a.getTime() > b.getTime(); }
bool operator>=(const Keyframe& a, const Keyframe& b) { return a.getTime() >= b.getTime(); }
bool operator<=(const Keyframe& a, const Keyframe& b) { return a.getTime() <= b.getTime(); }
bool operator<(const Keyframe& a, const Seconds& b) { return a.getTime() < b; }
bool operator<=(const Keyframe& a, const Seconds& b) { return a.getTime() <= b; }
bool operator>(const Keyframe& a, const Seconds& b) { return a.getTime() > b; }
bool operator>=(const Keyframe& a, const Seconds& b) { return a.getTime() >= b; }
bool operator<(const Seconds& a, const Keyframe& b) { return a < b.getTime(); }
bool operator<=(const Seconds& a, const Keyframe& b) { return a <= b.getTime(); }
bool operator>(const Seconds& a, const Keyframe& b) { return a > b.getTime(); }
bool operator>=(const Seconds& a, const Keyframe& b) { return a >= b.getTime(); }
} // namespace animation
} // namespace inviwo
|
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// 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.
#include "operation/conv2d_transpose.h"
#include "driver/mediatek_apu/converter/converter.h"
#include "operation/conv2d.h"
#include "utility/debug.h"
#include "utility/logging.h"
#include "utility/modeling.h"
namespace nnadapter {
namespace mediatek_apu {
int ConvertConv2DTranspose(Converter* converter, core::Operation* operation) {
CONV_2D_TRANSPOSE_OPERATION_EXTRACT_INPUTS_OUTPUTS
NNADAPTER_CHECK_EQ(output_padding_height, 0)
<< "Only supports output_padding_height = 0 and output_padding_width = "
"0.";
NNADAPTER_CHECK_EQ(output_padding_width, 0)
<< "Only supports output_padding_height = 0 and output_padding_width = "
"0.";
NNADAPTER_CHECK_EQ(output_shape_height, -1)
<< "Only supports output_shape_height = -1 and output_shape_width = -1.";
NNADAPTER_CHECK_EQ(output_shape_width, -1)
<< "Only supports output_shape_height = -1 and output_shape_width = -1.";
if (auto_pad != NNADAPTER_AUTO_PAD_NONE) {
// NHWC
operation::UpdateConv2DPadAndDilation(
input_operand->type.dimensions.data[1],
filter_height,
auto_pad,
&pad_height_top,
&pad_height_bottom,
stride_height,
&dilation_height);
operation::UpdateConv2DPadAndDilation(
input_operand->type.dimensions.data[2],
filter_width,
auto_pad,
&pad_width_left,
&pad_width_right,
stride_width,
&dilation_width);
}
NNADAPTER_CHECK_EQ(dilation_height, 1) << "Only supports dilations = [1,1]";
NNADAPTER_CHECK_EQ(dilation_width, 1) << "Only supports dilations = [1,1]";
// Convert to NNAPI operands and operations
auto input_index = converter->GetMappedIndex(input_operand);
if (input_index == INVALID_INDEX) {
input_index = converter->ConvertOperand(input_operand);
}
auto filter_index = converter->ConvertOperand(filter_operand);
NNADAPTER_VLOG(5) << "filter_index:" << filter_index;
auto bias_index = converter->ConvertOperand(bias_operand);
NNADAPTER_VLOG(5) << "bias_index:" << bias_index;
auto padding_width_left_index =
converter->AddInt32ConstantOperand(pad_width_left);
auto padding_width_right_index =
converter->AddInt32ConstantOperand(pad_width_right);
auto padding_height_top_index =
converter->AddInt32ConstantOperand(pad_height_top);
auto padding_height_bottom_index =
converter->AddInt32ConstantOperand(pad_height_bottom);
auto stride_width_index = converter->AddInt32ConstantOperand(stride_width);
auto stride_height_index = converter->AddInt32ConstantOperand(stride_height);
auto fuse_code_index = converter->AddInt32ConstantOperand(
ConvertFuseCodeToNeuronFuseCode(fuse_code));
auto is_nchw_index = converter->AddBool8ConstantOperand(false);
auto output_index = converter->ConvertOperand(output_operand);
NNADAPTER_CHECK_EQ(converter->AddOperation(NEURON_TRANSPOSE_CONV_2D,
{input_index,
filter_index,
bias_index,
padding_width_left_index,
padding_width_right_index,
padding_height_top_index,
padding_height_bottom_index,
stride_width_index,
stride_height_index,
fuse_code_index,
is_nchw_index},
{output_index}),
NEURON_NO_ERROR);
return NNADAPTER_NO_ERROR;
}
} // namespace mediatek_apu
} // namespace nnadapter
|
/*******************************************************************************
* Copyright 2016-2020 Intel Corporation
*
* 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.
*******************************************************************************/
#ifndef CPU_CPU_CONVOLUTION_PD_HPP
#define CPU_CPU_CONVOLUTION_PD_HPP
#include <assert.h>
#include "common/c_types_map.hpp"
#include "common/convolution_pd.hpp"
#include "common/type_helpers.hpp"
#include "common/utils.hpp"
#include "cpu/cpu_eltwise_pd.hpp"
#include "cpu/cpu_engine.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
struct cpu_convolution_fwd_pd_t : public convolution_fwd_pd_t {
using convolution_fwd_pd_t::convolution_fwd_pd_t;
bool has_padded_dst() const {
memory_desc_wrapper dst_d(&dst_md_);
return OC() != dst_d.padded_dims()[1];
}
bool wants_padded_bias() const {
if (!with_bias()) return false;
return has_padded_dst();
}
bool wants_zero_pad_dst() const {
if (!has_padded_dst()) return false;
const auto &po = attr()->post_ops_;
int idx = po.find(primitive_kind::eltwise);
if (idx == -1) return false;
const auto &ee = po.entry_[idx].eltwise;
return !cpu_eltwise_fwd_pd_t::eltwise_preserves_zero(
ee.alg, ee.alpha, ee.beta);
}
};
struct cpu_convolution_bwd_data_pd_t : public convolution_bwd_data_pd_t {
using convolution_bwd_data_pd_t::convolution_bwd_data_pd_t;
};
struct cpu_convolution_bwd_weights_pd_t : public convolution_bwd_weights_pd_t {
using convolution_bwd_weights_pd_t::convolution_bwd_weights_pd_t;
bool wants_padded_bias() const {
if (!with_bias()) return false;
memory_desc_wrapper diff_dst_d(&diff_dst_md_);
return OC() != diff_dst_d.padded_dims()[1];
}
};
} // namespace cpu
} // namespace impl
} // namespace dnnl
#endif
// vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
한번만 뒤집으면 해결되는지 여부를 리턴하는 one_time함수
이후 앞에 맞춰 뒤집어보고
one_time에서 true가 리턴되는지 확인
뒤에 맞춰 뒤집어보고
one_time에서 true가 리턴된느지 화인
one_time함수는 한번 뒤집어야 하는 위치를 a,b에 저장합니다.
*/
int a, b;
bool one_time(vector<int> v){
int i;
for(i = 0; i<v.size(); i++){
if(v[i] != i+1)
break;
}
if(i == v.size())
return true;
a = i;
for(; i<v.size()-1; i++){
if(v[i] - v[i+1] != 1)
break;
}
b = i;
i++;
for(; i<v.size(); i++){
if(v[i] != i+1)
break;
}
if(i == v.size())
return true;
return false;
}
int main() {
int n_data;
cin>>n_data;
vector<int> nums;
nums.resize(n_data);
for(int i=0; i<n_data; i++){
cin>>nums[i];
}
if(one_time(nums)){
cout<<1<<' '<<1<<'\n';
cout<<a+1<<' '<<b+1<<'\n';
return 0;
}
int strt, fin;
for(strt = 0; strt < n_data; strt++){
if(strt+1 != nums[strt])
break;
}
int head_idx = strt;
for(head_idx = strt; head_idx<n_data; head_idx++){
if(nums[head_idx] == strt+1){
break;
}
}
vector<int> temp = nums;
if(head_idx != n_data)
head_idx++;
reverse(&temp[strt], &temp[head_idx]);
if(one_time(temp)){
cout<<strt+1<<" "<<head_idx<<'\n';
cout<<a+1<<" "<<b+1;
return 0;
}
for(fin = n_data-1; fin >= 0; fin--){
if(fin+1 != nums[fin])
break;
}
int tail_idx = fin;
for(tail_idx = fin; tail_idx >= 0; tail_idx--){
if(nums[tail_idx] == fin+1){
break;
}
}
temp = nums;
fin++;
reverse(&temp[tail_idx], &temp[fin]);
if(one_time(temp)){
cout<<tail_idx+1<<" "<<fin<<'\n';
cout<<a+1<<" "<<b+1;
return 0;
}
return 0;
}
|
// SusyCouplings.cc is a part of the PYTHIA event generator.
// Copyright (C) 2015 Torbjorn Sjostrand.
// Main authors of this file: N. Desai, P. Skands
// PYTHIA is licenced under the GNU GPL version 2, see COPYING for details.
// Please respect the MCnet Guidelines, see GUIDELINES for details.
// Function definitions (not found in the header) for the
// supersymmetric couplings class.
#include "Pythia8/ParticleData.h"
#include "Pythia8/SusyCouplings.h"
namespace Pythia8 {
//==========================================================================
// The CoupSUSY class.
//--------------------------------------------------------------------------
// Constants: could be changed here if desired, but normally should not.
// These are of technical nature, as described for each.
// Allow verbose printout for debug purposes.
const bool CoupSUSY::DBSUSY = false;
//--------------------------------------------------------------------------
// Initialize SM+SUSY couplings (only performed once).
void CoupSUSY::initSUSY (SusyLesHouches* slhaPtrIn, Info* infoPtrIn,
ParticleData* particleDataPtrIn, Settings* settingsPtrIn) {
// Save pointers.
infoPtr = infoPtrIn;
slhaPtr = slhaPtrIn;
settingsPtr = settingsPtrIn;
particleDataPtr = particleDataPtrIn;
// Only initialize SUSY parts if SUSY is actually switched on
if (!slhaPtr->modsel.exists()) return;
// Is NMSSM switched on?
isNMSSM = (slhaPtr->modsel(3) != 1 ? false : true);
settingsPtr->flag("SLHA:NMSSM",isNMSSM);
int nNeut = (isNMSSM ? 5 : 4);
int nChar = 2;
// Initialize pole masses
mZpole = particleDataPtr->m0(23);
wZpole = particleDataPtr->mWidth(23);
mWpole = particleDataPtr->m0(24);
wWpole = particleDataPtr->mWidth(24);
// Running masses and weak mixing angle
// (default to pole values if no running available)
mW = mWpole;
mZ = mZpole;
sin2W = sin2thetaW();
if (settingsPtr->mode("SUSY:sin2thetaWMode") == 3) {
// Possibility to force on-shell sin2W definition, mostly intended for
// cross-checks
sin2W = 1.0 - pow(mW/mZ,2);
} else if (settingsPtr->mode("SUSY:sin2thetaWMode") == 2){
// Possibility to use running sin2W definition, derived from gauge
// couplings in running SLHA blocks (normally defined at SUSY scale)
if(slhaPtr->gauge.exists(1) && slhaPtr->gauge.exists(2)
&& slhaPtr->hmix.exists(3)) {
double gp=slhaPtr->gauge(1);
double g =slhaPtr->gauge(2);
double v =slhaPtr->hmix(3);
mW = g * v / 2.0;
mZ = sqrt(pow(gp,2)+pow(g,2)) * v / 2.0;
//double tan2W = pow2(gp)/pow2(g);
//if (DBSUSY) cout << " tan2W = " << tan2W << endl;
sin2W = pow2(gp)/(pow2(g)+pow2(gp));
} else {
infoPtr->errorMsg("Warning in CoupSUSY::initSUSY: Block GAUGE"
" not found or incomplete; using sin(thetaW) at mZ");
}
}
// Overload the SM value of sin2thetaW
s2tW = sin2W;
sinW = sqrt(sin2W);
cosW = sqrt(1.0-sin2W);
// Tan(beta)
// By default, use the running one in HMIX (if not found, use MINPAR)
if(slhaPtr->hmix.exists(2))
tanb = slhaPtr->hmix(2);
else{
tanb = slhaPtr->minpar(3);
infoPtr->errorMsg("Warning in CoupSUSY::initSUSY: Block HMIX"
" not found or incomplete; using MINPAR tan(beta)");
}
cosb = sqrt( 1.0 / (1.0 + tanb*tanb) );
sinb = sqrt( max(0.0, 1.0 - cosb*cosb));
double beta = acos(cosb);
// Verbose output
if (DBSUSY) {
cout << " sin2W(Q) = " << sin2W << " mW(Q) = " << mW
<< " mZ(Q) = " << mZ << endl;
cout << " vev(Q) = " << slhaPtr->hmix(3) << " tanb(Q) = " << tanb
<< endl;
for (int i=1;i<=3;i++) {
for (int j=1;j<=3;j++) {
cout << " VCKM [" << i << "][" << j << "] = "
<< scientific << setw(10) << VCKMgen(i,j) << endl;
}
}
}
// Higgs sector
if(slhaPtr->alpha.exists()) {
alphaHiggs = slhaPtr->alpha();
}
// If RPV, assume alpha = asin(RVHMIX(1,2)) (ignore Higgs-Sneutrino mixing)
else if (slhaPtr->modsel(4) == 1) {
alphaHiggs = asin(slhaPtr->rvhmix(1,2));
infoPtr->errorMsg("Info from CoupSUSY::initSUSY:","Extracting angle"
" alpha from RVHMIX", true);
} else {
infoPtr->errorMsg("Info from CoupSUSY::initSUSY:","Block ALPHA"
" not found; using alpha = beta.", true);
// Define approximate alpha by simple SM limit
alphaHiggs = atan(tanb);
}
if(slhaPtr->hmix.exists(1) && slhaPtr->hmix.exists(4)){
muHiggs = slhaPtr->hmix(1);
mAHiggs = sqrt(slhaPtr->hmix(4));
} else if (slhaPtr->rvamix.exists()){
mAHiggs = particleDataPtr->m0(36);
muHiggs = 0.0;
infoPtr->errorMsg("Warning from CoupSUSY::initSUSY: Block HMIX"
" not found or incomplete","; setting mu = 0.");
} else{
infoPtr->errorMsg("Warning from CoupSUSY::initSUSY: Block HMIX"
" not found or incomplete","; setting mu = mA = 0.");
muHiggs = 0.0;
mAHiggs = 0.0;
}
// Pass SLHA input to 2HDM sector
double sba = sin(beta-alphaHiggs);
double cba = cos(beta-alphaHiggs);
double cosa = cos(alphaHiggs);
double sina = sin(alphaHiggs);
// h0
settingsPtr->parm("HiggsH1:coup2d", -sina/cosb);
settingsPtr->parm("HiggsH1:coup2u", cosa/sinb);
settingsPtr->parm("HiggsH1:coup2l", cosa/sinb);
settingsPtr->parm("HiggsH1:coup2Z", sba);
settingsPtr->parm("HiggsH1:coup2W", sba);
// H0
settingsPtr->parm("HiggsH2:coup2d", cosa/cosb);
settingsPtr->parm("HiggsH2:coup2u", sina/sinb);
settingsPtr->parm("HiggsH2:coup2l", sina/sinb);
settingsPtr->parm("HiggsH2:coup2Z", cba);
settingsPtr->parm("HiggsH2:coup2W", cba);
settingsPtr->parm("HiggsH2:coup2H1Z", 0.0);
settingsPtr->parm("HiggsH2:coup2HchgW", sba);
// A0
settingsPtr->parm("HiggsA3:coup2d", tanb);
settingsPtr->parm("HiggsA3:coup2u", cosb/sinb);
settingsPtr->parm("HiggsA3:coup2l", cosb/sinb);
settingsPtr->parm("HiggsA3:coup2Z", 0.0);
settingsPtr->parm("HiggsA3:coup2W", 0.0);
settingsPtr->parm("HiggsA3:coup2H1Z", cba);
settingsPtr->parm("HiggsA3:coup2H2Z", sba);
settingsPtr->parm("HiggsA3:coup2HchgW", 1.0);
// H^+
settingsPtr->parm("HiggsHchg:tanBeta", tanb);
settingsPtr->parm("HiggsHchg:coup2H1W", cba);
settingsPtr->parm("HiggsHchg:coup2H2W", sba);
// Triple higgs couplings
double cbpa = cos(beta+alphaHiggs);
double sbpa = sin(beta+alphaHiggs);
settingsPtr->parm("HiggsH1:coup2Hchg", cos(2*beta)*sbpa + 2*pow2(cosW)*sba);
settingsPtr->parm("HiggsH2:coup2Hchg", -cos(2*beta)*cbpa + 2*pow2(cosW)*cba);
settingsPtr->parm("HiggsH2:coup2H1H1", 2*sin(2*alphaHiggs)*sbpa
- cos(2*alphaHiggs)*cbpa);
settingsPtr->parm("HiggsH2:coup2A3A3", -cos(2*beta)*cbpa);
settingsPtr->parm("HiggsH2:coup2A3H1", 0.0);
settingsPtr->parm("HiggsA3:coup2H1H1", 0.0);
settingsPtr->parm("HiggsA3:coup2Hchg", 0.0);
// Shorthand for squark mixing matrices
LHmatrixBlock<6> Ru(slhaPtr->usqmix);
LHmatrixBlock<6> Rd(slhaPtr->dsqmix);
LHmatrixBlock<6> imRu(slhaPtr->imusqmix);
LHmatrixBlock<6> imRd(slhaPtr->imdsqmix);
// Construct ~g couplings
for (int i=1; i<=6; i++) {
for (int j=1; j<=3; j++) {
LsddG[i][j] = complex( Rd(i,j) , imRd(i,j));
RsddG[i][j] = complex(-Rd(i,j+3), -imRd(i,j+3));
LsuuG[i][j] = complex( Ru(i,j) , imRu(i,j));
RsuuG[i][j] = complex(-Ru(i,j+3), -imRu(i,j+3));
if (DBSUSY) {
cout << " Lsddg [" << i << "][" << j << "] = "
<< scientific << setw(10) << LsddG[i][j]
<< " RsddG [" << i << "][" << j << "] = "
<< scientific << setw(10) << RsddG[i][j] << endl;
cout << " Lsuug [" << i << "][" << j << "] = "
<< scientific << setw(10) << LsuuG[i][j]
<< " RsuuG [" << i << "][" << j << "] = "
<< scientific << setw(10) << RsuuG[i][j] << endl;
}
}
}
// Construct qqZ couplings
for (int i=1 ; i<=6 ; i++) {
// q[i] q[i] Z (def with extra factor 2 compared to [Okun])
LqqZ[i] = af(i) - 2.0*ef(i)*sin2W ;
RqqZ[i] = - 2.0*ef(i)*sin2W ;
// tmp: verbose output
if (DBSUSY) {
cout << " LqqZ [" << i << "][" << i << "] = "
<< scientific << setw(10) << LqqZ[i]
<< " RqqZ [" << i << "][" << i << "] = "
<< scientific << setw(10) << RqqZ[i] << endl;
}
}
// Construct ~q~qZ couplings
for (int i=1 ; i<=6 ; i++) {
// Squarks can have off-diagonal couplings as well
for (int j=1 ; j<=6 ; j++) {
// ~d[i] ~d[j] Z
LsdsdZ[i][j] = 0.0;
RsdsdZ[i][j] = 0.0;
for (int k=1;k<=3;k++) {
complex Rdik = complex(Rd(i,k), imRd(i,k) );
complex Rdjk = complex(Rd(j,k), imRd(j,k) );
complex Rdik3 = complex(Rd(i,k+3),imRd(i,k+3));
complex Rdjk3 = complex(Rd(j,k+3),imRd(j,k+3));
LsdsdZ[i][j] += LqqZ[1] * (Rdik*conj(Rdjk));
RsdsdZ[i][j] += RqqZ[1] * (Rdik3*conj(Rdjk3));
}
// ~u[i] ~u[j] Z
LsusuZ[i][j] = 0.0;
RsusuZ[i][j] = 0.0;
for (int k=1;k<=3;k++) {
complex Ruik = complex(Ru(i,k) ,imRu(i,k) );
complex Rujk = complex(Ru(j,k) ,imRu(j,k) );
complex Ruik3 = complex(Ru(i,k+3),imRu(i,k+3));
complex Rujk3 = complex(Ru(j,k+3),imRu(j,k+3));
LsusuZ[i][j] += LqqZ[2] * (Ruik*conj(Rujk));
RsusuZ[i][j] += RqqZ[2] * (Ruik3*conj(Rujk3));
}
// tmp: verbose output
if (DBSUSY) {
if (max(abs(LsdsdZ[i][j]),abs(RsdsdZ[i][j])) > 1e-6) {
cout << " LsdsdZ[" << i << "][" << j << "] = "
<< scientific << setw(10) << LsdsdZ[i][j]
<< " RsdsdZ[" << i << "][" << j << "] = "
<< scientific << setw(10) << RsdsdZ[i][j] << endl;
}
if (max(abs(LsusuZ[i][j]),abs(RsusuZ[i][j]))> 1e-6) {
cout << " LsusuZ[" << i << "][" << j << "] = "
<< scientific << setw(10) << LsusuZ[i][j]
<< " RsusuZ[" << i << "][" << j << "] = "
<< scientific << setw(10) << RsusuZ[i][j] << endl;
}
}
}
}
for(int i = 1; i < 7; i++)
for(int j = 1; j < 7; j++){
Rsl[i][j] = slhaPtr->selmix(i,j);
}
for(int i = 1; i < 7; i++)
for(int j = 1; j < 7; j++){
if (i < 4 && j < 4) Rsv[i][j] = slhaPtr->snumix(i,j);
else Rsv[i][j] = 0.0;
}
// In RPV, the slepton mixing matrices include Higgs bosons
// Here we just extract the entries corresponding to the slepton PDG codes
// I.e., slepton-Higgs mixing is not supported.
// Charged sleptons
if (slhaPtr->modsel(4) >= 1 && slhaPtr->rvlmix.exists()) {
for (int i=1; i<=6; ++i)
for (int j=1; j<=6; ++j)
Rsl[i][j] = slhaPtr->rvlmix(i+1,j+2);
// Check for Higgs-slepton mixing in RVLMIX
bool hasCrossTerms = false;
for (int i=2; i<=7; ++i)
for (int j=1; j<=2; ++j)
if (abs(slhaPtr->rvlmix(i,j)) > 1e-5) {
hasCrossTerms = true;
break;
}
if (hasCrossTerms)
infoPtr->errorMsg("Warning from CoupSUSY::initSUSY: "
"slepton-Higgs mixing not supported internally in PYTHIA");
}
// Neutral sleptons
if (slhaPtr->modsel(4) >= 1 && slhaPtr->rvhmix.exists()) {
for (int i=1; i<=3; ++i)
for (int j=1; j<=3; ++j)
Rsv[i][j] = slhaPtr->rvhmix(i+2,j+2);
// Check for Higgs-sneutrino mixing in RVHMIX
bool hasCrossTerms = false;
for (int i=3; i<=7; ++i)
for (int j=1; j<=2; ++j)
if (abs(slhaPtr->rvhmix(i,j)) > 1e-5) {
hasCrossTerms = true;
break;
}
if (hasCrossTerms)
infoPtr->errorMsg("Warning from CoupSUSY::initSUSY: "
"sneutrino-Higgs mixing not supported internally in PYTHIA");
}
if(DBSUSY){
cout<<"Rsl"<<endl;
for(int i=1;i<=6;i++){
for(int j=1;j<=6;j++){
cout << scientific << setw(10) << Rsl[i][j]<<" ";
}
cout<<endl;
}
cout<<"Rsv"<<endl;
for(int i=1;i<=6;i++){
for(int j=1;j<=6;j++){
cout << scientific << setw(10) << Rsv[i][j]<<" ";
}
cout<<endl;
}
}
// Construct llZ couplings;
for (int i=11 ; i<=16 ; i++) {
LllZ[i-10] = af(i) - 2.0*ef(i)*sin2W ;
RllZ[i-10] = - 2.0*ef(i)*sin2W ;
// tmp: verbose output
if (DBSUSY) {
cout << " LllZ [" << i-10 << "][" << i-10 << "] = "
<< scientific << setw(10) << LllZ[i-10]
<< " RllZ [" << i-10 << "][" << i-10 << "] = "
<< scientific << setw(10) << RllZ[i-10] << endl;
}
}
// Construct ~l~lZ couplings
// Initialize
for(int i=1;i<=6;i++){
for(int j=1;j<=6;j++){
LslslZ[i][j] = 0.0;
RslslZ[i][j] = 0.0;
for (int k=1;k<=3;k++) {
LslslZ[i][j] += LllZ[1] * Rsl[i][k] * Rsl[j][k];
RslslZ[i][j] += RllZ[1] * Rsl[i][k+3] * Rsl[j][k+3];
}
// ~v[i] ~v[j] Z
LsvsvZ[i][j] = 0.0;
RsvsvZ[i][j] = 0.0;
for (int k=1;k<=3;k++)
LsvsvZ[i][j] += LllZ[2] * Rsv[i][k]*Rsv[j][k];
}
}
for(int i=1;i<=6;i++){
for(int j=1;j<=6;j++){
if (DBSUSY) {
if (max(abs(LsvsvZ[i][j]),abs(RsvsvZ[i][j])) > 1e-6) {
cout << " LsvsvZ[" << i << "][" << j << "] = "
<< scientific << setw(10) << LsvsvZ[i][j]
<< " RsvsvZ[" << i << "][" << j << "] = "
<< scientific << setw(10) << RsvsvZ[i][j] << endl;
}
if (max(abs(LslslZ[i][j]),abs(RslslZ[i][j]))> 1e-6) {
cout << " LslslZ[" << i << "][" << j << "] = "
<< scientific << setw(10) << LslslZ[i][j]
<< " RslslZ[" << i << "][" << j << "] = "
<< scientific << setw(10) << RslslZ[i][j] << endl;
}
}
}
}
// Construct udW couplings
// Loop over up [i] and down [j] quark generation
for (int i=1;i<=3;i++) {
for (int j=1;j<=3;j++) {
// CKM matrix (use Pythia one if no SLHA)
// (NB: could also try input one if no running one found, but
// would then need to compute from Wolfenstein)
complex Vij=VCKMgen(i,j);
if (slhaPtr->vckm.exists()) {
Vij=complex(slhaPtr->vckm(i,j),slhaPtr->imvckm(i,j));
}
// u[i] d[j] W
LudW[i][j] = sqrt(2.0) * cosW * Vij;
RudW[i][j] = 0.0;
// tmp: verbose output
if (DBSUSY) {
cout << " LudW [" << i << "][" << j << "] = "
<< scientific << setw(10) << LudW[i][j]
<< " RudW [" << i << "][" << j << "] = "
<< scientific << setw(10) << RudW[i][j] << endl;
}
}
}
// Construct ~u~dW couplings
// Loop over ~u[k] and ~d[l] flavours
for (int k=1;k<=6;k++) {
for (int l=1;l<=6;l++) {
LsusdW[k][l]=0.0;
RsusdW[k][l]=0.0;
// Loop over u[i] and d[j] flavours
for (int i=1;i<=3;i++) {
for (int j=1;j<=3;j++) {
// CKM matrix (use Pythia one if no SLHA)
// (NB: could also try input one if no running one found, but
// would then need to compute from Wolfenstein)
complex Vij=VCKMgen(i,j);
if (slhaPtr->vckm.exists()) {
Vij=complex(slhaPtr->vckm(i,j),slhaPtr->imvckm(i,j));
}
// ~u[k] ~d[l] W (add one term for each quark flavour i,j)
complex Ruki = complex(Ru(k,i),imRu(k,i));
complex Rdlj = complex(Rd(l,j),imRd(l,j));
LsusdW[k][l] += sqrt(2.0) * cosW * Vij * Ruki * conj(Rdlj);
RsusdW[k][l] += 0.0;
}
}
// tmp: verbose output
if (DBSUSY) {
if (max(abs(LsusdW[k][l]),abs(RsusdW[k][l]))> 1e-6) {
cout << " LsusdW[" << k << "][" << l << "] = "
<< scientific << setw(10) << LsusdW[k][l]
<< " RsusdW[" << k << "][" << l << "] = "
<< scientific << setw(10) << RsusdW[k][l] << endl;
}
}
}
}
// Construct lvW couplings
for (int i=1;i<=3;i++){
for (int j=1;j<=3;++j){
LlvW[i][j] = (i==j) ? sqrt(2.0) * cosW : 0.0 ;
RlvW[i][j] = 0.0;
// tmp: verbose output
if (DBSUSY) {
cout << " LlvW [" << i << "][" << j << "] = "
<< scientific << setw(10) << LlvW[i][j]
<< " RlvW [" << i << "][" << j << "] = "
<< scientific << setw(10) << RlvW[i][j] << endl;
}
}
}
// Construct ~l~vW couplings
for (int k=1;k<=6;k++) {
for (int l=1;l<=6;l++) {
LslsvW[k][l]=0.0;
RslsvW[k][l]=0.0;
if(l<=3) // Only left-handed sneutrinos
for(int i=1;i<=3;i++)
LslsvW[k][l] += sqrt(2.0) * cosW * Rsl[k][i] * Rsv[l][i];
// tmp: verbose output
if (DBSUSY) {
cout << " LslsvW [" << k << "][" << l << "] = "
<< scientific << setw(10) << LslsvW[k][l]
<< " RslsvW [" << k << "][" << l << "] = "
<< scientific << setw(10) << RslsvW[k][l] << endl;
}
}
}
// Now we come to the ones with really many indices
// RPV: check for lepton-neutralino mixing (not supported)
if (slhaPtr->modsel(4) >= 1 && slhaPtr->rvnmix.exists()) {
bool hasCrossTerms = false;
for (int i=1; i<=3; ++i)
for (int j=4; j<=7; ++j)
if (abs(slhaPtr->rvnmix(i,j)) > 1e-5) {
hasCrossTerms = true;
break;
}
if (hasCrossTerms)
infoPtr->errorMsg("Warning from CoupSUSY::initSUSY: "
"Neutrino-Neutralino mixing not supported internally in PYTHIA");
}
// Construct ~chi0 couplings (allow for 5 neutralinos in NMSSM)
for (int i=1;i<=nNeut;i++) {
// Ni1, Ni2, Ni3, Ni4, Ni5
complex ni1,ni2,ni3,ni4,ni5;
// In RPV, ignore neutrino-neutralino mixing
if (slhaPtr->modsel(4) >= 1 && slhaPtr->rvnmix.exists()) {
ni1=complex( slhaPtr->rvnmix(i+3,4), 0.0 );
ni2=complex( slhaPtr->rvnmix(i+3,5), 0.0 );
ni3=complex( slhaPtr->rvnmix(i+3,6), 0.0 );
ni4=complex( slhaPtr->rvnmix(i+3,7), 0.0 );
ni5=complex( 0.0, 0.0);
}
else if (!isNMSSM) {
ni1=complex( slhaPtr->nmix(i,1), slhaPtr->imnmix(i,1) );
ni2=complex( slhaPtr->nmix(i,2), slhaPtr->imnmix(i,2) );
ni3=complex( slhaPtr->nmix(i,3), slhaPtr->imnmix(i,3) );
ni4=complex( slhaPtr->nmix(i,4), slhaPtr->imnmix(i,4) );
ni5=complex( 0.0, 0.0);
} else {
ni1=complex( slhaPtr->nmnmix(i,1), slhaPtr->imnmnmix(i,1) );
ni2=complex( slhaPtr->nmnmix(i,2), slhaPtr->imnmnmix(i,2) );
ni3=complex( slhaPtr->nmnmix(i,3), slhaPtr->imnmnmix(i,3) );
ni4=complex( slhaPtr->nmnmix(i,4), slhaPtr->imnmnmix(i,4) );
ni5=complex( slhaPtr->nmnmix(i,5), slhaPtr->imnmnmix(i,5) );
}
// Change to positive mass convention
complex iRot( 0., 1.);
if (slhaPtr->mass(idNeut(i)) < 0.) {
ni1 *= iRot;
ni2 *= iRot;
ni3 *= iRot;
ni4 *= iRot;
ni5 *= iRot;
}
// ~chi0 [i] ~chi0 [j] Z : loop over [j]
for (int j=1; j<=nNeut; j++) {
// neutralino [j] higgsino components
complex nj3, nj4;
if (slhaPtr->modsel(4) >= 1 && slhaPtr->rvnmix.exists()) {
nj3=complex( slhaPtr->rvnmix(i+3,6), 0.0 );
nj4=complex( slhaPtr->rvnmix(i+3,7), 0.0 );
}
else if (!isNMSSM) {
nj3=complex( slhaPtr->nmix(j,3), slhaPtr->imnmix(j,3) );
nj4=complex( slhaPtr->nmix(j,4), slhaPtr->imnmix(j,4) );
} else {
nj3=complex( slhaPtr->nmnmix(j,3), slhaPtr->imnmnmix(j,3) );
nj4=complex( slhaPtr->nmnmix(j,4), slhaPtr->imnmnmix(j,4) );
}
// Change to positive mass convention
if (slhaPtr->mass(idNeut(j)) < 0.) {
nj3 *= iRot;
nj4 *= iRot;
}
// ~chi0 [i] ~chi0 [j] Z : couplings
OLpp[i][j] = -0.5 * ni3 * conj(nj3) + 0.5 * ni4 * conj(nj4);
ORpp[i][j] = 0.5 * conj(ni3) * nj3 - 0.5 * conj(ni4) * nj4;
// tmp: verbose output
if (DBSUSY) {
cout << " OL'' [" << i << "][" << j << "] = "
<< scientific << setw(10) << OLpp[i][j]
<< " OR'' [" << i << "][" << j << "] = "
<< scientific << setw(10) << ORpp[i][j] << endl;
}
}
// ~chi0 [i] ~chi+ [j] W : loop over [j]
for (int j=1; j<=nChar; j++) {
// Chargino mixing
complex uj1, uj2, vj1, vj2;
if (slhaPtr->modsel(4)<1 || !slhaPtr->rvumix.exists()) {
uj1=complex( slhaPtr->umix(j,1), slhaPtr->imumix(j,1) );
uj2=complex( slhaPtr->umix(j,2), slhaPtr->imumix(j,2) );
vj1=complex( slhaPtr->vmix(j,1), slhaPtr->imvmix(j,1) );
vj2=complex( slhaPtr->vmix(j,2), slhaPtr->imvmix(j,2) );
}
// RPV: ignore lepton-chargino mixing
else {
uj1=complex( slhaPtr->rvumix(j+3,4), 0.0 );
uj2=complex( slhaPtr->rvumix(j+3,5), 0.0 );
vj1=complex( slhaPtr->rvvmix(j+3,4), 0.0 );
vj2=complex( slhaPtr->rvvmix(j+3,5), 0.0 );
}
// ~chi0 [i] ~chi+ [j] W : couplings
OL[i][j] = -1.0/sqrt(2.0)*ni4*conj(vj2)+ni2*conj(vj1);
OR[i][j] = 1.0/sqrt(2.0)*conj(ni3)*uj2+conj(ni2)*uj1;
// tmp: verbose output
if (DBSUSY) {
cout << " OL [" << i << "][" << j << "] = "
<< scientific << setw(10) << OL[i][j]
<< " OR [" << i << "][" << j << "] = "
<< scientific << setw(10) << OR[i][j] << endl;
}
}
// ~qqX couplings
// Quark Charges
double ed = -1.0/3.0;
double T3d = -0.5;
double eu = 2.0/3.0;
double T3u = 0.5;
// Loop over quark [k] generation
for (int k=1;k<=3;k++) {
// Set quark masses
// Initial guess 0,0,0,mc,mb,mt with the latter from the PDT
double mu = particleDataPtr->m0(2*k);
double md = particleDataPtr->m0(2*k-1);
if (k == 1) { mu=0.0 ; md=0.0; }
if (k == 2) { md=0.0 ; mu=0.0; }
// Compute running mass from Yukawas and vevs if possible.
if (slhaPtr->yd.exists() && slhaPtr->hmix.exists(3)) {
double ykk=slhaPtr->yd(k,k);
double v1=slhaPtr->hmix(3)/sqrt(1+pow(tanb,2));
if (ykk > 0.0) md = ykk * v1 / sqrt(2.0) ;
}
if (slhaPtr->yu.exists() && slhaPtr->hmix.exists(3)) {
double ykk=slhaPtr->yu(k,k);
double v2=slhaPtr->hmix(3)/sqrt(1.0+1.0/pow(tanb,2));
if (ykk > 0.0) mu = ykk * v2 / sqrt(2.0) ;
}
// tmp: verbose output
if (DBSUSY) {
cout << " Gen = " << k << " mu = " << mu << " md = " << md
<< " yUU,DD = " << slhaPtr->yu(k,k) << ","
<< slhaPtr->yd(k,k) << endl;
}
// Loop over squark [j] flavour
for (int j=1;j<=6;j++) {
// Squark mixing
complex Rdjk = complex(Rd(j,k), imRd(j,k) );
complex Rdjk3 = complex(Rd(j,k+3),imRd(j,k+3));
complex Rujk = complex(Ru(j,k), imRu(j,k) );
complex Rujk3 = complex(Ru(j,k+3),imRu(j,k+3));
// ~d[j] d[k] ~chi0[i]
// Changed according to new notation
LsddX[j][k][i] = ((ed-T3d)*sinW*ni1 + T3d*cosW*ni2)*conj(Rdjk)
+ md*cosW*ni3*conj(Rdjk3)/2.0/mW/cosb;
RsddX[j][k][i] = -ed*sinW*conj(ni1)*conj(Rdjk3)
+ md*cosW*conj(ni3)*conj(Rdjk)/2.0/mW/cosb;
// ~u[j] u[k] ~chi0[i]
LsuuX[j][k][i] = ((eu-T3u)*sinW*ni1 + T3u*cosW*ni2)*conj(Rujk)
+ mu*cosW*ni4*conj(Rujk3)/2.0/mW/sinb;
RsuuX[j][k][i] = -eu*sinW*conj(ni1)*conj(Rujk3)
+ mu*cosW*conj(ni4)*conj(Rujk)/2.0/mW/sinb;
if (DBSUSY) {
if (abs(LsddX[j][k][i]) > 1e-6) {
// tmp: verbose output
cout << " LsddX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << LsddX[j][k][i] << endl;
}
if (abs(RsddX[j][k][i]) > 1e-6) {
// tmp: verbose output
cout << " RsddX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << RsddX[j][k][i] << endl;
}
if (abs(LsuuX[j][k][i]) > 1e-6) {
// tmp: verbose output
cout << " LsuuX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << LsuuX[j][k][i] << endl;
}
if (abs(RsuuX[j][k][i]) > 1e-6) {
// tmp: verbose output
cout << " RsuuX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << RsuuX[j][k][i] << endl;
}
}
}
}
// Start slepton couplings
// Lepton Charges
double el = -1.0;
double T3l = -0.5;
double ev = 0.0;
double T3v = 0.5;
// Need to define lepton mass
for (int k=1;k<=3;k++) {
// Set lepton masses
double ml(0.0);
if(k==3) ml = particleDataPtr->m0(15);
for(int j=1;j<=6;j++){
LsllX[j][k][i] = 0;
RsllX[j][k][i] = 0;
LsvvX[j][k][i] = 0;
RsvvX[j][k][i] = 0;
// ~l[j] l[k] ~chi0[i]
// Changed according to new notation
LsllX[j][k][i] = ((el-T3l)*sinW*ni1 + T3l*cosW*ni2)*Rsl[j][k]
+ ml*cosW*ni3/2.0/mW/cosb*Rsl[j][k+3];
RsllX[j][k][i] = -el*sinW*conj(ni1)*Rsl[j][k+3]
+ ml*cosW*conj(ni3)/2.0/mW/cosb*Rsl[j][k];
if(j<3 && j==k){
// No sneutrino mixing; only left handed
// ~v[j] v[k] ~chi0[i]
LsvvX[j][k][i] = ((ev-T3v)*sinW*ni1 + T3v*cosW*ni2);
}
if (DBSUSY) {
if (abs(LsllX[j][k][i]) > 1e-6) {
// tmp: verbose output
cout << " LsllX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << LsllX[j][k][i] << endl;
}
if (abs(RsllX[j][k][i]) > 1e-6) {
// tmp: verbose output
cout << " RsllX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << RsllX[j][k][i] << endl;
}
if (abs(LsvvX[j][k][i]) > 1e-6) {
// tmp: verbose output
cout << " LsvvX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << LsvvX[j][k][i] << endl;
}
}
}
}
}
// RPV: check for lepton-chargino mixing (not supported)
if (slhaPtr->modsel(4) >= 1 && slhaPtr->rvumix.exists()) {
bool hasCrossTerms = false;
for (int i=1; i<=3; ++i)
for (int j=4; j<=5; ++j)
if (abs(slhaPtr->rvumix(i,j)) > 1e-5
|| abs(slhaPtr->rvvmix(i,j)) > 1e-5) {
hasCrossTerms = true;
break;
}
if (hasCrossTerms)
infoPtr->errorMsg("Warning from CoupSUSY::initSUSY: "
"Lepton-Chargino mixing not supported internally in PYTHIA");
}
// Construct ~chi+ couplings
// sqrt(2)
double rt2 = sqrt(2.0);
for (int i=1;i<=nChar;i++) {
// Ui1, Ui2, Vi1, Vi2
complex ui1,ui2,vi1,vi2;
ui1=complex( slhaPtr->umix(i,1), slhaPtr->imumix(i,1) );
ui2=complex( slhaPtr->umix(i,2), slhaPtr->imumix(i,2) );
vi1=complex( slhaPtr->vmix(i,1), slhaPtr->imvmix(i,1) );
vi2=complex( slhaPtr->vmix(i,2), slhaPtr->imvmix(i,2) );
// ~chi+ [i] ~chi- [j] Z : loop over [j]
for (int j=1; j<=nChar; j++) {
// Chargino mixing
complex uj1, uj2, vj1, vj2;
uj1=complex( slhaPtr->umix(j,1), slhaPtr->imumix(j,1) );
uj2=complex( slhaPtr->umix(j,2), slhaPtr->imumix(j,2) );
vj1=complex( slhaPtr->vmix(j,1), slhaPtr->imvmix(j,1) );
vj2=complex( slhaPtr->vmix(j,2), slhaPtr->imvmix(j,2) );
// ~chi+ [i] ~chi- [j] Z : couplings
OLp[i][j] = -vi1*conj(vj1) - 0.5*vi2*conj(vj2)
+ ( (i == j) ? sin2W : 0.0);
ORp[i][j] = -conj(ui1)*uj1 - 0.5*conj(ui2)*uj2
+ ( (i == j) ? sin2W : 0.0);
if (DBSUSY) {
// tmp: verbose output
cout << " OL' [" << i << "][" << j << "] = "
<< scientific << setw(10) << OLp[i][j]
<< " OR' [" << i << "][" << j << "] = "
<< scientific << setw(10) << ORp[i][j] << endl;
}
}
// Loop over quark [l] flavour
for (int l=1;l<=3;l++) {
// Set quark [l] masses
// Initial guess 0,0,0,mc,mb,mt with the latter from the PDT
double mul = particleDataPtr->m0(2*l);
double mdl = particleDataPtr->m0(2*l-1);
if (l == 1 || l == 2) { mul=0.0 ; mdl=0.0; }
// Compute running mass from Yukawas and vevs if possible.
if (slhaPtr->yd.exists() && slhaPtr->hmix.exists(3)) {
double yll=slhaPtr->yd(l,l);
double v1=slhaPtr->hmix(3)/sqrt(1+pow(tanb,2));
if (yll > 0.0) mdl = yll * v1 / sqrt(2.0) ;
}
if (slhaPtr->yu.exists() && slhaPtr->hmix.exists(3)) {
double yll=slhaPtr->yu(l,l);
double v2=slhaPtr->hmix(3)/sqrt(1.0+1.0/pow(tanb,2));
if (yll > 0.0) mul = yll * v2 / sqrt(2.0) ;
}
// Loop over squark [j] flavour
for (int j=1;j<=6;j++) {
// Loop over off-diagonal quark [k] generation
for (int k=1;k<=3;k++) {
// Set quark [k] masses
// Initial guess 0,0,0,0,mb,mt with the latter from the PDT
double muk = particleDataPtr->m0(2*k);
double mdk = particleDataPtr->m0(2*k-1);
if (k == 1) { muk=0.0 ; mdk=0.0; }
if (k == 2) { mdk=0.0 ; muk=0.0; }
// Compute running mass from Yukawas and vevs if possible.
if (slhaPtr->yd.exists() && slhaPtr->hmix.exists(3)) {
double ykk=slhaPtr->yd(k,k);
double v1=slhaPtr->hmix(3)/sqrt(1+pow(tanb,2));
if (ykk > 0.0) mdk = ykk * v1 / sqrt(2.0) ;
}
if (slhaPtr->yu.exists() && slhaPtr->hmix.exists(3)) {
double ykk=slhaPtr->yu(k,k);
double v2=slhaPtr->hmix(3)/sqrt(1.0+1.0/pow(tanb,2));
if (ykk > 0.0) muk = ykk * v2 / sqrt(2.0) ;
}
// CKM matrix (use Pythia one if no SLHA)
// (NB: could also try input one if no running one found, but
// would then need to compute from Wolfenstein)
complex Vlk=VCKMgen(l,k);
complex Vkl=VCKMgen(k,l);
if (slhaPtr->vckm.exists()) {
Vlk=complex(slhaPtr->vckm(l,k),slhaPtr->imvckm(l,k));
Vkl=complex(slhaPtr->vckm(k,l),slhaPtr->imvckm(k,l));
}
// Squark mixing
complex Rdjk = complex(Rd(j,k), imRd(j,k) );
complex Rdjk3 = complex(Rd(j,k+3),imRd(j,k+3));
complex Rujk = complex(Ru(j,k), imRu(j,k) );
complex Rujk3 = complex(Ru(j,k+3),imRu(j,k+3));
// ~d[j] u[l] ~chi+[i]
LsduX[j][l][i] += (ui1*conj(Rdjk)
- mdk*ui2*conj(Rdjk3)/rt2/mW/cosb)*Vlk;
RsduX[j][l][i] -= mul*conj(vi2)*Vlk*conj(Rdjk)/rt2/mW/sinb;
// ~u[j] d[l] ~chi+[i]
LsudX[j][l][i] += (conj(vi1)*Rujk
- muk*conj(vi2)*Rujk3/rt2/mW/sinb)*Vkl;
RsudX[j][l][i] -= mdl*ui2*Vkl*Rujk/rt2/mW/cosb;
}
if (DBSUSY) {
if (max(abs(LsduX[j][l][i]),abs(RsduX[j][l][i])) > 1e-6) {
// tmp: verbose output
cout << " LsduX[" << j << "][" << l << "][" << i << "] = "
<< scientific << setw(10) << LsduX[j][l][i];
cout << " RsduX[" << j << "][" << l << "][" << i << "] = "
<< scientific << setw(10) << RsduX[j][l][i] << endl;
}
if (max(abs(LsudX[j][l][i]),abs(RsudX[j][l][i])) > 1e-6) {
// tmp: verbose output
cout << " LsudX[" << j << "][" << l << "][" << i << "] = "
<< scientific << setw(10) << LsudX[j][l][i];
cout << " RsudX[" << j << "][" << l << "][" << i << "] = "
<< scientific << setw(10) << RsudX[j][l][i] << endl;
}
}
}
}
// Loop over slepton [j] flavour
for (int j=1;j<=6;j++) {
for (int k=1;k<=3;k++) {
LslvX[j][k][i] = 0.0;
RslvX[j][k][i] = 0.0;
LsvlX[j][k][i] = 0.0;
RsvlX[j][k][i] = 0.0;
// Set lepton [k] masses
double ml = 0.0;
if (k == 3) ml = particleDataPtr->m0(15);
if(j==k || j==k+3){ // No lepton mixing
// ~l[j] v[l] ~chi+[i]
LslvX[j][k][i] += ui1- ml*ui2/rt2/mW/cosb;
RslvX[j][k][i] -= ml*conj(vi2)/rt2/mW/sinb;
// ~v[j] l[l] ~chi+[i]
if(j<=3){ // No right handed sneutrinos
LsvlX[j][k][i] += conj(vi1) - ml*conj(vi2)/rt2/mW/sinb;
}
}
if (DBSUSY) {
if (max(abs(LslvX[j][k][i]),abs(RslvX[j][k][i])) > 1e-6) {
// tmp: verbose output
cout << " LslvX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << LslvX[j][k][i];
cout << " RslvX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << RslvX[j][k][i] << endl;
}
if (max(abs(LsvlX[j][k][i]),abs(RsvlX[j][k][i])) > 1e-6) {
// tmp: verbose output
cout << " LsvlX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << LsvlX[j][k][i];
cout << " RsvlX[" << j << "][" << k << "][" << i << "] = "
<< scientific << setw(10) << RsvlX[j][k][i] << endl;
}
}
}
}
}
// Shorthand for RPV couplings
// The input LNV lambda couplings
LHtensor3Block<3> rvlle(slhaPtr->rvlamlle);
// The input LNV lambda' couplings
LHtensor3Block<3> rvlqd(slhaPtr->rvlamlqd);
// The input BNV lambda'' couplings
LHtensor3Block<3> rvudd(slhaPtr->rvlamudd);
isLLE = false;
isLQD = false;
isUDD = false;
// Symmetry properties
if(rvlle.exists()){
isLLE = true;
for(int i=1;i<=3;i++){
for(int j=i;j<=3;j++){
//lambda(i,j,k)=-lambda(j,i,k)
for(int k=1;k<=3;k++){
if(i==j){
rvLLE[i][j][k] = 0.0;
}else{
rvLLE[i][j][k] = rvlle(i,j,k);
rvLLE[j][i][k] = -rvlle(i,j,k);
}
}
}
}
}
if(rvlqd.exists()){
isLQD=true;
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
for(int k=1;k<=3;k++){
rvLQD[i][j][k] = rvlqd(i,j,k);
}
}
}
}
//lambda''(k,j,i)=-lambda''(k,i,j)
if(rvudd.exists()){
isUDD = true;
for(int i=1;i<=3;i++){
for(int j=i;j<=3;j++){
for(int k=1;k<=3;k++){
if(i==j){
rvUDD[k][i][j] = 0.0;
}else{
rvUDD[k][i][j] = rvudd(k,i,j);
rvUDD[k][j][i] = -rvudd(k,i,j);
}
}
}
}
}
if(DBSUSY){
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
for(int k=1;k<=3;k++){
if(rvlle.exists())
cout<<"LambdaLLE["<<i<<"]["<<j<<"]["<<k<<"]="<<rvLLE[i][j][k]<<" ";
if(rvlqd.exists())
cout<<"LambdaLQD["<<i<<"]["<<j<<"]["<<k<<"]="<<rvLQD[i][j][k]<<" ";
if(rvudd.exists())
cout<<"LambdaUDD["<<i<<"]["<<j<<"]["<<k<<"]="<<rvUDD[i][j][k]
<<"\n";
}
}
}
}
// Store the squark mixing matrix
for(int i=1;i<=6;i++){
for(int j=1;j<=3;j++){
Rusq[i][j] = complex(Ru(i,j), imRu(i,j) );
Rusq[i][j+3] = complex(Ru(i,j+3),imRu(i,j+3));
Rdsq[i][j] = complex(Rd(i,j), imRd(i,j) );
Rdsq[i][j+3] = complex(Rd(i,j+3),imRd(i,j+3));
}
}
if(DBSUSY){
cout<<"Ru"<<endl;
for(int i=1;i<=6;i++){
for(int j=1;j<=6;j++){
cout << real(Rusq[i][j])<<" ";
}
cout<<endl;
}
cout<<"Rd"<<endl;
for(int i=1;i<=6;i++){
for(int j=1;j<=6;j++){
cout << real(Rdsq[i][j])<<" ";
}
cout<<endl;
}
}
// Let everyone know we are ready
isInit = true;
}
//--------------------------------------------------------------------------
// Return neutralino flavour codes.
int CoupSUSY::idNeut(int idChi) {
int id = 0;
if (idChi == 1) id = 1000022;
else if (idChi == 2) id = 1000023;
else if (idChi == 3) id = 1000025;
else if (idChi == 4) id = 1000035;
else if (idChi == 5) id = 1000045;
return id;
}
//--------------------------------------------------------------------------
// Return chargino flavour codes.
int CoupSUSY::idChar(int idChi) {
int id = 0;
if (idChi == 1) id = 1000024;
else if (idChi == -1) id = -1000024;
else if (idChi == 2) id = 1000037;
else if (idChi == -2) id = -1000037;
return id;
}
//--------------------------------------------------------------------------
// Return sup flavour codes.
int CoupSUSY::idSup(int iSup) {
int id = 0;
int sgn = ( iSup > 0 ) ? 1 : -1;
iSup = abs(iSup);
if (iSup == 1) id = 1000002;
else if (iSup == 2) id = 1000004;
else if (iSup == 3) id = 1000006;
else if (iSup == 4) id = 2000002;
else if (iSup == 5) id = 2000004;
else if (iSup == 6) id = 2000006;
return sgn*id;
}
//--------------------------------------------------------------------------
// Return sdown flavour codes
int CoupSUSY::idSdown(int iSdown) {
int id = 0;
int sgn = ( iSdown > 0 ) ? 1 : -1;
iSdown = abs(iSdown);
if (iSdown == 1) id = 1000001;
else if (iSdown == 2) id = 1000003;
else if (iSdown == 3) id = 1000005;
else if (iSdown == 4) id = 2000001;
else if (iSdown == 5) id = 2000003;
else if (iSdown == 6) id = 2000005;
return sgn*id;
}
//--------------------------------------------------------------------------
// Function to return slepton flavour codes
int CoupSUSY::idSlep(int iSlep) {
int id = 0;
int sgn = ( iSlep > 0 ) ? 1 : -1;
iSlep = abs(iSlep);
if (iSlep == 1) id = 1000011;
else if (iSlep == 2) id = 1000013;
else if (iSlep == 3) id = 1000015;
else if (iSlep == 4) id = 2000011;
else if (iSlep == 5) id = 2000013;
else if (iSlep == 6) id = 2000015;
return sgn*id;
}
//--------------------------------------------------------------------------
// Return neutralino code; zero if not a (recognized) neutralino
int CoupSUSY::typeNeut(int idPDG) {
int type = 0;
int idAbs = abs(idPDG);
if(idAbs == 1000022) type = 1;
else if(idAbs == 1000023) type = 2;
else if(idAbs == 1000025) type = 3;
else if(idAbs == 1000035) type = 4;
else if(isNMSSM && idAbs == 1000045) type = 5;
return type;
}
//--------------------------------------------------------------------------
// Check whether particle is a Chargino
int CoupSUSY::typeChar(int idPDG) {
int type = 0;
if(abs(idPDG) == 1000024) type = 1;
else if (abs(idPDG) == 1000037)type = 2;
return type;
}
//==========================================================================
} // end namespace Pythia8
|
/*************************************************************************/
/* matrix3.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "matrix3.h"
#include "math_funcs.h"
#include "os/copymem.h"
#define cofac(row1,col1, row2, col2)\
(elements[row1][col1] * elements[row2][col2] - elements[row1][col2] * elements[row2][col1])
void Matrix3::from_z(const Vector3& p_z) {
if (Math::abs(p_z.z) > Math_SQRT12 ) {
// choose p in y-z plane
real_t a = p_z[1]*p_z[1] + p_z[2]*p_z[2];
real_t k = 1.0/Math::sqrt(a);
elements[0]=Vector3(0,-p_z[2]*k,p_z[1]*k);
elements[1]=Vector3(a*k,-p_z[0]*elements[0][2],p_z[0]*elements[0][1]);
} else {
// choose p in x-y plane
real_t a = p_z.x*p_z.x + p_z.y*p_z.y;
real_t k = 1.0/Math::sqrt(a);
elements[0]=Vector3(-p_z.y*k,p_z.x*k,0);
elements[1]=Vector3(-p_z.z*elements[0].y,p_z.z*elements[0].x,a*k);
}
elements[2]=p_z;
}
void Matrix3::invert() {
real_t co[3]={
cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1)
};
real_t det = elements[0][0] * co[0]+
elements[0][1] * co[1]+
elements[0][2] * co[2];
ERR_FAIL_COND( det == 0 );
real_t s = 1.0/det;
set( co[0]*s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s,
co[1]*s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s,
co[2]*s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s );
}
void Matrix3::orthonormalize() {
// Gram-Schmidt Process
Vector3 x=get_axis(0);
Vector3 y=get_axis(1);
Vector3 z=get_axis(2);
x.normalize();
y = (y-x*(x.dot(y)));
y.normalize();
z = (z-x*(x.dot(z))-y*(y.dot(z)));
z.normalize();
set_axis(0,x);
set_axis(1,y);
set_axis(2,z);
}
Matrix3 Matrix3::orthonormalized() const {
Matrix3 c = *this;
c.orthonormalize();
return c;
}
Matrix3 Matrix3::inverse() const {
Matrix3 inv=*this;
inv.invert();
return inv;
}
void Matrix3::transpose() {
SWAP(elements[0][1],elements[1][0]);
SWAP(elements[0][2],elements[2][0]);
SWAP(elements[1][2],elements[2][1]);
}
Matrix3 Matrix3::transposed() const {
Matrix3 tr=*this;
tr.transpose();
return tr;
}
void Matrix3::scale(const Vector3& p_scale) {
elements[0][0]*=p_scale.x;
elements[1][0]*=p_scale.x;
elements[2][0]*=p_scale.x;
elements[0][1]*=p_scale.y;
elements[1][1]*=p_scale.y;
elements[2][1]*=p_scale.y;
elements[0][2]*=p_scale.z;
elements[1][2]*=p_scale.z;
elements[2][2]*=p_scale.z;
}
Matrix3 Matrix3::scaled( const Vector3& p_scale ) const {
Matrix3 m = *this;
m.scale(p_scale);
return m;
}
Vector3 Matrix3::get_scale() const {
return Vector3(
Vector3(elements[0][0],elements[1][0],elements[2][0]).length(),
Vector3(elements[0][1],elements[1][1],elements[2][1]).length(),
Vector3(elements[0][2],elements[1][2],elements[2][2]).length()
);
}
void Matrix3::rotate(const Vector3& p_axis, real_t p_phi) {
*this = *this * Matrix3(p_axis, p_phi);
}
Matrix3 Matrix3::rotated(const Vector3& p_axis, real_t p_phi) const {
return *this * Matrix3(p_axis, p_phi);
}
Vector3 Matrix3::get_euler() const {
// rot = cy*cz -cy*sz sy
// cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx
// -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy
Matrix3 m = *this;
m.orthonormalize();
Vector3 euler;
euler.y = Math::asin(m[0][2]);
if ( euler.y < Math_PI*0.5) {
if ( euler.y > -Math_PI*0.5) {
euler.x = Math::atan2(-m[1][2],m[2][2]);
euler.z = Math::atan2(-m[0][1],m[0][0]);
} else {
real_t r = Math::atan2(m[1][0],m[1][1]);
euler.z = 0.0;
euler.x = euler.z - r;
}
} else {
real_t r = Math::atan2(m[0][1],m[1][1]);
euler.z = 0;
euler.x = r - euler.z;
}
return euler;
}
void Matrix3::set_euler(const Vector3& p_euler) {
real_t c, s;
c = Math::cos(p_euler.x);
s = Math::sin(p_euler.x);
Matrix3 xmat(1.0,0.0,0.0,0.0,c,-s,0.0,s,c);
c = Math::cos(p_euler.y);
s = Math::sin(p_euler.y);
Matrix3 ymat(c,0.0,s,0.0,1.0,0.0,-s,0.0,c);
c = Math::cos(p_euler.z);
s = Math::sin(p_euler.z);
Matrix3 zmat(c,-s,0.0,s,c,0.0,0.0,0.0,1.0);
//optimizer will optimize away all this anyway
*this = xmat*(ymat*zmat);
}
bool Matrix3::operator==(const Matrix3& p_matrix) const {
for (int i=0;i<3;i++) {
for (int j=0;j<3;j++) {
if (elements[i][j]!=p_matrix.elements[i][j])
return false;
}
}
return true;
}
bool Matrix3::operator!=(const Matrix3& p_matrix) const {
return (!(*this==p_matrix));
}
Matrix3::operator String() const {
String mtx;
for (int i=0;i<3;i++) {
for (int j=0;j<3;j++) {
if (i!=0 || j!=0)
mtx+=", ";
mtx+=rtos( elements[i][j] );
}
}
return mtx;
}
Matrix3::operator Quat() const {
Matrix3 m=*this;
m.orthonormalize();
real_t trace = m.elements[0][0] + m.elements[1][1] + m.elements[2][2];
real_t temp[4];
if (trace > 0.0)
{
real_t s = Math::sqrt(trace + 1.0);
temp[3]=(s * 0.5);
s = 0.5 / s;
temp[0]=((m.elements[2][1] - m.elements[1][2]) * s);
temp[1]=((m.elements[0][2] - m.elements[2][0]) * s);
temp[2]=((m.elements[1][0] - m.elements[0][1]) * s);
}
else
{
int i = m.elements[0][0] < m.elements[1][1] ?
(m.elements[1][1] < m.elements[2][2] ? 2 : 1) :
(m.elements[0][0] < m.elements[2][2] ? 2 : 0);
int j = (i + 1) % 3;
int k = (i + 2) % 3;
real_t s = Math::sqrt(m.elements[i][i] - m.elements[j][j] - m.elements[k][k] + 1.0);
temp[i] = s * 0.5;
s = 0.5 / s;
temp[3] = (m.elements[k][j] - m.elements[j][k]) * s;
temp[j] = (m.elements[j][i] + m.elements[i][j]) * s;
temp[k] = (m.elements[k][i] + m.elements[i][k]) * s;
}
return Quat(temp[0],temp[1],temp[2],temp[3]);
}
static const Matrix3 _ortho_bases[24]={
Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1),
Matrix3(0, -1, 0, 1, 0, 0, 0, 0, 1),
Matrix3(-1, 0, 0, 0, -1, 0, 0, 0, 1),
Matrix3(0, 1, 0, -1, 0, 0, 0, 0, 1),
Matrix3(1, 0, 0, 0, 0, -1, 0, 1, 0),
Matrix3(0, 0, 1, 1, 0, 0, 0, 1, 0),
Matrix3(-1, 0, 0, 0, 0, 1, 0, 1, 0),
Matrix3(0, 0, -1, -1, 0, 0, 0, 1, 0),
Matrix3(1, 0, 0, 0, -1, 0, 0, 0, -1),
Matrix3(0, 1, 0, 1, 0, 0, 0, 0, -1),
Matrix3(-1, 0, 0, 0, 1, 0, 0, 0, -1),
Matrix3(0, -1, 0, -1, 0, 0, 0, 0, -1),
Matrix3(1, 0, 0, 0, 0, 1, 0, -1, 0),
Matrix3(0, 0, -1, 1, 0, 0, 0, -1, 0),
Matrix3(-1, 0, 0, 0, 0, -1, 0, -1, 0),
Matrix3(0, 0, 1, -1, 0, 0, 0, -1, 0),
Matrix3(0, 0, 1, 0, 1, 0, -1, 0, 0),
Matrix3(0, -1, 0, 0, 0, 1, -1, 0, 0),
Matrix3(0, 0, -1, 0, -1, 0, -1, 0, 0),
Matrix3(0, 1, 0, 0, 0, -1, -1, 0, 0),
Matrix3(0, 0, 1, 0, -1, 0, 1, 0, 0),
Matrix3(0, 1, 0, 0, 0, 1, 1, 0, 0),
Matrix3(0, 0, -1, 0, 1, 0, 1, 0, 0),
Matrix3(0, -1, 0, 0, 0, -1, 1, 0, 0)
};
int Matrix3::get_orthogonal_index() const {
//could be sped up if i come up with a way
Matrix3 orth=*this;
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
float v = orth[i][j];
if (v>0.5)
v=1.0;
else if (v<-0.5)
v=-1.0;
else
v=0;
orth[i][j]=v;
}
}
for(int i=0;i<24;i++) {
if (_ortho_bases[i]==orth)
return i;
}
return 0;
}
void Matrix3::set_orthogonal_index(int p_index){
//there only exist 24 orthogonal bases in r3
ERR_FAIL_INDEX(p_index,24);
*this=_ortho_bases[p_index];
}
void Matrix3::get_axis_and_angle(Vector3 &r_axis,real_t& r_angle) const {
double angle,x,y,z; // variables for result
double epsilon = 0.01; // margin to allow for rounding errors
double epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees
if ( (Math::abs(elements[1][0]-elements[0][1])< epsilon)
&& (Math::abs(elements[2][0]-elements[0][2])< epsilon)
&& (Math::abs(elements[2][1]-elements[1][2])< epsilon)) {
// singularity found
// first check for identity matrix which must have +1 for all terms
// in leading diagonaland zero in other terms
if ((Math::abs(elements[1][0]+elements[0][1]) < epsilon2)
&& (Math::abs(elements[2][0]+elements[0][2]) < epsilon2)
&& (Math::abs(elements[2][1]+elements[1][2]) < epsilon2)
&& (Math::abs(elements[0][0]+elements[1][1]+elements[2][2]-3) < epsilon2)) {
// this singularity is identity matrix so angle = 0
r_axis=Vector3(0,1,0);
r_angle=0;
return;
}
// otherwise this singularity is angle = 180
angle = Math_PI;
double xx = (elements[0][0]+1)/2;
double yy = (elements[1][1]+1)/2;
double zz = (elements[2][2]+1)/2;
double xy = (elements[1][0]+elements[0][1])/4;
double xz = (elements[2][0]+elements[0][2])/4;
double yz = (elements[2][1]+elements[1][2])/4;
if ((xx > yy) && (xx > zz)) { // elements[0][0] is the largest diagonal term
if (xx< epsilon) {
x = 0;
y = 0.7071;
z = 0.7071;
} else {
x = Math::sqrt(xx);
y = xy/x;
z = xz/x;
}
} else if (yy > zz) { // elements[1][1] is the largest diagonal term
if (yy< epsilon) {
x = 0.7071;
y = 0;
z = 0.7071;
} else {
y = Math::sqrt(yy);
x = xy/y;
z = yz/y;
}
} else { // elements[2][2] is the largest diagonal term so base result on this
if (zz< epsilon) {
x = 0.7071;
y = 0.7071;
z = 0;
} else {
z = Math::sqrt(zz);
x = xz/z;
y = yz/z;
}
}
r_axis=Vector3(x,y,z);
r_angle=angle;
return;
}
// as we have reached here there are no singularities so we can handle normally
double s = Math::sqrt((elements[1][2] - elements[2][1])*(elements[1][2] - elements[2][1])
+(elements[2][0] - elements[0][2])*(elements[2][0] - elements[0][2])
+(elements[0][1] - elements[1][0])*(elements[0][1] - elements[1][0])); // used to normalise
if (Math::abs(s) < 0.001) s=1;
// prevent divide by zero, should not happen if matrix is orthogonal and should be
// caught by singularity test above, but I've left it in just in case
angle = Math::acos(( elements[0][0] + elements[1][1] + elements[2][2] - 1)/2);
x = (elements[1][2] - elements[2][1])/s;
y = (elements[2][0] - elements[0][2])/s;
z = (elements[0][1] - elements[1][0])/s;
r_axis=Vector3(x,y,z);
r_angle=angle;
}
Matrix3::Matrix3(const Vector3& p_euler) {
set_euler( p_euler );
}
Matrix3::Matrix3(const Quat& p_quat) {
real_t d = p_quat.length_squared();
real_t s = 2.0 / d;
real_t xs = p_quat.x * s, ys = p_quat.y * s, zs = p_quat.z * s;
real_t wx = p_quat.w * xs, wy = p_quat.w * ys, wz = p_quat.w * zs;
real_t xx = p_quat.x * xs, xy = p_quat.x * ys, xz = p_quat.x * zs;
real_t yy = p_quat.y * ys, yz = p_quat.y * zs, zz = p_quat.z * zs;
set( 1.0 - (yy + zz), xy - wz, xz + wy,
xy + wz, 1.0 - (xx + zz), yz - wx,
xz - wy, yz + wx, 1.0 - (xx + yy)) ;
}
Matrix3::Matrix3(const Vector3& p_axis, real_t p_phi) {
Vector3 axis_sq(p_axis.x*p_axis.x,p_axis.y*p_axis.y,p_axis.z*p_axis.z);
real_t cosine= Math::cos(p_phi);
real_t sine= Math::sin(p_phi);
elements[0][0] = axis_sq.x + cosine * ( 1.0 - axis_sq.x );
elements[0][1] = p_axis.x * p_axis.y * ( 1.0 - cosine ) + p_axis.z * sine;
elements[0][2] = p_axis.z * p_axis.x * ( 1.0 - cosine ) - p_axis.y * sine;
elements[1][0] = p_axis.x * p_axis.y * ( 1.0 - cosine ) - p_axis.z * sine;
elements[1][1] = axis_sq.y + cosine * ( 1.0 - axis_sq.y );
elements[1][2] = p_axis.y * p_axis.z * ( 1.0 - cosine ) + p_axis.x * sine;
elements[2][0] = p_axis.z * p_axis.x * ( 1.0 - cosine ) + p_axis.y * sine;
elements[2][1] = p_axis.y * p_axis.z * ( 1.0 - cosine ) - p_axis.x * sine;
elements[2][2] = axis_sq.z + cosine * ( 1.0 - axis_sq.z );
}
|
#include <torch/script.h> // One-stop header.
#include <iostream>
#include <memory>
using namespace torch;
int main(int argc, const char* argv[]) {
torch::Device device = torch::kCUDA;
// Deserialize the ScriptModule from a file using torch::jit::load().
std::shared_ptr<torch::jit::script::Module> module = torch::jit::load("../model_jit.pth");
module->to(device);
assert(module != nullptr);
std::cout << "model loading ok\n";
std::vector<torch::jit::IValue> inputs;
inputs.push_back(torch::ones({1000, 1, 28, 28}).to(device));
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
for (int64_t itr = 1; itr <= 10; ++itr) {
at::Tensor output = module->forward(inputs).toTensor();
}
std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now();
std::cout << "Time elapsed = " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << "ms" << std::endl;
return 0;
}
|
#include <stdio.h>
#include "../math/vector.h"
#include "../math/matrix.h"
#include <stdlib.h>
#include <time.h>
constexpr vec3_t rotation = vec3_t(0, M_PI / 2, 0);
constexpr matrix<3, 4> rotationMatrix = matrix<3, 4>::GetMatrix(rotation);
constexpr vec3_t rotatedVec = rotationMatrix.Vector3Rotate(vec3_t(1, 0, 0));
constexpr vec3_t expectedVec = vec3_t(0, 1, 0);
static_assert(rotatedVec.DistToSqr(expectedVec) < 0.1);
int exit_error(int i)
{
fprintf(stderr, "%d\n", i);
return i;
}
int main()
{
srand(time(nullptr));
vec3_t a(1), b(1, 2);
[[maybe_unused]] vec3soa<float, 8> stype = b;
[[maybe_unused]] vec3 v3 = b;
[[maybe_unused]] vec3_t d = {3.f, 3.f, 3.f};
printf("%f %f %f\n%f %f %f\n", a[0], a[1], a[2], b[0], b[1], b[2]);
{
vec3_t arr[100];
for (int i = 0; i < 100; i++)
arr[i] = vec3_t(rand() % 100 + 1, rand() % 100 + 1, rand() % 100 + 1, rand() % 100 + 1);
{
vec3_t combined[50];
for (int i = 0; i < 50; i++)
combined[i] = arr[i] + arr[i + 50];
vec3_t back[100];
for (int i = 0; i < 50; i++)
back[i] = combined[i] - arr[i + 50];
for (int i = 0; i < 50; i++)
back[i + 50] = combined[i] - arr[i];
for (int i = 0; i < 100; i++)
if (arr[i] != back[i])
return exit_error(1000 + i);
}
printf("Vec test 1 passed!\n");
{
vec3_t combined[50];
for (int i = 0; i < 50; i++)
combined[i] = arr[i] * arr[i + 50];
vec3_t back[100];
for (int i = 0; i < 50; i++)
back[i] = combined[i] / arr[i + 50];
for (int i = 0; i < 50; i++)
back[i + 50] = combined[i] / arr[i];
for (int i = 0; i < 100; i++)
if ((arr[i] - back[i]).LengthSqr() > 0.01f) {
printf("Mismatch! %f %f %f | %f %f %f\n", arr[i][0], arr[i][1], arr[i][2], back[i][0], back[i][1], back[i][2]);
return exit_error(2000 + i);
}
}
printf("Vec test 2 passed!\n");
{
vec3_t combined[100];
for (int i = 0; i < 100; i++)
combined[i] = arr[i] * arr[i];
vec3_t back[100];
for (int i = 0; i < 100; i++)
back[i] = combined[i].Sqrt();
for (int i = 0; i < 100; i++)
if ((arr[i] - back[i]).LengthSqr() > 0.01f)
return exit_error(3000 + i);
}
printf("Vec test 3 passed!\n");
}
{
vec3soa<float, 8> arr[100];
for (int i = 0; i < 100; i++)
for (int u = 0; u < 3; u++)
for (int o = 0; o < 8; o++)
arr[i][u][o] = rand() % 100 + 1;
{
vec3soa<float, 8> combined[50];
for (int i = 0; i < 50; i++)
combined[i] = arr[i] + arr[i + 50];
vec3soa<float, 8> back[100];
for (int i = 0; i < 50; i++)
back[i] = combined[i] - arr[i + 50];
for (int i = 0; i < 50; i++)
back[i + 50] = combined[i] - arr[i];
for (int i = 0; i < 100; i++)
if ((arr[i] - back[i]).Abs().AddedUpTotal() > 0.01f)
return exit_error(10000 + i);
}
printf("VecSoa test 1 passed!\n");
{
vec3soa<float, 8> combined[50];
for (int i = 0; i < 50; i++)
combined[i] = arr[i] * arr[i + 50];
vec3soa<float, 8> back[100];
for (int i = 0; i < 50; i++)
back[i] = combined[i] / arr[i + 50];
for (int i = 0; i < 50; i++)
back[i + 50] = combined[i] / arr[i];
for (int i = 0; i < 100; i++)
if ((arr[i] - back[i]).Abs().AddedUpTotal() > 0.01f)
return exit_error(20000 + i);
}
printf("VecSoa test 2 passed!\n");
{
vec3soa<float, 8> combined[100];
for (int i = 0; i < 100; i++)
combined[i] = arr[i] * arr[i];
printf("Part 1\n");
vec3soa<float, 8> back[100];
for (int i = 0; i < 100; i++)
back[i] = combined[i].Sqrt();
printf("Part 2\n");
for (int i = 0; i < 100; i++)
if ((arr[i] - back[i]).Abs().AddedUpTotal() > 0.01f)
return exit_error(30000 + i);
}
printf("VecSoa test 3 passed!\n");
}
return 0;
}
constexpr vec3_t v(1);
constexpr vec3_t v2(2);
static_assert(v[0] == 1);
static_assert((v * v2)[0] == 2);
constexpr vec3soa<float, 8> vs(1, 2);
static_assert(vs[0][0] == 1 && vs[1][0] == 1);
static_assert(vs[0][1] == 2 && vs[1][1] == 2);
static_assert(vs[0][2] == 1 && vs[1][2] == 1);
static_assert(!AllArithmetic<vecp<float, 3>, vecp<float, 3>>::value);
static_assert(AllArithmetic<int, float, double, long>::value);
static_assert(!AllArithmetic<int, float, char*>::value);
|
/********************************************************************
* 2014 -
* open source under Apache License Version 2.0
********************************************************************/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
#include "client/Token.h"
#include "datatransfer.pb.h"
#include "DataTransferProtocolSender.h"
#include "Exception.h"
#include "ExceptionInternal.h"
#include "hdfs.pb.h"
#include "Security.pb.h"
#include "WriteBuffer.h"
using namespace google::protobuf;
namespace Hdfs {
namespace Internal {
static inline void Send(Socket & sock, DataTransferOp op, Message * msg,
int writeTimeout) {
WriteBuffer buffer;
buffer.writeBigEndian(static_cast<int16_t>(DATA_TRANSFER_VERSION));
buffer.write(static_cast<char>(op));
int msgSize = msg->ByteSize();
buffer.writeVarint32(msgSize);
char * b = buffer.alloc(msgSize);
if (!msg->SerializeToArray(b, msgSize)) {
THROW(HdfsIOException,
"DataTransferProtocolSender cannot serialize header to send buffer.");
}
sock.writeFully(buffer.getBuffer(0), buffer.getDataSize(0), writeTimeout);
}
static inline void BuildBaseHeader(const ExtendedBlock & block,
const Token & accessToken, BaseHeaderProto * header) {
ExtendedBlockProto * eb = header->mutable_block();
TokenProto * token = header->mutable_token();
eb->set_blockid(block.getBlockId());
eb->set_generationstamp(block.getGenerationStamp());
eb->set_numbytes(block.getNumBytes());
eb->set_poolid(block.getPoolId());
token->set_identifier(accessToken.getIdentifier());
token->set_password(accessToken.getPassword());
token->set_kind(accessToken.getKind());
token->set_service(accessToken.getService());
}
static inline void BuildClientHeader(const ExtendedBlock & block,
const Token & accessToken, const char * clientName,
ClientOperationHeaderProto * header) {
header->set_clientname(clientName);
BuildBaseHeader(block, accessToken, header->mutable_baseheader());
}
static inline void BuildNodeInfo(const DatanodeInfo & node,
DatanodeInfoProto * info) {
DatanodeIDProto * id = info->mutable_id();
id->set_hostname(node.getHostName());
id->set_infoport(node.getInfoPort());
id->set_ipaddr(node.getIpAddr());
id->set_ipcport(node.getIpcPort());
id->set_datanodeuuid(node.getDatanodeId());
id->set_xferport(node.getXferPort());
info->set_location(node.getLocation());
}
static inline void BuildNodesInfo(const std::vector<DatanodeInfo> & nodes,
RepeatedPtrField<DatanodeInfoProto> * infos) {
for (std::size_t i = 0; i < nodes.size(); ++i) {
BuildNodeInfo(nodes[i], infos->Add());
}
}
DataTransferProtocolSender::DataTransferProtocolSender(Socket & sock,
int writeTimeout, const std::string & datanodeAddr) :
sock(sock), writeTimeout(writeTimeout), datanode(datanodeAddr) {
}
DataTransferProtocolSender::~DataTransferProtocolSender() {
}
void DataTransferProtocolSender::readBlock(const ExtendedBlock & blk,
const Token & blockToken, const char * clientName,
int64_t blockOffset, int64_t length) {
try {
OpReadBlockProto op;
op.set_len(length);
op.set_offset(blockOffset);
BuildClientHeader(blk, blockToken, clientName, op.mutable_header());
Send(sock, READ_BLOCK, &op, writeTimeout);
} catch (const HdfsCanceled & e) {
throw;
} catch (const HdfsException & e) {
NESTED_THROW(HdfsIOException,
"DataTransferProtocolSender cannot send read request to datanode %s.",
datanode.c_str());
}
}
void DataTransferProtocolSender::writeBlock(const ExtendedBlock & blk,
const Token & blockToken, const char * clientName,
const std::vector<DatanodeInfo> & targets, int stage, int pipelineSize,
int64_t minBytesRcvd, int64_t maxBytesRcvd,
int64_t latestGenerationStamp, int checksumType, int bytesPerChecksum) {
try {
OpWriteBlockProto op;
op.set_latestgenerationstamp(latestGenerationStamp);
op.set_minbytesrcvd(minBytesRcvd);
op.set_maxbytesrcvd(maxBytesRcvd);
op.set_pipelinesize(targets.size());
op.set_stage((OpWriteBlockProto_BlockConstructionStage) stage);
BuildClientHeader(blk, blockToken, clientName, op.mutable_header());
ChecksumProto * ck = op.mutable_requestedchecksum();
ck->set_bytesperchecksum(bytesPerChecksum);
ck->set_type((ChecksumTypeProto) checksumType);
BuildNodesInfo(targets, op.mutable_targets());
Send(sock, WRITE_BLOCK, &op, writeTimeout);
} catch (const HdfsCanceled & e) {
throw;
} catch (const HdfsException & e) {
NESTED_THROW(HdfsIOException,
"DataTransferProtocolSender cannot send write request to datanode %s.",
datanode.c_str());
}
}
void DataTransferProtocolSender::transferBlock(const ExtendedBlock & blk,
const Token & blockToken, const char * clientName,
const std::vector<DatanodeInfo> & targets) {
try {
OpTransferBlockProto op;
BuildClientHeader(blk, blockToken, clientName, op.mutable_header());
BuildNodesInfo(targets, op.mutable_targets());
Send(sock, TRANSFER_BLOCK, &op, writeTimeout);
} catch (const HdfsCanceled & e) {
throw;
} catch (const HdfsException & e) {
NESTED_THROW(HdfsIOException,
"DataTransferProtocolSender cannot send transfer request to datanode %s.",
datanode.c_str());
}
}
void DataTransferProtocolSender::blockChecksum(const ExtendedBlock & blk,
const Token & blockToken) {
try {
//TODO
} catch (const HdfsCanceled & e) {
throw;
} catch (const HdfsException & e) {
NESTED_THROW(HdfsIOException,
"DataTransferProtocolSender cannot send checksum request to datanode %s.",
datanode.c_str());
}
}
void DataTransferProtocolSender::requestShortCircuitFds(const ExtendedBlock blk,
const Token& blockToken,
uint32_t maxVersion) {
try {
OpRequestShortCircuitAccessProto op;
BuildBaseHeader(blk, blockToken, op.mutable_header());
op.set_maxversion(maxVersion);
Send(sock, REQUEST_SHORT_CIRCUIT_FDS, &op, writeTimeout);
} catch (const HdfsCanceled& e) {
throw;
} catch (const HdfsException& e) {
NESTED_THROW(HdfsIOException,
"DataTransferProtocolSender cannot send request "
"short-circuit fds request "
"to datanode %s.",
datanode.c_str());
}
}
}
}
|
/** @file movecreator.cpp*/
#include "movecreator.h"
#include <iomanip>
#ifdef ENABLE_MPI
# include <mpi.h>
extern MPI_Datatype MPI_vector, MPI_Particle, MPI_exchange;
#endif
double MoveCreator::particleMove() {
double edriftchanges =0.0;
long target;
/*=== This is a particle move step ===*/
target = ran2() * (long)conf->pvec.size();
if ( /*!( ((wl.wlm[0] == 3) || (wl.wlm[1] == 3) ) && (target == 0) ) && chceme at se hybe*/ \
((ran2() < 0.5) || (topo.ia_params[conf->pvec[target].type][conf->pvec[target].type].geotype[0] >= SP)) ) { // no rotation for spheres
edriftchanges = partDisplace(target);
} else {
//=== Rotation step ===//
// BTW: partAcialRotate pro uhel 180.0 a pouziti Vector::getRandomUnitConeUniform by se mel chovat stejne jako normalni partRotate ....
if(sim->coneAngle == 0.0){
edriftchanges = partRotate(target);
} else {
edriftchanges = partAxialRotate(target);
}
}
//=== End particle move step ===
return edriftchanges;
}
double MoveCreator::clusterMove() {
double edriftchanges =0.0;
long target;
target = ran2() * (long)conf->pvec.size();// Select random particle from config
edriftchanges = clusterMoveGeom(target);// Call geometric cluster move
return edriftchanges;
}
int MoveCreator::isInCluster(double *list, int size, double value){
for(int i=0; i< size; i++){
if(list[i] == value){
return 1;
}
}
return 0;
}
double MoveCreator::clusterMoveGeom(long target) {
/*
* For reference to this move see:
* Liu, Jiwen, and Erik Luijten. "Rejection-free geometric cluster algorithm for complex fluids." Physical review letters 92.3 (2004): 035504.
* DOI: 10.1103/PhysRevLett.92.035504
*/
if(conf->pvec.empty())
return 0.0;
double edriftchanges = calcEnergy->allToAll(), cluster[MAXN];
Vector r_center;
/*=============================================*/
/* Set reflection center */
/*=============================================*/
/*There exists two ways how to select reflection center, Global and Local.
* Global ---- select random point in simulation box as reflection center
* Local ---- select vector from selected particle of random length in interval (0; max_len>
*
* Both ways of selecting reflection center should be equal where in case of Local selection maximal displacement (max_len) must be set.
*
* From test simulations on rather small systems it seems Global relection have faster convergence
*/
/*____________Global____________*/
r_center = conf->geo.randomPos();
/*____________Local (displacement like)____________*/
// double max_displacement= 1.5;
// r_center.randomUnitSphere();// create unit random vector
// r_center *= ran2() * max_displacement;// set displacement from range [0:max_displacement]
// r_center += conf->pvec[target].pos;// set center of reflection to be shifted by length of DISPLACEMENT in random direction from target
Particle reflection;
Molecule selected_chain;
std::vector<Molecule> chainsToFix; // thse are all cahins that might be disturbed by application of PBC
int counter= 0, num_particles=0;
double energy_old, energy_new;
/*=============================================*/
/* Addition of particles into cluster */
/*=============================================*/
/*
* Here we chose to add whole chain into cluster if one particle of chain is includedtarget in cluster
* This make move slightly faster but
* !!!!SIMULATION OF CHAINS WITHOUT SINGLE PARTICLE MOVES CANT CONVERGE!!!!
*
* TODO: change it in way that intra chain energy is used to determine if other particles from chain should be added
* into cluster
*/
double molecule_size;
//topo.moleculeParam[conf->pvec[target].molType].particleTypes.size() == number of particles in chain ... special case is single particle of length 1
molecule_size = topo.moleculeParam[conf->pvec[target].molType].particleTypes.size();
if ( molecule_size == 1 ){
cluster[num_particles] = target;
num_particles++;
}else{
selected_chain = conf->pvec.getMolOfPart(target);
chainsToFix.push_back(selected_chain);
for(unsigned int i=0; i < selected_chain.size(); i++){
cluster[num_particles] = selected_chain[i];
num_particles++;
}
}
/*=============================================*/
/* Cluster Creation Loop */
/*=============================================*/
do{
reflection = conf->pvec[cluster[counter]];// copy old particle into reflected particle
//Reflect particle cluster[counter] by point reflection by center r_center point
reflection.pos = 2.0*r_center - reflection.pos;// reflect center of particle around r_center
reflection.dir *=1.0;// reflect orientation of particle
reflection.patchdir[0] *=-1.0;// reflect orientation of patch1
reflection.patchdir[1] *=-1.0;// reflect orientation of patch2
reflection.patchsides[0]*=-1.0;// reflect all sides of patch
reflection.patchsides[1]*=-1.0;
reflection.patchsides[2]*=-1.0;
reflection.patchsides[3]*=-1.0;
reflection.chdir[0] *=-1.0;
reflection.chdir[1] *=-1.0;
conf->geo.usePBC(&reflection);
// bring reflected particle into box (if not particles could start to spread too far and numerical errors acumulate!)
//Iterate through reflection "Neighbours"
for (unsigned int i = 0; i < conf->pvec.size(); i++){
if (!isInCluster(cluster, num_particles, i)){
energy_old = calcEnergy->p2p(cluster[counter], i);
energy_new = calcEnergy->p2p(&reflection, i);
if (ran2() < (1-exp((energy_old-energy_new)/sim->temper))){//ran2() < (1-exp(-1.0*((energy_new-energy_old)/sim->temper))) acceptance criteria vis. Reference
//Addition of chain into cluster
//-----------------------------------------------------
molecule_size = topo.moleculeParam[conf->pvec[i].molType].particleTypes.size();
if(molecule_size == 1){
cluster[num_particles] = i;
num_particles++;
}else{
selected_chain = conf->pvec.getMolOfPart(i);
chainsToFix.push_back(selected_chain);
for(unsigned int t=0; t < selected_chain.size(); t++){
cluster[num_particles] = selected_chain[t];
num_particles++;
}
}
//-----------------------------------------------------
}
}
}
conf->pvec[cluster[counter]] = reflection;
counter++;
}while(counter < num_particles);
for ( std::vector<Molecule>::iterator it = chainsToFix.begin(); it != chainsToFix.end(); ++it ){
conf->makeMoleculeWhole(&(*it));
}
return calcEnergy->allToAll()-edriftchanges;
}
double MoveCreator::printClustersConf() {
// in cluster when dist < 3
// Breadth-first search, BFS
double energy;
vector<vector<unsigned int> > cluster;
bool push = true;
for(unsigned int w=0; w<1; w++) {
cluster.push_back(vector<unsigned int>());
cluster.back().push_back(w);
for(unsigned int i=0; i<cluster.back().size(); i++) {
for(unsigned int j=0; j<conf->pvec.size(); j++) {
push = true;
energy = calcEnergy->p2p(i,j);
//cout << energy << " ";
if(energy < -7) {
for(unsigned int q=0; q<cluster.back().size(); q++)
if(j == cluster.back()[q])
push=false;
if(push)
cluster.back().push_back(j);
}
}
}
cout << cluster.back().size() << " ";
}
for(unsigned int i=0; i< cluster.back().size(); i++) {
cout << cluster.back()[i] << " ";
}
int q;
for(unsigned int i=0; i<1; i++) {
FILE* outfile;
outfile = fopen("cluster", "w");
cout << cluster[i].size() << endl;
fprintf (outfile, "%ld\n", (long)cluster[i].size());
fprintf (outfile, "sweep %ld; box %.10f %.10f %.10f\n", (long)0, conf->geo.box.x, conf->geo.box.y, conf->geo.box.z);
for(unsigned int j=0; j<cluster[i].size(); j++) {
q=cluster[i][j];
fprintf (outfile, "%15.8e %15.8e %15.8e %15.8e %15.8e %15.8e %15.8e %15.8e %15.8e %d %d\n",
conf->geo.box.x * ((conf->pvec[q].pos.x) - anInt(conf->pvec[q].pos.x)),
conf->geo.box.y * ((conf->pvec[q].pos.y) - anInt(conf->pvec[q].pos.y)),
conf->geo.box.z * ((conf->pvec[q].pos.z) - anInt(conf->pvec[q].pos.z)),
conf->pvec[q].dir.x, conf->pvec[q].dir.y, conf->pvec[q].dir.z,
conf->pvec[q].patchdir[0].x, conf->pvec[q].patchdir[0].y, conf->pvec[q].patchdir[0].z,
conf->pvec[q].switched,
conf->pvec[q].molType);
}
fclose(outfile);
}
return 0.0;
}
double MoveCreator::switchTypeMove() {
double edriftchanges=0.0, energy,enermove=0.0, switchE=0.0,wlener=0.0;
int reject=0;
long target;
double radiusholemax_orig=0;
int switchType, sequence_num=0, delta_mu;
//=== This is an attempt to switch a type ===
target = ran2() * conf->pvec.switchPartCount();
target = conf->pvec.getSwitchPart(target, sequence_num); // stores sequence number
delta_mu = topo.moleculeParam[conf->pvec[target].molType ].deltaMu[sequence_num];
if(conf->pvec[target].switched == 0)
switchType = topo.moleculeParam[conf->pvec[target].molType ].switchTypes[sequence_num];
else
switchType = topo.moleculeParam[conf->pvec[target].molType ].particleTypes[sequence_num];
DEBUG_SIM("Switching the particle type");
DEBUG_SIM("PARTICLE: %ld", target);
energy = calcEnergy->oneToAll(target);
// Start switching the type
int switched = conf->pvec[target].switched;
int pmone = PMONE(switched);
DEBUG_SIM("switched = %d", switched);
DEBUG_SIM("pmone = %d", pmone);
int tmp_type = conf->pvec[target].type;
conf->pvec[target].type = switchType;//conf->pvec[target].switchtype;
/*conf->pvec[target].switchtype*/ switchType = tmp_type;
conf->pvec[target].switched += pmone;
conf->pvec[target].init(&(topo.ia_params[conf->pvec[target].type][conf->pvec[target].type]));
DEBUG_SIM("Particle %ld is %d switched", target, switched);
//DEBUG
#ifdef DEBUGGING_SIM
if ((abs(pmone) != 1) || (conf->pvec[target].type == conf->pvec[target].switchtype)){
fprintf(stderr, "ERROR: Something went wrong, when switching the type of particle %ld\n", target);
exit(1);
}
#endif
if(wl.wlm[0] > 0)
wlener = wl.runSwitch(reject, radiusholemax_orig);
if (!reject) {
switchE = delta_mu * pmone;
// DEBUG
//double dmu = enermove;
//pvec[target].switched += pmone;
enermove = calcEnergy->oneToAllTrial(target);
//printf("energy: %f \t %f\t%f\n",pvec[target].delta_mu, dmu, enermove);
}
// If not accepted: switch back
if ( reject || moveTry(energy+wlener,enermove+switchE,sim->temper) ) { // probability acceptance
DEBUG_SIM("Did NOT switch it\n");
conf->pvec[target].type = tmp_type;
conf->pvec[target].switched -= pmone;
conf->pvec[target].init(&(topo.ia_params[conf->pvec[target].type][conf->pvec[target].type]));
wl.reject(radiusholemax_orig, wl.wlm);
sim->stat.switchMv[conf->pvec[target].type].rej++;
} else { // move was accepted
wl.accept(wl.wlm[0]);
sim->stat.switchMv[conf->pvec[target].type].acc++;
edriftchanges = enermove - energy;
calcEnergy->update(target);
}
return edriftchanges;
}
double MoveCreator::chainMove() {
//
// TODO: Check that moves dont change intenal chain energy
//
double edriftchanges =0.0;
long target;
if(conf->pvec.getChainCount() == 0) // no chains to displace - muVTmove deleted all
return 0.0;
//=== This is a chain move step ===
target = ran2() * conf->pvec.getChainCount();
if (ran2() < 0.5) {
//=== Displacement step of cluster/chain ===
edriftchanges = chainDisplace(target);
} else {
//=== Rotation step of cluster/chain ===
edriftchanges = chainRotate(target);
} // ==== END OF CHAIN MOVES =====
return edriftchanges;
}
double MoveCreator::pressureMove() {
double edriftchanges,energy,enermove=0.0,wlener;
int reject=0;
double old_side; // geo.box length before attempted change
double *side; // geo.box dimension to try changing
double psch,psx,psy;// Size of a geo.box change during pressure
double pvol; // Size of a volume during pressure
double pvoln; // Size of a new volume during pressure
double rsave; // Saved random number
double area;
double radiusholemax_orig=0;
//=== This is a volume change step ===
edriftchanges=0.0;
wlener = 0.0;
energy = calcEnergy->allToAll();
// Choose an edge
switch (sim->ptype) {
case 0:
// Anisotropic pressure coupling
rsave = ran2();
if (rsave < 1.0/3.0) {
side = &(conf->geo.box.x);
area = conf->geo.box.y * conf->geo.box.z;
} else if (rsave < 2.0/3.0) {
side = &(conf->geo.box.y);
area = conf->geo.box.x * conf->geo.box.z;
} else {
side = &(conf->geo.box.z);
area = conf->geo.box.x * conf->geo.box.y;
}
old_side = *side;
*side += sim->stat.edge.mx * (ran2() - 0.5);
reject = 0;
if (wl.wlm[0] > 0) { // get new neworder for wang-landau
wlener = wl.runPress(reject, radiusholemax_orig);
}
if (!reject) { // wang-landaou ok, try move - calculate energy
// enermove = (p*(V_new - V_old) - N * k * T * ln(V_new / V_old)
enermove = sim->press * area * (*side - old_side) - (double)conf->pvec.size() * sim->temper * log(*side/old_side);
enermove += calcEnergy->allToAllTrial();
}
//
// probability(old -> new) = min[ 1, exp{-(E_new - E_old)/(kT) + (p*(V_new - V_old) - NkT* ln(V_new / V_old))/(kT) ]}
//
if ( reject || *side <= 0.0 || ( moveTry(energy+wlener,enermove,sim->temper) ) ) { // probability acceptance
*side = old_side;
sim->stat.edge.rej++;
wl.reject(radiusholemax_orig, wl.wlm);
} else { // move was accepted
sim->stat.edge.acc++;
calcEnergy->update();
wl.accept(wl.wlm[0]);
edriftchanges = enermove - energy;
}
break;
case 1:
/* Isotropic pressure coupling */
psch = sim->stat.edge.mx * (ran2() - 0.5);
pvol = conf->geo.box.x * conf->geo.box.y * conf->geo.box.z;
conf->geo.box.x += psch;
conf->geo.box.y += psch;
conf->geo.box.z += psch;
pvoln = conf->geo.box.x * conf->geo.box.y * conf->geo.box.z;
reject = 0;
if (wl.wlm[0] > 0) { /* get new neworder for wang-landau */
wlener = wl.runPress(reject, radiusholemax_orig);
}
if (!reject) { /* wang-landaou ok, try move - calcualte energy */
// enermove = (p*(V_new - V_old) - N * k * T * ln(V_new / V_old)
enermove = sim->press * (pvoln - pvol) - (double)conf->pvec.size() * sim->temper * log(pvoln/pvol);
enermove += calcEnergy->allToAllTrial();
}
if ( reject || moveTry(energy+wlener,enermove,sim->temper) ) { /* probability acceptance */
conf->geo.box.x -= psch;
conf->geo.box.y -= psch;
conf->geo.box.z -= psch;
sim->stat.edge.rej++;
wl.reject(radiusholemax_orig, wl.wlm);
} else { // move was accepted
sim->stat.edge.acc++;
wl.accept(wl.wlm[0]);
calcEnergy->update();
edriftchanges = enermove - energy;
}
break;
case 2:
// Isotropic pressure coupling in xy, z constant
psch = sim->stat.edge.mx * (ran2() - 0.5);
pvol = conf->geo.box.x * conf->geo.box.y;
conf->geo.box.x += psch;
conf->geo.box.y += psch;
pvoln = conf->geo.box.x * conf->geo.box.y;
reject = 0;
if (wl.wlm[0] > 0) { // get new neworder for wang-landau
wlener = wl.runPress(reject, radiusholemax_orig, true);
}
if (!reject) { // wang-landaou ok, try move - calculate energy
// enermove = (p*(V_new - V_old) - N * k * T * ln(V_new / V_old)
enermove = sim->press * conf->geo.box.z * (pvoln - pvol) - (double)conf->pvec.size() * sim->temper * log(pvoln/pvol);
enermove += calcEnergy->allToAllTrial();
}
if ( reject || moveTry(energy+wlener,enermove,sim->temper) ) { // probability acceptance
conf->geo.box.x -= psch;
conf->geo.box.y -= psch;
sim->stat.edge.rej++;
wl.reject(radiusholemax_orig, wl.wlm);
} else { // move was accepted
sim->stat.edge.acc++;
wl.accept(wl.wlm[0]);
calcEnergy->update();
edriftchanges = enermove - energy;
}
break;
case 3:
// Isotropic pressure coupling in xy, z coupled to have fixed volume
psch = sim->stat.edge.mx * (ran2() - 0.5);
pvol = conf->geo.box.x * conf->geo.box.y * conf->geo.box.z;
conf->geo.box.x += psch;
conf->geo.box.y += psch;
conf->geo.box.z = pvol / conf->geo.box.x / conf->geo.box.y;
reject = 0;
if (wl.wlm[0] > 0) { // get new neworder for wang-landau
wlener = wl.runPress(reject, radiusholemax_orig);
}
if (!reject) { // wang-landaou ok, try move - calculate energy
enermove += calcEnergy->allToAllTrial();
}
if ( reject || moveTry(energy+wlener,enermove,sim->temper) ) { // probability acceptance
conf->geo.box.x -= psch;
conf->geo.box.y -= psch;
conf->geo.box.z = pvol / conf->geo.box.x / conf->geo.box.y;
sim->stat.edge.rej++;
wl.reject(radiusholemax_orig, wl.wlm);
} else { // move was accepted
sim->stat.edge.acc++;
wl.accept(wl.wlm[0]);
calcEnergy->update();
edriftchanges = enermove - energy;
}
break;
case 4:
// Anisotropic pressure coupling in xy, z const
pvol = conf->geo.box.x * conf->geo.box.y;
psx = 0.0;
psy = 0.0;
if (ran2() - 0.5) psx = sim->stat.edge.mx * (ran2() - 0.5);
else psy = sim->stat.edge.mx * (ran2() - 0.5);
conf->geo.box.x += psx;
conf->geo.box.y += psy;
pvoln = conf->geo.box.x * conf->geo.box.y;
reject = 0;
if (wl.wlm[0] > 0) { // get new neworder for wang-landau
wlener = wl.runPress(reject, radiusholemax_orig);
}
if (!reject) { // wang-landaou ok, try move - calculate energy
// enermove = (p*(V_new - V_old) - N * k * T * ln(V_new / V_old)
enermove = sim->press * conf->geo.box.z * (pvoln - pvol) - (double)conf->pvec.size() * sim->temper * log(pvoln/pvol);
enermove += calcEnergy->allToAllTrial();
}
if ( reject || moveTry(energy+wlener,enermove,sim->temper) ) { // probability acceptance
conf->geo.box.x -= psx;
conf->geo.box.y -= psy;
sim->stat.edge.rej++;
wl.reject(radiusholemax_orig, wl.wlm);
} else { // move was accepted
sim->stat.edge.acc++;
wl.accept(wl.wlm[0]);
calcEnergy->update();
edriftchanges = enermove - energy;
}
break;
case 5:
// Box size change only in y direction
pvol = conf->geo.box.y;
psy = sim->stat.edge.mx * (ran2() - 0.5);
conf->geo.box.y += psy;
pvoln = conf->geo.box.y;
reject = 0;
if (wl.wlm[0] > 0) { // get new neworder for wang-landau
wlener = wl.runPress(reject, radiusholemax_orig);
}
if (!reject) { // wang-landaou ok, try move - calculate energy
// enermove = (p*(V_new - V_old) - N * k * T * ln(V_new / V_old)
enermove = sim->press * conf->geo.box.z * conf->geo.box.x * (pvoln - pvol) - (double)conf->pvec.size() * sim->temper * log(pvoln/pvol);
enermove += calcEnergy->allToAllTrial();
}
if ( reject || moveTry(energy+wlener,enermove,sim->temper) ) { // probability acceptance
conf->geo.box.y -= psy;
sim->stat.edge.rej++;
wl.reject(radiusholemax_orig, wl.wlm);
} else { // move was accepted
sim->stat.edge.acc++;
wl.accept(wl.wlm[0]);
calcEnergy->update();
edriftchanges = enermove - energy;
}
break;
default:
fprintf (stderr, "ERROR: unknown type of pressure coupling %d",sim->ptype);
exit(1);
}
//=== End volume change step ===
return edriftchanges;
}
double MoveCreator::replicaExchangeMove(long sweep) {
double edriftchanges=0.0;
#ifdef ENABLE_MPI
double change; // energy
double *recwlweights;
double volume = conf->geo.volume();
double entrophy = sim->press * volume - (double)conf->pvec.size() * log(volume) * sim->temper;
int sizewl = 0, receiverRank = -1, receivedRank = -1;
int rank;
//
// TAGS for mpi communications
//
int tagExchangeMPI = 1001, tagDouble = 2022, tagInt = 3333, tagStat = 54321;
long localwl,receivedwl;
bool reject=true;
MpiExchangeData localmpi, receivedmpi;
MpiExchangeData* locMpi;
MpiExchangeData* recMpi;
Statistics localStat, recStat;
localStat = sim->stat;
if (wl.length[1] > 0) {
sizewl = wl.length[1] * wl.length[0];
} else {
sizewl = wl.length[0];
}
recwlweights = (double*) malloc( sizeof(double) * sizewl );
MPI_Status status;
MPI_Datatype MPI_exchange;
MPI_Datatype MPI_vector2;
MPI_Datatype MPI_stat;
localmpi.defDataType(&MPI_exchange, &MPI_vector2);
localStat.defDataType(&MPI_stat);
//
// Init local mpi data
//
localmpi.energy = calcEnergy->allToAll();
localmpi.press = sim->press;
localmpi.volume = conf->geo.box.x * conf->geo.box.y * conf->geo.box.z;
localmpi.accepted = 0;
localmpi.radiusholemax = wl.radiusholemax;
localmpi.mpiRank = sim->mpirank;
for(int i=0; i<conf->pvec.molTypeCount; i++) {
localmpi.partNum[i] = conf->pvec.molCountOfType(i);
}
localmpi.pseudoMpiRank = sim->pseudoRank;
localmpi.temperature = sim->temper;
for (int wli=0;wli<wl.wlmdim;wli++) {
localmpi.wl_order[wli] = wl.currorder[wli];
}
//
//=== This is an attempt to switch replicas ===
//
int oddoreven;
if ( (sweep % (2*sim->nrepchange)) == 0) // exchange odd ones with even ones
oddoreven=1;
else
oddoreven=0; // exchange even ones with odd ones
if (sim->mpinprocs == 2)
oddoreven=1;
if (sim->pseudoRank % 2 == oddoreven) {
if(sim->pseudoRank > 0 ) { // all except for 0
localmpi.wantedTemp = sim->pTemp[sim->pseudoRank-1];
}
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Comm_rank(MPI_COMM_WORLD, &rank );
assert(rank != sim->mpirank && "THIS CAN NEVER HAPPEN!!!");
locMpi = new MpiExchangeData[sim->mpinprocs];
recMpi = new MpiExchangeData[sim->mpinprocs];
for ( int i=0 ; i < sim->mpinprocs ; ++i ) {
locMpi[i] = localmpi;
}
MPI_Alltoall(locMpi, 1, MPI_exchange, recMpi, 1, MPI_exchange, MPI_COMM_WORLD);
for ( int i=0 ; i < sim->mpinprocs ; ++i ) {
if(recMpi[i].wantedTemp == sim->temper)
receivedmpi = recMpi[i];
}
delete locMpi;
delete recMpi;
//
// SEND, OTHER_PROCESS_EVALUATES, WAIT, RECEIVE, END
//
// Processes are sending on rank mod 2 == 0 or mod 2 == 1, which is periodically switched based on sweep value, sending to higher temp
//
if (sim->pseudoRank % 2 == oddoreven) {
if(sim->pseudoRank > 0 ) { // all except for 0
MPI_Recv(&receiverRank, 1, MPI_INT, MPI_ANY_SOURCE, sim->pseudoRank-1+tagInt, MPI_COMM_WORLD, &status); // receive from all processes, ONLY ONE RESPONDS
MPI_Send(wl.shared_weights, sizewl, MPI_DOUBLE, receiverRank, tagDouble, MPI_COMM_WORLD);
MPI_Recv(&receivedmpi, 1, MPI_exchange, receiverRank, tagExchangeMPI, MPI_COMM_WORLD, &status);
if (receivedmpi.accepted == 1) { //decision of accepting or rejecting the exchange was done on other process
//
// exchange statistics
//
MPI_Recv(&recStat, 1, MPI_stat, receiverRank, tagStat, MPI_COMM_WORLD, &status);
MPI_Send(&localStat, 1, MPI_stat, receiverRank, tagStat, MPI_COMM_WORLD);
sim->stat = recStat;
sim->stat.mpiexch.acc++;
localmpi.accepted = receivedmpi.accepted;
edriftchanges += sim->press * (receivedmpi.volume - localmpi.volume) - (double)conf->pvec.size() * log(receivedmpi.volume / localmpi.volume) * sim->temper;
sim->temper = receivedmpi.temperature;
sim->press = receivedmpi.press;
sim->pseudoRank = receivedmpi.pseudoMpiRank;
volume = conf->geo.volume();
edriftchanges += (sim->press * volume - (double)conf->pvec.size() * log(volume) * sim->temper) - entrophy;
} else {
sim->stat.mpiexch.rej++;
if ( wl.wlm[0] > 0 ) {
wl.shared_weights[wl.currorder[0]+wl.currorder[1]*wl.length[0]] -= wl.alpha;
wl.shared_hist[wl.currorder[0]+wl.currorder[1]*wl.length[0]]++;
}
}
}
} else {
//
// WAIT, RECEIVE, EVALUATE, SEND_BACK, END
//
if (sim->pseudoRank+1 < sim->mpinprocs ) { // all except MAX
//there is above process
receivedRank = receivedmpi.mpiRank;
MPI_Send(&sim->mpirank, 1, MPI_INT, receivedRank, sim->pseudoRank+tagInt, MPI_COMM_WORLD); // respond to correct process so that it knows who is the correct receiver
MPI_Recv(recwlweights, sizewl, MPI_DOUBLE, receivedRank, tagDouble, MPI_COMM_WORLD, &status);
//valuate if accepte or reject the configuration
//
// i = here, j = received
//
// Canonical: P(1, exp( (E_i - E_j) * (1/kT_i - 1/kT_j) ))
//
// Isobaric-Isotermal:
// acc = exp( (1/T_here - 1/T_received) * (E_here - E_received) + (press /T_here - press_received /(T_received)) * (V_here - V_received) )
//
// GrandCanonical
// P(1, exp( (1/T_here - 1/T_received) * (mu * (N_here - N_received) + (E_here - E_received)) )
//
reject = false;
double temp = (1/sim->temper - 1/(sim->temper + sim->dtemp));
// Canonical
change = temp * ( (localmpi.energy - receivedmpi.energy) );
// ISOBARIC-ISOTERMAL
change += (sim->press/sim->temper - (sim->press + sim->dpress)/(sim->temper + sim->dtemp)) * (localmpi.volume - receivedmpi.volume);
// GrandCanonical, chempot stored as mu/kT
for(int i=0; i< conf->pvec.molTypeCount; i++) {
if(topo.moleculeParam[i].activity != -1)
change += temp * topo.moleculeParam[i].chemPot * sim->temper * (localmpi.partNum[i] - receivedmpi.partNum[i]);
}
if (wl.wlm[0] > 0) {
localwl = wl.currorder[0]+wl.currorder[1]*wl.length[0];
receivedwl = receivedmpi.wl_order[0] + receivedmpi.wl_order[1]*wl.length[0];
change += (-wl.shared_weights[localwl] + wl.shared_weights[receivedwl] )/sim->temper + ( -recwlweights[receivedwl] + recwlweights[localwl])/(sim->temper + sim->dtemp) ;
}
//
// CRITERION FOR REPLICA EXCHANGE
//
if ( (!(reject)) && ( (change > 0) || (ran2() < exp(change)) ) ) { // Exchange ACCEPTED send local stuff
localmpi.accepted = 1;
edriftchanges += sim->press * (receivedmpi.volume - localmpi.volume) - (double)conf->pvec.size() * log(receivedmpi.volume / localmpi.volume) * sim->temper;
// change temperature and pseudorank
sim->temper = receivedmpi.temperature;
sim->press = receivedmpi.press;
sim->pseudoRank = receivedmpi.pseudoMpiRank;
volume = conf->geo.volume();
edriftchanges += (sim->press * volume - (double)conf->pvec.size() * log(volume) * sim->temper) - entrophy;
if ( wl.wlm[0] > 0 ) {
for (int wli=0;wli<wl.wlmdim;wli++) {
wl.neworder[wli] = receivedmpi.wl_order[wli];
}
wl.accept(wl.wlm[0]);
}
MPI_Send(&localmpi, 1, MPI_exchange, receivedRank, tagExchangeMPI, MPI_COMM_WORLD);
// exchange statistics
MPI_Send(&localStat, 1, MPI_stat, receivedRank, tagStat, MPI_COMM_WORLD);
MPI_Recv(&recStat, 1, MPI_stat, receivedRank, tagStat, MPI_COMM_WORLD, &status);
sim->stat = recStat;
sim->stat.mpiexch.acc++;
} else {
//if exchange rejected send back info
sim->stat.mpiexch.rej++;
localmpi.accepted = 0;
MPI_Send(&localmpi, 1, MPI_exchange, receivedRank, tagExchangeMPI, MPI_COMM_WORLD);
if ( wl.wlm[0] > 0 ) {
wl.shared_weights[wl.currorder[0]+wl.currorder[1]*wl.length[0]] -= wl.alpha;
wl.shared_hist[wl.currorder[0]+wl.currorder[1]*wl.length[0]]++;
}
}
}
}
MPI_Barrier(MPI_COMM_WORLD); // to ensure we dont read a message that was neccesary for replica exchange
MPI_Type_free(&MPI_exchange);
MPI_Type_free(&MPI_vector2);
MPI_Type_free(&MPI_stat);
free(recwlweights);
#endif
return edriftchanges;
}
double MoveCreator::muVTMove() {
#ifndef NDEBUG // For tests of energy
double e = calcEnergy->allToAll();
#endif
Molecule target;
double volume = conf->geo.volume();
double entrophy = log(volume)*sim->temper;
double energy = 0.0;
unsigned int molSize=0;
Vector displace;
// Determine what type we will be inserting/deleting
int molType = getRandomMuVTType();
molSize = topo.moleculeParam[molType].molSize();
/*assert(molType == 0 && "delete this assert, only of one atomic type simulation");
assert(molSize == 1 && "delete this assert, only of one atomic type simulation");
assert(conf->pvec.molCountOfType(molType) == (int)conf->pvec.size() && "should be true for one atom type simulation");*/
assert(insert.empty() && "Insert vector must be empty at the begining of grand canonical move");
sim->stat.grand[molType].muVtSteps++;
//////////////////////////////////////////////////////////////
// INSERT MOVE //
//////////////////////////////////////////////////////////////
if(ran2() > 0.5) {
if(topo.moleculeParam[molType].isAtomic()) { // RANDOM PARTICLE
// create particle
insert.push_back(Particle(conf->geo.randomPos(), Vector::getRandomUnitSphere(), Vector::getRandomUnitSphere()
, molType, topo.moleculeParam[molType].particleTypes[0]));
insert[0].init(&(topo.ia_params[insert[0].type][insert[0].type]));
assert(insert[0].testInit( topo.ia_params[insert[0].type][insert[0].type].geotype[0], 99999999 ) && "GrandCanonical, insertion, Particle initialized incorectly");
assert(insert.size() == 1);
} else { // RANDOM CHAIN FROM POOL + RANDOMIZE POSITION AND ROTATION
displace.randomUnitCube();
// get configuration
insert = conf->getRandomPoolConf(molType);
// randomize position
for(unsigned int i=0; i<insert.size(); i++)
insert[i].pos += displace;
// randomize - rotate chain
clusterRotate(insert, (double)PIH);
for(unsigned int i=0; i<insert.size(); i++)
insert[i].init(&(topo.ia_params[insert[i].type][insert[i].type]));
}
assert(!insert.empty());
// calc energ
energy = calcEnergy->mol2others(insert);
// accept with probability -> V/N+1 * e^(ln(a*Nav*1e-27)) -U(new)/kT), NOTE: faunus uses exp(log(V/N+1) * ln(a*Nav*1e-27)) -U(new)/kT)
if(( (volume / (conf->pvec.molCountOfType(molType) + 1.0)) *
(exp( topo.moleculeParam[molType].chemPot - (energy/sim->temper) ) ) ) > ran2() ) {
if(!topo.moleculeParam[molType].isAtomic())
energy += calcEnergy->chainInner(insert);
conf->insertMolecule(insert);
for(unsigned int i=0; i<insert.size(); i++)
conf->sysvolume += topo.ia_params[insert[i].type][insert[i].type].volume;
insert.clear();
sim->stat.grand[molType].insAcc++;
sim->stat.grand[molType].muVtAverageParticles += conf->pvec.molCountOfType(molType);
calcEnergy->update(EMResize()); // just a dummy datatype for resize of energy matrix
return energy - molSize*entrophy;
} else { // rejected
insert.clear();
sim->stat.grand[molType].insRej++;
sim->stat.grand[molType].muVtAverageParticles += conf->pvec.molCountOfType(molType);
assert(e == calcEnergy->allToAll() && "GrandCanonical, insertion rejected but energy of system changed");
return 0;
}
//////////////////////////////////////////////////////////////
// DELETE MOVE //
//////////////////////////////////////////////////////////////
} else {
if(conf->pvec.molCountOfType(molType) == 0) { // check if there are molecules of certain type
sim->stat.grand[molType].delRej++;
sim->stat.grand[molType].muVtAverageParticles += conf->pvec.molCountOfType(molType);
return 0;
}
target = conf->pvec.getMolecule(ran2() * conf->pvec.molCountOfType(molType), molType, topo.moleculeParam[molType].molSize()); // get random molecule of molType
energy = calcEnergy->mol2others(target);
// accept with probability -> N/V * e^(3*ln(wavelenght) - mu/kT + U(del)/kT)
if( ( ((double)conf->pvec.molCountOfType(molType)/volume) * exp( (energy/sim->temper) - topo.moleculeParam[molType].chemPot) ) > ran2()) {
for(unsigned int i=0; i<molSize; i++)
conf->sysvolume -= topo.ia_params[conf->pvec[target[0]+i].type][conf->pvec[target[0]+i].type].volume;
if(!topo.moleculeParam[molType].isAtomic())
energy += calcEnergy->chainInner(target);
conf->removeMolecule(target);
sim->stat.grand[molType].delAcc++;
sim->stat.grand[molType].muVtAverageParticles += conf->pvec.molCountOfType(molType);
calcEnergy->update(EMResize()); // just a dummy datatype for resize of energy matrix
return -energy + molSize*entrophy;
} else {
sim->stat.grand[molType].delRej++;
sim->stat.grand[molType].muVtAverageParticles += conf->pvec.molCountOfType(molType);
assert(e == calcEnergy->allToAll() && "GrandCanonical, deletion rejected but energy of system changed");
return 0;
}
}
assert(false && "IMPOSIBRU!!!");
return 0;
}
int MoveCreator::getRandomMuVTType() {
int molType = 0;
molType = ran2() * topo.gcSpecies;
for(int i=0; i<conf->pvec.molTypeCount; i++) {
if(topo.moleculeParam[i].activity != -1.0) {
if(molType == 0) {
molType = i;
break;
}
molType--;
}
}
assert(topo.moleculeParam[molType].chemPot != -1.0);
assert(molType >= 0);
assert(topo.gcSpecies >= 1 && "GrandCanonical with no defined activity, This should never happen");
return molType;
}
double MoveCreator::partDisplace(long target) {
double edriftchanges = 0.0,energy,enermove,wlener = 0.0;
chorig[0] = conf->pvec[target];
Vector dr, origsyscm = conf->syscm;
int reject=0;
double radiusholemax_orig=0;
energy = calcEnergy->oneToAll(target);
dr.randomUnitSphere();
dr.x *= sim->stat.trans[conf->pvec[target].type].mx/conf->geo.box.x;
dr.y *= sim->stat.trans[conf->pvec[target].type].mx/conf->geo.box.y;
dr.z *= sim->stat.trans[conf->pvec[target].type].mx/conf->geo.box.z;
conf->pvec[target].pos.x += dr.x;
conf->pvec[target].pos.y += dr.y;
conf->pvec[target].pos.z += dr.z;
if(wl.wlm[0] > 0) {
Molecule tar;
tar.resize(1);
tar[0] = target;
dr.scale(topo.ia_params[conf->pvec[target].type][conf->pvec[target].type].volume);
wlener = wl.run(reject, chorig, dr, radiusholemax_orig, tar);
}
if (!reject) { // wang-landaou ok, try move - calcualte energy
enermove = calcEnergy->oneToAllTrial(target);
}
if (reject || moveTry(energy+wlener, enermove, sim->temper)) { // probability acceptance
conf->pvec[target].pos = chorig[0].pos;
sim->stat.trans[conf->pvec[target].type].rej++;
if ( (wl.wlm[0] == 1) || (wl.wlm[0] == 5) || (wl.wlm[1] == 1) || (wl.wlm[1] == 5) )
conf->syscm = origsyscm;
wl.reject(radiusholemax_orig, wl.wlm);
} else { // move was accepted
sim->stat.trans[conf->pvec[target].type].acc++;
wl.accept(wl.wlm[0]);
edriftchanges = enermove - energy;
calcEnergy->update(target);
}
return edriftchanges;
}
double MoveCreator::partRotate(long target) {
double edriftchanges = 0.0, energy, enermove, wlener = 0.0;
Particle origpart = conf->pvec[target];
int reject = 0;
energy = calcEnergy->oneToAll(target);
conf->pvec[target].rotateRandom(sim->stat.rot[conf->pvec[target].type].angle, topo.ia_params[origpart.type][origpart.type].geotype[0]);
//should be normalised and ortogonal but we do for safety
assert(isSame(conf->pvec[target].dir.size(), 1.0));
conf->pvec[target].patchdir[0].ortogonalise(conf->pvec[target].dir);
if(wl.wlm[0] > 0)
wlener = wl.runRot(reject, target);
if (!reject) { // wang-landaou ok, try move - calcualte energy
enermove = calcEnergy->oneToAllTrial(target);
}
if ( reject || moveTry(energy+wlener,enermove,sim->temper) ) { // probability acceptance
conf->pvec[target] = origpart;
sim->stat.rot[conf->pvec[target].type].rej++;
wl.reject(wl.radiusholemax, wl.wlm);
} else { // move was accepted
sim->stat.rot[conf->pvec[target].type].acc++;
wl.accept(wl.wlm[0]);
edriftchanges = enermove - energy;
calcEnergy->update(target);
}
return edriftchanges;
}
double MoveCreator::partAxialRotate(long target){
double edriftchanges = 0.0;
double energyold;
double energynew = 0.0;
Vector rotaxis;
Particle origpart = conf->pvec[target];
energyold = calcEnergy->oneToAll(target);
//=============================================//
// Get vector from cone //
//=============================================//
// Get vector which is randomly distributed in cone around patch direction. Cone is specified by angle in radians in options coneAngle
rotaxis = Vector::getRandomUnitConeUniform( conf->pvec[target].dir,\
sim->coneAngle);
//=============================================//
// Rotate particle //
//=============================================//
// Now rotate particle around rotaxis in specified cone around patch direction
conf->pvec[target].pscRotate( sim->stat.rot[conf->pvec[target].type].angle*ran2(),\
topo.ia_params[conf->pvec[target].type][conf->pvec[target].type].geotype[0],\
rotaxis);
//=============================================//
// MC criterium //
//=============================================//
energynew = calcEnergy->oneToAllTrial(target);
if (moveTry(energyold, energynew, sim->temper)){
// move was rejected
sim->stat.rot[conf->pvec[target].type].rej++;
conf->pvec[target] = origpart; // return to old configuration
} else {
// move was accepted
sim->stat.rot[conf->pvec[target].type].acc++;
edriftchanges = energynew - energyold;
calcEnergy->update(target);
}
return edriftchanges;
}
double MoveCreator::chainDisplace(long target) {
Molecule chain = conf->pvec.getChain(target);
assert(chain.size() > 1);
double edriftchanges=0.0,energy=0.0,enermove=0.0,wlener=0.0;
Vector dr, origsyscm = conf->syscm;
int reject=0;
Vector cluscm(0.0, 0.0, 0.0);
double radiusholemax_orig=0.0;
//=== Displacement step of cluster/chain ===
//printf ("move chain\n\n");
for(unsigned int i=0; i<chain.size(); i++) // store old configuration
chorig[i].pos = conf->pvec[chain[i]].pos;
energy += calcEnergy->mol2others(chain);
dr.randomUnitSphere();
dr.x *= sim->stat.chainm[conf->pvec[chain[0]].molType].mx/conf->geo.box.x;
dr.y *= sim->stat.chainm[conf->pvec[chain[0]].molType].mx/conf->geo.box.y;
dr.z *= sim->stat.chainm[conf->pvec[chain[0]].molType].mx/conf->geo.box.z;
if ( ((wl.wlm[0] == 3)||(wl.wlm[1] == 3)) && (target == 0) ) {
dr.z = 0;
dr.y = 0;
dr.x = 0;
}
for(unsigned int j=0; j<chain.size(); j++) { // move chaine to new position
if ( (wl.wlm[0] == 1) || (wl.wlm[0] == 5) || (wl.wlm[1] == 1) || (wl.wlm[1] == 5) ) { /* calculate move of center of mass */
cluscm.x += dr.x*topo.ia_params[conf->pvec[chain[j]].type][conf->pvec[chain[j]].type].volume;
cluscm.y += dr.y*topo.ia_params[conf->pvec[chain[j]].type][conf->pvec[chain[j]].type].volume;
cluscm.z += dr.z*topo.ia_params[conf->pvec[chain[j]].type][conf->pvec[chain[j]].type].volume;
}
conf->pvec[chain[j]].pos.x += dr.x;
conf->pvec[chain[j]].pos.y += dr.y;
conf->pvec[chain[j]].pos.z += dr.z;
}
if(wl.wlm[0] > 0)
wlener = wl.run(reject, chorig, cluscm, radiusholemax_orig, chain);
if (!reject) { // wang-landaou ok, try move - calcualte energy
enermove += calcEnergy->mol2othersTrial(chain);
}
if ( reject || moveTry(energy+wlener, enermove, sim->temper) ) { // probability acceptance
for(unsigned int j=0; j<chain.size(); j++)
conf->pvec[chain[j]].pos = chorig[j].pos;
sim->stat.chainm[conf->pvec[chain[0]].molType].rej++;
if ( (wl.wlm[0] == 1) || (wl.wlm[0] == 5) || (wl.wlm[1] == 1) || (wl.wlm[1] == 5) )
conf->syscm = origsyscm;
wl.reject(radiusholemax_orig, wl.wlm);
} else { // move was accepted
sim->stat.chainm[conf->pvec[chain[0]].molType].acc++;
wl.accept(wl.wlm[0]);
calcEnergy->update(chain);
edriftchanges = enermove - energy;
}
return edriftchanges;
}
double MoveCreator::chainRotate(long target) {
Molecule chain = conf->pvec.getChain(target);
double edriftchanges=0.0, energy=0.0, enermove=0.0, wlener=0.0;
int reject=0;
Particle chorig[MAXCHL];
double radiusholemax_orig=0;
//=== Rotation step of cluster/chain ===
for(unsigned int j=0; j<chain.size(); j++) { // store old configuration calculate energy
chorig[j] = conf->pvec[chain[j]];
}
energy += calcEnergy->mol2others(chain);
/*double test=0.0;
if(verbose) {
cout << "\n\nNEW\n" << endl;
calcEnergy->pairE.verbose=true;
test = calcEnergy->p2p(23,20);
calcEnergy->pairE.verbose=false;
}
Particle p1 = conf->pvec[20];
Particle p2 = conf->pvec[23];*/
//do actual rotations around geometrical center
clusterRotate(chain, sim->stat.chainr[conf->pvec[chain[0]].molType].angle);
/*if(verbose) {
calcEnergy->pairE.verbose=true;
double test2 = calcEnergy->p2p(23,20);
calcEnergy->pairE.verbose=false;
Particle p3 = conf->pvec[20];
Particle p4 = conf->pvec[23];
//////////////////////////////////////////
cout << "\n BOX: " << calcEnergy->pairE.pbc->box.x << " " << calcEnergy->pairE.pbc->box.y << " " << calcEnergy->pairE.pbc->box.z << "\n"<< endl;
Vector r1 = p1.pos;
Vector r2 = p2.pos;
cout << r1.info() << endl;
cout << r2.info() << endl;
Vector r_cm( r1.x - r2.x, r1.y - r2.y, r1.z - r2.z );
cout << (r_cm.x) << " " << (r_cm.y) << " " << (r_cm.z) << endl;
cout << round(r_cm.x) << " " << round(r_cm.y) << " " << round(r_cm.z) << endl;
r_cm.x = (r_cm.x - round(r_cm.x) );
r_cm.y = (r_cm.y - round(r_cm.y) );
r_cm.z = (r_cm.z - round(r_cm.z) );
cout << (r_cm.x) << " " << (r_cm.y) << " " << (r_cm.z) << endl;
cout << r_cm.dot(r_cm) << endl;
r_cm.x *= calcEnergy->pairE.pbc->box.x;
r_cm.y *= calcEnergy->pairE.pbc->box.y;
r_cm.z *= calcEnergy->pairE.pbc->box.z;
cout << (r_cm.x) << " " << (r_cm.y) << " " << (r_cm.z) << endl;
cout << r_cm.dot(r_cm) << endl;
////////////////////////////////////////////
cout << endl;
r1 = p3.pos;
r2 = p4.pos;
cout << r1.info() << endl;
cout << r2.info() << endl;
r_cm = Vector( r1.x - r2.x, r1.y - r2.y, r1.z - r2.z );
cout << (r_cm.x) << " " << (r_cm.y) << " " << (r_cm.z) << endl;
cout << round(r_cm.x) << " " << round(r_cm.y) << " " << round(r_cm.z) << endl;
r_cm.x = (r_cm.x - round(r_cm.x) );
r_cm.y = (r_cm.y - round(r_cm.y) );
r_cm.z = (r_cm.z - round(r_cm.z) );
cout << (r_cm.x) << " " << (r_cm.y) << " " << (r_cm.z) << endl;
cout << r_cm.dot(r_cm) << endl;
r_cm.x *= calcEnergy->pairE.pbc->box.x;
r_cm.y *= calcEnergy->pairE.pbc->box.y;
r_cm.z *= calcEnergy->pairE.pbc->box.z;
cout << (r_cm.x) << " " << (r_cm.y) << " " << (r_cm.z) << endl;
cout << r_cm.dot(r_cm) << endl;
////////////////////////////////////////////
if(fabs(test-test2) > 0.000000001) {
cout << "Energy: " << test << " " << test2 << endl;
}
assert(fabs(test-test2) < 0.000000001 );
}*/
if(wl.wlm[0] > 0)
wlener = wl.runChainRot(reject, chorig, radiusholemax_orig, chain);
if (!reject) { // wang-landaou ok, try move - calcualte energy
enermove += calcEnergy->mol2othersTrial(chain);
}
if ( reject || moveTry(energy+wlener, enermove, sim->temper) ) { // probability acceptance
for(unsigned int j=0; j<chain.size(); j++)
conf->pvec[chain[j]] = chorig[j];
sim->stat.chainr[conf->pvec[chain[0]].molType].rej++;
wl.reject(radiusholemax_orig, wl.wlm);
} else { // move was accepted
sim->stat.chainr[conf->pvec[chain[0]].molType].acc++;
wl.accept(wl.wlm[0]);
edriftchanges = enermove - energy;
calcEnergy->update(chain);
}
return edriftchanges;
}
void MoveCreator::clusterRotate(vector<Particle> &cluster, double max_angle) {
Vector cluscm;
double vc,vs;
Vector newaxis;
cluscm = clusterCM(cluster);
// create rotation quaternion
newaxis.randomUnitSphere(); /*random axes for rotation*/
vc = cos(max_angle * ran2() );
if (ran2() <0.5) vs = sqrt(1.0 - vc*vc);
else vs = -sqrt(1.0 - vc*vc); /*randomly choose orientation of direction of rotation clockwise or counterclockwise*/
Quat newquat(vc, newaxis.x*vs, newaxis.y*vs, newaxis.z*vs);
//quatsize=sqrt(newquat.w*newquat.w+newquat.x*newquat.x+newquat.y*newquat.y+newquat.z*newquat.z);
//shift position to geometrical center
for(unsigned int i=0; i<cluster.size(); i++) {
//shift position to geometrical center
cluster[i].pos.x -= cluscm.x;
cluster[i].pos.y -= cluscm.y;
cluster[i].pos.z -= cluscm.z;
//scale things by geo.box not to have them distorted
cluster[i].pos.x *= conf->geo.box.x;
cluster[i].pos.y *= conf->geo.box.y;
cluster[i].pos.z *= conf->geo.box.z;
//do rotation
cluster[i].pos.rotate(newquat);
cluster[i].dir.rotate(newquat);
cluster[i].patchdir[0].rotate(newquat);
cluster[i].patchdir[1].rotate(newquat);
cluster[i].chdir[0].rotate(newquat);
cluster[i].chdir[1].rotate(newquat);
cluster[i].patchsides[0].rotate(newquat);
cluster[i].patchsides[1].rotate(newquat);
cluster[i].patchsides[2].rotate(newquat);
cluster[i].patchsides[3].rotate(newquat);
//sclae back
cluster[i].pos.x /= conf->geo.box.x;
cluster[i].pos.y /= conf->geo.box.y;
cluster[i].pos.z /= conf->geo.box.z;
//shift positions back
cluster[i].pos.x += cluscm.x;
cluster[i].pos.y += cluscm.y;
cluster[i].pos.z += cluscm.z;
}
}
Vector MoveCreator::clusterCM(vector<Particle> &cluster) {
double chainVolume=0.0;
Vector cluscm(0.0, 0.0, 0.0);
for(unsigned int i=0; i<cluster.size(); i++) {
cluscm.x += cluster[i].pos.x * topo.ia_params[cluster[i].type][cluster[i].type].volume;
cluscm.y += cluster[i].pos.y * topo.ia_params[cluster[i].type][cluster[i].type].volume;
cluscm.z += cluster[i].pos.z * topo.ia_params[cluster[i].type][cluster[i].type].volume;
chainVolume += topo.ia_params[cluster[i].type][cluster[i].type].volume;
}
cluscm.x /= chainVolume;
cluscm.y /= chainVolume;
cluscm.z /= chainVolume;
return cluscm;
}
Vector MoveCreator::clusterCM(vector<int> &cluster) {
double chainVolume=0.0;
Vector cluscm(0.0, 0.0, 0.0);
for(unsigned int i=0; i<cluster.size(); i++) {
cluscm.x += conf->pvec[cluster[i]].pos.x * topo.ia_params[conf->pvec[cluster[i]].type][conf->pvec[cluster[i]].type].volume;
cluscm.y += conf->pvec[cluster[i]].pos.y * topo.ia_params[conf->pvec[cluster[i]].type][conf->pvec[cluster[i]].type].volume;
cluscm.z += conf->pvec[cluster[i]].pos.z * topo.ia_params[conf->pvec[cluster[i]].type][conf->pvec[cluster[i]].type].volume;
chainVolume += topo.ia_params[conf->pvec[cluster[i]].type][conf->pvec[cluster[i]].type].volume;
}
cluscm.x /= chainVolume;
cluscm.y /= chainVolume;
cluscm.z /= chainVolume;
return cluscm;
}
void MoveCreator::clusterRotate(vector<int> &cluster, double max_angle) {
Vector cluscm;
double vc,vs;
Vector newaxis;
cluscm = clusterCM(cluster);
// create rotation quaternion
newaxis.randomUnitSphere(); /*random axes for rotation*/
vc = cos(max_angle * ran2() );
if (ran2() <0.5) vs = sqrt(1.0 - vc*vc);
else vs = -sqrt(1.0 - vc*vc); /*randomly choose orientation of direction of rotation clockwise or counterclockwise*/
Quat newquat(vc, newaxis.x*vs, newaxis.y*vs, newaxis.z*vs);
//quatsize=sqrt(newquat.w*newquat.w+newquat.x*newquat.x+newquat.y*newquat.y+newquat.z*newquat.z);
//shift position to geometrical center
for(unsigned int i=0; i<cluster.size(); i++) {
//shift position to geometrical center
conf->pvec[cluster[i]].pos.x -= cluscm.x;
conf->pvec[cluster[i]].pos.y -= cluscm.y;
conf->pvec[cluster[i]].pos.z -= cluscm.z;
//scale things by geo.box not to have them distorted
conf->pvec[cluster[i]].pos.x *= conf->geo.box.x;
conf->pvec[cluster[i]].pos.y *= conf->geo.box.y;
conf->pvec[cluster[i]].pos.z *= conf->geo.box.z;
//do rotation
conf->pvec[cluster[i]].pos.rotate(newquat);
conf->pvec[cluster[i]].dir.rotate(newquat);
conf->pvec[cluster[i]].patchdir[0].rotate(newquat);
conf->pvec[cluster[i]].patchdir[1].rotate(newquat);
conf->pvec[cluster[i]].chdir[0].rotate(newquat);
conf->pvec[cluster[i]].chdir[1].rotate(newquat);
conf->pvec[cluster[i]].patchsides[0].rotate(newquat);
conf->pvec[cluster[i]].patchsides[1].rotate(newquat);
conf->pvec[cluster[i]].patchsides[2].rotate(newquat);
conf->pvec[cluster[i]].patchsides[3].rotate(newquat);
//sclae back
conf->pvec[cluster[i]].pos.x /= conf->geo.box.x;
conf->pvec[cluster[i]].pos.y /= conf->geo.box.y;
conf->pvec[cluster[i]].pos.z /= conf->geo.box.z;
//shift positions back
conf->pvec[cluster[i]].pos.x += cluscm.x;
conf->pvec[cluster[i]].pos.y += cluscm.y;
conf->pvec[cluster[i]].pos.z += cluscm.z;
}
}
|
/**
* MBeatBoxChannelControl (C)2001-2003 MRoc hifiShock
*/
#include "MBeatBoxChannelControl.h"
MBeatBoxChannelControl::MBeatBoxChannelControl() :
MDCControl()
{
}
MBeatBoxChannelControl::~MBeatBoxChannelControl()
{
}
void MBeatBoxChannelControl::paintControl( IGraphics* pDC )
{
if( getSelected() )
MGuiUtils::paintSunkenBorder(
pDC,
MRect( ivRect.getX(), ivRect.getY(), ivRect.getWidth() - 1, ivRect.getHeight() - 1 ),
ivBkColor );
else
MGuiUtils::paintRaisedBorder(
pDC,
MRect( ivRect.getX(), ivRect.getY(), ivRect.getWidth() - 1, ivRect.getHeight() - 1 ),
ivBkColor );
// Draw WavePlayer name
pDC->drawText(
ivPtWavePlayer->getSampleName(),
MRect(
ivRect.getX() + 3,
ivRect.getY() + 3,
ivRect.getWidth() - 6,
ivRect.getHeight() - 6 ),
this->ivBkColorSelected );
}
void MBeatBoxChannelControl::setWavePlayer( MWavePlayer* ptWavePlayer )
{
ivPtWavePlayer = ptWavePlayer;
}
MWavePlayer* MBeatBoxChannelControl::getWavePlayer()
{
return ivPtWavePlayer;
}
|
#ifndef SERVER_HPP
# define SERVER_HPP
# include "common.hpp"
class server
{
private:
std::vector<bool> _cnct;
int _opt;
size_t _nbClients;
size_t _minClients;
int _listen_sd;
size_t _connected;
int _max_sd;
int _new_sd;
struct sockaddr_in6 _addr;
fd_set _master_set;
fd_set _working_set;
char _req[1024];
char _resp[1024];
bool _closeConct;
int _key;
bool _completed;
size_t _recv;
int _initSocket();
int _checkSelect(struct timeval *time);
void _closeConnection(int i);
void _closeSockets(void);
bool _newClient();
bool _getRequest(int i);
void _analyzeReq(int const i);
bool _sendResponse(int i);
void _encrypt(int i);
void _getKey();
public:
server();
server(const int n);
server(server const &src);
~server();
server &operator=(server const &src);
int runServer();
};
#endif
|
/*
* Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved
*
* 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 <dxgi1_4.h>
#include <algorithm>
#include <cmath>
#include <d3dcompiler.h>
#include <future>
#include "source/core/sl.log/log.h"
#include "source/platforms/sl.chi/d3d12.h"
#include "shaders/copy_to_buffer_cs.h"
namespace sl
{
namespace chi
{
// helper function for texture subresource calculations
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn705766(v=vs.85).aspx
inline static uint32_t calcSubresource(uint32_t MipSlice, uint32_t ArraySlice, uint32_t PlaneSlice, uint32_t MipLevels, uint32_t ArraySize)
{
return MipSlice + (ArraySlice * MipLevels) + (PlaneSlice * MipLevels * ArraySize);
}
D3D12 s_d3d12;
ICompute *getD3D12()
{
return &s_d3d12;
}
std::wstring D3D12::getDebugName(Resource res)
{
auto unknown = (IUnknown*)res;
ID3D12Pageable* pageable;
IDXGIObject* dxgi;
unknown->QueryInterface(&pageable);
unknown->QueryInterface(&dxgi);
wchar_t name[128] = {};
std::wstring wname = L"Unknown";
if (pageable)
{
UINT size = sizeof(name);
if (FAILED(pageable->GetPrivateData(WKPDID_D3DDebugObjectNameW, &size, name)))
{
char sname[128] = {};
size = sizeof(sname);
if (SUCCEEDED(pageable->GetPrivateData(WKPDID_D3DDebugObjectName, &size, sname)))
{
std::string tmp(sname);
wname = std::wstring(tmp.begin(), tmp.end());
}
}
else
{
wname = name;
}
pageable->Release();
}
else if(dxgi)
{
UINT size = sizeof(name);
if (FAILED(dxgi->GetPrivateData(WKPDID_D3DDebugObjectNameW, &size, name)))
{
char sname[128] = {};
size = sizeof(sname);
if (SUCCEEDED(dxgi->GetPrivateData(WKPDID_D3DDebugObjectName, &size, sname)))
{
std::string tmp(sname);
wname = std::wstring(tmp.begin(), tmp.end());
}
}
else
{
wname = name;
}
dxgi->Release();
}
return wname;
}
const char * getDXGIFormatStr(uint32_t format)
{
static constexpr const char *GDXGI_FORMAT_STR[] = {
"DXGI_FORMAT_UNKNOWN",
"DXGI_FORMAT_R32G32B32A32_TYPELESS",
"DXGI_FORMAT_R32G32B32A32_FLOAT",
"DXGI_FORMAT_R32G32B32A32_UINT",
"DXGI_FORMAT_R32G32B32A32_SINT",
"DXGI_FORMAT_R32G32B32_TYPELESS",
"DXGI_FORMAT_R32G32B32_FLOAT",
"DXGI_FORMAT_R32G32B32_UINT",
"DXGI_FORMAT_R32G32B32_SINT",
"DXGI_FORMAT_R16G16B16A16_TYPELESS",
"DXGI_FORMAT_R16G16B16A16_FLOAT",
"DXGI_FORMAT_R16G16B16A16_UNORM",
"DXGI_FORMAT_R16G16B16A16_UINT",
"DXGI_FORMAT_R16G16B16A16_SNORM",
"DXGI_FORMAT_R16G16B16A16_SINT",
"DXGI_FORMAT_R32G32_TYPELESS",
"DXGI_FORMAT_R32G32_FLOAT",
"DXGI_FORMAT_R32G32_UINT",
"DXGI_FORMAT_R32G32_SINT",
"DXGI_FORMAT_R32G8X24_TYPELESS",
"DXGI_FORMAT_D32_FLOAT_S8X24_UINT",
"DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS",
"DXGI_FORMAT_X32_TYPELESS_G8X24_UINT",
"DXGI_FORMAT_R10G10B10A2_TYPELESS",
"DXGI_FORMAT_R10G10B10A2_UNORM",
"DXGI_FORMAT_R10G10B10A2_UINT",
"DXGI_FORMAT_R11G11B10_FLOAT",
"DXGI_FORMAT_R8G8B8A8_TYPELESS",
"DXGI_FORMAT_R8G8B8A8_UNORM",
"DXGI_FORMAT_R8G8B8A8_UNORM_SRGB",
"DXGI_FORMAT_R8G8B8A8_UINT",
"DXGI_FORMAT_R8G8B8A8_SNORM",
"DXGI_FORMAT_R8G8B8A8_SINT",
"DXGI_FORMAT_R16G16_TYPELESS",
"DXGI_FORMAT_R16G16_FLOAT",
"DXGI_FORMAT_R16G16_UNORM",
"DXGI_FORMAT_R16G16_UINT",
"DXGI_FORMAT_R16G16_SNORM",
"DXGI_FORMAT_R16G16_SINT",
"DXGI_FORMAT_R32_TYPELESS",
"DXGI_FORMAT_D32_FLOAT",
"DXGI_FORMAT_R32_FLOAT",
"DXGI_FORMAT_R32_UINT",
"DXGI_FORMAT_R32_SINT",
"DXGI_FORMAT_R24G8_TYPELESS",
"DXGI_FORMAT_D24_UNORM_S8_UINT",
"DXGI_FORMAT_R24_UNORM_X8_TYPELESS",
"DXGI_FORMAT_X24_TYPELESS_G8_UINT",
"DXGI_FORMAT_R8G8_TYPELESS",
"DXGI_FORMAT_R8G8_UNORM",
"DXGI_FORMAT_R8G8_UINT",
"DXGI_FORMAT_R8G8_SNORM",
"DXGI_FORMAT_R8G8_SINT",
"DXGI_FORMAT_R16_TYPELESS",
"DXGI_FORMAT_R16_FLOAT",
"DXGI_FORMAT_D16_UNORM",
"DXGI_FORMAT_R16_UNORM",
"DXGI_FORMAT_R16_UINT",
"DXGI_FORMAT_R16_SNORM",
"DXGI_FORMAT_R16_SINT",
"DXGI_FORMAT_R8_TYPELESS",
"DXGI_FORMAT_R8_UNORM",
"DXGI_FORMAT_R8_UINT",
"DXGI_FORMAT_R8_SNORM",
"DXGI_FORMAT_R8_SINT",
"DXGI_FORMAT_A8_UNORM",
"DXGI_FORMAT_R1_UNORM",
"DXGI_FORMAT_R9G9B9E5_SHAREDEXP",
"DXGI_FORMAT_R8G8_B8G8_UNORM",
"DXGI_FORMAT_G8R8_G8B8_UNORM",
"DXGI_FORMAT_BC1_TYPELESS",
"DXGI_FORMAT_BC1_UNORM",
"DXGI_FORMAT_BC1_UNORM_SRGB",
"DXGI_FORMAT_BC2_TYPELESS",
"DXGI_FORMAT_BC2_UNORM",
"DXGI_FORMAT_BC2_UNORM_SRGB",
"DXGI_FORMAT_BC3_TYPELESS",
"DXGI_FORMAT_BC3_UNORM",
"DXGI_FORMAT_BC3_UNORM_SRGB",
"DXGI_FORMAT_BC4_TYPELESS",
"DXGI_FORMAT_BC4_UNORM",
"DXGI_FORMAT_BC4_SNORM",
"DXGI_FORMAT_BC5_TYPELESS",
"DXGI_FORMAT_BC5_UNORM",
"DXGI_FORMAT_BC5_SNORM",
"DXGI_FORMAT_B5G6R5_UNORM",
"DXGI_FORMAT_B5G5R5A1_UNORM",
"DXGI_FORMAT_B8G8R8A8_UNORM",
"DXGI_FORMAT_B8G8R8X8_UNORM",
"DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM",
"DXGI_FORMAT_B8G8R8A8_TYPELESS",
"DXGI_FORMAT_B8G8R8A8_UNORM_SRGB",
"DXGI_FORMAT_B8G8R8X8_TYPELESS",
"DXGI_FORMAT_B8G8R8X8_UNORM_SRGB",
"DXGI_FORMAT_BC6H_TYPELESS",
"DXGI_FORMAT_BC6H_UF16",
"DXGI_FORMAT_BC6H_SF16",
"DXGI_FORMAT_BC7_TYPELESS",
"DXGI_FORMAT_BC7_UNORM",
"DXGI_FORMAT_BC7_UNORM_SRGB",
"DXGI_FORMAT_AYUV",
"DXGI_FORMAT_Y410",
"DXGI_FORMAT_Y416",
"DXGI_FORMAT_NV12",
"DXGI_FORMAT_P010",
"DXGI_FORMAT_P016",
"DXGI_FORMAT_420_OPAQUE",
"DXGI_FORMAT_YUY2",
"DXGI_FORMAT_Y210",
"DXGI_FORMAT_Y216",
"DXGI_FORMAT_NV11",
"DXGI_FORMAT_AI44",
"DXGI_FORMAT_IA44",
"DXGI_FORMAT_P8",
"DXGI_FORMAT_A8P8",
"DXGI_FORMAT_B4G4R4A4_UNORM",
"DXGI_FORMAT_P208",
"DXGI_FORMAT_V208",
"DXGI_FORMAT_V408",
};
if (format < countof(GDXGI_FORMAT_STR))
{
return GDXGI_FORMAT_STR[format];
}
return "DXGI_INVALID_FORMAT";
}
struct CommandListContext : public ICommandListContext
{
ID3D12CommandQueue* cmdQueue;
ID3D12GraphicsCommandList* cmdList;
std::vector<ID3D12CommandAllocator*> allocator;
std::vector <ID3D12Fence*> fence;
HANDLE fenceEvent;
std::vector<UINT64> fenceValue = {};
bool cmdListIsRecording = false;
std::atomic<uint32_t> index = 0;
std::atomic<uint32_t> lastIndex = UINT_MAX;
uint32_t bufferCount = 0;
std::wstring name;
void init(const char* debugName, ID3D12Device* device, ID3D12CommandQueue* queue, uint32_t count)
{
std::string tmp = debugName;
name = std::wstring(tmp.begin(), tmp.end());
cmdQueue = queue;
auto cmdQueueDesc = cmdQueue->GetDesc();
bufferCount = count;
allocator.resize(count);
fence.resize(count);
fenceValue.resize(count);
for (uint32_t i = 0; i < count; i++)
{
device->CreateCommandAllocator(cmdQueueDesc.Type, IID_PPV_ARGS(&allocator[i]));
fenceValue[i] = 0;
device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence[i]));
}
device->CreateCommandList(0, cmdQueueDesc.Type, allocator[0], nullptr, IID_PPV_ARGS(&cmdList));
cmdList->Close(); // Immediately close since it will be reset on first use
cmdList->SetName((name + L" command list").c_str());
fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
}
void shutdown()
{
SL_SAFE_RELEASE(cmdList);
for (uint32_t i = 0; i < bufferCount; i++)
{
SL_SAFE_RELEASE(allocator[i]);
SL_SAFE_RELEASE(fence[i]);
}
CloseHandle(fenceEvent);
allocator.clear();
fence.clear();
}
CommandList getCmdList()
{
return cmdList;
}
CommandQueue getCmdQueue()
{
return cmdQueue;
}
CommandAllocator getCmdAllocator()
{
return allocator[index];
}
Handle getFenceEvent()
{
return fenceEvent;
}
bool beginCommandList()
{
if (cmdListIsRecording)
{
return true;
}
// Only rest allocator if we are done with the work
if (fence[index]->GetCompletedValue() >= fenceValue[index])
{
allocator[index]->Reset();
}
cmdListIsRecording = SUCCEEDED(cmdList->Reset(allocator[index], nullptr));
if (!cmdListIsRecording)
{
SL_LOG_ERROR("%S command buffer - cannot reset command list", name.c_str());
}
return cmdListIsRecording;
}
void executeCommandList()
{
assert(cmdListIsRecording);
cmdListIsRecording = false;
if (FAILED(cmdList->Close()))
return;
ID3D12CommandList* const cmd_lists[] = { cmdList };
cmdQueue->ExecuteCommandLists(ARRAYSIZE(cmd_lists), cmd_lists);
}
bool flushAll()
{
for (uint32_t i = 0; i < bufferCount; i++)
{
const UINT64 syncValue = fenceValue[i] + 1;
if (FAILED(cmdQueue->Signal(fence[i], syncValue)))
return false;
if (SUCCEEDED(fence[i]->SetEventOnCompletion(syncValue, fenceEvent)))
{
WaitForSingleObject(fenceEvent, 500); // don't wait INFINITE
}
else
{
return false;
}
}
return true;
}
uint32_t getBufferCount()
{
return bufferCount;
}
uint32_t getCurrentBufferIndex()
{
return index;
}
uint32_t acquireNextBufferIndex(SwapChain chain)
{
// VK specific, nothing to do here
return index;
}
bool didFrameFinish(uint32_t index)
{
if (index >= bufferCount)
{
SL_LOG_ERROR("Invalid index");
return false;
}
return fence[index]->GetCompletedValue() >= fenceValue[index];
}
void waitOnGPUForTheOtherQueue(const ICommandListContext* other)
{
auto tmp = (const CommandListContext*)other;
if (tmp->cmdQueue != cmdQueue && tmp->lastIndex != UINT_MAX)
{
if (FAILED(cmdQueue->Wait(tmp->fence[tmp->lastIndex], tmp->fenceValue[tmp->lastIndex])))
{
SL_LOG_ERROR("Failed to wait on the command queue");
}
}
}
bool waitForCommandList(FlushType ft)
{
// Flush command list, to avoid it still referencing resources that may be destroyed after this call
if (cmdListIsRecording)
executeCommandList();
// Increment fence value to ensure it has not been signaled before
const UINT64 syncValue = fenceValue[index] + 1;
if (FAILED(cmdQueue->Signal(fence[index], syncValue)))
return false; // Cannot wait on fence if signaling was not successful
if (ft == eCurrent)
{
// Flushing so wait for current sync value
if (SUCCEEDED(fence[index]->SetEventOnCompletion(syncValue, fenceEvent)))
WaitForSingleObject(fenceEvent, 500); // don't wait INFINITE
}
else if (ft == ePrevious && lastIndex != UINT_MAX)
{
// If previous frame did not finish let's wait for it
if (fence[lastIndex]->GetCompletedValue() < fenceValue[lastIndex])
{
if (SUCCEEDED(fence[lastIndex]->SetEventOnCompletion(fenceValue[lastIndex], fenceEvent)))
WaitForSingleObject(fenceEvent, 500); // don't wait INFINITE
}
}
else
{
// If old frame (bufferCount ago) at this index did not finish let's wait for it
if (fence[index]->GetCompletedValue() < fenceValue[index])
{
if (SUCCEEDED(fence[index]->SetEventOnCompletion(fenceValue[index], fenceEvent)))
WaitForSingleObject(fenceEvent, 500); // don't wait INFINITE
}
}
// Update CPU side fence value now that it is guaranteed to have come through
fenceValue[index] = syncValue;
lastIndex.store(index.load());
index = (index + 1) % bufferCount;
return true;
}
bool present(SwapChain chain, uint32_t sync, uint32_t flags)
{
if (FAILED(((IDXGISwapChain*)chain)->Present(sync, flags)))
{
SL_LOG_ERROR("Present failed");
return false;
}
return true;
}
};
ComputeStatus D3D12::init(Device InDevice, param::IParameters* params)
{
Generic::init(InDevice, params);
m_device = (ID3D12Device*)InDevice;
UINT NodeCount = m_device->GetNodeCount();
m_visibleNodeMask = (1 << NodeCount) - 1;
if (NodeCount > MAX_NUM_NODES)
{
SL_LOG_ERROR(" too many GPU nodes");
return eComputeStatusError;
}
HRESULT hr = S_OK;
// The ability to cast one fully typed resource to a compatible fully typed cast resource
// (instead of creating the resource typeless)
// should be supported by all our GPUs with drivers going back as far as RS2 which is way before the introduction of DLSS
// There are some restrictions though see :
// https://microsoft.github.io/DirectX-Specs/d3d/RelaxedCasting.html
D3D12_FEATURE_DATA_D3D12_OPTIONS3 FeatureOptions3;
hr = m_device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &FeatureOptions3, sizeof(FeatureOptions3));
if (FAILED(hr) || !FeatureOptions3.CastingFullyTypedFormatSupported)
{
SL_LOG_ERROR(" CheckFeatureSupport() call did not succeed or the driver did not report CastingFullyTypedFormatSupported. Windows 10 RS2 or higher was expected. hr=%d", hr);
m_dbgSupportRs2RelaxedConversionRules = false;
}
else
{
m_dbgSupportRs2RelaxedConversionRules = true;
}
SL_LOG_INFO("GPU nodes %u - visible node mask %u", NodeCount, m_visibleNodeMask);
m_heap = new HeapInfo;
for(UINT Node = 0; Node < NodeCount; Node++)
{
// create desc heaps for SRV/UAV/CBV
{
D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
// Each wraparound we target a different part of the heap to prevent direct reuse
heapDesc.NumDescriptors = SL_MAX_D3D12_DESCRIPTORS * SL_DESCRIPTOR_WRAPAROUND_CAPACITY;
heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
heapDesc.NodeMask = (1 << Node);
hr = m_device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&m_heap->descriptorHeap[Node]));
if (FAILED(hr)) { SL_LOG_ERROR(" failed to create descriptor heap, hr=%d", hr); return eComputeStatusError; }
m_heap->descriptorHeap[Node]->SetName(L"sl.chi.heapGPU");
heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
hr = m_device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&m_heap->descriptorHeapCPU[Node]));
if (FAILED(hr)) { SL_LOG_ERROR(" failed to create descriptor heap, hr=%d", hr); return eComputeStatusError; }
m_heap->descriptorHeapCPU[Node]->SetName(L"sl.chi.heapCPU");
}
m_descriptorSize = m_device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
}
m_bFastUAVClearSupported = true;
genericPostInit();
CHI_CHECK(createKernel((void*)copy_to_buffer_cs, copy_to_buffer_cs_len, "copy_to_buffer.cs", "main", m_copyKernel));
m_workCompleteEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!m_workCompleteEvent)
{
SL_LOG_ERROR("error: failed to create event");
return eComputeStatusError;
}
hr = m_device->CreateFence(0ull, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), (void**)&m_fence);
if (FAILED(hr))
{
SL_LOG_ERROR("error: failed to create fence, hr=%d", hr);
return eComputeStatusError;
}
return eComputeStatusOk;
}
ComputeStatus D3D12::shutdown()
{
SL_SAFE_RELEASE(m_fence);
CHI_CHECK(destroyKernel(m_copyKernel));
m_copyKernel = {};
for (auto& rb : m_readbackMap)
{
CHI_CHECK(destroyResource(rb.second.target));
for (int i = 0; i < SL_READBACK_QUEUE_SIZE; i++)
{
CHI_CHECK(destroyResource(rb.second.readback[i]));
}
}
for (UINT node = 0; node < MAX_NUM_NODES; node++)
{
#if SL_ENABLE_PERF_TIMING
for (auto section : m_sectionPerfMap[node])
{
for (int i = 0; i < SL_READBACK_QUEUE_SIZE; i++)
{
SL_SAFE_RELEASE(section.second.queryHeap[i]);
SL_SAFE_RELEASE(section.second.queryBufferReadback[i]);
}
}
m_sectionPerfMap[node].clear();
#endif
SL_SAFE_RELEASE(m_heap->descriptorHeap[node]);
SL_SAFE_RELEASE(m_heap->descriptorHeapCPU[node]);
}
delete m_heap;
m_heap = {};
for (auto& v : m_psoMap)
{
SL_LOG_VERBOSE("Destroying pipeline state 0x%llx", v.second);
SL_SAFE_RELEASE(v.second);
}
for (auto& v : m_rootSignatureMap)
{
SL_LOG_VERBOSE("Destroying root signature 0x%llx", v.second);
SL_SAFE_RELEASE(v.second);
}
m_rootSignatureMap.clear();
m_psoMap.clear();
ComputeStatus Res = eComputeStatusOk;
for (auto& k : m_kernels)
{
auto kernel = (KernelDataBase*)k.second;
SL_LOG_VERBOSE("Destroying kernel %s", kernel->name.c_str());
delete kernel;
}
m_kernels.clear();
return Generic::shutdown();
}
ComputeStatus D3D12::getPlatformType(PlatformType &OutType)
{
OutType = ePlatformTypeD3D12;
return eComputeStatusOk;
}
ComputeStatus D3D12::restorePipeline(CommandList pCmdList)
{
D3D12ThreadContext* thread = (D3D12ThreadContext*)m_getThreadContext();
auto cmdList = ((ID3D12GraphicsCommandList*)pCmdList);
assert(thread->cmdList->m_base == pCmdList);
if (thread->cmdList->m_numHeaps > 0)
{
cmdList->SetDescriptorHeaps(thread->cmdList->m_numHeaps, thread->cmdList->m_heaps);
}
if (thread->cmdList->m_rootSignature)
{
cmdList->SetComputeRootSignature(thread->cmdList->m_rootSignature);
for (auto& pair : thread->cmdList->m_mapHandles)
{
cmdList->SetComputeRootDescriptorTable(pair.first, pair.second);
}
for (auto& pair : thread->cmdList->m_mapCBV)
{
cmdList->SetComputeRootConstantBufferView(pair.first, pair.second);
}
for (auto& pair : thread->cmdList->m_mapSRV)
{
cmdList->SetComputeRootShaderResourceView(pair.first, pair.second);
}
for (auto& pair : thread->cmdList->m_mapUAV)
{
cmdList->SetComputeRootUnorderedAccessView(pair.first, pair.second);
}
for (auto& pair : thread->cmdList->m_mapConstants)
{
cmdList->SetComputeRoot32BitConstants(pair.first, pair.second.Num32BitValuesToSet, pair.second.SrcData, pair.second.DestOffsetIn32BitValues);
}
}
if (thread->cmdList->m_pso)
{
cmdList->SetPipelineState(thread->cmdList->m_pso);
}
if (thread->cmdList->m_so)
{
static_cast<ID3D12GraphicsCommandList4*>(cmdList)->SetPipelineState1(thread->cmdList->m_so);
}
return eComputeStatusOk;
}
ComputeStatus D3D12::getResourceState(uint32_t states, ResourceState& resourceStates)
{
resourceStates = ResourceState::ePresent;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)
resourceStates = resourceStates | (ResourceState::eConstantBuffer | ResourceState::eVertexBuffer);
if (states & (D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE))
resourceStates = resourceStates | (ResourceState::eTextureRead);
if (states & (D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE))
resourceStates = resourceStates | (ResourceState::eStorageRead);
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_INDEX_BUFFER)
resourceStates = resourceStates | ResourceState::eIndexBuffer;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT)
resourceStates = resourceStates | ResourceState::eArgumentBuffer;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_UNORDERED_ACCESS)
resourceStates = resourceStates | ResourceState::eStorageRW;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RENDER_TARGET)
resourceStates = resourceStates | ResourceState::eColorAttachmentWrite;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_DEPTH_READ)
resourceStates = resourceStates | ResourceState::eDepthStencilAttachmentRead;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_DEPTH_WRITE)
resourceStates = resourceStates | ResourceState::eDepthStencilAttachmentWrite;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COPY_SOURCE)
resourceStates = resourceStates | ResourceState::eCopySource;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COPY_DEST)
resourceStates = resourceStates | ResourceState::eCopyDestination;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE)
resourceStates = resourceStates | (ResourceState::eAccelStructRead | ResourceState::eAccelStructWrite);
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RESOLVE_DEST)
resourceStates = resourceStates | ResourceState::eResolveDestination;
if (states & D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RESOLVE_SOURCE)
resourceStates = resourceStates | ResourceState::eResolveSource;
return eComputeStatusOk;
}
ComputeStatus D3D12::getNativeResourceState(ResourceState states, uint32_t& resourceStates)
{
resourceStates = D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COMMON;
if (states & (ResourceState::eConstantBuffer | ResourceState::eVertexBuffer))
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
if (states & (ResourceState::eTextureRead))
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
if (states & (ResourceState::eGenericRead))
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_GENERIC_READ;
if (states & (ResourceState::eStorageRead))
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
if (states & ResourceState::eIndexBuffer)
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_INDEX_BUFFER;
if (states & ResourceState::eArgumentBuffer)
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
if ((states & ResourceState::eStorageWrite) && (states & ResourceState::eStorageRead))
{
// Clear out incompatible state if we want read/write access
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
resourceStates &= ~(D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE |
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
}
if (states & ResourceState::eColorAttachmentWrite)
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RENDER_TARGET;
if (states & ResourceState::eDepthStencilAttachmentRead)
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_DEPTH_READ;
if (states & ResourceState::eDepthStencilAttachmentWrite)
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_DEPTH_WRITE;
if (states & ResourceState::eCopySource)
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COPY_SOURCE;
if (states & ResourceState::eCopyDestination)
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COPY_DEST;
if (states & (ResourceState::eAccelStructRead | ResourceState::eAccelStructWrite))
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE;
if (states & ResourceState::eResolveDestination)
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RESOLVE_DEST;
if (states & ResourceState::eResolveSource)
resourceStates |= D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RESOLVE_SOURCE;
return eComputeStatusOk;
}
ComputeStatus D3D12::createKernel(void *blobData, unsigned int blobSize, const char* fileName, const char *entryPoint, Kernel &kernel)
{
if (!blobData) return eComputeStatusInvalidArgument;
size_t hash = 0;
auto i = blobSize;
while (i--)
{
hash_combine(hash, ((char*)blobData)[i]);
}
ComputeStatus Res = eComputeStatusOk;
KernelDataBase*data = {};
bool missing = false;
{
std::lock_guard<std::mutex> lock(m_mutex);
auto it = m_kernels.find(hash);
missing = it == m_kernels.end();
if (missing)
{
data = new KernelDataBase;
data->hash = hash;
m_kernels[hash] = data;
}
else
{
data = (KernelDataBase*)(*it).second;
}
}
if (missing)
{
data->name = fileName;
data->entryPoint = entryPoint;
const char* blob = (const char*)blobData;
if (blob[0] == 'D' && blob[1] == 'X' && blob[2] == 'B' && blob[3] == 'C')
{
data->kernelBlob.resize(blobSize);
memcpy(data->kernelBlob.data(), blob, blobSize);
SL_LOG_VERBOSE("Creating DXBC kernel %s:%s hash %llu", fileName, entryPoint, hash);
}
else
{
SL_LOG_ERROR("Unsupported kernel blob");
return eComputeStatusInvalidArgument;
}
}
else
{
if (data->entryPoint != entryPoint || data->name != fileName)
{
SL_LOG_ERROR("Shader %s:%s has overlapping hash with shader %s:%s", data->name.c_str(), data->entryPoint.c_str(), fileName, entryPoint);
return eComputeStatusError;
}
SL_LOG_WARN("Kernel %s:%s with hash 0x%llx already created!", fileName, entryPoint, hash);
}
kernel = hash;
return Res;
}
ComputeStatus D3D12::destroyKernel(Kernel& InKernel)
{
if (!InKernel) return eComputeStatusOk; // fine to destroy null kernels
std::lock_guard<std::mutex> lock(m_mutex);
auto it = m_kernels.find(InKernel);
if (it == m_kernels.end())
{
return eComputeStatusInvalidCall;
}
auto data = (KernelDataBase*)(it->second);
SL_LOG_VERBOSE("Destroying kernel %s", data->name.c_str());
delete it->second;
m_kernels.erase(it);
InKernel = {};
return eComputeStatusOk;
}
ComputeStatus D3D12::createCommandListContext(CommandQueue queue, uint32_t count, ICommandListContext*& ctx, const char friendlyName[])
{
auto tmp = new CommandListContext();
tmp->init(friendlyName, m_device, (ID3D12CommandQueue*)queue, count);
ctx = tmp;
return eComputeStatusOk;
}
ComputeStatus D3D12::destroyCommandListContext(ICommandListContext* ctx)
{
auto tmp = (CommandListContext*)ctx;
tmp->shutdown();
delete tmp;
return eComputeStatusOk;
}
ComputeStatus D3D12::createCommandQueue(CommandQueueType type, CommandQueue& queue, const char friendlyName[])
{
D3D12_COMMAND_QUEUE_DESC desc = {};
desc.Type = type == CommandQueueType::eGraphics ? D3D12_COMMAND_LIST_TYPE_DIRECT : D3D12_COMMAND_LIST_TYPE_COMPUTE;
desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_HIGH;
ID3D12CommandQueue* tmp;
if (FAILED(m_device->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), (void**)&tmp)))
{
SL_LOG_ERROR("Failed to create command queue %s", friendlyName);
return eComputeStatusError;
}
queue = tmp;
setDebugName(queue, friendlyName);
return eComputeStatusOk;
}
ComputeStatus D3D12::destroyCommandQueue(CommandQueue& queue)
{
if (queue)
{
auto tmp = (ID3D12CommandQueue*)queue;
SL_SAFE_RELEASE(tmp);
}
return eComputeStatusOk;
}
ComputeStatus D3D12::setFullscreenState(SwapChain chain, bool fullscreen, Output out)
{
if (!chain) return eComputeStatusInvalidArgument;
IDXGISwapChain* swapChain = (IDXGISwapChain*)chain;
if (FAILED(swapChain->SetFullscreenState(fullscreen, (IDXGIOutput*)out)))
{
SL_LOG_ERROR("Failed to set fullscreen state");
}
return eComputeStatusOk;
}
ComputeStatus D3D12::getRefreshRate(SwapChain chain, float& refreshRate)
{
if (!chain) return eComputeStatusInvalidArgument;
IDXGISwapChain* swapChain = (IDXGISwapChain*)chain;
IDXGIOutput* dxgiOutput;
HRESULT hr = swapChain->GetContainingOutput(&dxgiOutput);
// if swap chain get failed to get DXGIoutput then follow the below link get the details from remarks section
//https://docs.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgiswapchain-getcontainingoutput
if (SUCCEEDED(hr))
{
// get the descriptor for current output
// from which associated mornitor will be fetched
DXGI_OUTPUT_DESC outputDes{};
hr = dxgiOutput->GetDesc(&outputDes);
dxgiOutput->Release();
if (SUCCEEDED(hr))
{
MONITORINFOEXW info;
info.cbSize = sizeof(info);
// get the associated monitor info
if (GetMonitorInfoW(outputDes.Monitor, &info) != 0)
{
// using the CCD get the associated path and display configuration
UINT32 requiredPaths, requiredModes;
if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &requiredPaths, &requiredModes) == ERROR_SUCCESS)
{
std::vector<DISPLAYCONFIG_PATH_INFO> paths(requiredPaths);
std::vector<DISPLAYCONFIG_MODE_INFO> modes2(requiredModes);
if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &requiredPaths, paths.data(), &requiredModes, modes2.data(), nullptr) == ERROR_SUCCESS)
{
// iterate through all the paths until find the exact source to match
for (auto& p : paths) {
DISPLAYCONFIG_SOURCE_DEVICE_NAME sourceName;
sourceName.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
sourceName.header.size = sizeof(sourceName);
sourceName.header.adapterId = p.sourceInfo.adapterId;
sourceName.header.id = p.sourceInfo.id;
if (DisplayConfigGetDeviceInfo(&sourceName.header) == ERROR_SUCCESS)
{
// find the matched device which is associated with current device
// there may be the possibility that display may be duplicated and windows may be one of them in such scenario
// there may be two callback because source is same target will be different
// as window is on both the display so either selecting either one is ok
if (wcscmp(info.szDevice, sourceName.viewGdiDeviceName) == 0) {
// get the refresh rate
UINT numerator = p.targetInfo.refreshRate.Numerator;
UINT denominator = p.targetInfo.refreshRate.Denominator;
double refrate = (double)numerator / (double)denominator;
refreshRate = (float)refrate;
return eComputeStatusOk;
}
}
}
}
}
}
}
}
SL_LOG_ERROR("Failed to retrieve refresh rate from swapchain 0x%llx", chain);
return eComputeStatusError;
}
ComputeStatus D3D12::getSwapChainBuffer(SwapChain chain, uint32_t index, Resource& buffer)
{
ID3D12Resource* tmp;
if (FAILED(((IDXGISwapChain*)chain)->GetBuffer(index, IID_PPV_ARGS(&tmp))))
{
SL_LOG_ERROR("Failed to get buffer from swapchain");
return eComputeStatusError;
}
buffer = tmp;
return eComputeStatusOk;
}
ComputeStatus D3D12::bindSharedState(CommandList InCmdList, UINT node)
{
auto& ctx = m_dispatchContext.getContext();
ctx.node = node;
ctx.cmdList = (ID3D12GraphicsCommandList*)InCmdList;
ID3D12DescriptorHeap *Heaps[] = { m_heap->descriptorHeap[ctx.node] };
ctx.cmdList->SetDescriptorHeaps(1, Heaps);
return eComputeStatusOk;
}
ComputeStatus D3D12::bindKernel(const Kernel kernelToBind)
{
auto& ctx = m_dispatchContext.getContext();
{
std::lock_guard<std::mutex> lock(m_mutex);
auto it = m_kernels.find(kernelToBind);
if (it == m_kernels.end())
{
SL_LOG_ERROR("Trying to bind kernel which has not been created");
return eComputeStatusInvalidCall;
}
ctx.kernel = (KernelDataBase*)(*it).second;
}
if (!ctx.kddMap)
{
ctx.kddMap = new KernelDispatchDataMap();
}
auto it = ctx.kddMap->find(ctx.kernel->hash);
if (it == ctx.kddMap->end())
{
(*ctx.kddMap)[ctx.kernel->hash] = {};
}
else
{
(*it).second.numSamplers = 0;
(*it).second.slot = 0;
}
//SL_LOG_INFO("Binding kernel %s:%s", ctx.kernel->name.c_str(), ctx.kernel->entryPoint.c_str());
return eComputeStatusOk;
}
ComputeStatus D3D12::bindSampler(uint32_t pos, uint32_t base, Sampler sampler)
{
auto& ctx = m_dispatchContext.getContext();
if (!ctx.kernel || base >= 8) return eComputeStatusInvalidArgument;
auto &kdd = (*ctx.kddMap)[ctx.kernel->hash];
if (sampler == Sampler::eSamplerPointClamp)
{
kdd.samplers[base] = CD3DX12_STATIC_SAMPLER_DESC(base, D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
}
else if (sampler == Sampler::eSamplerPointMirror)
{
kdd.samplers[base] = CD3DX12_STATIC_SAMPLER_DESC(base, D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_MIRROR, D3D12_TEXTURE_ADDRESS_MODE_MIRROR);
}
else if (sampler == Sampler::eSamplerLinearClamp)
{
kdd.samplers[base] = CD3DX12_STATIC_SAMPLER_DESC(base, D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
}
else if (sampler == Sampler::eSamplerLinearMirror)
{
kdd.samplers[base] = CD3DX12_STATIC_SAMPLER_DESC(base, D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_MIRROR, D3D12_TEXTURE_ADDRESS_MODE_MIRROR);
}
else
{
kdd.samplers[base] = CD3DX12_STATIC_SAMPLER_DESC(base, D3D12_FILTER_ANISOTROPIC, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
}
kdd.numSamplers = std::max(base + 1, kdd.numSamplers);
return eComputeStatusOk;
}
ComputeStatus D3D12::bindConsts(uint32_t pos, uint32_t base, void *data, size_t dataSize, uint32_t instances)
{
auto& ctx = m_dispatchContext.getContext();
if (!ctx.kernel) return eComputeStatusInvalidArgument;
auto &kdd = (*ctx.kddMap)[ctx.kernel->hash];
if (kdd.addSlot(kdd.slot))
{
kdd.rootRanges[kdd.slot].Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, base);
kdd.rootParameters[kdd.slot].InitAsConstantBufferView(base);
kdd.cb[kdd.slot] = new ConstantBuffer();
kdd.cb[kdd.slot]->create(m_device, (uint32_t)dataSize, instances);
}
if (data)
{
auto idx = kdd.cb[kdd.slot]->getIndex();
kdd.cb[kdd.slot]->copyStagingToGpu(data, idx);
kdd.handles[kdd.slot] = kdd.cb[kdd.slot]->getGpuVirtualAddress(idx);
kdd.cb[kdd.slot]->advanceIndex();
}
#ifndef SL_PRODUCTION
kdd.validate(kdd.slot, D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, base);
//SL_LOG_INFO("binding CBV 0x%llx", kdd.handles[slot]);
#endif
kdd.slot++;
return eComputeStatusOk;
}
ComputeStatus D3D12::bindTexture(uint32_t pos, uint32_t base, Resource resource, uint32_t mipOffset, uint32_t mipLevels)
{
auto& ctx = m_dispatchContext.getContext();
if (!ctx.kernel) return eComputeStatusInvalidArgument;
auto &kdd = (*ctx.kddMap)[ctx.kernel->hash];
if (kdd.addSlot(kdd.slot))
{
kdd.rootRanges[kdd.slot].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, base);
kdd.rootParameters[kdd.slot].InitAsDescriptorTable(1, &kdd.rootRanges[kdd.slot]);
}
// Resource can be null if shader is not using this slot
if (resource)
{
ResourceDriverData data = {};
CHI_CHECK(getTextureDriverData(resource, data, mipOffset, mipLevels));
auto handle = CD3DX12_GPU_DESCRIPTOR_HANDLE(m_heap->descriptorHeap[ctx.node]->GetGPUDescriptorHandleForHeapStart(), data.descIndex, m_descriptorSize);
kdd.handles[kdd.slot] = handle.ptr;
#ifndef SL_PRODUCTION
kdd.validate(kdd.slot, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, base);
//std::wstring name = getDebugName(resource);
//chi::ResourceDescription desc;
//getResourceDescription(resource, desc);
//SL_LOG_INFO("binding SRV 0x%llx(%S) mip:%u mips:%u (%u,%u:%u)", kdd.handles[slot], name.c_str(), mipOffset, mipLevels, desc.width, desc.height, desc.mips);
#endif
}
else
{
kdd.handles[kdd.slot] = 0;
}
kdd.slot++;
return eComputeStatusOk;
}
ComputeStatus D3D12::bindRWTexture(uint32_t pos, uint32_t base, Resource resource, uint32_t mipOffset)
{
auto& ctx = m_dispatchContext.getContext();
if (!ctx.kernel) return eComputeStatusInvalidArgument;
auto &kdd = (*ctx.kddMap)[ctx.kernel->hash];
if (kdd.addSlot(kdd.slot))
{
kdd.rootRanges[kdd.slot].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, base);
kdd.rootParameters[kdd.slot].InitAsDescriptorTable(1, &kdd.rootRanges[kdd.slot]);
}
// Resource can be null if shader is not using this slot
if (resource)
{
ResourceDriverData data = {};
CHI_CHECK(getSurfaceDriverData((ID3D12Resource*)resource, data, mipOffset));
auto handle = CD3DX12_GPU_DESCRIPTOR_HANDLE(m_heap->descriptorHeap[ctx.node]->GetGPUDescriptorHandleForHeapStart(), data.descIndex, m_descriptorSize);
kdd.handles[kdd.slot] = handle.ptr;
#ifndef SL_PRODUCTION
kdd.validate(kdd.slot, D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, base);
//std::wstring name = getDebugName(resource);
//chi::ResourceDescription desc;
//getResourceDescription(resource, desc);
//SL_LOG_INFO("binding UAV 0x%llx(%S) mip:%u (%u,%u:%u)", kdd.handles[slot], name.c_str(), mipOffset, desc.width, desc.height, desc.mips);
#endif
}
else
{
kdd.handles[kdd.slot] = 0;
}
kdd.slot++;
return eComputeStatusOk;
}
ComputeStatus D3D12::bindRawBuffer(uint32_t pos, uint32_t base, Resource resource)
{
// This is still just a UAV for D3D12 so reuse the other method
// Note that UAV creation checks for buffers and modifies view accordingly (D3D12_BUFFER_UAV_FLAG_RAW etc.)
return bindRWTexture(pos, base, resource);
}
ComputeStatus D3D12::dispatch(unsigned int blocksX, unsigned int blocksY, unsigned int blocksZ)
{
auto& ctx = m_dispatchContext.getContext();
if (!ctx.kernel) return eComputeStatusInvalidArgument;
auto &kdd = (*ctx.kddMap)[ctx.kernel->hash];
ComputeStatus Res = eComputeStatusOk;
{
if (!kdd.rootSignature)
{
CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
rootSignatureDesc.Init((UINT)kdd.rootParameters.size(), kdd.rootParameters.data(), kdd.numSamplers, kdd.samplers, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
auto hash = hashRootSignature(rootSignatureDesc);
auto node = ctx.node << 1;
{
std::lock_guard<std::mutex> lock(m_mutex);
auto it = m_rootSignatureMap.find(hash);
if (it == m_rootSignatureMap.end())
{
ID3DBlob *signature;
ID3DBlob *error;
D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error);
if (error)
{
SL_LOG_ERROR("D3D12SerializeRootSignature failed %s", (const char*)error->GetBufferPointer());
error->Release();
return eComputeStatusError;
}
if (FAILED(m_device->CreateRootSignature(node, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&kdd.rootSignature))))
{
SL_LOG_ERROR("Failed to create root signature");
return eComputeStatusError;
}
SL_LOG_VERBOSE("Created root signature 0x%llx with hash %llu", kdd.rootSignature, hash);
m_rootSignatureMap[hash] = kdd.rootSignature;
}
else
{
kdd.rootSignature = (*it).second;
}
}
{
hash_combine(hash, ctx.kernel->hash);
std::lock_guard<std::mutex> lock(m_mutex);
auto it = m_psoMap.find(hash);
if (it == m_psoMap.end())
{
D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.pRootSignature = kdd.rootSignature;
psoDesc.CS = { ctx.kernel->kernelBlob.data(), ctx.kernel->kernelBlob.size() };
psoDesc.NodeMask = node;
if (FAILED(m_device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&kdd.pso))))
{
SL_LOG_ERROR("Failed to create CS pipeline state");
return eComputeStatusError;
}
SL_LOG_VERBOSE("Created pipeline state 0x%llx with hash %llu", kdd.pso, hash);
m_psoMap[hash] = kdd.pso;
}
else
{
kdd.pso = (*it).second;
}
}
}
if (!kdd.rootSignature || !kdd.pso)
{
SL_LOG_ERROR("Failed to create root signature or pso for kernel %s:%s", ctx.kernel->name.c_str(), ctx.kernel->entryPoint.c_str());
return eComputeStatusError;
}
ctx.cmdList->SetComputeRootSignature(kdd.rootSignature);
ctx.cmdList->SetPipelineState(kdd.pso);
auto numSlots = kdd.rootParameters.size();
for (auto i = 0; i < numSlots; i++)
{
if (kdd.rootParameters[i].ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV)
{
ctx.cmdList->SetComputeRootConstantBufferView(i, { kdd.handles[i] });
}
else if (kdd.rootParameters[i].ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE)
{
// To avoid triggering debug layer error, nullptr is not allowed
if (kdd.handles[i])
{
ctx.cmdList->SetComputeRootDescriptorTable(i, { kdd.handles[i] });
}
}
}
ctx.cmdList->Dispatch(blocksX, blocksY, blocksZ);
}
return Res;
}
size_t D3D12::hashRootSignature(const CD3DX12_ROOT_SIGNATURE_DESC& desc)
{
size_t h = 0;
hash_combine(h, desc.Flags);
hash_combine(h, desc.NumParameters);
hash_combine(h, desc.NumStaticSamplers);
for (uint32_t i = 0; i < desc.NumStaticSamplers; i++)
{
hash_combine(h, desc.pStaticSamplers[i].Filter);
hash_combine(h, desc.pStaticSamplers[i].ShaderRegister);
hash_combine(h, desc.pStaticSamplers[i].AddressU);
hash_combine(h, desc.pStaticSamplers[i].AddressV);
hash_combine(h, desc.pStaticSamplers[i].AddressW);
hash_combine(h, desc.pStaticSamplers[i].MipLODBias);
hash_combine(h, desc.pStaticSamplers[i].ShaderVisibility);
}
for (uint32_t i = 0; i < desc.NumParameters; i++)
{
hash_combine(h, desc.pParameters[i].ParameterType);
hash_combine(h, desc.pParameters[i].ShaderVisibility);
if (desc.pParameters[i].ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE)
{
hash_combine(h, desc.pParameters[i].DescriptorTable.NumDescriptorRanges);
for (uint32_t j = 0; j < desc.pParameters[i].DescriptorTable.NumDescriptorRanges; j++)
{
hash_combine(h, desc.pParameters[i].DescriptorTable.pDescriptorRanges[j].RangeType);
}
}
else if (desc.pParameters[i].ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV)
{
hash_combine(h, desc.pParameters[i].Descriptor.RegisterSpace);
}
else
{
SL_LOG_ERROR("Unsupported parameter type in root signature");
}
}
return h;
}
UINT D3D12::getNewAndIncreaseDescIndex()
{
// This method is thread safe since it is just a helper for cache texture or surface
auto node = 0; // FIX THIS
if ((m_heap->descIndex[node] + 1) >= SL_MAX_D3D12_DESCRIPTORS)
{
// We've looped around our Descriptor heap
// There's no way we can keep the old cached Descriptors as valid..
// Invalidate all caches and force the SetInput() calls to set up new ones
// It will be a slow burn for a while, but hopefully that isn't too frequent ??
SL_LOG_WARN("D3D12 Descriptor heap wrap around. Clearing all cache and reallocating from scratch again. This is impacting performance - please do NOT change the tagged resources every frame");
memset(m_heap->descIndex, 0, MAX_NUM_NODES * sizeof(UINT));
assert(m_heap->descIndex[node] == 0);
m_heap->wrapAroundCount = (m_heap->wrapAroundCount + 1) % SL_DESCRIPTOR_WRAPAROUND_CAPACITY;
m_resourceData.clear();
}
UINT ReturnedIndex = m_heap->descIndex[node] + SL_MAX_D3D12_DESCRIPTORS * m_heap->wrapAroundCount;
m_heap->descIndex[node] = (m_heap->descIndex[node] + 1) % SL_MAX_D3D12_DESCRIPTORS;
return ReturnedIndex;
}
ComputeStatus D3D12::getTextureDriverData(Resource res, ResourceDriverData &data, uint32_t mipOffset, uint32_t mipLevels, Sampler sampler)
{
ID3D12Resource *resource = (ID3D12Resource*)res;
if (!resource) return eComputeStatusInvalidArgument;
std::lock_guard<std::mutex> lock(m_mutex);
uint32_t hash = (mipOffset << 16) | mipLevels;
auto it = m_resourceData.find(resource);
if (it == m_resourceData.end() || (*it).second.find(hash) == (*it).second.end())
{
auto node = 0; // FIX THIS
data.descIndex = getNewAndIncreaseDescIndex();
auto currentCPUHandle = CD3DX12_CPU_DESCRIPTOR_HANDLE(m_heap->descriptorHeap[node]->GetCPUDescriptorHandleForHeapStart(), data.descIndex, m_descriptorSize);
D3D12_RESOURCE_DESC desc = resource->GetDesc();
D3D12_SHADER_RESOURCE_VIEW_DESC SRVDesc = {};
SRVDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Format = getCorrectFormat(desc.Format);
SRVDesc.Texture2D.MipLevels = mipLevels ? mipLevels : desc.MipLevels;
SRVDesc.Texture2D.MostDetailedMip = mipOffset;
auto name = getDebugName(resource);
SL_LOG_VERBOSE("Caching texture 0x%llx(%S) node %u fmt %s size (%u,%u) mip %u mips %u sampler[%d]", resource, name.c_str(), node, getDXGIFormatStr(desc.Format), (UINT)desc.Width, (UINT)desc.Height, SRVDesc.Texture2D.MostDetailedMip, SRVDesc.Texture2D.MipLevels, sampler);
m_device->CreateShaderResourceView(resource, &SRVDesc, currentCPUHandle);
data.heap = m_heap;
m_resourceData[resource][hash] = data;
}
else
{
data = (*it).second[hash];
}
assert(data.heap == m_heap);
return eComputeStatusOk;
}
ComputeStatus D3D12::getSurfaceDriverData(Resource res, ResourceDriverData &data, uint32_t mipOffset)
{
ID3D12Resource *resource = (ID3D12Resource*)res;
if (!resource) return eComputeStatusInvalidArgument;
std::lock_guard<std::mutex> lock(m_mutex);
uint32_t hash = mipOffset << 16;
auto it = m_resourceData.find(resource);
if (it == m_resourceData.end() || (*it).second.find(hash) == (*it).second.end())
{
auto node = 0; // FIX THIS
data.descIndex = getNewAndIncreaseDescIndex();
D3D12_RESOURCE_DESC desc = resource->GetDesc();
auto name = getDebugName(resource);
D3D12_UNORDERED_ACCESS_VIEW_DESC UAVDesc = {};
if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER)
{
UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
UAVDesc.Format = DXGI_FORMAT_R32_TYPELESS;
UAVDesc.Buffer.CounterOffsetInBytes = 0;
UAVDesc.Buffer.FirstElement = 0;
UAVDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
UAVDesc.Buffer.NumElements = (UINT)desc.Width / 4;
UAVDesc.Buffer.StructureByteStride = 0;
SL_LOG_VERBOSE("Caching raw buffer 0x%llx(%S) node %u fmt %s size (%u,%u)", resource, name.c_str(), node, getDXGIFormatStr(desc.Format), (UINT)desc.Width, (UINT)desc.Height);
}
else
{
UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
UAVDesc.Format = getCorrectFormat(desc.Format);
UAVDesc.Texture2D.MipSlice = mipOffset;
if (!isSupportedFormat(UAVDesc.Format, 0, D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD | D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE))
{
SL_LOG_ERROR("Format %s cannot be used as UAV", getDXGIFormatStr(UAVDesc.Format));
return eComputeStatusError;
}
SL_LOG_VERBOSE("Caching rwtexture 0x%llx(%S) node %u fmt %s size (%u,%u) mip %u", resource, name.c_str(), node, getDXGIFormatStr(desc.Format), (UINT)desc.Width, (UINT)desc.Height, UAVDesc.Texture2D.MipSlice);
}
{
auto cpuHandle = CD3DX12_CPU_DESCRIPTOR_HANDLE(m_heap->descriptorHeap[node]->GetCPUDescriptorHandleForHeapStart(), data.descIndex, m_descriptorSize);
m_device->CreateUnorderedAccessView(resource, nullptr, &UAVDesc, cpuHandle);
}
data.heap = m_heap;
m_resourceData[resource][hash] = data;
}
else
{
data = (*it).second[hash];
}
assert(data.heap == m_heap);
return eComputeStatusOk;
}
bool D3D12::isSupportedFormat(DXGI_FORMAT format, int flag1, int flag2)
{
// Make sure all typeless formats are converted before the check is done
D3D12_FEATURE_DATA_FORMAT_SUPPORT FormatSupport = { getCorrectFormat(format), D3D12_FORMAT_SUPPORT1_NONE, D3D12_FORMAT_SUPPORT2_NONE };
HRESULT hr = m_device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &FormatSupport, sizeof(FormatSupport));
if (SUCCEEDED(hr))
{
return (FormatSupport.Support1 & flag1) != 0 || (FormatSupport.Support2 & flag2) != 0;
}
SL_LOG_ERROR("Format %s is unsupported - hres %lu flags %d %d", getDXGIFormatStr(format), hr, flag1, flag2);
return false;
}
ComputeStatus D3D12::createTexture2DResourceSharedImpl(ResourceDescription &InOutResourceDesc, Resource &OutResource, bool UseNativeFormat, ResourceState InitialState)
{
ID3D12Resource *Res = nullptr;
D3D12_HEAP_TYPE NativeHeapType;
D3D12_RESOURCE_STATES NativeInitialState = toD3D12States(InitialState);
D3D12_RESOURCE_DESC texDesc = {};
texDesc.Alignment = 65536;
texDesc.MipLevels = (UINT16)InOutResourceDesc.mips;
if (UseNativeFormat)
{
assert(InOutResourceDesc.nativeFormat != NativeFormatUnknown &&
InOutResourceDesc.format == eFormatINVALID);
texDesc.Format = (DXGI_FORMAT)InOutResourceDesc.nativeFormat;
}
else
{
assert(InOutResourceDesc.nativeFormat == NativeFormatUnknown && InOutResourceDesc.format != eFormatINVALID);
NativeFormat native;
getNativeFormat(InOutResourceDesc.format, native);
texDesc.Format = (DXGI_FORMAT)native;
}
texDesc.Width = InOutResourceDesc.width;
texDesc.Height = InOutResourceDesc.height;
switch(InOutResourceDesc.heapType)
{
case eHeapTypeReadback:
texDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
NativeHeapType = D3D12_HEAP_TYPE_READBACK;
break;
case eHeapTypeUpload:
texDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
NativeHeapType = D3D12_HEAP_TYPE_UPLOAD;
break;
default:
assert(0);// fall through
case eHeapTypeDefault:
texDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
NativeHeapType = D3D12_HEAP_TYPE_DEFAULT;
break;
}
texDesc.DepthOrArraySize = 1;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
texDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
CD3DX12_HEAP_PROPERTIES heapProp(NativeHeapType, InOutResourceDesc.creationMask, InOutResourceDesc.visibilityMask ? InOutResourceDesc.visibilityMask : m_visibleNodeMask);
if (m_allocateCallback)
{
ResourceDesc desc = { ResourceType::eResourceTypeTex2d, &texDesc, (uint32_t)NativeInitialState, &heapProp, nullptr };
auto result = m_allocateCallback(&desc);
Res = (ID3D12Resource*)result.native;
}
else
{
m_device->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &texDesc, NativeInitialState, nullptr, IID_PPV_ARGS(&Res));
}
OutResource = Res;
if (!OutResource)
{
SL_LOG_ERROR(" CreateCommittedResource failed");
return eComputeStatusError;
}
return eComputeStatusOk;
}
ComputeStatus D3D12::createBufferResourceImpl(ResourceDescription &InOutResourceDesc, Resource &OutResource, ResourceState InitialState)
{
ID3D12Resource *Res = nullptr;
D3D12_RESOURCE_DESC bufferDesc = {};
bufferDesc.MipLevels = 1;
bufferDesc.Format = DXGI_FORMAT_UNKNOWN;
bufferDesc.Width = InOutResourceDesc.width;
assert(InOutResourceDesc.height == 1);
bufferDesc.Height = 1;
bufferDesc.DepthOrArraySize = 1;
bufferDesc.SampleDesc.Count = 1;
bufferDesc.SampleDesc.Quality = 0;
bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
switch (InOutResourceDesc.heapType)
{
default: assert(0); // Fall through
case eHeapTypeDefault:
bufferDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
break;
case eHeapTypeUpload:
bufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
break;
case eHeapTypeReadback:
bufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
break;
}
D3D12_HEAP_TYPE NativeHeapType = (D3D12_HEAP_TYPE) InOutResourceDesc.heapType; // TODO : proper conversion !
D3D12_RESOURCE_STATES NativeInitialState = toD3D12States(InitialState);
CD3DX12_HEAP_PROPERTIES heapProp(NativeHeapType, InOutResourceDesc.creationMask, InOutResourceDesc.visibilityMask ? InOutResourceDesc.visibilityMask : m_visibleNodeMask);
if (m_allocateCallback)
{
ResourceDesc desc = { ResourceType::eResourceTypeBuffer, &bufferDesc, (uint32_t)NativeInitialState, &heapProp };
auto result = m_allocateCallback(&desc);
Res = (ID3D12Resource*)result.native;
}
else
{
m_device->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufferDesc, NativeInitialState, nullptr, IID_PPV_ARGS(&Res));
}
OutResource = Res;
if (!OutResource)
{
SL_LOG_ERROR(" CreateCommittedResource failed");
return eComputeStatusError;
}
return eComputeStatusOk;
}
ComputeStatus D3D12::setDebugName(Resource res, const char name[])
{
ID3D12Pageable *resource = (ID3D12Pageable*)res;
resource->SetPrivateData(WKPDID_D3DDebugObjectName, (UINT)strlen(name), name);
return eComputeStatusOk;
}
ComputeStatus D3D12::copyHostToDeviceBufferImpl(CommandList InCmdList, uint64_t InSize, const void *InData, Resource InUploadResource, Resource InTargetResource, unsigned long long InUploadOffset, unsigned long long InDstOffset)
{
UINT8 *StagingPtr = nullptr;
ID3D12Resource *Resource = (ID3D12Resource*)InTargetResource;
ID3D12Resource *Scratch = (ID3D12Resource*)InUploadResource;
//SL_LOG_INFO("Scratch size %llu", Scratch->GetDesc().Width * Scratch->GetDesc().Height);
HRESULT hr = Scratch->Map(0, NULL, reinterpret_cast<void**>(&StagingPtr));
if (hr != S_OK)
{
SL_LOG_ERROR(" failed to map buffer - error 0x%lx", hr);
return eComputeStatusError;
}
memcpy(StagingPtr + InUploadOffset, InData, InSize);
Scratch->Unmap(0, nullptr);
((ID3D12GraphicsCommandList*)InCmdList)->CopyBufferRegion(Resource, InDstOffset, Scratch, InUploadOffset, InSize);
return eComputeStatusOk;
}
ComputeStatus D3D12::writeTextureImpl(CommandList InCmdList, uint64_t InSize, uint64_t RowPitch, const void* InData, Resource InTargetResource, Resource& InUploadResource)
{
uint64_t depthPitch = 1;
uint64_t mipLevel = 0;
uint64_t arraySlice = 0;
ID3D12Resource* dest = (ID3D12Resource*)InTargetResource;
D3D12_RESOURCE_DESC resourceDesc = dest->GetDesc();
uint32_t subresource = calcSubresource((uint32_t)mipLevel, (uint32_t)arraySlice, 0, (uint32_t)resourceDesc.MipLevels, resourceDesc.DepthOrArraySize);
D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint = {};
uint32_t numRows;
uint64_t rowSizeInBytes;
uint64_t totalBytes;
m_device->GetCopyableFootprints(&resourceDesc, subresource, 1, 0, &footprint, &numRows, &rowSizeInBytes, &totalBytes);
assert(numRows <= footprint.Footprint.Height);
ResourceDescription bufferDesc((uint32_t)totalBytes, 1, chi::eFormatINVALID, HeapType::eHeapTypeUpload, ResourceState::eUnknown);
CHI_CHECK(createBuffer(bufferDesc, InUploadResource, "writeUploadBuffer"));
if (!InUploadResource) {
return eComputeStatusError;
}
void* cpuVA = nullptr;
ID3D12Resource* uploadBuffer = (ID3D12Resource*)InUploadResource;
uploadBuffer->Map(0, nullptr, &cpuVA);
for (uint32_t depthSlice = 0; depthSlice < footprint.Footprint.Depth; depthSlice++)
{
for (uint32_t row = 0; row < numRows; row++)
{
void* destAddress = (char*)cpuVA + footprint.Footprint.RowPitch * (row + depthSlice * numRows);
void* srcAddress = (char*)InData + RowPitch * row + depthPitch * depthSlice;
memcpy(destAddress, srcAddress, std::min(RowPitch, rowSizeInBytes));
}
}
uploadBuffer->Unmap(0, nullptr);
D3D12_TEXTURE_COPY_LOCATION destCopyLocation = {};
destCopyLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
destCopyLocation.SubresourceIndex = subresource;
destCopyLocation.pResource = dest;
D3D12_TEXTURE_COPY_LOCATION srcCopyLocation = {};
srcCopyLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
srcCopyLocation.PlacedFootprint = footprint;
srcCopyLocation.pResource = uploadBuffer;
((ID3D12GraphicsCommandList*)InCmdList)->CopyTextureRegion(&destCopyLocation, 0, 0, 0, &srcCopyLocation, nullptr);
return eComputeStatusOk;
}
ComputeStatus D3D12::clearView(CommandList InCmdList, Resource InResource, const float4 Color, const RECT * pRects, unsigned int NumRects, CLEAR_TYPE &outType)
{
outType = CLEAR_UNDEFINED;
ID3D12Resource *Resource = (ID3D12Resource*) InResource;
ResourceDriverData Data = {};
if (getSurfaceDriverData(Resource, Data) == eComputeStatusOk)
{
auto node = 0; // FIX THIS
CD3DX12_CPU_DESCRIPTOR_HANDLE CPUVisibleCPUHandle = CD3DX12_CPU_DESCRIPTOR_HANDLE(m_heap->descriptorHeapCPU[node]->GetCPUDescriptorHandleForHeapStart(), Data.descIndex, m_descriptorSize);
CD3DX12_GPU_DESCRIPTOR_HANDLE GPUHandle = CD3DX12_GPU_DESCRIPTOR_HANDLE(m_heap->descriptorHeap[node]->GetGPUDescriptorHandleForHeapStart(), Data.descIndex, m_descriptorSize);
((ID3D12GraphicsCommandList*)InCmdList)->ClearUnorderedAccessViewFloat(GPUHandle, CPUVisibleCPUHandle, (ID3D12Resource*)InResource, (const FLOAT*)&Color, NumRects, pRects);
outType = Data.bZBCSupported ? CLEAR_ZBC_WITH_PADDING : CLEAR_NON_ZBC;
return eComputeStatusOk;
}
return eComputeStatusError;
}
ComputeStatus D3D12::insertGPUBarrierList(CommandList InCmdList, const Resource* InResources, unsigned int InResourceCount, BarrierType InBarrierType)
{
if (InBarrierType == BarrierType::eBarrierTypeUAV)
{
std::vector< D3D12_RESOURCE_BARRIER> Barriers;
for (unsigned int i = 0; i < InResourceCount; i++)
{
const Resource& Res = InResources[i];
Barriers.push_back(CD3DX12_RESOURCE_BARRIER::UAV((ID3D12Resource*)Res));
}
((ID3D12GraphicsCommandList*)InCmdList)->ResourceBarrier((UINT)Barriers.size(), Barriers.data());
}
else
{
assert(false);
return eComputeStatusNotSupported;
}
return eComputeStatusOk;
}
ComputeStatus D3D12::insertGPUBarrier(CommandList InCmdList, Resource InResource, BarrierType InBarrierType)
{
if (InBarrierType == BarrierType::eBarrierTypeUAV)
{
D3D12_RESOURCE_BARRIER UAV = CD3DX12_RESOURCE_BARRIER::UAV((ID3D12Resource*)InResource);
((ID3D12GraphicsCommandList*)InCmdList)->ResourceBarrier(1, &UAV);
}
else
{
assert(false);
return eComputeStatusNotSupported;
}
return eComputeStatusOk;
}
ComputeStatus D3D12::transitionResourceImpl(CommandList cmdList, const ResourceTransition *transitions, uint32_t count)
{
if (!cmdList || !transitions)
{
return eComputeStatusInvalidArgument;
}
std::vector<D3D12_RESOURCE_BARRIER> barriers;
while (count--)
{
if (transitions[count].from != transitions[count].to)
{
auto from = toD3D12States(transitions[count].from);
auto to = toD3D12States(transitions[count].to);
//SL_LOG_HINT("%S %s->%s %s->%s", getDebugName(transitions[count].resource).c_str(),d3d12state2str(from).c_str(), d3d12state2str(to).c_str(), state2str(transitions[count].from).c_str(), state2str(transitions[count].to).c_str());
barriers.push_back({ CD3DX12_RESOURCE_BARRIER::Transition((ID3D12Resource*)transitions[count].resource, from, to, transitions[count].subresource) });
}
}
((ID3D12GraphicsCommandList*)cmdList)->ResourceBarrier((uint32_t)barriers.size(), barriers.data());
return eComputeStatusOk;
}
ComputeStatus D3D12::copyResource(CommandList InCmdList, Resource InDstResource, Resource InSrcResource)
{
if (!InCmdList || !InDstResource || !InSrcResource) return eComputeStatusInvalidArgument;
((ID3D12GraphicsCommandList*)InCmdList)->CopyResource((ID3D12Resource*)InDstResource, (ID3D12Resource*)InSrcResource);
return eComputeStatusOk;
}
ComputeStatus D3D12::cloneResource(Resource resource, Resource &clone, const char friendlyName[], ResourceState initialState, unsigned int creationMask, unsigned int visibilityMask)
{
if (!resource) return eComputeStatusInvalidArgument;
D3D12_RESOURCE_DESC desc1 = ((ID3D12Resource*)resource)->GetDesc();
ID3D12Resource *res = nullptr;
CD3DX12_HEAP_PROPERTIES heapProp(D3D12_HEAP_TYPE_DEFAULT, creationMask, visibilityMask ? visibilityMask : m_visibleNodeMask);
if (isSupportedFormat(desc1.Format, 0, D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD | D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE))
{
desc1.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
}
else
{
initialState &= ~ResourceState::eStorageRW;
}
if (isSupportedFormat(desc1.Format, D3D12_FORMAT_SUPPORT1_RENDER_TARGET, 0))
{
desc1.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
}
else
{
initialState &= ~(ResourceState::eColorAttachmentRead | ResourceState::eColorAttachmentWrite);
}
if (isSupportedFormat(desc1.Format, D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL, 0))
{
desc1.Flags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
}
else
{
initialState &= ~(ResourceState::eDepthStencilAttachmentRead | ResourceState::eDepthStencilAttachmentWrite);
}
if (m_allocateCallback)
{
ResourceDesc desc = { desc1.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? ResourceType::eResourceTypeBuffer : ResourceType::eResourceTypeTex2d, &desc1, (uint32_t)initialState, &heapProp, nullptr };
auto result = m_allocateCallback(&desc);
res = (ID3D12Resource*)result.native;
// This will trigger onHostResourceCreated which will set state correctly
}
else
{
HRESULT hr = m_device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT, creationMask, visibilityMask),
D3D12_HEAP_FLAG_NONE,
&desc1,
toD3D12States(initialState),
nullptr,
IID_PPV_ARGS(&res));
if (hr != S_OK)
{
SL_LOG_ERROR(" unable to clone resource");
return eComputeStatusError;
}
// Internal resource, set state
setResourceState(res, initialState);
setDebugName(res, friendlyName);
++m_allocCount;
auto currentSize = getResourceSize(res);
m_totalAllocatedSize += currentSize;
SL_LOG_VERBOSE("Cloning 0x%llx (%s:%u:%u:%s), m_allocCount=%d, currentSize %.1lf MB, totalSize %.1lf MB", res, friendlyName, desc1.Width, desc1.Height, getDXGIFormatStr(desc1.Format), m_allocCount.load(), (double)currentSize / (1024 * 1024), (double)m_totalAllocatedSize.load() / (1024 * 1024));
}
clone = res;
return eComputeStatusOk;
}
ComputeStatus D3D12::copyBufferToReadbackBuffer(CommandList InCmdList, Resource InResource, Resource OutResource, unsigned int InBytesToCopy)
{
ID3D12Resource *InD3dResource = (ID3D12Resource*)InResource;
ID3D12Resource *OutD3dResource = (ID3D12Resource*)OutResource;
ID3D12GraphicsCommandList* CmdList = (ID3D12GraphicsCommandList*)InCmdList;
#if 0
ResourceDescription ResourceDesc;
GetResourceDescription(OutResource, ResourceDesc);
const size_t readbackBufferSize = ResourceDesc.Width;
D3D12_RANGE readbackBufferRange{ 0, readbackBufferSize };
FLOAT * pReadbackBufferData{};
OutD3dResource->Map(0, &readbackBufferRange, reinterpret_cast<void**>(&pReadbackBufferData));
memset(pReadbackBufferData, 0xAA, readbackBufferSize);
D3D12_RANGE emptyRange{ 0, 0 };
OutD3dResource->Unmap(0, &emptyRange);
#endif
CmdList->CopyBufferRegion(OutD3dResource, 0, InD3dResource, 0, InBytesToCopy);
return eComputeStatusOk;
}
ComputeStatus D3D12::getLUIDFromDevice(NVSDK_NGX_LUID *OutId)
{
memcpy(OutId, &(m_device->GetAdapterLuid()), sizeof(LUID));
return eComputeStatusOk;
}
ComputeStatus D3D12::beginPerfSection(CommandList cmdList, const char *key, unsigned int node, bool reset)
{
#ifndef SL_PRODUCTION
PerfData* data = {};
{
std::lock_guard<std::mutex> lock(m_mutex);
auto section = m_sectionPerfMap[node].find(key);
if (section == m_sectionPerfMap[node].end())
{
m_sectionPerfMap[node][key] = {};
section = m_sectionPerfMap[node].find(key);
}
data = &(*section).second;
}
if (reset)
{
for (int i = 0; i < SL_READBACK_QUEUE_SIZE; i++)
{
data->reset[i] = true;
}
data->values.clear();
}
if (!data->queryHeap[data->queryIdx])
{
D3D12_QUERY_HEAP_DESC queryHeapDesc = {};
queryHeapDesc.Count = 2;
queryHeapDesc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
queryHeapDesc.NodeMask = (1 << node);
m_device->CreateQueryHeap(&queryHeapDesc, __uuidof(ID3D12QueryHeap), (void **)&data->queryHeap[data->queryIdx]);
D3D12_RESOURCE_DESC bufferDesc = {};
bufferDesc.MipLevels = 1;
bufferDesc.Format = DXGI_FORMAT_UNKNOWN;
bufferDesc.Width = 2 * sizeof(uint64_t);
bufferDesc.Height = 1;
bufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
bufferDesc.DepthOrArraySize = 1;
bufferDesc.SampleDesc.Count = 1;
bufferDesc.SampleDesc.Quality = 0;
bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
D3D12_RESOURCE_STATES initialState = D3D12_RESOURCE_STATE_COPY_DEST;
m_device->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_READBACK, queryHeapDesc.NodeMask, queryHeapDesc.NodeMask), D3D12_HEAP_FLAG_NONE, &bufferDesc, initialState, nullptr, IID_PPV_ARGS(&data->queryBufferReadback[data->queryIdx]));
}
else
{
((ID3D12GraphicsCommandList*)cmdList)->ResolveQueryData(data->queryHeap[data->queryIdx], D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, data->queryBufferReadback[data->queryIdx], 0);
UINT8* pStagingPtr = nullptr;
uint64_t dxNanoSecondTS[2];
D3D12_RANGE mapRange = { 0, sizeof(uint64_t) * 2 };
data->queryBufferReadback[data->queryIdx]->Map(0, &mapRange, reinterpret_cast<void**>(&pStagingPtr));
if (pStagingPtr)
{
dxNanoSecondTS[0] = ((uint64_t*)pStagingPtr)[0];
dxNanoSecondTS[1] = ((uint64_t*)pStagingPtr)[1];
data->queryBufferReadback[data->queryIdx]->Unmap(0, NULL);
float delta = (dxNanoSecondTS[1] - dxNanoSecondTS[0]) / 1e06f;
if (!data->reset[data->queryIdx])
{
if (delta > 0)
{
// Average over last N executions
if (data->values.size() == 100)
{
data->accumulatedTimeMS -= data->values.front();
data->values.erase(data->values.begin());
}
data->accumulatedTimeMS += delta;
data->values.push_back(delta);
}
}
else
{
data->reset[data->queryIdx] = false;
data->accumulatedTimeMS = 0;
data->values.clear();
}
}
else
{
data->reset[data->queryIdx] = false;
data->accumulatedTimeMS = 0;
data->values.clear();
}
}
((ID3D12GraphicsCommandList*)cmdList)->EndQuery(data->queryHeap[data->queryIdx], D3D12_QUERY_TYPE_TIMESTAMP, 0);
#endif
return eComputeStatusOk;
}
ComputeStatus D3D12::endPerfSection(CommandList cmdList, const char* key, float &avgTimeMS, unsigned int node)
{
#ifndef SL_PRODUCTION
PerfData* data = {};
{
std::lock_guard<std::mutex> lock(m_mutex);
auto section = m_sectionPerfMap[node].find(key);
if (section == m_sectionPerfMap[node].end())
{
return eComputeStatusError;
}
data = &(*section).second;
}
((ID3D12GraphicsCommandList*)cmdList)->EndQuery(data->queryHeap[data->queryIdx], D3D12_QUERY_TYPE_TIMESTAMP, 1);
data->queryIdx = (data->queryIdx + 1) % SL_READBACK_QUEUE_SIZE;
avgTimeMS = data->values.size() ? data->accumulatedTimeMS / (float)data->values.size() : 0;
#else
avgTimeMS = 0;
#endif
return eComputeStatusOk;
}
#if SL_ENABLE_PERF_TIMING
ComputeStatus D3D12::beginProfiling(CommandList cmdList, unsigned int Metadata, const void *pData, unsigned int Size)
{
std::string test(static_cast<const char*>(pData), Size);
//std::string test = "test";
((ID3D12GraphicsCommandList*)cmdList)->BeginEvent(1, test.c_str(), (UINT)test.size());
return eComputeStatusOk;
}
ComputeStatus D3D12::endProfiling(CommandList cmdList)
{
((ID3D12GraphicsCommandList*)cmdList)->EndEvent();
return eComputeStatusOk;
}
#endif
ComputeStatus D3D12::dumpResource(CommandList cmdList, Resource src, const char *path)
{
ResourceDescription srcDesc;
CHI_CHECK(getResourceDescription(src, srcDesc));
ResourceReadbackQueue* rrq = {};
{
std::lock_guard<std::mutex> lock(m_mutex);
auto it = m_readbackMap.find(src);
if (it == m_readbackMap.end())
{
m_readbackMap[src] = {};
rrq = &m_readbackMap[src];
}
else
{
rrq = &(*it).second;
}
}
uint32_t bytes = 3 * sizeof(float) * srcDesc.width * srcDesc.height;
if (rrq->readback[rrq->index])
{
for (auto i = m_readbackThreads.begin(); i != m_readbackThreads.end(); i++)
{
if ((*i).wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
i = m_readbackThreads.erase(i);
if (i == m_readbackThreads.end()) break;
}
}
ID3D12Resource *res = (ID3D12Resource*)rrq->readback[rrq->index];
void *data;
D3D12_RANGE range{ 0, bytes };
res->Map(0, &range, &data);
if (!data)
{
SL_LOG_ERROR("Failed to map readback resource");
}
else
{
std::vector<char> pixels(bytes);
memcpy(pixels.data(), data, bytes);
res->Unmap(0, nullptr);
std::string fpath(path);
m_readbackThreads.push_back(std::async(std::launch::async, [this, srcDesc, pixels, fpath]()->bool
{
return savePFM(fpath, pixels.data(), srcDesc.width, srcDesc.height);
}));
}
}
else
{
if(!rrq->target)
{
ResourceDescription desc(bytes, 1, chi::eFormatINVALID,HeapType::eHeapTypeDefault,ResourceState::eStorageRW,ResourceFlags::eRawOrStructuredBuffer);
CHI_CHECK(createBuffer(desc, rrq->target, (std::string("chi.target.") + std::to_string((size_t)src)).c_str()));
}
ResourceDescription desc(bytes, 1, chi::eFormatINVALID, chi::eHeapTypeReadback, chi::ResourceState::eCopyDestination);
CHI_CHECK(createBuffer(desc, rrq->readback[rrq->index], (std::string("chi.readback.") + std::to_string((size_t)src) + "." + std::to_string(rrq->index)).c_str()));
}
{
extra::ScopedTasks revTransitions;
chi::ResourceTransition transitions[] =
{
{src, chi::ResourceState::eTextureRead, srcDesc.state},
};
CHI_CHECK(transitionResources(cmdList, transitions, (uint32_t)countof(transitions), &revTransitions));
struct alignas(16) CopyDataCB
{
sl::float4 sizeAndInvSize;
};
CopyDataCB cb;
cb.sizeAndInvSize = { (float)srcDesc.width, (float)srcDesc.height, 1.0f / (float)srcDesc.width, 1.0f / (float)srcDesc.height };
CHI_CHECK(bindKernel(m_copyKernel));
CHI_CHECK(bindConsts(0, 0, &cb, sizeof(CopyDataCB), 3));
CHI_CHECK(bindTexture(1, 0, src));
CHI_CHECK(bindRawBuffer(2, 0, rrq->target));
uint32_t grid[] = { (srcDesc.width + 16 - 1) / 16, (srcDesc.height + 16 - 1) / 16, 1 };
CHI_CHECK(dispatch(grid[0], grid[1], grid[2]));
}
{
extra::ScopedTasks revTransitions;
chi::ResourceTransition transitions[] =
{
{rrq->target, chi::ResourceState::eCopySource, chi::ResourceState::eStorageRW},
{rrq->readback[rrq->index], chi::ResourceState::eCopyDestination, chi::ResourceState::eStorageRW},
};
CHI_CHECK(transitionResources(cmdList, transitions, (uint32_t)countof(transitions), &revTransitions));
CHI_CHECK(copyResource(cmdList, rrq->readback[rrq->index], rrq->target));
}
rrq->index = (rrq->index + 1) % SL_READBACK_QUEUE_SIZE;
return eComputeStatusOk;
}
void D3D12::destroyResourceDeferredImpl(const Resource resource)
{
auto unknown = (IUnknown*)resource;
ID3D12Pageable* pageable;
unknown->QueryInterface(&pageable);
uint64_t currentSize = 0;
if (pageable)
{
pageable->Release();
if (m_allocCount && m_totalAllocatedSize)
{
m_allocCount--;
currentSize = getResourceSize(resource);
if (m_totalAllocatedSize >= currentSize)
{
m_totalAllocatedSize -= currentSize;
}
}
}
auto name = getDebugName((ID3D12Resource*)resource);
auto ref = ((IUnknown*)resource)->Release();
SL_LOG_VERBOSE("Releasing resource 0x%llx (%S) ref count %u - currentSize %.2f - totalSize %.2f", resource, name.c_str(), ref, currentSize / (1024.0f * 1024.0f), m_totalAllocatedSize / (1024.0f * 1024.0f));
}
DXGI_FORMAT D3D12::getCorrectFormat(DXGI_FORMAT Format)
{
switch (Format)
{
case DXGI_FORMAT_D16_UNORM: // casting from non typeless is supported from RS2+
assert(m_dbgSupportRs2RelaxedConversionRules);
return DXGI_FORMAT_R16_UNORM;
case DXGI_FORMAT_D32_FLOAT: // casting from non typeless is supported from RS2+
assert(m_dbgSupportRs2RelaxedConversionRules); // fallthrough
case DXGI_FORMAT_R32_TYPELESS:
return DXGI_FORMAT_R32_FLOAT;
case DXGI_FORMAT_R16G16B16A16_TYPELESS:
return DXGI_FORMAT_R16G16B16A16_FLOAT;
case DXGI_FORMAT_R32G32B32A32_TYPELESS:
return DXGI_FORMAT_R32G32B32A32_FLOAT;
case DXGI_FORMAT_R32G32_TYPELESS:
return DXGI_FORMAT_R32G32_FLOAT;
case DXGI_FORMAT_R16G16_TYPELESS:
return DXGI_FORMAT_R16G16_FLOAT;
case DXGI_FORMAT_R16_TYPELESS:
return DXGI_FORMAT_R16_FLOAT;
case DXGI_FORMAT_R8G8B8A8_TYPELESS:
return DXGI_FORMAT_R8G8B8A8_UNORM;
case DXGI_FORMAT_B8G8R8X8_TYPELESS:
return DXGI_FORMAT_B8G8R8X8_UNORM;
case DXGI_FORMAT_B8G8R8A8_TYPELESS:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case DXGI_FORMAT_R10G10B10A2_TYPELESS:
return DXGI_FORMAT_R10G10B10A2_UNORM;
case DXGI_FORMAT_D24_UNORM_S8_UINT: // casting from non typeless is supported from RS2+
assert(m_dbgSupportRs2RelaxedConversionRules); // fallthrough
case DXGI_FORMAT_R24G8_TYPELESS:
return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: // casting from non typeless is supported from RS2+
assert(m_dbgSupportRs2RelaxedConversionRules); // fallthrough
case DXGI_FORMAT_R32G8X24_TYPELESS:
return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
default:
return Format;
};
}
// {694B3E1C-0E33-416F-BA83-FE248DA1E85D}
static const GUID sResourceStateGUID = { 0x694b3e1c, 0xe33, 0x416f, { 0xba, 0x83, 0xfe, 0x24, 0x8d, 0xa1, 0xe8, 0x5d } };
ComputeStatus D3D12::onHostResourceCreated(Resource resource, const ResourceInfo& info)
{
{
std::lock_guard<std::mutex> lock(m_mutex);
// If we have this resource in cache then it is stale since MS just created a new one with recycled pointer
auto it = m_resourceData.find(resource);
if (it != m_resourceData.end())
{
auto name = getDebugName((ID3D12Resource*)resource);
SL_LOG_VERBOSE("Detected stale resource 0x%llx(%S) - removing from cache", resource, name.c_str());
m_resourceData.erase(it);
}
}
setResourceState(resource, info.desc.state);
// Not calling generic method since we already locked on mutex
//m_resourceStateMap[resource] = info;
return eComputeStatusOk;
}
ComputeStatus D3D12::setResourceState(Resource resource, ResourceState state, uint32_t subresource)
{
if (!resource)
{
return eComputeStatusOk;
}
ID3D12Pageable* pageable = {};
((IUnknown*)resource)->QueryInterface(&pageable);
if (pageable)
{
if (FAILED(pageable->SetPrivateData(sResourceStateGUID, sizeof(state), &state)))
{
SL_LOG_ERROR("Failed to set state for resource 0x%llx", resource);
}
pageable->Release();
}
return eComputeStatusOk;
}
ComputeStatus D3D12::getResourceState(Resource resource, ResourceState& state)
{
if (!resource)
{
state = ResourceState::eUnknown;
return eComputeStatusOk;
}
state = ResourceState::eGeneral;
ID3D12Pageable* pageable = {};
((IUnknown*)resource)->QueryInterface(&pageable);
if (pageable)
{
uint32_t size = sizeof(state);
if (FAILED(pageable->GetPrivateData(sResourceStateGUID, &size, &state)))
{
SL_LOG_ERROR("resource 0x%llx does not have a state", resource);
return eComputeStatusInvalidArgument;
}
pageable->Release();
}
return eComputeStatusOk;
}
ComputeStatus D3D12::getResourceDescription(Resource resource, ResourceDescription& outDesc)
{
if (!resource) return eComputeStatusInvalidArgument;
// First make sure this is not an DXGI or some other resource
auto unknown = (IUnknown*)resource;
ID3D12Resource* pageable;
unknown->QueryInterface(&pageable);
if (!pageable)
{
return eComputeStatusError;
}
D3D12_RESOURCE_DESC desc = ((ID3D12Resource*)resource)->GetDesc();
outDesc = {};
outDesc.format = eFormatINVALID;
outDesc.width = (UINT)desc.Width;
outDesc.height = desc.Height;
outDesc.nativeFormat = desc.Format;
outDesc.mips = desc.MipLevels;
if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER)
{
outDesc.gpuVirtualAddress = pageable->GetGPUVirtualAddress();
outDesc.flags |= ResourceFlags::eRawOrStructuredBuffer | ResourceFlags::eConstantBuffer;
}
else
{
outDesc.flags |= ResourceFlags::eShaderResource;
}
if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)
{
outDesc.flags |= ResourceFlags::eShaderResourceStorage;
}
uint32_t size = sizeof(outDesc.state);
if (FAILED(pageable->GetPrivateData(sResourceStateGUID, &size, &outDesc.state)))
{
std::wstring name = getDebugName(resource);
SL_LOG_ERROR("resource 0x%llx(%S) does not have a state", resource, name.c_str());
return eComputeStatusInvalidArgument;
}
pageable->Release();
return eComputeStatusOk;
}
}
}
|
/**
* TemplateConverter.cpp
*
* Created on: 2015/08/01
* Author: vagrant
*/
#include "boost/regex.hpp"
#include "TemplateConverter.h"
TemplateConverter::TemplateConverter() : className_("") {
}
TemplateConverter::TemplateConverter(std::string className) : className_(className){
}
TemplateConverter::~TemplateConverter() {
}
std::string TemplateConverter::convert(const std::string targetString) {
boost::regex r;
r.assign( "#{CLASS}" );
return boost::regex_replace(targetString, r, className_);
}
|
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkMipMap.h"
#include "SkBitmap.h"
#include "SkColorPriv.h"
static void downsampleby2_proc32(SkBitmap* dst, int x, int y,
const SkBitmap& src) {
x <<= 1;
y <<= 1;
const SkPMColor* p = src.getAddr32(x, y);
const SkPMColor* baseP = p;
SkPMColor c, ag, rb;
c = *p; ag = (c >> 8) & 0xFF00FF; rb = c & 0xFF00FF;
if (x < src.width() - 1) {
p += 1;
}
c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
p = baseP;
if (y < src.height() - 1) {
p += src.rowBytes() >> 2;
}
c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
if (x < src.width() - 1) {
p += 1;
}
c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
*dst->getAddr32(x >> 1, y >> 1) =
((rb >> 2) & 0xFF00FF) | ((ag << 6) & 0xFF00FF00);
}
static inline uint32_t expand16(U16CPU c) {
return (c & ~SK_G16_MASK_IN_PLACE) | ((c & SK_G16_MASK_IN_PLACE) << 16);
}
// returns dirt in the top 16bits, but we don't care, since we only
// store the low 16bits.
static inline U16CPU pack16(uint32_t c) {
return (c & ~SK_G16_MASK_IN_PLACE) | ((c >> 16) & SK_G16_MASK_IN_PLACE);
}
static void downsampleby2_proc16(SkBitmap* dst, int x, int y,
const SkBitmap& src) {
x <<= 1;
y <<= 1;
const uint16_t* p = src.getAddr16(x, y);
const uint16_t* baseP = p;
SkPMColor c;
c = expand16(*p);
if (x < src.width() - 1) {
p += 1;
}
c += expand16(*p);
p = baseP;
if (y < src.height() - 1) {
p += src.rowBytes() >> 1;
}
c += expand16(*p);
if (x < src.width() - 1) {
p += 1;
}
c += expand16(*p);
*dst->getAddr16(x >> 1, y >> 1) = (uint16_t)pack16(c >> 2);
}
static uint32_t expand4444(U16CPU c) {
return (c & 0xF0F) | ((c & ~0xF0F) << 12);
}
static U16CPU collaps4444(uint32_t c) {
return (c & 0xF0F) | ((c >> 12) & ~0xF0F);
}
static void downsampleby2_proc4444(SkBitmap* dst, int x, int y,
const SkBitmap& src) {
x <<= 1;
y <<= 1;
const uint16_t* p = src.getAddr16(x, y);
const uint16_t* baseP = p;
uint32_t c;
c = expand4444(*p);
if (x < src.width() - 1) {
p += 1;
}
c += expand4444(*p);
p = baseP;
if (y < src.height() - 1) {
p += src.rowBytes() >> 1;
}
c += expand4444(*p);
if (x < src.width() - 1) {
p += 1;
}
c += expand4444(*p);
*dst->getAddr16(x >> 1, y >> 1) = (uint16_t)collaps4444(c >> 2);
}
SkMipMap::Level* SkMipMap::AllocLevels(int levelCount, size_t pixelSize) {
if (levelCount < 0) {
return NULL;
}
int64_t size = sk_64_mul(levelCount + 1, sizeof(Level)) + pixelSize;
if (!sk_64_isS32(size)) {
return NULL;
}
return (Level*)sk_malloc_throw(sk_64_asS32(size));
}
SkMipMap* SkMipMap::Build(const SkBitmap& src) {
void (*proc)(SkBitmap* dst, int x, int y, const SkBitmap& src);
const SkBitmap::Config config = src.config();
switch (config) {
case SkBitmap::kARGB_8888_Config:
proc = downsampleby2_proc32;
break;
case SkBitmap::kRGB_565_Config:
proc = downsampleby2_proc16;
break;
case SkBitmap::kARGB_4444_Config:
proc = downsampleby2_proc4444;
break;
case SkBitmap::kIndex8_Config:
case SkBitmap::kA8_Config:
default:
return NULL; // don't build mipmaps for these configs
}
SkAutoLockPixels alp(src);
if (!src.readyToDraw()) {
return NULL;
}
// whip through our loop to compute the exact size needed
size_t size = 0;
int countLevels = 0;
{
int width = src.width();
int height = src.height();
for (;;) {
width >>= 1;
height >>= 1;
if (0 == width || 0 == height) {
break;
}
size += SkBitmap::ComputeRowBytes(config, width) * height;
countLevels += 1;
}
}
if (0 == countLevels) {
return NULL;
}
Level* levels = SkMipMap::AllocLevels(countLevels, size);
if (NULL == levels) {
return NULL;
}
uint8_t* baseAddr = (uint8_t*)&levels[countLevels];
uint8_t* addr = baseAddr;
int width = src.width();
int height = src.height();
uint32_t rowBytes;
SkBitmap srcBM(src);
for (int i = 0; i < countLevels; ++i) {
width >>= 1;
height >>= 1;
rowBytes = SkToU32(SkBitmap::ComputeRowBytes(config, width));
levels[i].fPixels = addr;
levels[i].fWidth = width;
levels[i].fHeight = height;
levels[i].fRowBytes = rowBytes;
levels[i].fScale = (float)width / src.width();
SkBitmap dstBM;
dstBM.setConfig(config, width, height, rowBytes);
dstBM.setPixels(addr);
srcBM.lockPixels();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
proc(&dstBM, x, y, srcBM);
}
}
srcBM.unlockPixels();
srcBM = dstBM;
addr += height * rowBytes;
}
SkASSERT(addr == baseAddr + size);
return SkNEW_ARGS(SkMipMap, (levels, countLevels, size));
}
///////////////////////////////////////////////////////////////////////////////
//static int gCounter;
SkMipMap::SkMipMap(Level* levels, int count, size_t size)
: fSize(size), fLevels(levels), fCount(count) {
SkASSERT(levels);
SkASSERT(count > 0);
// SkDebugf("mips %d\n", ++gCounter);
}
SkMipMap::~SkMipMap() {
sk_free(fLevels);
// SkDebugf("mips %d\n", --gCounter);
}
static SkFixed compute_level(SkScalar scale) {
SkFixed s = SkAbs32(SkScalarToFixed(SkScalarInvert(scale)));
if (s < SK_Fixed1) {
return 0;
}
int clz = SkCLZ(s);
SkASSERT(clz >= 1 && clz <= 15);
return SkIntToFixed(15 - clz) + ((unsigned)(s << (clz + 1)) >> 16);
}
bool SkMipMap::extractLevel(SkScalar scale, Level* levelPtr) const {
if (scale >= SK_Scalar1) {
return false;
}
int level = compute_level(scale) >> 16;
SkASSERT(level >= 0);
if (level <= 0) {
return false;
}
if (level > fCount) {
level = fCount;
}
if (levelPtr) {
*levelPtr = fLevels[level - 1];
}
return true;
}
|
//===========================================================================//
// Purpose : Method definitions for the TOS_RouteOptions class.
//
// Public methods include:
// - TOS_RouteOptions_c, ~TOS_RouteOptions_c
// - Print
//
//===========================================================================//
//---------------------------------------------------------------------------//
// Copyright (C) 2012 Jeff Rudolph, Texas Instruments (jrudolph@ti.com) //
// //
// 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; version 3 of the License, or any later version. //
// //
// This program is distributed in the hope that it will be useful, but //
// WITHOUT ANY WARRANTY; without even an 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 "TC_MinGrid.h"
#include "TIO_PrintHandler.h"
#include "TOS_StringUtils.h"
#include "TOS_RouteOptions.h"
//===========================================================================//
// Method : TOS_RouteOptions_c
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 05/01/12 jeffr : Original
//===========================================================================//
TOS_RouteOptions_c::TOS_RouteOptions_c(
void )
:
algorithmMode( TOS_ROUTE_ALGORITHM_UNDEFINED ),
abstractMode( TOS_ROUTE_ABSTRACT_UNDEFINED ),
windowSize( 0 ),
channelWidth( 0 ),
maxIterations( 0 ),
histCongestionFactor( 0.0 ),
initCongestionFactor( 0.0 ),
presentCongestionFactor( 0.0 ),
bendCostFactor( 0.0 ),
resourceMode( TOS_ROUTE_RESOURCE_UNDEFINED ),
costMode( TOS_ROUTE_COST_UNDEFINED ),
fixedDelay( 0.0 ),
timingAStarFactor( 0.0 ),
timingMaxCriticality( 0.0 ),
slackCriticality( 0.0 )
{
}
//===========================================================================//
TOS_RouteOptions_c::TOS_RouteOptions_c(
TOS_RouteAlgorithmMode_t algorithmMode_,
TOS_RouteAbstractMode_t abstractMode_,
unsigned int windowSize_,
unsigned int channelWidth_,
unsigned int maxIterations_,
double histCongestionFactor_,
double initCongestionFactor_,
double presentCongestionFactor_,
double bendCostFactor_,
TOS_RouteResourceMode_t resourceMode_,
TOS_RouteCostMode_t costMode_,
double timingAStarFactor_,
double timingMaxCriticality_,
double slackCriticality_ )
:
algorithmMode( algorithmMode_ ),
abstractMode( abstractMode_ ),
windowSize( windowSize_ ),
channelWidth( channelWidth_ ),
maxIterations( maxIterations_ ),
histCongestionFactor( histCongestionFactor_ ),
initCongestionFactor( initCongestionFactor_ ),
presentCongestionFactor( presentCongestionFactor_ ),
bendCostFactor( bendCostFactor_ ),
resourceMode( resourceMode_ ),
costMode( costMode_ ),
fixedDelay( 0.0 ),
timingAStarFactor( timingAStarFactor_ ),
timingMaxCriticality( timingMaxCriticality_ ),
slackCriticality( slackCriticality_ )
{
}
//===========================================================================//
// Method : ~TOS_RouteOptions_c
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 05/01/12 jeffr : Original
//===========================================================================//
TOS_RouteOptions_c::~TOS_RouteOptions_c(
void )
{
}
//===========================================================================//
// Method : Print
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 05/01/12 jeffr : Original
//===========================================================================//
void TOS_RouteOptions_c::Print(
FILE* pfile,
size_t spaceLen ) const
{
TC_MinGrid_c& MinGrid = TC_MinGrid_c::GetInstance( );
unsigned int precision = MinGrid.GetPrecision( );
TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( );
string srAlgorithmMode, srAbstractMode, srResourceMode, srCostMode;
TOS_ExtractStringRouteAlgorithmMode( this->algorithmMode, &srAlgorithmMode );
TOS_ExtractStringRouteAbstractMode( this->abstractMode, &srAbstractMode );
TOS_ExtractStringRouteResourceMode( this->resourceMode, &srResourceMode );
TOS_ExtractStringRouteCostMode( this->costMode, &srCostMode );
printHandler.Write( pfile, spaceLen, "ROUTE_ALGORITHM = %s\n", TIO_SR_STR( srAlgorithmMode ));
printHandler.Write( pfile, spaceLen, "ROUTE_TYPE = %s\n", TIO_SR_STR( srAbstractMode ));
printHandler.Write( pfile, spaceLen, "ROUTE_WINDOW_SIZE = %u\n", this->windowSize );
printHandler.Write( pfile, spaceLen, "ROUTE_CHANNEL_WIDTH = %u\n", this->channelWidth );
printHandler.Write( pfile, spaceLen, "ROUTE_MAX_ITERATIONS = %u\n", this->maxIterations );
printHandler.Write( pfile, spaceLen, "ROUTE_CONG_HIST_FACTOR = %0.*f\n", precision, this->histCongestionFactor );
printHandler.Write( pfile, spaceLen, "ROUTE_CONG_INIT_FACTOR = %0.*f\n", precision, this->initCongestionFactor );
printHandler.Write( pfile, spaceLen, "ROUTE_CONG_PRESENT_FACTOR = %0.*f\n", precision, this->presentCongestionFactor );
printHandler.Write( pfile, spaceLen, "ROUTE_BEND_COST_FACTOR = %0.*f\n", precision, this->bendCostFactor );
printHandler.Write( pfile, spaceLen, "ROUTE_RESOURCE_COST_MODE = %s\n", TIO_SR_STR( srResourceMode ));
printHandler.Write( pfile, spaceLen, "ROUTE_COST_MODE = %s\n", TIO_SR_STR( srCostMode ));
printHandler.Write( pfile, spaceLen, "ROUTE_TIMING_ASTAR_FACTOR = %0.*f\n", precision, this->timingAStarFactor );
printHandler.Write( pfile, spaceLen, "ROUTE_TIMING_MAX_CRIT = %0.*f\n", precision, this->timingMaxCriticality );
printHandler.Write( pfile, spaceLen, "ROUTE_TIMING_SLACK_CRIT = %0.*f\n", precision, this->slackCriticality );
}
|
#include "static_assert.h"
#include "nodemurmurhash.h"
#include "MurmurHash2.h"
#include "PMurHash.h"
#include "PMurHash128.h"
#include "murmurhashutils.h"
#include "inputdata.h"
#include "asyncworker.h"
NAN_INLINE void MurmurHash2_x64_64 (
const void * key, int len, uint32_t seed, void * out)
{
*(uint64_t *)out = MurmurHash64A( key, len, (uint64_t) seed );
}
NAN_INLINE void MurmurHash2_x86_64 (
const void * key, int len, uint32_t seed, void * out)
{
*(uint64_t *)out = MurmurHash64B( key, len, (uint64_t) seed );
}
namespace MurmurHash {
using v8::Object;
using v8::Uint32;
using v8::Function;
using v8::PropertyAttribute;
using v8::ReadOnly;
using v8::DontDelete;
#define GET_ARG_OFFSET(INFO,INDEX,ARGC) \
((INDEX) + 1 < (ARGC) \
? Nan::To<int32_t>((INFO)[(INDEX) + 1]).FromMaybe(0) \
: 0)
#define GET_ARG_LENGTH(INFO,INDEX,ARGC,DEF) \
((INDEX) + 2 < (ARGC) \
? Nan::To<int32_t>((INFO)[(INDEX) + 2]).FromMaybe(DEF) \
: (DEF))
/**
* Calculate MurmurHash from data
*
* murmurHash(data[, callback])
* murmurHash(data, output[, offset[, length]][, callback])
* murmurHash(data{String}, encoding|output_type[, callback])
* murmurHash(data, output_type[, seed][, callback])
* murmurHash(data, seed[, output[, offset[, length]]][, callback])
* murmurHash(data, seed[, output_type][, callback])
* murmurHash(data, encoding, output_type[, callback])
* murmurHash(data{String}, encoding, output[, offset[, length]][, callback])
* murmurHash(data{String}, encoding, seed[, output[, offset[, length]]][, callback])
* murmurHash(data{String}, encoding, seed[, output_type][, callback])
*
* @param {string|Buffer} data - a byte-string to calculate hash from
* @param {string} encoding - data string encoding, should be:
* 'utf8', 'ucs2', 'ascii', 'hex', 'base64' or 'binary';
* 'binary' by default
* @param {Uint32} seed - murmur hash seed, 0 by default
* @param {Buffer} output - a Buffer object to write hash bytes to;
* the same object will be returned
* @param {number} offset - start writing into output at offset byte;
* negative offset starts from the end of the output buffer
* @param {number} length - a number of bytes to write from calculated hash;
* negative length starts from the end of the hash;
* if absolute value of length is larger than the size of calculated
* hash, bytes are written only up to the hash size
* @param {string} output_type - a string indicating return type:
* 'number' - for murmurHash32 an unsigned 32-bit integer,
* other hashes - hexadecimal string
* 'hex' - hexadecimal string
* 'base64' - base64 string
* 'binary' - binary string
* 'buffer' - a new Buffer object;
* 'number' by default
* @param {Function} callback - optional callback(err, result)
* if provided the hash will be calculated asynchronously using libuv
* worker queue, the return value in this instance will be `undefined`
* and the result will be provided to the callback function;
* Be carefull as reading and writing by multiple threads to the same
* memory may render undetermined results
*
* The order of bytes written to a Buffer or encoded string depends on
* function's endianness.
*
* `data` and `output` arguments might reference the same Buffer object
* or buffers referencing the same memory (views).
*
* @return {number|Buffer|String|undefined}
**/
template<MurmurHashFunctionType HashFunction, typename HashValueType, int32_t HashLength, ByteOrderType OutputByteOrder>
NAN_METHOD(MurmurHash)
{
STATIC_ASSERT((HashSize & 0x1c) && (HashSize|(HashSize-1))+1 == HashSize<<1, "HashSize is not 4, 8 or 16");
InputData data;
OutputType outputType( DefaultOutputType );
uint32_t seed = 0;
/* parse args */
int argc = std::min( 7, info.Length() );
int outputTypeIndex = argc;
int callbackIndex = -1;
bool validEncoding = true;
enum Nan::Encoding encoding = Nan::BUFFER;
if ( argc > 0 && info[argc - 1]->IsFunction() ) {
callbackIndex = --argc;
}
if ( argc > 0 ) {
if ( info[0]->IsString() ) {
encoding = Nan::BINARY;
}
if ( argc >= 2 ) {
if ( info[1]->IsString() ) { // input_encoding or output_type
if ( argc == 2 ) { // try output_type
InputData::ReadEncodingString( info[1].As<String>() );
outputType = InputData::DetermineOutputType();
switch(outputType) {
case HexStringOutputType:
case BinaryStringOutputType:
case Base64StringOutputType:
// ambiguous if input is string
case UnknownOutputType: // input_encoding
if (encoding != Nan::BUFFER) {
validEncoding = InputData::DetermineEncoding( encoding );
outputType = DefaultOutputType; // revert to default
}
break;
default:
void(0); // unambiguous - "number" or "buffer"
}
} else if (encoding == Nan::BUFFER) { // output_type
if ( info[2]->IsNumber() ) {
InputData::ReadEncodingString( info[1].As<String>() );
seed = Nan::To<uint32_t>(info[2]).FromMaybe(0U);
} else if ( info[2]->IsString() ) {
InputData::ReadEncodingString( info[2].As<String>() );
} else {
InputData::ReadEncodingString( info[1].As<String>() );
}
outputType = InputData::DetermineOutputType();
} else { // try input_encoding
InputData::ReadEncodingString( info[1].As<String>() );
if ( !(validEncoding = InputData::DetermineEncoding( encoding )) ) {
outputType = InputData::DetermineOutputType(); // try output_type
if (outputType == UnknownOutputType) {
outputType = DefaultOutputType;
} else {
validEncoding = true;
if ( info[2]->IsNumber() ) seed = Nan::To<uint32_t>(info[2]).FromMaybe(0U);
}
}
outputTypeIndex = 2; // continue from 2
}
} else {
// output or seed
if ( node::Buffer::HasInstance(info[1]) ) {
outputType = ProvidedBufferOutputType;
outputTypeIndex = 1;
} else {
if ( info[1]->IsNumber() ) seed = Nan::To<uint32_t>(info[1]).FromMaybe(0U);
outputTypeIndex = 2; // continue from 2
}
}
if ( outputType == DefaultOutputType ) { // output_type or output or seed
for (; outputTypeIndex < argc; ++outputTypeIndex ) {
if ( info[outputTypeIndex]->IsNumber() ) {
seed = Nan::To<uint32_t>(info[outputTypeIndex]).FromMaybe(0U);
} else if ( info[outputTypeIndex]->IsString() ) {
InputData::ReadEncodingString( info[outputTypeIndex].As<String>() );
outputType = InputData::DetermineOutputType();
break;
} else if ( node::Buffer::HasInstance(info[outputTypeIndex]) ) {
outputType = ProvidedBufferOutputType;
break;
} else
break;
}
}
}
}
if ( callbackIndex > -1 ) {
MurmurHashWorker<HashFunction,HashValueType,HashLength,OutputByteOrder> *asyncWorker;
Nan::Callback *callback = new Nan::Callback(
Local<Function>::Cast(info[callbackIndex]));
if ( argc > 0 ) {
asyncWorker = new MurmurHashWorker<HashFunction,HashValueType,HashLength,OutputByteOrder>(
callback, outputType, seed, info[0], encoding, validEncoding);
} else {
asyncWorker = new MurmurHashWorker<HashFunction,HashValueType,HashLength,OutputByteOrder>(callback);
}
if (outputType == ProvidedBufferOutputType) {
asyncWorker->SaveOutputBuffer(
info[outputTypeIndex],
GET_ARG_OFFSET(info, outputTypeIndex, argc),
GET_ARG_LENGTH(info, outputTypeIndex, argc, HashSize));
}
Nan::AsyncQueueWorker(asyncWorker);
info.GetReturnValue().Set(Nan::Undefined());
} else {
if ( argc > 0 ) {
data.Setup( info[0], encoding, validEncoding );
}
if ( ! data.IsValid() )
return Nan::ThrowTypeError(data.Error());
Local<Value> result;
HashValueType hash[HashLength];
HashFunction( (const void *) *data, (int) data.length(), seed, (void *)hash );
switch(outputType) {
case DefaultOutputType:
case NumberOutputType:
if (HashSize == sizeof(uint32_t)) {
result = Nan::New<Uint32>( (uint32_t) (*hash) );
} else {
result = HashToEncodedString<OutputByteOrder, HashLength>( hash, Nan::HEX );
}
break;
case HexStringOutputType:
result = HashToEncodedString<OutputByteOrder, HashLength>( hash, Nan::HEX );
break;
case BinaryStringOutputType:
result = HashToEncodedString<OutputByteOrder, HashLength>( hash, Nan::BINARY );
break;
case Base64StringOutputType:
result = HashToEncodedString<OutputByteOrder, HashLength>( hash, Nan::BASE64 );
break;
case BufferOutputType:
result = Nan::NewBuffer( HashSize ).ToLocalChecked();
WriteHashBytes<OutputByteOrder, HashLength>(hash, (uint8_t *) node::Buffer::Data(result));
break;
case ProvidedBufferOutputType:
result = info[outputTypeIndex];
WriteHashToBuffer<OutputByteOrder, HashLength>(
hash,
node::Buffer::Data(result),
(int32_t) node::Buffer::Length(result),
GET_ARG_OFFSET(info, outputTypeIndex, argc),
GET_ARG_LENGTH(info, outputTypeIndex, argc, HashSize));
break;
default:
return Nan::ThrowTypeError("Unknown output type: should be \"number\", \"buffer\", \"binary\", \"base64\" or \"hex\"");
}
info.GetReturnValue().Set(result);
}
}
#undef GET_ARG_OFFSET
#undef GET_ARG_LENGTH
template<ByteOrderType OutputByteOrder>
NAN_MODULE_INIT(InitWithOrder)
{
Nan::SetMethod(target, "murmurHash", MurmurHash< PMurHash32, uint32_t, 1, OutputByteOrder>);
Nan::SetMethod(target, "murmurHash32", MurmurHash< PMurHash32, uint32_t, 1, OutputByteOrder>);
Nan::SetMethod(target, "murmurHash64x64", MurmurHash<MurmurHash2_x64_64, uint64_t, 1, OutputByteOrder>);
Nan::SetMethod(target, "murmurHash64x86", MurmurHash<MurmurHash2_x86_64, uint64_t, 1, OutputByteOrder>);
Nan::SetMethod(target, "murmurHash128x64", MurmurHash< PMurHash128x64, uint64_t, 2, OutputByteOrder>);
Nan::SetMethod(target, "murmurHash128x86", MurmurHash< PMurHash128x86, uint32_t, 4, OutputByteOrder>);
#if defined(NODE_MURMURHASH_DEFAULT_32BIT)
Nan::SetMethod(target, "murmurHash64", MurmurHash<MurmurHash2_x86_64, uint64_t, 1, OutputByteOrder>);
Nan::SetMethod(target, "murmurHash128", MurmurHash< PMurHash128x86, uint32_t, 4, OutputByteOrder>);
#else
Nan::SetMethod(target, "murmurHash64", MurmurHash<MurmurHash2_x64_64, uint64_t, 1, OutputByteOrder>);
Nan::SetMethod(target, "murmurHash128", MurmurHash< PMurHash128x64, uint64_t, 2, OutputByteOrder>);
#endif
}
NAN_MODULE_INIT(Init)
{
InitWithOrder<MSBFirst>( target );
Local<Object> bigEndian( Nan::New<Object>() );
InitWithOrder<MSBFirst>( bigEndian );
Nan::DefineOwnProperty(target, Nan::New<String>("BE").ToLocalChecked(), bigEndian,
static_cast<PropertyAttribute>(ReadOnly | DontDelete) ).FromJust();
Local<Object> littleEndian( Nan::New<Object>() );
InitWithOrder<LSBFirst>( littleEndian );
Nan::DefineOwnProperty(target, Nan::New<String>("LE").ToLocalChecked(), littleEndian,
static_cast<PropertyAttribute>(ReadOnly | DontDelete) ).FromJust();
Nan::DefineOwnProperty(target, Nan::New<String>("platform").ToLocalChecked(),
IsBigEndian() ? bigEndian : littleEndian,
static_cast<PropertyAttribute>(ReadOnly | DontDelete) ).FromJust();
}
}
NODE_MODULE(murmurhash, MurmurHash::Init)
|
/*
** ClanLib SDK
** Copyright (c) 1997-2005 The ClanLib Team
**
** 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.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** (if your name is missing here, please add it)
*/
/*
Test for a compatible and working library.
*/
#include <X11/extensions/Xrender.h>
// todo: add headers needed here.
int main(int, char**)
{
// todo: Add version info check here (if possible)
// return 1; // failure
return 0; // success
}
void used_stuff()
{
// todo: call all functions used here (to make sure parameters are
// still the same, and that functions are resolved at linking.
XRenderQueryExtension(0, 0, 0);
}
|
// CSS Preprocessor -- Test Suite
// Copyright (C) 2015-2017 Made to Order Software Corp.
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
/** \file
* \brief Test the node.cpp file.
*
* This test runs a battery of tests agains the node.cpp
* implementation to ensure full coverage.
*/
#include "catch_tests.h"
#include "csspp/exceptions.h"
#include "csspp/lexer.h"
#include "csspp/unicode_range.h"
#include <iostream>
#include <sstream>
#include <string.h>
namespace
{
} // no name namespace
TEST_CASE("Node types", "[node] [type]")
{
// we expect the test suite to be compiled with the exact same version
csspp::node_type_t w(csspp::node_type_t::UNKNOWN);
while(w <= csspp::node_type_t::max_type)
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(w, pos));
// verify the type
REQUIRE(n->get_type() == w);
n->set_flag("important", true);
REQUIRE(n->get_flag("important"));
n->set_flag("important", false);
REQUIRE_FALSE(n->get_flag("important"));
// boolean
switch(w)
{
case csspp::node_type_t::BOOLEAN:
case csspp::node_type_t::OPEN_CURLYBRACKET:
{
bool b(rand() % 1 == 0);
n->set_boolean(b);
REQUIRE(n->get_boolean() == b);
if(w == csspp::node_type_t::OPEN_CURLYBRACKET)
{
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_INVALID);
}
else
{
REQUIRE(n->to_boolean() == (b ? csspp::boolean_t::BOOLEAN_TRUE : csspp::boolean_t::BOOLEAN_FALSE));
}
}
break;
case csspp::node_type_t::DECIMAL_NUMBER:
case csspp::node_type_t::INTEGER:
case csspp::node_type_t::PERCENT:
{
bool b(rand() % 1 == 0);
n->set_boolean(b);
REQUIRE(n->get_boolean() == b);
// the to_boolean() converts the value not the f_boolean field
// this test MUST happen before the next or we would not know
// whether it true or false
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
}
break;
default:
REQUIRE_THROWS_AS(n->set_boolean(true), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_boolean(), csspp::csspp_exception_logic);
break;
}
// integer
switch(w)
{
case csspp::node_type_t::AN_PLUS_B:
case csspp::node_type_t::ARG:
case csspp::node_type_t::AT_KEYWORD:
case csspp::node_type_t::COMMENT:
case csspp::node_type_t::INTEGER:
case csspp::node_type_t::UNICODE_RANGE:
{
if(w == csspp::node_type_t::INTEGER)
{
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
}
csspp::integer_t i(static_cast<csspp::integer_t>(rand()) + (static_cast<csspp::integer_t>(rand()) << 32));
n->set_integer(i);
REQUIRE(n->get_integer() == i);
if(w == csspp::node_type_t::INTEGER)
{
REQUIRE(n->to_boolean() == (i != 0 ? csspp::boolean_t::BOOLEAN_TRUE : csspp::boolean_t::BOOLEAN_FALSE));
}
}
break;
default:
REQUIRE_THROWS_AS(n->set_integer(123), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_integer(), csspp::csspp_exception_logic);
break;
}
// decimal number
switch(w)
{
case csspp::node_type_t::DECIMAL_NUMBER:
case csspp::node_type_t::PERCENT:
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
n->set_decimal_number(123.456);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
REQUIRE(n->get_decimal_number() == 123.456);
#pragma GCC diagnostic pop
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_TRUE);
break;
case csspp::node_type_t::FRAME:
// no boolean for FRAME (TBD?)
n->set_decimal_number(123.456);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
REQUIRE(n->get_decimal_number() == 123.456);
#pragma GCC diagnostic pop
break;
default:
REQUIRE_THROWS_AS(n->set_decimal_number(3.14159), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_decimal_number(), csspp::csspp_exception_logic);
break;
}
// string
switch(w)
{
case csspp::node_type_t::AT_KEYWORD:
case csspp::node_type_t::COMMENT:
case csspp::node_type_t::DECIMAL_NUMBER:
case csspp::node_type_t::DECLARATION:
case csspp::node_type_t::EXCLAMATION:
case csspp::node_type_t::FUNCTION:
case csspp::node_type_t::HASH:
case csspp::node_type_t::IDENTIFIER:
case csspp::node_type_t::INTEGER:
case csspp::node_type_t::PLACEHOLDER:
case csspp::node_type_t::STRING:
case csspp::node_type_t::URL:
case csspp::node_type_t::VARIABLE:
case csspp::node_type_t::VARIABLE_FUNCTION:
if(w == csspp::node_type_t::STRING)
{
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
}
n->set_lowercase_string("test-boolean-string");
REQUIRE(n->get_lowercase_string() == "test-boolean-string");
REQUIRE(n->get_string() == "");
if(w == csspp::node_type_t::STRING)
{
// the lowercase string has no effect on the boolean value
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
}
n->set_string("test-string");
REQUIRE(n->get_string() == "test-string");
REQUIRE(n->get_lowercase_string() == "test-boolean-string");
if(w == csspp::node_type_t::STRING)
{
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_TRUE);
}
n->set_lowercase_string("test-lowercase-string");
REQUIRE(n->get_lowercase_string() == "test-lowercase-string");
REQUIRE(n->get_string() == "test-string");
if(w == csspp::node_type_t::STRING)
{
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_TRUE);
}
break;
default:
REQUIRE_THROWS_AS(n->set_string("add"), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_string(), csspp::csspp_exception_logic);
break;
}
{
csspp::color c;
switch(w)
{
case csspp::node_type_t::COLOR:
{
// by default a color is black (transparent) and thus
// represents false
REQUIRE_FALSE(n->to_boolean());
c.set_color(rand() % 255, rand() % 255, rand() % 255, rand() % 255);
n->set_color(c);
csspp::color d(n->get_color());
REQUIRE(c.get_color() == d.get_color());
if((c.get_color() & 0x00FFFFFF) == 0)
{
// we tested with black... so it is still false
REQUIRE_FALSE(n->to_boolean());
}
else
{
// otherwise we have a "true color"
REQUIRE(n->to_boolean());
}
}
break;
default:
REQUIRE_THROWS_AS(n->set_color(c), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_color(), csspp::csspp_exception_logic);
break;
}
}
// font metrics
switch(w)
{
case csspp::node_type_t::FONT_METRICS:
n->set_font_size(12.5);
n->set_dim1("px");
n->set_line_height(24.3);
n->set_dim2("%");
//REQUIRE(n->get_string() == "px/%"); -- we do not allow get_string()
//REQUIRE(n->get_integer() == 12.5 as a double); -- we do not allow get_integer()
//REQUIRE(n->get_decimal_number() == 24.3); -- we do not allow get_decimal_number()
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
REQUIRE(n->get_font_size() == 12.5);
REQUIRE(n->get_dim1() == "px");
REQUIRE(n->get_line_height() == 24.3);
REQUIRE(n->get_dim2() == "%");
#pragma GCC diagnostic pop
// dimensions require a few more tests
n->set_dim2("deg"); // chane dim2
REQUIRE(n->get_dim1() == "px");
REQUIRE(n->get_dim2() == "deg");
n->set_dim2(""); // remove dim2
REQUIRE(n->get_dim1() == "px");
REQUIRE(n->get_dim2() == "");
n->set_dim1(""); // remove dim1
REQUIRE(n->get_dim1() == "");
REQUIRE(n->get_dim2() == "");
n->set_dim2("em"); // set dim2 without a dim1
REQUIRE(n->get_dim1() == "");
REQUIRE(n->get_dim2() == "em");
n->set_dim1("px"); // set a dim1 with a dim2
REQUIRE(n->get_dim1() == "px");
REQUIRE(n->get_dim2() == "em");
n->set_dim1(""); // remove dim1 with a dim2
REQUIRE(n->get_dim1() == "");
REQUIRE(n->get_dim2() == "em");
n->set_dim2(""); // remove dim2 without a dim1
REQUIRE(n->get_dim1() == "");
REQUIRE(n->get_dim2() == "");
break;
default:
REQUIRE_THROWS_AS(n->set_font_size(12.5), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_font_size(), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->set_line_height(24.3), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_line_height(), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->set_dim1("px"), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_dim1(), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->set_dim2("%"), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_dim2(), csspp::csspp_exception_logic);
break;
}
// children
switch(w)
{
case csspp::node_type_t::ARG:
case csspp::node_type_t::ARRAY:
case csspp::node_type_t::AT_KEYWORD:
case csspp::node_type_t::COMPONENT_VALUE:
case csspp::node_type_t::DECLARATION:
case csspp::node_type_t::FUNCTION:
case csspp::node_type_t::LIST:
case csspp::node_type_t::MAP:
case csspp::node_type_t::OPEN_CURLYBRACKET:
case csspp::node_type_t::OPEN_PARENTHESIS:
case csspp::node_type_t::OPEN_SQUAREBRACKET:
case csspp::node_type_t::VARIABLE_FUNCTION:
case csspp::node_type_t::FRAME:
{
// try adding one child
if(w == csspp::node_type_t::LIST)
{
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
}
REQUIRE(n->empty());
REQUIRE(n->size() == 0);
REQUIRE_THROWS_AS(n->get_child(0), csspp::csspp_exception_overflow);
REQUIRE_THROWS_AS(n->get_last_child(), csspp::csspp_exception_overflow);
REQUIRE_THROWS_AS(n->remove_child(0), csspp::csspp_exception_overflow);
REQUIRE_THROWS_AS(n->remove_child(n), csspp::csspp_exception_logic);
csspp::node::pointer_t child1(new csspp::node(csspp::node_type_t::COMMA, n->get_position()));
csspp::node::pointer_t child2(new csspp::node(csspp::node_type_t::EXCLAMATION, n->get_position()));
csspp::node::pointer_t eof_token(new csspp::node(csspp::node_type_t::EOF_TOKEN, n->get_position()));
csspp::node::pointer_t whitespace1(new csspp::node(csspp::node_type_t::WHITESPACE, n->get_position()));
csspp::node::pointer_t whitespace2(new csspp::node(csspp::node_type_t::WHITESPACE, n->get_position()));
n->add_child(child1);
if(w == csspp::node_type_t::LIST)
{
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_TRUE);
}
REQUIRE(n->size() == 1);
REQUIRE_FALSE(n->empty());
REQUIRE(n->get_last_child() == child1);
REQUIRE(n->get_child(0) == child1);
REQUIRE_THROWS_AS(n->remove_child(n), csspp::csspp_exception_logic);
n->add_child(child2);
if(w == csspp::node_type_t::LIST)
{
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_TRUE);
}
REQUIRE(n->size() == 2);
REQUIRE_FALSE(n->empty());
REQUIRE(n->get_last_child() == child2);
REQUIRE(n->get_child(0) == child1);
REQUIRE(n->get_child(1) == child2);
REQUIRE_THROWS_AS(n->remove_child(n), csspp::csspp_exception_logic);
if(rand() & 1)
{
n->remove_child(0);
REQUIRE(n->size() == 1);
n->remove_child(child2);
}
else
{
n->remove_child(child2);
REQUIRE(n->size() == 1);
n->remove_child(0);
}
// fully empty again, all fails like follow
if(w == csspp::node_type_t::LIST)
{
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
}
REQUIRE(n->empty());
REQUIRE(n->size() == 0);
REQUIRE_THROWS_AS(n->get_child(0), csspp::csspp_exception_overflow);
REQUIRE_THROWS_AS(n->get_last_child(), csspp::csspp_exception_overflow);
REQUIRE_THROWS_AS(n->remove_child(0), csspp::csspp_exception_overflow);
REQUIRE_THROWS_AS(n->remove_child(n), csspp::csspp_exception_logic);
// test a few more things
n->add_child(child1);
REQUIRE(n->size() == 1);
n->insert_child(1, whitespace1);
REQUIRE(n->size() == 2);
n->add_child(whitespace2); // ignore two whitespaces in a row
REQUIRE(n->size() == 2);
n->insert_child(0, child2);
REQUIRE(n->size() == 3);
n->add_child(eof_token); // never add EOF_TOKEN
REQUIRE(n->size() == 3);
REQUIRE(n->get_child(0) == child2);
REQUIRE(n->get_child(1) == child1);
REQUIRE(n->get_child(2) == whitespace1);
REQUIRE(n->child_position(child1) == 1);
REQUIRE(n->child_position(child2) == 0);
REQUIRE(n->child_position(whitespace1) == 2);
REQUIRE(n->child_position(whitespace2) == csspp::node::npos);
REQUIRE(n->child_position(eof_token) == csspp::node::npos);
n->clear();
REQUIRE(n->size() == 0);
REQUIRE(n->child_position(child1) == csspp::node::npos);
REQUIRE(n->child_position(child2) == csspp::node::npos);
REQUIRE(n->child_position(whitespace1) == csspp::node::npos);
REQUIRE(n->child_position(whitespace2) == csspp::node::npos);
REQUIRE(n->child_position(eof_token) == csspp::node::npos);
// test the replace
n->add_child(child1);
REQUIRE(n->size() == 1);
REQUIRE(n->get_child(0) == child1);
n->replace_child(child1, child2);
REQUIRE(n->size() == 1);
REQUIRE(n->get_child(0) == child2);
csspp::node::pointer_t list(new csspp::node(csspp::node_type_t::LIST, n->get_position()));
n->add_child(child1);
list->take_over_children_of(n);
REQUIRE(n->size() == 0);
REQUIRE(list->size() == 2);
REQUIRE(list->get_child(0) == child2);
REQUIRE(list->get_child(1) == child1);
}
break;
default:
REQUIRE_THROWS_AS(n->empty(), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->size(), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->clear(), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->add_child(n), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->remove_child(n), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->remove_child(0), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_child(0), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->get_last_child(), csspp::csspp_exception_logic);
REQUIRE_THROWS_AS(n->take_over_children_of(0), csspp::csspp_exception_logic);
break;
}
// all invalid node types for to_boolean()
switch(w)
{
case csspp::node_type_t::ARRAY:
case csspp::node_type_t::BOOLEAN:
case csspp::node_type_t::COLOR:
case csspp::node_type_t::DECIMAL_NUMBER:
case csspp::node_type_t::INTEGER:
case csspp::node_type_t::LIST:
case csspp::node_type_t::MAP:
case csspp::node_type_t::NULL_TOKEN:
case csspp::node_type_t::PERCENT:
case csspp::node_type_t::STRING:
break;
default:
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_INVALID);
break;
}
// move to the next type
w = static_cast<csspp::node_type_t>(static_cast<int>(w) + 1);
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Invalid tree handling", "[node] [invalid]")
{
// replace with an invalid child
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(csspp::node_type_t::LIST, pos));
csspp::node::pointer_t child1(new csspp::node(csspp::node_type_t::INTEGER, pos));
child1->set_integer(33);
csspp::node::pointer_t child2(new csspp::node(csspp::node_type_t::STRING, pos));
child2->set_string("hello!");
n->add_child(child1);
// child2, child1 are inverted
REQUIRE_THROWS_AS(n->replace_child(child2, child1), csspp::csspp_exception_logic);
}
// insert with invalid index
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(csspp::node_type_t::LIST, pos));
csspp::node::pointer_t child1(new csspp::node(csspp::node_type_t::INTEGER, pos));
child1->set_integer(345);
csspp::node::pointer_t child2(new csspp::node(csspp::node_type_t::STRING, pos));
child2->set_string("world.");
n->insert_child(0, child1);
// insert index can be 0 or 1, anything else and it is an overflow
for(int i(-100); i < 0; ++i)
{
REQUIRE_THROWS_AS(n->insert_child(i, child2), csspp::csspp_exception_overflow);
}
for(int i(2); i <= 100; ++i)
{
REQUIRE_THROWS_AS(n->insert_child(i, child2), csspp::csspp_exception_overflow);
}
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("True and false", "[node] [type] [output]")
{
// test boolean values from an identifier
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(csspp::node_type_t::IDENTIFIER, pos));
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_INVALID);
n->set_string("true");
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_TRUE);
n->set_string("false");
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
n->set_string("null");
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
n->set_string("other");
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_INVALID);
// fortuitious...
n->set_string("invalid");
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_INVALID);
}
// test boolean values from the NULL token
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(csspp::node_type_t::NULL_TOKEN, pos));
REQUIRE(n->to_boolean() == csspp::boolean_t::BOOLEAN_FALSE);
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Node variables", "[node] [variable]")
{
// set/get variables
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(csspp::node_type_t::LIST, pos));
csspp::node::pointer_t t[21];
for(int i(-10); i <= 10; ++i)
{
std::string nb(std::to_string(i));
t[i + 10].reset(new csspp::node(csspp::node_type_t::IDENTIFIER, pos));
t[i + 10]->set_string("test" + nb);
n->set_variable("t" + nb, t[i + 10]);
REQUIRE(n->get_variable("t" + nb) == t[i + 10]);
}
// check contents again
for(int i(-10); i <= 10; ++i)
{
std::string nb(std::to_string(i));
csspp::node::pointer_t p(n->get_variable("t" + nb));
REQUIRE(p == t[i + 10]);
REQUIRE(p->get_string() == "test" + nb);
}
n->clear_variables();
// all are gone now!
for(int i(-10); i <= 10; ++i)
{
std::string nb(std::to_string(i));
csspp::node::pointer_t p(n->get_variable("t" + nb));
REQUIRE(!p);
}
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Node flags", "[node] [flag]")
{
// read/write flags
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(csspp::node_type_t::LIST, pos));
for(int i(-10); i <= 10; ++i)
{
std::string nb("t" + std::to_string(i));
n->set_flag(nb, true);
REQUIRE(n->get_flag(nb));
n->set_flag(nb, false);
REQUIRE_FALSE(n->get_flag(nb));
n->set_flag(nb, true);
REQUIRE(n->get_flag(nb));
}
// check contents again
for(int i(-10); i <= 10; ++i)
{
std::string nb("t" + std::to_string(i));
REQUIRE(n->get_flag(nb));
}
n->clear_flags();
// all are gone now!
for(int i(-10); i <= 10; ++i)
{
std::string nb("t" + std::to_string(i));
REQUIRE_FALSE(n->get_flag(nb));
}
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Type names", "[node] [type] [output]")
{
// we expect the test suite to be compiled with the exact same version
csspp::node_type_t w(csspp::node_type_t::UNKNOWN);
while(w <= csspp::node_type_t::max_type)
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(w, pos));
std::stringstream ss;
ss << n->get_type();
std::string const name(ss.str());
switch(w)
{
case csspp::node_type_t::UNKNOWN:
REQUIRE(name == "UNKNOWN");
break;
case csspp::node_type_t::ADD:
REQUIRE(name == "ADD");
break;
case csspp::node_type_t::AND:
REQUIRE(name == "AND");
break;
case csspp::node_type_t::ASSIGNMENT:
REQUIRE(name == "ASSIGNMENT");
break;
case csspp::node_type_t::AT_KEYWORD:
REQUIRE(name == "AT_KEYWORD");
break;
case csspp::node_type_t::BOOLEAN:
REQUIRE(name == "BOOLEAN");
break;
case csspp::node_type_t::CDC:
REQUIRE(name == "CDC");
break;
case csspp::node_type_t::CDO:
REQUIRE(name == "CDO");
break;
case csspp::node_type_t::CLOSE_CURLYBRACKET:
REQUIRE(name == "CLOSE_CURLYBRACKET");
break;
case csspp::node_type_t::CLOSE_PARENTHESIS:
REQUIRE(name == "CLOSE_PARENTHESIS");
break;
case csspp::node_type_t::CLOSE_SQUAREBRACKET:
REQUIRE(name == "CLOSE_SQUAREBRACKET");
break;
case csspp::node_type_t::COLON:
REQUIRE(name == "COLON");
break;
case csspp::node_type_t::COLOR:
REQUIRE(name == "COLOR");
break;
case csspp::node_type_t::COLUMN:
REQUIRE(name == "COLUMN");
break;
case csspp::node_type_t::COMMA:
REQUIRE(name == "COMMA");
break;
case csspp::node_type_t::COMMENT:
REQUIRE(name == "COMMENT");
break;
case csspp::node_type_t::CONDITIONAL:
REQUIRE(name == "CONDITIONAL");
break;
case csspp::node_type_t::DASH_MATCH:
REQUIRE(name == "DASH_MATCH");
break;
case csspp::node_type_t::DECIMAL_NUMBER:
REQUIRE(name == "DECIMAL_NUMBER");
break;
case csspp::node_type_t::DIVIDE:
REQUIRE(name == "DIVIDE");
break;
case csspp::node_type_t::DOLLAR:
REQUIRE(name == "DOLLAR");
break;
case csspp::node_type_t::EOF_TOKEN:
REQUIRE(name == "EOF_TOKEN");
break;
case csspp::node_type_t::EQUAL:
REQUIRE(name == "EQUAL");
break;
case csspp::node_type_t::EXCLAMATION:
REQUIRE(name == "EXCLAMATION");
break;
case csspp::node_type_t::FONT_METRICS:
REQUIRE(name == "FONT_METRICS");
break;
case csspp::node_type_t::FUNCTION:
REQUIRE(name == "FUNCTION");
break;
case csspp::node_type_t::GREATER_EQUAL:
REQUIRE(name == "GREATER_EQUAL");
break;
case csspp::node_type_t::GREATER_THAN:
REQUIRE(name == "GREATER_THAN");
break;
case csspp::node_type_t::HASH:
REQUIRE(name == "HASH");
break;
case csspp::node_type_t::IDENTIFIER:
REQUIRE(name == "IDENTIFIER");
break;
case csspp::node_type_t::INCLUDE_MATCH:
REQUIRE(name == "INCLUDE_MATCH");
break;
case csspp::node_type_t::INTEGER:
REQUIRE(name == "INTEGER");
break;
case csspp::node_type_t::LESS_EQUAL:
REQUIRE(name == "LESS_EQUAL");
break;
case csspp::node_type_t::LESS_THAN:
REQUIRE(name == "LESS_THAN");
break;
case csspp::node_type_t::MODULO:
REQUIRE(name == "MODULO");
break;
case csspp::node_type_t::MULTIPLY:
REQUIRE(name == "MULTIPLY");
break;
case csspp::node_type_t::NOT_EQUAL:
REQUIRE(name == "NOT_EQUAL");
break;
case csspp::node_type_t::NULL_TOKEN:
REQUIRE(name == "NULL_TOKEN");
break;
case csspp::node_type_t::OPEN_CURLYBRACKET:
REQUIRE(name == "OPEN_CURLYBRACKET");
break;
case csspp::node_type_t::OPEN_PARENTHESIS:
REQUIRE(name == "OPEN_PARENTHESIS");
break;
case csspp::node_type_t::OPEN_SQUAREBRACKET:
REQUIRE(name == "OPEN_SQUAREBRACKET");
break;
case csspp::node_type_t::PERCENT:
REQUIRE(name == "PERCENT");
break;
case csspp::node_type_t::PERIOD:
REQUIRE(name == "PERIOD");
break;
case csspp::node_type_t::PLACEHOLDER:
REQUIRE(name == "PLACEHOLDER");
break;
case csspp::node_type_t::POWER:
REQUIRE(name == "POWER");
break;
case csspp::node_type_t::PRECEDED:
REQUIRE(name == "PRECEDED");
break;
case csspp::node_type_t::PREFIX_MATCH:
REQUIRE(name == "PREFIX_MATCH");
break;
case csspp::node_type_t::REFERENCE:
REQUIRE(name == "REFERENCE");
break;
case csspp::node_type_t::SCOPE:
REQUIRE(name == "SCOPE");
break;
case csspp::node_type_t::SEMICOLON:
REQUIRE(name == "SEMICOLON");
break;
case csspp::node_type_t::STRING:
REQUIRE(name == "STRING");
break;
case csspp::node_type_t::SUBSTRING_MATCH:
REQUIRE(name == "SUBSTRING_MATCH");
break;
case csspp::node_type_t::SUBTRACT:
REQUIRE(name == "SUBTRACT");
break;
case csspp::node_type_t::SUFFIX_MATCH:
REQUIRE(name == "SUFFIX_MATCH");
break;
case csspp::node_type_t::UNICODE_RANGE:
REQUIRE(name == "UNICODE_RANGE");
break;
case csspp::node_type_t::URL:
REQUIRE(name == "URL");
break;
case csspp::node_type_t::VARIABLE:
REQUIRE(name == "VARIABLE");
break;
case csspp::node_type_t::VARIABLE_FUNCTION:
REQUIRE(name == "VARIABLE_FUNCTION");
break;
case csspp::node_type_t::WHITESPACE:
REQUIRE(name == "WHITESPACE");
break;
// second part
case csspp::node_type_t::AN_PLUS_B:
REQUIRE(name == "AN_PLUS_B");
break;
case csspp::node_type_t::ARG:
REQUIRE(name == "ARG");
break;
case csspp::node_type_t::ARRAY:
REQUIRE(name == "ARRAY");
break;
case csspp::node_type_t::COMPONENT_VALUE:
REQUIRE(name == "COMPONENT_VALUE");
break;
case csspp::node_type_t::DECLARATION:
REQUIRE(name == "DECLARATION");
break;
case csspp::node_type_t::LIST:
REQUIRE(name == "LIST");
break;
case csspp::node_type_t::MAP:
REQUIRE(name == "MAP");
break;
case csspp::node_type_t::FRAME:
REQUIRE(name == "FRAME");
break;
case csspp::node_type_t::max_type:
REQUIRE(name == "max_type");
break;
}
// move to the next type
w = static_cast<csspp::node_type_t>(static_cast<int>(w) + 1);
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Node output", "[node] [output]")
{
// we expect the test suite to be compiled with the exact same version
csspp::node_type_t w(csspp::node_type_t::UNKNOWN);
while(w <= csspp::node_type_t::max_type)
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(w, pos));
std::stringstream ss;
ss << n->get_type();
std::string const name(ss.str());
switch(w)
{
case csspp::node_type_t::UNKNOWN:
REQUIRE(name == "UNKNOWN");
break;
case csspp::node_type_t::ADD:
REQUIRE(name == "ADD");
break;
case csspp::node_type_t::AND:
REQUIRE(name == "AND");
break;
case csspp::node_type_t::ASSIGNMENT:
REQUIRE(name == "ASSIGNMENT");
break;
case csspp::node_type_t::AT_KEYWORD:
REQUIRE(name == "AT_KEYWORD");
break;
case csspp::node_type_t::BOOLEAN:
REQUIRE(name == "BOOLEAN");
break;
case csspp::node_type_t::CDC:
REQUIRE(name == "CDC");
break;
case csspp::node_type_t::CDO:
REQUIRE(name == "CDO");
break;
case csspp::node_type_t::CLOSE_CURLYBRACKET:
REQUIRE(name == "CLOSE_CURLYBRACKET");
break;
case csspp::node_type_t::CLOSE_PARENTHESIS:
REQUIRE(name == "CLOSE_PARENTHESIS");
break;
case csspp::node_type_t::CLOSE_SQUAREBRACKET:
REQUIRE(name == "CLOSE_SQUAREBRACKET");
break;
case csspp::node_type_t::COLON:
REQUIRE(name == "COLON");
break;
case csspp::node_type_t::COLOR:
REQUIRE(name == "COLOR");
break;
case csspp::node_type_t::COLUMN:
REQUIRE(name == "COLUMN");
break;
case csspp::node_type_t::COMMA:
REQUIRE(name == "COMMA");
break;
case csspp::node_type_t::COMMENT:
REQUIRE(name == "COMMENT");
break;
case csspp::node_type_t::CONDITIONAL:
REQUIRE(name == "CONDITIONAL");
break;
case csspp::node_type_t::DASH_MATCH:
REQUIRE(name == "DASH_MATCH");
break;
case csspp::node_type_t::DECIMAL_NUMBER:
REQUIRE(name == "DECIMAL_NUMBER");
break;
case csspp::node_type_t::DIVIDE:
REQUIRE(name == "DIVIDE");
break;
case csspp::node_type_t::DOLLAR:
REQUIRE(name == "DOLLAR");
break;
case csspp::node_type_t::EOF_TOKEN:
REQUIRE(name == "EOF_TOKEN");
break;
case csspp::node_type_t::EQUAL:
REQUIRE(name == "EQUAL");
break;
case csspp::node_type_t::EXCLAMATION:
REQUIRE(name == "EXCLAMATION");
break;
case csspp::node_type_t::FONT_METRICS:
REQUIRE(name == "FONT_METRICS");
break;
case csspp::node_type_t::FUNCTION:
REQUIRE(name == "FUNCTION");
break;
case csspp::node_type_t::GREATER_EQUAL:
REQUIRE(name == "GREATER_EQUAL");
break;
case csspp::node_type_t::GREATER_THAN:
REQUIRE(name == "GREATER_THAN");
break;
case csspp::node_type_t::HASH:
REQUIRE(name == "HASH");
break;
case csspp::node_type_t::IDENTIFIER:
REQUIRE(name == "IDENTIFIER");
break;
case csspp::node_type_t::INCLUDE_MATCH:
REQUIRE(name == "INCLUDE_MATCH");
break;
case csspp::node_type_t::INTEGER:
REQUIRE(name == "INTEGER");
break;
case csspp::node_type_t::LESS_EQUAL:
REQUIRE(name == "LESS_EQUAL");
break;
case csspp::node_type_t::LESS_THAN:
REQUIRE(name == "LESS_THAN");
break;
case csspp::node_type_t::MODULO:
REQUIRE(name == "MODULO");
break;
case csspp::node_type_t::MULTIPLY:
REQUIRE(name == "MULTIPLY");
break;
case csspp::node_type_t::NOT_EQUAL:
REQUIRE(name == "NOT_EQUAL");
break;
case csspp::node_type_t::NULL_TOKEN:
REQUIRE(name == "NULL_TOKEN");
break;
case csspp::node_type_t::OPEN_CURLYBRACKET:
REQUIRE(name == "OPEN_CURLYBRACKET");
break;
case csspp::node_type_t::OPEN_PARENTHESIS:
REQUIRE(name == "OPEN_PARENTHESIS");
break;
case csspp::node_type_t::OPEN_SQUAREBRACKET:
REQUIRE(name == "OPEN_SQUAREBRACKET");
break;
case csspp::node_type_t::PERCENT:
REQUIRE(name == "PERCENT");
break;
case csspp::node_type_t::PERIOD:
REQUIRE(name == "PERIOD");
break;
case csspp::node_type_t::PLACEHOLDER:
REQUIRE(name == "PLACEHOLDER");
break;
case csspp::node_type_t::POWER:
REQUIRE(name == "POWER");
break;
case csspp::node_type_t::PRECEDED:
REQUIRE(name == "PRECEDED");
break;
case csspp::node_type_t::PREFIX_MATCH:
REQUIRE(name == "PREFIX_MATCH");
break;
case csspp::node_type_t::REFERENCE:
REQUIRE(name == "REFERENCE");
break;
case csspp::node_type_t::SCOPE:
REQUIRE(name == "SCOPE");
break;
case csspp::node_type_t::SEMICOLON:
REQUIRE(name == "SEMICOLON");
break;
case csspp::node_type_t::STRING:
REQUIRE(name == "STRING");
break;
case csspp::node_type_t::SUBSTRING_MATCH:
REQUIRE(name == "SUBSTRING_MATCH");
break;
case csspp::node_type_t::SUBTRACT:
REQUIRE(name == "SUBTRACT");
break;
case csspp::node_type_t::SUFFIX_MATCH:
REQUIRE(name == "SUFFIX_MATCH");
break;
case csspp::node_type_t::UNICODE_RANGE:
REQUIRE(name == "UNICODE_RANGE");
break;
case csspp::node_type_t::URL:
REQUIRE(name == "URL");
break;
case csspp::node_type_t::VARIABLE:
REQUIRE(name == "VARIABLE");
break;
case csspp::node_type_t::VARIABLE_FUNCTION:
REQUIRE(name == "VARIABLE_FUNCTION");
break;
case csspp::node_type_t::WHITESPACE:
REQUIRE(name == "WHITESPACE");
break;
// second part
case csspp::node_type_t::AN_PLUS_B:
REQUIRE(name == "AN_PLUS_B");
break;
case csspp::node_type_t::ARG:
REQUIRE(name == "ARG");
break;
case csspp::node_type_t::ARRAY:
REQUIRE(name == "ARRAY");
break;
case csspp::node_type_t::COMPONENT_VALUE:
REQUIRE(name == "COMPONENT_VALUE");
break;
case csspp::node_type_t::DECLARATION:
REQUIRE(name == "DECLARATION");
break;
case csspp::node_type_t::LIST:
REQUIRE(name == "LIST");
break;
case csspp::node_type_t::MAP:
REQUIRE(name == "MAP");
break;
case csspp::node_type_t::FRAME:
REQUIRE(name == "FRAME");
break;
case csspp::node_type_t::max_type:
REQUIRE(name == "max_type");
break;
}
// move to the next type
w = static_cast<csspp::node_type_t>(static_cast<int>(w) + 1);
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Node to string", "[node] [type] [output]")
{
// we expect the test suite to be compiled with the exact same version
for(int flags(0); flags < 4; ++flags)
{
csspp::node_type_t w(csspp::node_type_t::UNKNOWN);
while(w <= csspp::node_type_t::max_type)
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(w, pos));
switch(w)
{
case csspp::node_type_t::ADD:
REQUIRE(n->to_string(flags) == "+");
break;
case csspp::node_type_t::AND:
REQUIRE(n->to_string(flags) == "&&");
break;
case csspp::node_type_t::ASSIGNMENT:
REQUIRE(n->to_string(flags) == ":=");
break;
case csspp::node_type_t::AT_KEYWORD:
REQUIRE(n->to_string(flags) == "@");
n->set_string("test");
REQUIRE(n->to_string(flags) == "@test");
break;
case csspp::node_type_t::BOOLEAN:
REQUIRE(n->to_string(flags) == "false");
n->set_boolean(true);
REQUIRE(n->to_string(flags) == "true");
break;
case csspp::node_type_t::COLON:
REQUIRE(n->to_string(flags) == ":");
break;
case csspp::node_type_t::COLOR:
{
REQUIRE(n->to_string(flags) == "transparent");
csspp::color c;
c.set_color(0x58, 0x32, 0xff, 0xff);
n->set_color(c);
REQUIRE(n->to_string(flags) == "#5832ff");
c.set_color(0x58, 0x32, 0xff, 0x7f);
n->set_color(c);
REQUIRE(n->to_string(flags) == "rgba(88,50,255,.5)");
}
break;
case csspp::node_type_t::COLUMN:
REQUIRE(n->to_string(flags) == "||");
break;
case csspp::node_type_t::COMMA:
REQUIRE(n->to_string(flags) == ",");
break;
case csspp::node_type_t::COMMENT:
// once we remove the @preserve, this could happen
REQUIRE(n->to_string(flags) == "");
n->set_string("the comment");
REQUIRE(n->to_string(flags) == "// the comment\n");
n->set_string("the comment\non two lines");
REQUIRE(n->to_string(flags) == "// the comment\n// on two lines\n");
n->set_integer(1);
n->set_string("the C-like comment\non two lines");
REQUIRE(n->to_string(flags) == "/* the C-like comment\non two lines */");
break;
case csspp::node_type_t::CONDITIONAL:
REQUIRE(n->to_string(flags) == "?");
break;
case csspp::node_type_t::DASH_MATCH:
REQUIRE(n->to_string(flags) == "|=");
break;
case csspp::node_type_t::DECIMAL_NUMBER:
REQUIRE(n->to_string(flags) == "0");
n->set_string("em");
REQUIRE(n->to_string(flags) == "0em");
n->set_decimal_number(1.25);
REQUIRE(n->to_string(flags) == "1.25em");
break;
case csspp::node_type_t::DIVIDE:
if((flags & csspp::node::g_to_string_flag_add_spaces) != 0)
{
REQUIRE(n->to_string(flags) == " / ");
}
else
{
REQUIRE(n->to_string(flags) == "/");
}
break;
case csspp::node_type_t::DOLLAR:
REQUIRE(n->to_string(flags) == "$");
break;
case csspp::node_type_t::EQUAL:
REQUIRE(n->to_string(flags) == "=");
break;
case csspp::node_type_t::EXCLAMATION:
REQUIRE(n->to_string(flags) == "!");
break;
case csspp::node_type_t::FONT_METRICS:
REQUIRE(n->to_string(flags) ==
csspp::decimal_number_to_string(n->get_font_size(), false)
+ n->get_dim1()
+ "/"
+ csspp::decimal_number_to_string(n->get_line_height(), false)
+ n->get_dim2());
break;
case csspp::node_type_t::FUNCTION:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "()");
// test with an actual function
n->set_string("rgba");
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(1.0);
n->add_child(p);
REQUIRE(n->to_string(flags) == "rgba(0,0,0,1)");
}
break;
case csspp::node_type_t::GREATER_EQUAL:
REQUIRE(n->to_string(flags) == ">=");
break;
case csspp::node_type_t::GREATER_THAN:
REQUIRE(n->to_string(flags) == ">");
break;
case csspp::node_type_t::HASH:
REQUIRE(n->to_string(flags) == "#");
n->set_string("random");
REQUIRE(n->to_string(flags) == "#random");
break;
case csspp::node_type_t::IDENTIFIER:
REQUIRE(n->to_string(flags) == "");
n->set_string("an identifier in CSS can be absolutely anything!");
REQUIRE(n->to_string(flags) == "an identifier in CSS can be absolutely anything!");
break;
case csspp::node_type_t::INCLUDE_MATCH:
REQUIRE(n->to_string(flags) == "~=");
break;
case csspp::node_type_t::INTEGER:
{
REQUIRE(n->to_string(flags) == "0");
csspp::integer_t i(static_cast<csspp::integer_t>(rand()) + (static_cast<csspp::integer_t>(rand()) << 32));
n->set_integer(i);
REQUIRE(n->to_string(flags) == std::to_string(i));
n->set_string("px");
REQUIRE(n->to_string(flags) == std::to_string(i) + "px");
}
break;
case csspp::node_type_t::LESS_EQUAL:
REQUIRE(n->to_string(flags) == "<=");
break;
case csspp::node_type_t::LESS_THAN:
REQUIRE(n->to_string(flags) == "<");
break;
case csspp::node_type_t::MODULO:
if((flags & csspp::node::g_to_string_flag_add_spaces) != 0)
{
REQUIRE(n->to_string(flags) == " % ");
}
else
{
REQUIRE(n->to_string(flags) == "%");
}
break;
case csspp::node_type_t::MULTIPLY:
REQUIRE(n->to_string(flags) == "*");
break;
case csspp::node_type_t::NOT_EQUAL:
REQUIRE(n->to_string(flags) == "!=");
break;
case csspp::node_type_t::NULL_TOKEN:
REQUIRE(n->to_string(flags) == "");
break;
case csspp::node_type_t::OPEN_CURLYBRACKET:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "{}");
// test with an actual expression
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(7);
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::MODULO, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(52);
n->add_child(p);
if((flags & csspp::node::g_to_string_flag_add_spaces) != 0)
{
REQUIRE(n->to_string(flags) == "{7 % 52}");
}
else
{
REQUIRE(n->to_string(flags) == "{7%52}");
}
}
break;
case csspp::node_type_t::OPEN_PARENTHESIS:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "()");
// test with an actual function
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(17);
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::MULTIPLY, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(502);
n->add_child(p);
REQUIRE(n->to_string(flags) == "(17*502)");
}
break;
case csspp::node_type_t::OPEN_SQUAREBRACKET:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "[]");
// test with an actual function
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(5);
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DIVIDE, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(152);
n->add_child(p);
if((flags & csspp::node::g_to_string_flag_add_spaces) != 0)
{
REQUIRE(n->to_string(flags) == "[5 / 152]");
}
else
{
REQUIRE(n->to_string(flags) == "[5/152]");
}
}
break;
case csspp::node_type_t::PERCENT:
REQUIRE(n->to_string(flags) == "0%");
n->set_decimal_number(1.25);
REQUIRE(n->to_string(flags) == "125%");
break;
case csspp::node_type_t::PERIOD:
REQUIRE(n->to_string(flags) == ".");
break;
case csspp::node_type_t::PLACEHOLDER:
REQUIRE(n->to_string(flags) == "%");
n->set_string("the-name-of-the-placeholder");
REQUIRE(n->to_string(flags) == "%the-name-of-the-placeholder");
break;
case csspp::node_type_t::POWER:
REQUIRE(n->to_string(flags) == "**");
break;
case csspp::node_type_t::PRECEDED:
REQUIRE(n->to_string(flags) == "~");
break;
case csspp::node_type_t::PREFIX_MATCH:
REQUIRE(n->to_string(flags) == "^=");
break;
case csspp::node_type_t::REFERENCE:
REQUIRE(n->to_string(flags) == "&");
break;
case csspp::node_type_t::SCOPE:
REQUIRE(n->to_string(flags) == "|");
break;
case csspp::node_type_t::SEMICOLON:
REQUIRE(n->to_string(flags) == ";");
break;
case csspp::node_type_t::STRING:
// with an empty string
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "\"\"");
}
else
{
REQUIRE(n->to_string(flags) == "");
}
// with a ' in the string
n->set_string("whatever string content we'd want really...");
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "\"whatever string content we'd want really...\"");
}
else
{
REQUIRE(n->to_string(flags) == "whatever string content we'd want really...");
}
// with a " in the string
n->set_string("yet if we have one quote like this: \" then the other is used to quote the string");
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "'yet if we have one quote like this: \" then the other is used to quote the string'");
}
else
{
REQUIRE(n->to_string(flags) == "yet if we have one quote like this: \" then the other is used to quote the string");
}
// with both ' and ", more '
n->set_string("counter: ''''' > \"\"\"");
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "\"counter: ''''' > \\\"\\\"\\\"\"");
}
else
{
REQUIRE(n->to_string(flags) == "counter: ''''' > \"\"\"");
}
// with both ' and ", more "
n->set_string("counter: ''' < \"\"\"\"\"");
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "'counter: \\'\\'\\' < \"\"\"\"\"'");
}
else
{
REQUIRE(n->to_string(flags) == "counter: ''' < \"\"\"\"\"");
}
break;
case csspp::node_type_t::SUBSTRING_MATCH:
REQUIRE(n->to_string(flags) == "*=");
break;
case csspp::node_type_t::SUBTRACT:
REQUIRE(n->to_string(flags) == "-");
break;
case csspp::node_type_t::SUFFIX_MATCH:
REQUIRE(n->to_string(flags) == "$=");
break;
case csspp::node_type_t::UNICODE_RANGE:
REQUIRE(n->to_string(flags) == "U+0");
n->set_integer(0x00004FFF00004000);
REQUIRE(n->to_string(flags) == "U+4???");
break;
case csspp::node_type_t::URL:
REQUIRE(n->to_string(flags) == "url()");
n->set_string("http://this.should.be/a/valid/url");
REQUIRE(n->to_string(flags) == "url(http://this.should.be/a/valid/url)");
break;
case csspp::node_type_t::VARIABLE:
REQUIRE(n->to_string(flags) == "$");
n->set_string("varname");
REQUIRE(n->to_string(flags) == "$varname");
break;
case csspp::node_type_t::VARIABLE_FUNCTION:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "$()");
// test with an actual function
n->set_string("my_function");
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("colorful");
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(33);
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(1.0);
n->add_child(p);
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "$my_function(0,\"colorful\",33,1)");
}
else
{
REQUIRE(n->to_string(flags) == "$my_function(0,colorful,33,1)");
}
}
break;
case csspp::node_type_t::WHITESPACE:
REQUIRE(n->to_string(flags) == " ");
break;
// second part
case csspp::node_type_t::AN_PLUS_B:
REQUIRE(n->to_string(flags) == "0");
n->set_integer(0x0000000500000003);
REQUIRE(n->to_string(flags) == "3n+5");
break;
case csspp::node_type_t::ARG:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "");
REQUIRE(n->get_integer() == 0);
// test with an actual function
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::ADD, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(33);
n->add_child(p);
REQUIRE(n->to_string(flags) == "0+33");
}
break;
case csspp::node_type_t::ARRAY:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "()");
// each item is comma separated
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::IDENTIFIER, n->get_position()));
p->set_string("number");
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(3.22);
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::POWER, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("hello world!");
n->add_child(p);
REQUIRE(n->to_string(flags) == "(number, 3.22, **, \"hello world!\")");
}
break;
case csspp::node_type_t::COMPONENT_VALUE:
// test with the default (undefined) separator
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "");
// test with an actual function
csspp::node::pointer_t a(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
n->add_child(a);
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
a->add_child(p);
a.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
n->add_child(a);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("orange");
a->add_child(p);
a.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
n->add_child(a);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(33);
a->add_child(p);
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "0,\"orange\",33");
}
else
{
REQUIRE(n->to_string(flags) == "0,orange,33");
}
// test with an actual function but not argified
n->clear();
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(111);
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::COMMA, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("purple");
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::COMMA, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(301);
n->add_child(p);
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "111,\"purple\",301");
}
else
{
REQUIRE(n->to_string(flags) == "111,purple,301");
}
}
// test again with "," as the ARG separator
{
n->clear();
// test with an actual function
csspp::node::pointer_t a(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
a->set_integer(static_cast<int>(csspp::node_type_t::COMMA));
n->add_child(a);
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
a->add_child(p);
a.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
a->set_integer(static_cast<int>(csspp::node_type_t::COMMA));
n->add_child(a);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("orange");
a->add_child(p);
a.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
a->set_integer(static_cast<int>(csspp::node_type_t::COMMA));
n->add_child(a);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(33);
a->add_child(p);
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "0,\"orange\",33");
}
else
{
REQUIRE(n->to_string(flags) == "0,orange,33");
}
// test with an actual function but not argified
n->clear();
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(111);
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::COMMA, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("purple");
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::COMMA, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(301);
n->add_child(p);
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "111,\"purple\",301");
}
else
{
REQUIRE(n->to_string(flags) == "111,purple,301");
}
}
// test again with "/" as the ARG separator
{
n->clear();
// test with an actual function
csspp::node::pointer_t a(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
a->set_integer(static_cast<int>(csspp::node_type_t::DIVIDE));
n->add_child(a);
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
a->add_child(p);
a.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
a->set_integer(static_cast<int>(csspp::node_type_t::DIVIDE));
n->add_child(a);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("orange");
a->add_child(p);
a.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
a->set_integer(static_cast<int>(csspp::node_type_t::DIVIDE));
n->add_child(a);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(33);
a->add_child(p);
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
REQUIRE(n->to_string(flags) == "0/\"orange\"/33");
}
else
{
REQUIRE(n->to_string(flags) == "0/orange/33");
}
// test with an actual function but not argified
n->clear();
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(111);
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DIVIDE, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("purple");
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DIVIDE, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(301);
n->add_child(p);
if((flags & csspp::node::g_to_string_flag_show_quotes) != 0)
{
if((flags & csspp::node::g_to_string_flag_add_spaces) != 0)
{
REQUIRE(n->to_string(flags) == "111 / \"purple\" / 301");
}
else
{
REQUIRE(n->to_string(flags) == "111/\"purple\"/301");
}
}
else
{
if((flags & csspp::node::g_to_string_flag_add_spaces) != 0)
{
REQUIRE(n->to_string(flags) == "111 / purple / 301");
}
else
{
REQUIRE(n->to_string(flags) == "111/purple/301");
}
}
}
break;
case csspp::node_type_t::DECLARATION:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "");
n->set_string("name");
REQUIRE(n->to_string(flags) == "name: ");
// test with an actual function
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::WHITESPACE, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::SUBTRACT, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::WHITESPACE, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(33);
n->add_child(p);
REQUIRE(n->to_string(flags) == "name: 0 - 33");
}
{
n->clear();
// 1.45 + 15, 7 - 1.15
csspp::node::pointer_t arg(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
n->add_child(arg);
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(1.45);
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::ADD, n->get_position()));
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(15);
arg->add_child(p);
// there is no comma in the tree once compiled, just another ARG
arg.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
n->add_child(arg);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(7);
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::SUBTRACT, n->get_position()));
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(1.15);
arg->add_child(p);
REQUIRE(n->to_string(flags) == "name: 1.45+15,7-1.15");
}
break;
case csspp::node_type_t::LIST:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "");
// test with an actual expression
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(3.22);
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::WHITESPACE, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::POWER, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::WHITESPACE, n->get_position()));
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(5.3);
n->add_child(p);
REQUIRE(n->to_string(flags) == "3.22 ** 5.3");
}
{
n->clear();
// test with a couple of declarations to make sure we get
// the semi-colon in between
csspp::node::pointer_t declaration(new csspp::node(csspp::node_type_t::DECLARATION, n->get_position()));
n->add_child(declaration);
// and a declaration may have multiple arguments
csspp::node::pointer_t arg(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
declaration->add_child(arg);
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(14.53);
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::ADD, n->get_position()));
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(150);
arg->add_child(p);
// there is no comma in the tree once compiled, just another ARG
arg.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
declaration->add_child(arg);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(107);
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::SUBTRACT, n->get_position()));
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(115.23);
arg->add_child(p);
// second declaration
declaration.reset(new csspp::node(csspp::node_type_t::DECLARATION, n->get_position()));
n->add_child(declaration);
// second argument of this declaration
arg.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
declaration->add_child(arg);
p.reset(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(1.453);
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::ADD, n->get_position()));
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(1);
arg->add_child(p);
// there is no comma in the tree once compiled, just another ARG
arg.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
declaration->add_child(arg);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(19);
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::SUBTRACT, n->get_position()));
arg->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(15.03);
arg->add_child(p);
REQUIRE(n->to_string(flags) == "14.53+150,107-115.23;1.453+1,19-15.03");
}
break;
case csspp::node_type_t::MAP:
{
// the defaults are empty...
REQUIRE(n->to_string(flags) == "()");
// number: 3.22
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::IDENTIFIER, n->get_position()));
p->set_string("number");
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, n->get_position()));
p->set_decimal_number(3.22);
n->add_child(p);
// string: "hello world!"
p.reset(new csspp::node(csspp::node_type_t::IDENTIFIER, n->get_position()));
p->set_string("string");
n->add_child(p);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("hello world!");
n->add_child(p);
REQUIRE(n->to_string(flags) == "(number: 3.22, string: \"hello world!\")");
}
break;
case csspp::node_type_t::FRAME:
{
REQUIRE(n->to_string(flags) == "from{}");
n->set_decimal_number(0.25);
REQUIRE(n->to_string(flags) == "25%{}");
n->set_decimal_number(1.0);
REQUIRE(n->to_string(flags) == "to{}");
// 68% { right: 322px }
n->set_decimal_number(0.68);
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::DECLARATION, n->get_position()));
p->set_string("right");
n->add_child(p);
csspp::node::pointer_t q(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
p->add_child(q);
csspp::node::pointer_t r(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
r->set_string("px");
r->set_integer(322);
q->add_child(r);
REQUIRE(n->to_string(flags) == "68%{right: 322px}");
}
break;
// anything else is an error
default:
// other node types generate a throw
REQUIRE_THROWS_AS(n->to_string(flags), csspp::csspp_exception_logic);
break;
}
// move to the next type
w = static_cast<csspp::node_type_t>(static_cast<int>(w) + 1);
}
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Node to string ARG with wrong type", "[node] [output] [invalid]")
{
// we expect the test suite to be compiled with the exact same version
for(int flags(0); flags < 4; ++flags)
{
for(csspp::node_type_t w(csspp::node_type_t::UNKNOWN);
w <= csspp::node_type_t::max_type;
w = static_cast<csspp::node_type_t>(static_cast<int>(w) + 1))
{
switch(w)
{
case csspp::node_type_t::UNKNOWN:
case csspp::node_type_t::COMMA:
case csspp::node_type_t::DIVIDE:
continue;
default:
break;
}
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(csspp::node_type_t::COMPONENT_VALUE, pos));
// test with an actual function
csspp::node::pointer_t a(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
a->set_integer(static_cast<csspp::integer_t>(w));
n->add_child(a);
csspp::node::pointer_t p(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
a->add_child(p);
a.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
a->set_integer(static_cast<csspp::integer_t>(w));
n->add_child(a);
p.reset(new csspp::node(csspp::node_type_t::STRING, n->get_position()));
p->set_string("orange");
a->add_child(p);
a.reset(new csspp::node(csspp::node_type_t::ARG, n->get_position()));
a->set_integer(static_cast<csspp::integer_t>(w));
n->add_child(a);
p.reset(new csspp::node(csspp::node_type_t::INTEGER, n->get_position()));
p->set_integer(33);
a->add_child(p);
// w is not valid as an ARG separator so it throws
REQUIRE_THROWS_AS(n->to_string(flags), csspp::csspp_exception_logic);
}
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Error with node names", "[node] [type] [output]")
{
// we expect the test suite to be compiled with the exact same version
csspp::node_type_t w(csspp::node_type_t::UNKNOWN);
while(w <= csspp::node_type_t::max_type)
{
csspp::position pos("test.css");
csspp::node::pointer_t n(new csspp::node(w, pos));
csspp::error::instance() << pos
<< "node name \""
<< n->get_type()
<< "\"."
<< csspp::error_mode_t::ERROR_ERROR;
std::string name("good");
switch(w)
{
case csspp::node_type_t::UNKNOWN:
REQUIRE_ERRORS("test.css(1): error: node name \"UNKNOWN\".\n");
break;
case csspp::node_type_t::ADD:
REQUIRE_ERRORS("test.css(1): error: node name \"ADD\".\n");
break;
case csspp::node_type_t::AND:
REQUIRE_ERRORS("test.css(1): error: node name \"AND\".\n");
break;
case csspp::node_type_t::ASSIGNMENT:
REQUIRE_ERRORS("test.css(1): error: node name \"ASSIGNMENT\".\n");
break;
case csspp::node_type_t::AT_KEYWORD:
REQUIRE_ERRORS("test.css(1): error: node name \"AT_KEYWORD\".\n");
break;
case csspp::node_type_t::BOOLEAN:
REQUIRE_ERRORS("test.css(1): error: node name \"BOOLEAN\".\n");
break;
case csspp::node_type_t::CDC:
REQUIRE_ERRORS("test.css(1): error: node name \"CDC\".\n");
break;
case csspp::node_type_t::CDO:
REQUIRE_ERRORS("test.css(1): error: node name \"CDO\".\n");
break;
case csspp::node_type_t::CLOSE_CURLYBRACKET:
REQUIRE_ERRORS("test.css(1): error: node name \"CLOSE_CURLYBRACKET\".\n");
break;
case csspp::node_type_t::CLOSE_PARENTHESIS:
REQUIRE_ERRORS("test.css(1): error: node name \"CLOSE_PARENTHESIS\".\n");
break;
case csspp::node_type_t::CLOSE_SQUAREBRACKET:
REQUIRE_ERRORS("test.css(1): error: node name \"CLOSE_SQUAREBRACKET\".\n");
break;
case csspp::node_type_t::COLON:
REQUIRE_ERRORS("test.css(1): error: node name \"COLON\".\n");
break;
case csspp::node_type_t::COLOR:
REQUIRE_ERRORS("test.css(1): error: node name \"COLOR\".\n");
break;
case csspp::node_type_t::COLUMN:
REQUIRE_ERRORS("test.css(1): error: node name \"COLUMN\".\n");
break;
case csspp::node_type_t::COMMA:
REQUIRE_ERRORS("test.css(1): error: node name \"COMMA\".\n");
break;
case csspp::node_type_t::COMMENT:
REQUIRE_ERRORS("test.css(1): error: node name \"COMMENT\".\n");
break;
case csspp::node_type_t::CONDITIONAL:
REQUIRE_ERRORS("test.css(1): error: node name \"CONDITIONAL\".\n");
break;
case csspp::node_type_t::DASH_MATCH:
REQUIRE_ERRORS("test.css(1): error: node name \"DASH_MATCH\".\n");
break;
case csspp::node_type_t::DECIMAL_NUMBER:
REQUIRE_ERRORS("test.css(1): error: node name \"DECIMAL_NUMBER\".\n");
break;
case csspp::node_type_t::DIVIDE:
REQUIRE_ERRORS("test.css(1): error: node name \"DIVIDE\".\n");
break;
case csspp::node_type_t::DOLLAR:
REQUIRE_ERRORS("test.css(1): error: node name \"DOLLAR\".\n");
break;
case csspp::node_type_t::EOF_TOKEN:
REQUIRE_ERRORS("test.css(1): error: node name \"EOF_TOKEN\".\n");
break;
case csspp::node_type_t::EQUAL:
REQUIRE_ERRORS("test.css(1): error: node name \"EQUAL\".\n");
break;
case csspp::node_type_t::EXCLAMATION:
REQUIRE_ERRORS("test.css(1): error: node name \"EXCLAMATION\".\n");
break;
case csspp::node_type_t::FONT_METRICS:
REQUIRE_ERRORS("test.css(1): error: node name \"FONT_METRICS\".\n");
break;
case csspp::node_type_t::FUNCTION:
REQUIRE_ERRORS("test.css(1): error: node name \"FUNCTION\".\n");
break;
case csspp::node_type_t::GREATER_EQUAL:
REQUIRE_ERRORS("test.css(1): error: node name \"GREATER_EQUAL\".\n");
break;
case csspp::node_type_t::GREATER_THAN:
REQUIRE_ERRORS("test.css(1): error: node name \"GREATER_THAN\".\n");
break;
case csspp::node_type_t::HASH:
REQUIRE_ERRORS("test.css(1): error: node name \"HASH\".\n");
break;
case csspp::node_type_t::IDENTIFIER:
REQUIRE_ERRORS("test.css(1): error: node name \"IDENTIFIER\".\n");
break;
case csspp::node_type_t::INCLUDE_MATCH:
REQUIRE_ERRORS("test.css(1): error: node name \"INCLUDE_MATCH\".\n");
break;
case csspp::node_type_t::INTEGER:
REQUIRE_ERRORS("test.css(1): error: node name \"INTEGER\".\n");
break;
case csspp::node_type_t::LESS_EQUAL:
REQUIRE_ERRORS("test.css(1): error: node name \"LESS_EQUAL\".\n");
break;
case csspp::node_type_t::LESS_THAN:
REQUIRE_ERRORS("test.css(1): error: node name \"LESS_THAN\".\n");
break;
case csspp::node_type_t::MODULO:
REQUIRE_ERRORS("test.css(1): error: node name \"MODULO\".\n");
break;
case csspp::node_type_t::MULTIPLY:
REQUIRE_ERRORS("test.css(1): error: node name \"MULTIPLY\".\n");
break;
case csspp::node_type_t::NOT_EQUAL:
REQUIRE_ERRORS("test.css(1): error: node name \"NOT_EQUAL\".\n");
break;
case csspp::node_type_t::NULL_TOKEN:
REQUIRE_ERRORS("test.css(1): error: node name \"NULL_TOKEN\".\n");
break;
case csspp::node_type_t::OPEN_CURLYBRACKET:
REQUIRE_ERRORS("test.css(1): error: node name \"OPEN_CURLYBRACKET\".\n");
break;
case csspp::node_type_t::OPEN_PARENTHESIS:
REQUIRE_ERRORS("test.css(1): error: node name \"OPEN_PARENTHESIS\".\n");
break;
case csspp::node_type_t::OPEN_SQUAREBRACKET:
REQUIRE_ERRORS("test.css(1): error: node name \"OPEN_SQUAREBRACKET\".\n");
break;
case csspp::node_type_t::PERCENT:
REQUIRE_ERRORS("test.css(1): error: node name \"PERCENT\".\n");
break;
case csspp::node_type_t::PERIOD:
REQUIRE_ERRORS("test.css(1): error: node name \"PERIOD\".\n");
break;
case csspp::node_type_t::PLACEHOLDER:
REQUIRE_ERRORS("test.css(1): error: node name \"PLACEHOLDER\".\n");
break;
case csspp::node_type_t::POWER:
REQUIRE_ERRORS("test.css(1): error: node name \"POWER\".\n");
break;
case csspp::node_type_t::PRECEDED:
REQUIRE_ERRORS("test.css(1): error: node name \"PRECEDED\".\n");
break;
case csspp::node_type_t::PREFIX_MATCH:
REQUIRE_ERRORS("test.css(1): error: node name \"PREFIX_MATCH\".\n");
break;
case csspp::node_type_t::REFERENCE:
REQUIRE_ERRORS("test.css(1): error: node name \"REFERENCE\".\n");
break;
case csspp::node_type_t::SCOPE:
REQUIRE_ERRORS("test.css(1): error: node name \"SCOPE\".\n");
break;
case csspp::node_type_t::SEMICOLON:
REQUIRE_ERRORS("test.css(1): error: node name \"SEMICOLON\".\n");
break;
case csspp::node_type_t::STRING:
REQUIRE_ERRORS("test.css(1): error: node name \"STRING\".\n");
break;
case csspp::node_type_t::SUBSTRING_MATCH:
REQUIRE_ERRORS("test.css(1): error: node name \"SUBSTRING_MATCH\".\n");
break;
case csspp::node_type_t::SUBTRACT:
REQUIRE_ERRORS("test.css(1): error: node name \"SUBTRACT\".\n");
break;
case csspp::node_type_t::SUFFIX_MATCH:
REQUIRE_ERRORS("test.css(1): error: node name \"SUFFIX_MATCH\".\n");
break;
case csspp::node_type_t::UNICODE_RANGE:
REQUIRE_ERRORS("test.css(1): error: node name \"UNICODE_RANGE\".\n");
break;
case csspp::node_type_t::URL:
REQUIRE_ERRORS("test.css(1): error: node name \"URL\".\n");
break;
case csspp::node_type_t::VARIABLE:
REQUIRE_ERRORS("test.css(1): error: node name \"VARIABLE\".\n");
break;
case csspp::node_type_t::VARIABLE_FUNCTION:
REQUIRE_ERRORS("test.css(1): error: node name \"VARIABLE_FUNCTION\".\n");
break;
case csspp::node_type_t::WHITESPACE:
REQUIRE_ERRORS("test.css(1): error: node name \"WHITESPACE\".\n");
break;
// second part
case csspp::node_type_t::AN_PLUS_B:
REQUIRE_ERRORS("test.css(1): error: node name \"AN_PLUS_B\".\n");
break;
case csspp::node_type_t::ARG:
REQUIRE_ERRORS("test.css(1): error: node name \"ARG\".\n");
break;
case csspp::node_type_t::ARRAY:
REQUIRE_ERRORS("test.css(1): error: node name \"ARRAY\".\n");
break;
case csspp::node_type_t::COMPONENT_VALUE:
REQUIRE_ERRORS("test.css(1): error: node name \"COMPONENT_VALUE\".\n");
break;
case csspp::node_type_t::DECLARATION:
REQUIRE_ERRORS("test.css(1): error: node name \"DECLARATION\".\n");
break;
case csspp::node_type_t::LIST:
REQUIRE_ERRORS("test.css(1): error: node name \"LIST\".\n");
break;
case csspp::node_type_t::MAP:
REQUIRE_ERRORS("test.css(1): error: node name \"MAP\".\n");
break;
case csspp::node_type_t::FRAME:
REQUIRE_ERRORS("test.css(1): error: node name \"FRAME\".\n");
break;
case csspp::node_type_t::max_type:
REQUIRE_ERRORS("test.css(1): error: node name \"max_type\".\n");
break;
}
// move to the next type
w = static_cast<csspp::node_type_t>(static_cast<int>(w) + 1);
}
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Print nodes", "[node] [output]")
{
// create a tree of nodes, then print it to exercise all the possible
// cases of the display() function
csspp::position pos("print.css");
csspp::node::pointer_t root(new csspp::node(csspp::node_type_t::LIST, pos));
csspp::node::pointer_t integer(new csspp::node(csspp::node_type_t::INTEGER, pos));
integer->set_integer(123);
root->add_child(integer);
csspp::node::pointer_t string(new csspp::node(csspp::node_type_t::STRING, pos));
string->set_string("bear");
root->add_child(string);
csspp::node::pointer_t decimal_number(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, pos));
decimal_number->set_decimal_number(100.0);
root->add_child(decimal_number);
csspp::node::pointer_t child(new csspp::node(csspp::node_type_t::AT_KEYWORD, pos));
child->set_string("@-char");
child->set_flag("important", true);
csspp::node::pointer_t var(new csspp::node(csspp::node_type_t::IDENTIFIER, pos));
var->set_string("colorous");
child->set_variable("test", var);
root->add_child(child);
csspp::node::pointer_t boolean(new csspp::node(csspp::node_type_t::BOOLEAN, pos));
boolean->set_boolean(true);
child->add_child(boolean);
csspp::node::pointer_t integer2(new csspp::node(csspp::node_type_t::INTEGER, pos));
integer2->set_integer(409);
child->add_child(integer2);
csspp::node::pointer_t string2(new csspp::node(csspp::node_type_t::STRING, pos));
string2->set_string("rabbit");
child->add_child(string2);
csspp::node::pointer_t bracket(new csspp::node(csspp::node_type_t::OPEN_CURLYBRACKET, pos));
bracket->set_boolean(true);
child->add_child(bracket);
csspp::node::pointer_t decimal_number2(new csspp::node(csspp::node_type_t::DECIMAL_NUMBER, pos));
decimal_number2->set_decimal_number(208.0);
bracket->add_child(decimal_number2);
csspp::node::pointer_t an_plus_b(new csspp::node(csspp::node_type_t::AN_PLUS_B, pos));
an_plus_b->set_integer(0x0000000700000003);
bracket->add_child(an_plus_b);
csspp::node::pointer_t color(new csspp::node(csspp::node_type_t::COLOR, pos));
csspp::color c;
c.set_color(0x11, 0x34, 0x78, 0xFF);
color->set_color(c);
bracket->add_child(color);
csspp::node::pointer_t font_metrics(new csspp::node(csspp::node_type_t::FONT_METRICS, pos));
font_metrics->set_font_size(3.45);
font_metrics->set_dim1("cm");
font_metrics->set_line_height(1.5);
font_metrics->set_dim2("%");
bracket->add_child(font_metrics);
std::stringstream ss;
ss << *root;
REQUIRE_TREES(ss.str(),
"LIST\n"
" INTEGER \"\" I:123\n"
" STRING \"bear\"\n"
" DECIMAL_NUMBER \"\" D:100\n"
" AT_KEYWORD \"@-char\" I:0 F:important\n"
" V:test\n"
" IDENTIFIER \"colorous\"\n"
" BOOLEAN B:true\n"
" INTEGER \"\" I:409\n"
" STRING \"rabbit\"\n"
" OPEN_CURLYBRACKET B:true\n"
" DECIMAL_NUMBER \"\" D:208\n"
" AN_PLUS_B S:3n+7\n"
" COLOR H:ff783411\n"
" FONT_METRICS FM:3.45cm/150%\n"
);
// also test a clone() and see that the clone is a 1:1 an equivalent
csspp::node::pointer_t p(root->clone());
std::stringstream ss2;
ss2 << *p;
REQUIRE_TREES(ss2.str(),
"LIST\n"
" INTEGER \"\" I:123\n"
" STRING \"bear\"\n"
" DECIMAL_NUMBER \"\" D:100\n"
" AT_KEYWORD \"@-char\" I:0 F:important\n"
" V:test\n"
" IDENTIFIER \"colorous\"\n"
" BOOLEAN B:true\n"
" INTEGER \"\" I:409\n"
" STRING \"rabbit\"\n"
" OPEN_CURLYBRACKET B:true\n"
" DECIMAL_NUMBER \"\" D:208\n"
" AN_PLUS_B S:3n+7\n"
" COLOR H:ff783411\n"
" FONT_METRICS FM:3.45cm/150%\n"
);
// no error left over
REQUIRE_ERRORS("");
}
TEST_CASE("Font metrics", "[node] [output]")
{
// create a tree of nodes, then print it to exercise all the possible
// cases of the display() function
csspp::position pos("font-metrics.css");
csspp::node::pointer_t font_metrics(new csspp::node(csspp::node_type_t::FONT_METRICS, pos));
for(int i(0); i < 100; ++i)
{
csspp::decimal_number_t const size(static_cast<csspp::decimal_number_t>(rand() % 1000) / 10.0);
font_metrics->set_font_size(size);
REQUIRE((font_metrics->get_font_size() - size) < 0.0001);
csspp::decimal_number_t const height(static_cast<csspp::decimal_number_t>(rand() % 1000) / 10.0);
font_metrics->set_line_height(height);
REQUIRE((font_metrics->get_line_height() - height) < 0.0001);
// line height has no effect on the font size
REQUIRE((font_metrics->get_font_size() - size) < 0.0001);
// to see that font size has no effect on line height...
csspp::decimal_number_t const size2(static_cast<csspp::decimal_number_t>(rand() % 1000) / 10.0);
font_metrics->set_font_size(size2);
REQUIRE((font_metrics->get_font_size() - size2) < 0.0001);
REQUIRE((font_metrics->get_line_height() - height) < 0.0001);
}
// no error left over
REQUIRE_ERRORS("");
}
// Local Variables:
// mode: cpp
// indent-tabs-mode: nil
// c-basic-offset: 4
// tab-width: 4
// End:
// vim: ts=4 sw=4 et
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_82_goodB2G.cpp
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-82_goodB2G.tmpl.cpp
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
* BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_82.h"
#define HELLO_STRING "hello"
namespace CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_82
{
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_82_goodB2G::action(size_t data)
{
{
char * myString;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING) && data < 100)
{
myString = (char *)malloc(data*sizeof(char));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
}
#endif /* OMITGOOD */
|
/* Copyright 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/base/init.h"
#include "mongo/client/connpool.h"
#include "mongo/platform/cstdint.h"
#include "mongo/util/net/listen.h"
#include "mongo/util/net/message_port.h"
#include "mongo/util/net/message_server.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/log.h"
#include "mongo/util/quick_exit.h"
#include "mongo/util/time_support.h"
#include "mongo/util/timer.h"
#include "mongo/unittest/unittest.h"
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/thread.hpp>
/**
* Tests for ScopedDbConnection, particularly in connection pool management.
* The tests also indirectly tests DBClientConnection's failure detection
* logic (hence the use of the dummy server as opposed to mocking the
* connection).
*/
using boost::scoped_ptr;
using mongo::DBClientBase;
using mongo::FailPoint;
using mongo::ScopedDbConnection;
using std::string;
using std::vector;
namespace {
const string TARGET_HOST = "localhost:27017";
const int TARGET_PORT = 27017;
mongo::mutex shutDownMutex("shutDownMutex");
bool shuttingDown = false;
}
namespace mongo {
class OperationContext;
// Symbols defined to build the binary correctly.
bool inShutdown() {
scoped_lock sl(shutDownMutex);
return shuttingDown;
}
DBClientBase* createDirectClient(OperationContext* txn) { return NULL; }
void dbexit(ExitCode rc, const char *why){
{
scoped_lock sl(shutDownMutex);
shuttingDown = true;
}
quickExit(rc);
}
void exitCleanly(ExitCode rc, OperationContext* txn) {
dbexit(rc, "");
}
bool haveLocalShardingInfo(const string& ns) {
return false;
}
class DummyMessageHandler: public MessageHandler {
public:
virtual void connected(AbstractMessagingPort* p) {
}
virtual void process(Message& m,
AbstractMessagingPort* port,
LastError * le) {
boost::this_thread::interruption_point();
}
virtual void disconnected(AbstractMessagingPort* p) {
}
};
}
namespace mongo_test {
mongo::DummyMessageHandler dummyHandler;
// TODO: Take this out and make it as a reusable class in a header file. The only
// thing that is preventing this from happening is the dependency on the inShutdown
// method to terminate the socket listener thread.
/**
* Very basic server that accepts connections. Note: can only create one instance
* at a time. Should not create as a static global instance because of dependency
* with ListeningSockets::_instance.
*
* Warning: Not thread-safe
*
* Note: external symbols used:
* shutDownMutex, shuttingDown
*/
class DummyServer {
public:
/**
* Creates a new server that listens to the given port.
*
* @param port the port number to listen to.
*/
DummyServer(int port): _port(port), _server(NULL) {
}
~DummyServer() {
stop();
}
/**
* Starts the server if it is not yet running.
*
* @param messageHandler the message handler to use for this server. Ownership
* of this object is passed to this server.
*/
void run(mongo::MessageHandler* messsageHandler) {
if (_server != NULL) {
return;
}
mongo::MessageServer::Options options;
options.port = _port;
{
mongo::mutex::scoped_lock sl(shutDownMutex);
shuttingDown = false;
}
_server = mongo::createServer(options, messsageHandler);
_serverThread = boost::thread(runServer, _server);
}
/**
* Stops the server if it is running.
*/
void stop() {
if (_server == NULL) {
return;
}
{
mongo::mutex::scoped_lock sl(shutDownMutex);
shuttingDown = true;
}
mongo::ListeningSockets::get()->closeAll();
_serverThread.join();
int connCount = mongo::Listener::globalTicketHolder.used();
size_t iterCount = 0;
while (connCount > 0) {
if ((++iterCount % 20) == 0) {
mongo::log() << "DummyServer: Waiting for " << connCount
<< " connections to close." << std::endl;
}
mongo::sleepmillis(500);
connCount = mongo::Listener::globalTicketHolder.used();
}
delete _server;
_server = NULL;
}
/**
* Helper method for running the server on a separate thread.
*/
static void runServer(mongo::MessageServer* server) {
server->setupSockets();
server->run();
}
private:
const int _port;
boost::thread _serverThread;
mongo::MessageServer* _server;
};
/**
* Warning: cannot run in parallel
*/
class DummyServerFixture: public mongo::unittest::Test {
public:
void setUp() {
_maxPoolSizePerHost = mongo::pool.getMaxPoolSize();
_dummyServer = new DummyServer(TARGET_PORT);
_dummyServer->run(&dummyHandler);
mongo::DBClientConnection conn;
mongo::Timer timer;
// Make sure the dummy server is up and running before proceeding
while (true) {
try {
conn.connect(TARGET_HOST);
break;
} catch (const mongo::ConnectException&) {
if (timer.seconds() > 20) {
FAIL("Timed out connecting to dummy server");
}
}
}
}
void tearDown() {
ScopedDbConnection::clearPool();
delete _dummyServer;
mongo::pool.setMaxPoolSize(_maxPoolSizePerHost);
}
protected:
static void assertGreaterThan(uint64_t a, uint64_t b) {
ASSERT_GREATER_THAN(a, b);
}
static void assertNotEqual(uint64_t a, uint64_t b) {
ASSERT_NOT_EQUALS(a, b);
}
/**
* Tries to grab a series of connections from the pool, perform checks on
* them, then put them back into the pool. After that, it checks these
* connections can be retrieved again from the pool.
*
* @param checkFunc method for comparing new connections and arg2.
* @param arg2 the value to pass as the 2nd parameter of checkFunc.
* @param newConnsToCreate the number of new connections to make.
*/
void checkNewConns(void (*checkFunc)(uint64_t, uint64_t), uint64_t arg2,
size_t newConnsToCreate) {
vector<ScopedDbConnection*> newConnList;
for (size_t x = 0; x < newConnsToCreate; x++) {
ScopedDbConnection* newConn = new ScopedDbConnection(TARGET_HOST);
checkFunc(newConn->get()->getSockCreationMicroSec(), arg2);
newConnList.push_back(newConn);
}
const uint64_t oldCreationTime = mongo::curTimeMicros64();
for (vector<ScopedDbConnection*>::iterator iter = newConnList.begin();
iter != newConnList.end(); ++iter) {
(*iter)->done();
delete *iter;
}
newConnList.clear();
// Check that connections created after the purge was put back to the pool.
for (size_t x = 0; x < newConnsToCreate; x++) {
ScopedDbConnection* newConn = new ScopedDbConnection(TARGET_HOST);
ASSERT_LESS_THAN(newConn->get()->getSockCreationMicroSec(), oldCreationTime);
newConnList.push_back(newConn);
}
for (vector<ScopedDbConnection*>::iterator iter = newConnList.begin();
iter != newConnList.end(); ++iter) {
(*iter)->done();
delete *iter;
}
}
private:
static void runServer(mongo::MessageServer* server) {
server->setupSockets();
server->run();
}
DummyServer* _dummyServer;
uint32_t _maxPoolSizePerHost;
};
TEST_F(DummyServerFixture, BasicScopedDbConnection) {
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
DBClientBase* conn1Ptr = conn1.get();
conn1.done();
ScopedDbConnection conn3(TARGET_HOST);
ASSERT_EQUALS(conn1Ptr, conn3.get());
conn2.done();
conn3.done();
}
TEST_F(DummyServerFixture, InvalidateBadConnInPool) {
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
ScopedDbConnection conn3(TARGET_HOST);
conn1.done();
conn3.done();
const uint64_t badCreationTime = mongo::curTimeMicros64();
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::alwaysOn);
try {
conn2->query("test.user", mongo::Query());
}
catch (const mongo::SocketException&) {
}
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::off);
conn2.done();
checkNewConns(assertGreaterThan, badCreationTime, 10);
}
TEST_F(DummyServerFixture, DontReturnKnownBadConnToPool) {
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
ScopedDbConnection conn3(TARGET_HOST);
conn1.done();
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::alwaysOn);
try {
conn3->query("test.user", mongo::Query());
}
catch (const mongo::SocketException&) {
}
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::off);
const uint64_t badCreationTime = conn3->getSockCreationMicroSec();
conn3.done();
// attempting to put a 'bad' connection back to the pool
conn2.done();
checkNewConns(assertGreaterThan, badCreationTime, 10);
}
TEST_F(DummyServerFixture, InvalidateBadConnEvenWhenPoolIsFull) {
mongo::pool.setMaxPoolSize(2);
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
ScopedDbConnection conn3(TARGET_HOST);
conn1.done();
conn3.done();
const uint64_t badCreationTime = mongo::curTimeMicros64();
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::alwaysOn);
try {
conn2->query("test.user", mongo::Query());
}
catch (const mongo::SocketException&) {
}
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::off);
conn2.done();
checkNewConns(assertGreaterThan, badCreationTime, 2);
}
TEST_F(DummyServerFixture, DontReturnConnGoneBadToPool) {
ScopedDbConnection conn1(TARGET_HOST);
const uint64_t conn1CreationTime = conn1->getSockCreationMicroSec();
uint64_t conn2CreationTime = 0;
{
ScopedDbConnection conn2(TARGET_HOST);
conn2CreationTime = conn2->getSockCreationMicroSec();
conn1.done();
// conn2 gets out of scope without calling done()
}
// conn2 should not have been put back into the pool but it should
// also not invalidate older connections since it didn't encounter
// a socket exception.
ScopedDbConnection conn1Again(TARGET_HOST);
ASSERT_EQUALS(conn1CreationTime, conn1Again->getSockCreationMicroSec());
checkNewConns(assertNotEqual, conn2CreationTime, 10);
conn1Again.done();
}
}
|
#include <QtWidgets>
#include <QtMath>
#include "ma_jpeg_codec.h"
#define BYTECLIP(v) Clip8[(uint)(v) & 0x3FF]
#define JPEG_MARKER_SOF0 0xFFC0
#define JPEG_MARKER_SOF1 0xFFC1
#define JPEG_MARKER_SOF2 0xFFC2
#define JPEG_MARKER_SOF3 0xFFC3
#define JPEG_MARKER_SOF5 0xFFC5
#define JPEG_MARKER_SOF6 0xFFC6
#define JPEG_MARKER_SOF7 0xFFC7
#define JPEG_MARKER_JPG 0xFFC8
#define JPEG_MARKER_SOF9 0xFFC9
#define JPEG_MARKER_SOF10 0xFFCA
#define JPEG_MARKER_SOF11 0xFFCB
#define JPEG_MARKER_SOF13 0xFFCD
#define JPEG_MARKER_SOF14 0xFFCE
#define JPEG_MARKER_SOF15 0xFFCF
#define JPEG_MARKER_DHT 0xFFC4
#define JPEG_MARKER_DAC 0xFFCC
//#define JPEG_MARKER_RST 0xFFD0 - 0xFFD7
#define IS_JPEG_MARKER_RST(m) (m >= 0xFFD0) && (m <= 0xFFD7) ? 1 : 0
#define JPEG_MARKER_SOI 0xFFD8
#define JPEG_MARKER_EOI 0xFFD9
#define JPEG_MARKER_SOS 0xFFDA
#define JPEG_MARKER_DQT 0xFFDB
#define JPEG_MARKER_DNL 0xFFDC
#define JPEG_MARKER_DRI 0xFFDD
#define JPEG_MARKER_DHP 0xFFDE
#define JPEG_MARKER_EXP 0xFFDF
//#define JPEG_MARKER_APP 0xFFE0 - 0xFFEF
//#define JPEG_MARKER_JPG 0xFFF0 - 0xFFFD
#define IS_JPEG_MARKER_APP(m) (m >= 0xFFE0) && (m <= 0xFFEF) ? 1 : 0
#define IS_JPEG_MARKER_JPG(m) (m >= 0xFFF0) && (m <= 0xFFFD) ? 1 : 0
#define JPEG_MARKER_COM 0xFFFE
#define JPEG_MARKER_TEM 0xFF01
//#define JPEG_MARKER_RES 0xFF02 - 0xFFBF
using namespace std;
// Zig-zag sequence of quantized DCT coefficients
const uint8_t ma_jpeg_codec::zigzad_order[64] =
{
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63,
};
const uint8_t ma_jpeg_codec::zigzad_reverse_order[64] = {
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63
};
static int16_t fsd[1024] = {
/* 0..255 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
/* 256..511 */
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
/* -512..-257 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* -256..-1 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
const uint8_t ma_jpeg_codec::default_quantization_table_luma[] =
{
16,11,10,16, 24, 40, 51, 61,
12,12,14,19, 26, 58, 60, 55,
14,13,16,24, 40, 57, 69, 56,
14,17,22,29, 51, 87, 80, 62,
18,22,37,56, 68,109,103, 77,
24,35,55,64, 81,104,113, 92,
49,64,78,87,103,121,120,101,
72,92,95,98,112,100,103, 99,
};
const uint8_t ma_jpeg_codec::default_quantization_table_chroma[] =
{
17,18,24,47,99,99,99,99,
18,21,26,66,99,99,99,99,
24,26,56,99,99,99,99,99,
47,66,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,
};
const uint8_t ma_jpeg_codec::default_huffman_table_dc_len_luma[16] =
{
0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0
};
const uint8_t ma_jpeg_codec::default_huffman_table_dc_len_chroma[16] =
{
0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0
};
const uint8_t ma_jpeg_codec::default_huffman_table_dc_val_luma[12] =
{
0,1,2,3,4,5,6,7,8,9,10,11
};
const uint8_t ma_jpeg_codec::default_huffman_table_dc_val_chroma[12] =
{
0,1,2,3,4,5,6,7,8,9,10,11
};
const uint8_t ma_jpeg_codec::default_huffman_table_ac_len_luma[16] =
{
0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x05,0x05,0x04,0x04,0x00,0x00,0x01,0x7D
};
const uint8_t ma_jpeg_codec::default_huffman_table_ac_len_chroma[16] =
{
0x00,0x02,0x01,0x02,0x04,0x04,0x03,0x04,0x07,0x05,0x04,0x04,0x00,0x01,0x02,0x77
};
const uint8_t ma_jpeg_codec::default_huffman_table_ac_val_luma[] =
{
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
0xF9, 0xFA
};
const uint8_t ma_jpeg_codec::default_huffman_table_ac_val_chroma[] =
{
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0,
0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26,
0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5,
0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3,
0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA,
0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
0xF9, 0xFA
};
uint16_t get_ptr_16bits_data(char * ptr)
{
uint16_t data;
QByteArray tempData;
tempData = tempData + *ptr;
tempData = tempData + *(ptr+1) + *(ptr+2) + *(ptr+3);
data = strtoul(tempData.data(), NULL, 16);
return data;
}
uint8_t get_ptr_8bits_data(char * ptr)
{
uint8_t data;
QByteArray tempData;
tempData = tempData + *ptr;
tempData = tempData + *(ptr+1);
data = strtoul(tempData.data(), NULL, 16);
return data;
}
uint8_t get_ptr_4bits_data(char * ptr)
{
uint8_t data;
QByteArray tempData;
tempData = tempData + *ptr;
data = strtoul(tempData.data(), NULL, 16);
return data;
}
bool isMarkerTableOrMisStart(uint16_t marker)
{
return ((JPEG_MARKER_DQT == marker)
|| (JPEG_MARKER_DHT == marker)
|| (JPEG_MARKER_DAC == marker)
|| (JPEG_MARKER_DRI == marker)
|| IS_JPEG_MARKER_APP(marker)
|| (JPEG_MARKER_COM == marker));
}
bool isMarkerSOF(uint16_t marker)
{
return ((JPEG_MARKER_SOF0 == marker)
|| (JPEG_MARKER_SOF1 == marker)
|| (JPEG_MARKER_SOF2 == marker)
|| (JPEG_MARKER_SOF3 == marker)
|| (JPEG_MARKER_SOF5 == marker)
|| (JPEG_MARKER_SOF6 == marker)
|| (JPEG_MARKER_SOF7 == marker)
|| (JPEG_MARKER_JPG == marker)
|| (JPEG_MARKER_SOF9 == marker)
|| (JPEG_MARKER_SOF10 == marker)
|| (JPEG_MARKER_SOF11 == marker)
|| (JPEG_MARKER_SOF13 == marker)
|| (JPEG_MARKER_SOF14 == marker)
|| (JPEG_MARKER_SOF15 == marker));
}
bool isMarkerFrameStart(uint16_t marker)
{
return (isMarkerSOF(marker)
|| isMarkerTableOrMisStart(marker)
|| (JPEG_MARKER_EXP == marker));
}
bool isMarkerScanStart(uint16_t marker)
{
return ((JPEG_MARKER_SOS == marker)
|| isMarkerTableOrMisStart(marker));
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_tableORmis(
char ** pCur,
Decode *dec)
{
uint16_t marker;
parse_tableORmis_part_loop:
marker = get_ptr_16bits_data(*pCur);
switch (marker & 0xffff)
{
//Define quantization table(s)/DQT
case JPEG_MARKER_DQT:
jpeg_parse_tableORmis_qtable(pCur,dec);
goto parse_tableORmis_part_loop;
// Huffman table/DHT
case JPEG_MARKER_DHT:
jpeg_parse_tableORmis_hufftable(pCur,dec);
goto parse_tableORmis_part_loop;
//Arithmetic coding conditioning
case JPEG_MARKER_DAC:
jpeg_parse_tableORmis_arithtable(pCur,dec);
goto parse_tableORmis_part_loop;
// Define restart interval/DRI
case JPEG_MARKER_DRI:
jpeg_parse_tableORmis_restart(pCur,dec);
goto parse_tableORmis_part_loop;
// Comment/COM
case JPEG_MARKER_COM:
jpeg_parse_tableORmis_comment(pCur,dec);
goto parse_tableORmis_part_loop;
//Reserved for application segments/APP
case 0xFFE0:
case 0xFFE1:
case 0xFFE2:
case 0xFFE3:
case 0xFFE4:
case 0xFFE5:
case 0xFFE6:
case 0xFFE7:
case 0xFFE8:
case 0xFFE9:
case 0xFFEA:
case 0xFFEB:
case 0xFFEC:
case 0xFFED:
case 0xFFEE:
case 0xFFEF:
jpeg_parse_tableORmis_app(pCur,dec);
goto parse_tableORmis_part_loop;
default:
break;
}
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_tableORmis_qtable(
char **pCur,
Decode *dec)
{
//DQT
uint16_t length;
uint16_t offset_byte_from_Lh = 0;
uint qtable_precosion,
qtable_dst_id;
*pCur+=4;
//Quantization table definition length
length = get_ptr_16bits_data(*pCur);
*pCur+=4;
// Quantization table elements
while ((offset_byte_from_Lh + 2) < length)
{
//Quantization table element precision
qtable_precosion = get_ptr_4bits_data(*pCur);
qtable_precosion &= 1;
(*pCur)++;
//Quantization table destination identifie
qtable_dst_id = get_ptr_4bits_data(*pCur);
qtable_dst_id &= 3;
(*pCur)++;
//8-bit.the precision of the Qk values.
if(qtable_precosion == 0)
{
for(int i = 0; i < 64; i++)
{
dec->qtable[qtable_dst_id][i] = (uint16_t)get_ptr_8bits_data(*pCur);
*pCur+=2;
}
}
//16-bit
else if(qtable_precosion == 1)
{
for(int i = 0; i < 64; i++)
{
dec->qtable[qtable_dst_id][i] = get_ptr_16bits_data(*pCur);
(*pCur)++;
}
}
offset_byte_from_Lh = 65 + 64 * qtable_precosion + offset_byte_from_Lh;
}
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_tableORmis_hufftable(
char * *pCur,
Decode *dec)
{
uint16_t length;
uint16_t offset_byte_from_Lh = 0;
uint8_t hufftable_class, //Table class-- 0 = DC table or lossless table, 1 = AC table
hufftable_dst_id; //Th
*pCur+=4;
//Huffman table definition length
length = get_ptr_16bits_data(*pCur);
*pCur+=4;
//Multiple huffman table
while ((offset_byte_from_Lh + 2) < length)
{
uint16_t sum_temp = 0;
//table class,AC or DC
hufftable_class = (HUFFCLASS)(uint8_t)get_ptr_4bits_data(*pCur);
(*pCur)++;
//des id
hufftable_dst_id = (HUFFTABLE_ID)(uint8_t)get_ptr_4bits_data(*pCur);
(*pCur)++;
//Number of Huffman codes of length
for(int i = 0; i < 16; i++)
{
dec->bits[hufftable_class][hufftable_dst_id][i] = get_ptr_8bits_data(*pCur);
*pCur+=2;
sum_temp+= dec->bits[hufftable_class][hufftable_dst_id][i];
}
// Value associated with each Huffman code
delete[] dec->huffval[hufftable_class][hufftable_dst_id];
dec->huffval[hufftable_class][hufftable_dst_id] = new uint8_t[sum_temp];
for(int i = 0; i < sum_temp; i++)
{
dec->huffval[hufftable_class][hufftable_dst_id][i] = get_ptr_8bits_data(*pCur);
*pCur+=2;
}
offset_byte_from_Lh = 17 + sum_temp + offset_byte_from_Lh; //class-4bits,id-4bits,huffcode-16bytes
}
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_tableORmis_arithtable(
char **pCur,
Decode *dec)
{
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_tableORmis_restart(
char **pCur,
Decode *dec)
{
//RSTi = get_ptr_16bits_data(pCur+8);
*pCur+=12;
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_tableORmis_comment(
char **pCur,
Decode *dec)
{
//COM
uint16_t length;
length = get_ptr_16bits_data(*pCur+4);
length+=2;
*pCur+=(2 * length);
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_tableORmis_app(
char **pCur,
Decode *dec)
{
//APP
uint16_t length;
length = get_ptr_16bits_data(*pCur+4);
length+=2;
*pCur+=(2 * length);
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_SOI(
char **pCur,
Decode *dec)
{
//parse SOI
if((get_ptr_16bits_data(*pCur) & 0xffff) != 0xffd8)
{ return JPEG_SOI_NOT_FOUND; }
*pCur+=4;
return JPEG_OK;
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_DHP(
char * *pCur,
Decode *dec)
{
if(JPEG_MARKER_DHP != get_ptr_16bits_data(*pCur)){ return JPEG_OK; }
//APP
uint16_t length;
length = get_ptr_16bits_data(*pCur+4);
length+=2;
*pCur+=(2 * length);
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_EOI(
char **pCur,
Decode *dec)
{
//APP
if(JPEG_MARKER_EOI != get_ptr_16bits_data(*pCur)){ return JPEG_EOI_NOT_FOUND; }
uint16_t length;
length = get_ptr_16bits_data(*pCur+4);
length+=2;
*pCur+=(2 * length);
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_EXP(
char **pCur,
Decode *dec)
{
if(JPEG_MARKER_EXP != get_ptr_16bits_data(*pCur)){ return JPEG_OK; }
//APP
uint16_t length;
length = get_ptr_16bits_data(*pCur+4);
length+=2;
*pCur+=(2 * length);
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_SOF(
char **pCur,
Decode *dec)
{
//SOF
uint16_t length;
*pCur+=4;
//frame header length
length = get_ptr_16bits_data(*pCur);
*pCur+=4;
//sample precision
dec->sample_precision = get_ptr_8bits_data(*pCur);
*pCur+=2;
//number of lines
dec->height = get_ptr_16bits_data(*pCur);
*pCur+=4;
//number of samples per line
dec->width = get_ptr_16bits_data(*pCur);
*pCur+=4;
//number of image components in frame
dec->frame_component_num = get_ptr_8bits_data(*pCur);
if(dec->frame_component_num != 3) { return JPEG_ONLY_SUPPORT_THREE_COM; }
*pCur+=2;
dec->frame_components = new FrameComponent[3];
for(int i = 0; i < dec->frame_component_num; i++)
{
//component id
(dec->frame_components[i]).id = get_ptr_8bits_data(*pCur);
*pCur+=2;
//hor sampling factors
(dec->frame_components[i]).h = (H_FACTOR)get_ptr_4bits_data(*pCur);
(*pCur)++;
//ver sampling factors
(dec->frame_components[i]).v = (V_FACTOR)get_ptr_4bits_data(*pCur);
(*pCur)++;
//quantization table destination selector
(dec->frame_components[i]).qtable = (QTABLE_ID)get_ptr_8bits_data(*pCur);
*pCur+=2;
dec->block8x8_per_comp[i] = (dec->frame_components[i]).h * (dec->frame_components[i]).v;
}
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_SOS(
char **pCur,
Decode *dec)
{
//SOS
uint16_t length;
uint8_t sample_precision,
image_component;
*pCur+=4;
// Scan header length
length = get_ptr_16bits_data(*pCur);
*pCur+=4;
// Number of image components in scan
dec->scan_component_num = get_ptr_8bits_data(*pCur);
*pCur+=2;
delete dec->scan_components;
dec->scan_components = new ScanComponent[dec->scan_component_num];
for(int i = 0; i < dec->scan_component_num; i++)
{
//Scan component selector
(dec->scan_components[i]).id = get_ptr_8bits_data(*pCur);
*pCur+=2;
//DC entropy coding table destination selector
(dec->scan_components[i]).DC_dst_id = (HUFFTABLE_ID)get_ptr_4bits_data(*pCur);
(*pCur)++;
//AC entropy coding table destination selector
(dec->scan_components[i]).AC_dst_id = (HUFFTABLE_ID)get_ptr_4bits_data(*pCur);
(*pCur)++;
}
//Start of spectral or predictor selection
//spectral_start = get_ptr_8bits_data(pCur);
*pCur+=2;
//End of spectral selection
//spectral_end = get_ptr_8bits_data(pCur);
*pCur+=2;
//Successive approximation bit position high
//approx_high = get_ptr_4bits_data(pCur);
(*pCur)++;
//Successive approximation bit position low or point transform
//approx_low = get_ptr_4bits_data(pCur);
(*pCur)++;
}
void
ma_jpeg_codec::jpeg_decode_MCU(
char ** pCur,
Decode *dec)
{
int MCU_Ns_sum = 0;
int MCU_Ns_cop[dec->frame_component_num];
int MCU_cop_id[16];
for(int k = 0, i = 0; k < dec->frame_component_num; k++)
{
MCU_Ns_cop[k] = (dec->frame_components[k]).h * (dec->frame_components[k]).v;
MCU_Ns_sum+=MCU_Ns_cop[k];
MCU_Ns_cop[k] = MCU_Ns_sum;
for( ; i < MCU_Ns_sum; i++)
{
dec->MCU_comp_id[i] = k;
MCU_cop_id[i] = k;
}
}
int i = 0;
int sum = 0;
dec->hor_MCU_num = (dec->width)/16 + 1;
dec->ver_MCU_num = (dec->height)/16 + 1;
const int stored_width = dec->hor_MCU_num * 16;
const int stored_height = dec->ver_MCU_num * 16;
dec->decodedata = new uint8_t[stored_width*stored_height*3]; //not sufficient here, need to make imporvement
memset(dec->block8X8, 0, sizeof(dec->block8X8[0][0]) * 64 * 12);
while(true)
{
if(JPEG_ECS_OK == jpeg_decode_DC((dec->scan_components[MCU_cop_id[i]]).DC_dst_id,pCur,dec))
{
break;
}
if(JPEG_ECS_OK == jpeg_decode_AC((dec->scan_components[MCU_cop_id[i]]).AC_dst_id,pCur,dec))
{
break;
}
i++;
(dec->comp_count)++;
if(i == MCU_Ns_sum)
{
switch (dec->block8x8_per_comp[1])
{
case 4:
decode8x8(dec->decodedata,dec->block8X8,0,4,8,dec);
decode8x8(dec->decodedata,dec->block8X8,1,5,9,dec);
decode8x8(dec->decodedata,dec->block8X8,2,6,10,dec);
decode8x8(dec->decodedata,dec->block8X8,3,7,11,dec);
break;
case 2:
decode8x8(dec->decodedata,dec->block8X8,0,4,6,dec);
decode8x8(dec->decodedata,dec->block8X8,1,4,6,dec);
decode8x8(dec->decodedata,dec->block8X8,2,5,7,dec);
decode8x8(dec->decodedata,dec->block8X8,3,5,7,dec);
break;
case 1:
decode8x8(dec->decodedata,dec->block8X8,0,4,5,dec);
decode8x8(dec->decodedata,dec->block8X8,1,4,5,dec);
decode8x8(dec->decodedata,dec->block8X8,2,4,5,dec);
decode8x8(dec->decodedata,dec->block8X8,3,4,5,dec);
break;
default:
break;
}
sum++;
dec->hor_MCU_count = sum % dec->hor_MCU_num;
dec->ver_MCU_count = sum / dec->hor_MCU_num;
}
i = i % MCU_Ns_sum;
dec->comp_count = i;
}
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_decode_DC(
HUFFTABLE_ID id,
char ** pCur,
Decode *dec)
{
#define iC (dec->comp_count)
#define idC (dec->MCU_comp_id)
uint8_t t;
uint16_t diff;
int16_t result;
if(JPEG_ECS_OK == jpeg_decode_DECODE(HUFFCLASS_DC,id,pCur,dec))
{
return JPEG_ECS_OK;
}
t = dec->decoded_temp_val;
diff = jpeg_decode_RECEIVE(t,pCur,dec);
result = jpeg_decode_EXTEND(diff,t);
dec->block8X8[iC][0] = result + dec->preDC[idC[iC]];
dec->preDC[idC[iC]] = dec->block8X8[iC][0];
return JPEG_OK;
#undef iC
#undef idC
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_decode_AC(
HUFFTABLE_ID id,
char ** pCur,
Decode *dec)
{
#define iC (dec->comp_count)
uint8_t RS,SSSS,RRRR,R;
int16_t ZZ_k;
int k = 1;
while(true)
{
if(JPEG_ECS_OK == jpeg_decode_DECODE(HUFFCLASS_AC,id,pCur,dec))
{
return JPEG_ECS_OK;
}
RS = dec->decoded_temp_val;
SSSS = RS % 16;
RRRR = RS >> 4;
R = RRRR;
if(SSSS != 0)
{
k+=R;
ZZ_k = jpeg_decode_ZZ(SSSS,pCur,dec);
dec->block8X8[iC][k] = ZZ_k;
if(k == 63){ return JPEG_OK; }
else
{
k++;
continue;
}
}
else
{
if(R == 15)
{
k+=16;
continue;
}
else { return JPEG_OK; }
}
}
#undef iC
}
void
ma_jpeg_codec::jpeg_decode_decodeTableGeneration(
HUFFCLASS huffclass,
HUFFTABLE_ID id,
Decode *dec)
{
std::fill_n(dec->MINCODE[huffclass][id], 16, -1);
std::fill_n(dec->MAXCODE[huffclass][id], 16, -1);
int8_t bitcount = 0;
for(int i=0; i < 16 ; i++)
{
for(int j = 0; j < dec->bits[huffclass][id][i]; j++)
{
if((dec->huffcode[huffclass][id][j+bitcount] < dec->MINCODE[huffclass][id][i])
|| (dec->MINCODE[huffclass][id][i] == -1))
{
dec->MINCODE[huffclass][id][i] = dec->huffcode[huffclass][id][j+bitcount];
}
if(dec->huffcode[huffclass][id][j+bitcount] > dec->MAXCODE[huffclass][id][i])
{
dec->MAXCODE[huffclass][id][i] = dec->huffcode[huffclass][id][j+bitcount];
}
}
dec->valptr[huffclass][id][i] = bitcount;
bitcount = bitcount + dec->bits[huffclass][id][i];
}
}
void
ma_jpeg_codec::jpeg_decode_huffsizeGeneration(
HUFFCLASS huffclass,
HUFFTABLE_ID id,
Decode *dec)
{
dec->huffsize[huffclass][id] = new uint8_t[256];
uint8_t index = 0;
for(int i = 0; i < 16; i++)
{
for(int j = 0; j < dec->bits[huffclass][id][i]; j++)
{
dec->huffsize[huffclass][id][index] = (uint8_t) (i+1);
index++;
}
}
}
void
ma_jpeg_codec::jpeg_decode_huffcodeGeneration(
HUFFCLASS huffclass,
HUFFTABLE_ID id,
Decode *dec)
{
uint16_t si = dec->huffsize[huffclass][id][0];
uint16_t code = 0;
dec->huffcode[huffclass][id] = new uint16_t[256];
for(int i = 0, k = 0; i < 16; i++)
{
while(si == dec->huffsize[huffclass][id][k])
{
dec->huffcode[huffclass][id][k] = code;
code++;
k++;
}
code <<= 1;
si++;
}
}
int16_t
ma_jpeg_codec::jpeg_decode_ZZ(
uint8_t size,
char ** pCur,
Decode *dec)
{
uint16_t ZZ_k;
int16_t result;
ZZ_k = jpeg_decode_RECEIVE(size,pCur,dec);
result = jpeg_decode_EXTEND(ZZ_k,size);
return result;
}
uint8_t
ma_jpeg_codec::jpeg_decode_NEXTBYTE(
char * pCur)
{
uint8_t data;
QByteArray tempData;
tempData = tempData + *pCur;
tempData = tempData + *(pCur+1);
data = strtoul(tempData.data(), NULL, 16);
return data;
}
int8_t
ma_jpeg_codec::jpeg_decode_NEXTBIT(
char ** pCur,
Decode *dec)
{
uint8_t b,b2,bit;
if(dec->count == 0)
{
b = jpeg_decode_NEXTBYTE(*pCur);
dec->count = 8;
if(b == 0xFF)
{
b2 = jpeg_decode_NEXTBYTE(*pCur+2);
if(b2 == 0)
{
dec->is_stuff = true;
goto return_BIT;
}
else
{
if(b2 == 0xDC)
{
//jpeg_parse_DNL();
}
else
{
return -1;//error
}
}
}
else
{
goto return_BIT;
}
}
else
{
b = jpeg_decode_NEXTBYTE(*pCur);
}
return_BIT:
(dec->count)--;
//qDebug() << "b" <<b;
//qDebug() << "count" << dec->count;
bit = (b & ( 1 << (dec->count) )) >> (dec->count);
//qDebug() << "bit" <<bit;
if(dec->count == 0)
{
if(dec->is_stuff == true)
{
//qDebug() << "1111111111";
(*pCur)+=4;
dec->is_stuff = false;
}
else
{
(*pCur)+=2;
}
}
//qDebug() << "16bits:" << get_ptr_16bits_data(*pCur);;
//qDebug() << "----";
return bit;
}
uint16_t
ma_jpeg_codec::jpeg_decode_RECEIVE(
uint8_t ssss,
char ** pCur,
Decode *dec)
{
uint16_t V = 0;
for(int i = 0; i != ssss; i++)
{
V = (V << 1) + (uint16_t)jpeg_decode_NEXTBIT(pCur,dec);
}
//qDebug() << "receive:" << V;
return V;
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_decode_DECODE(
HUFFCLASS huffclass,
HUFFTABLE_ID id,
char ** pCur,
Decode *dec)
{
int i = 0;
uint16_t J;
int8_t nextbit;
uint16_t code;
nextbit = jpeg_decode_NEXTBIT(pCur,dec);
if(-1 == nextbit){ return JPEG_ECS_OK; }
code = (uint16_t)nextbit;
while(code > dec->MAXCODE[huffclass][id][i])
{
nextbit = jpeg_decode_NEXTBIT(pCur,dec);
if(-1 == nextbit) { return JPEG_ECS_OK; }
code = (code << 1) + (uint16_t)nextbit;
i++;
}
J = dec->valptr[huffclass][id][i];
J = J + code - dec->MINCODE[huffclass][id][i];
dec->decoded_temp_val = dec->huffval[huffclass][id][J];
return JPEG_OK;
}
int16_t
ma_jpeg_codec::jpeg_decode_EXTEND(
uint16_t diff,
uint8_t t)
{
int16_t Vt = (int)qPow(2,(t-1));
int16_t V = diff;
if(V < Vt)
{
Vt = (-1 << t) + 1;
V = V + Vt;
}
return V;
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_ECS(
char **pCur,
Decode *dec)
{
//APP
uint16_t length;
for(int i = 0; i < dec->scan_component_num; i++)
{
jpeg_decode_huffsizeGeneration(HUFFCLASS_DC,(dec->scan_components[i]).DC_dst_id,dec);
jpeg_decode_huffcodeGeneration(HUFFCLASS_DC,(dec->scan_components[i]).DC_dst_id,dec);
jpeg_decode_decodeTableGeneration(HUFFCLASS_DC,(dec->scan_components[i]).DC_dst_id,dec);
jpeg_decode_huffsizeGeneration(HUFFCLASS_AC,(dec->scan_components[i]).AC_dst_id,dec);
jpeg_decode_huffcodeGeneration(HUFFCLASS_AC,(dec->scan_components[i]).AC_dst_id,dec);
jpeg_decode_decodeTableGeneration(HUFFCLASS_AC,(dec->scan_components[i]).AC_dst_id,dec);
}
jpeg_decode_MCU(pCur,dec);
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_parse_DNL(
char ** pCur,
Decode *dec)
{
//APP
uint16_t length;
length = get_ptr_16bits_data(*pCur+4);
length+=2;
*pCur+=(2 * length);
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_reserve_ZIG(
int16_t * src,
int * des)
{
for (int i = 0; i < 64; i++)
{
des[zigzad_reverse_order[i]] = src[i];
}
return JPEG_OK;
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_dequantize(
int16_t * block,
uint16_t * qtable)
{
for (int i = 0; i < 64; i++)
{
block[i]*=qtable[i];
}
return JPEG_OK;
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::decode8x8(uint8_t * result,
int16_t block[12][64],int i,int j,int k,
Decode *dec)
{
#define y (dec->ver_MCU_count)
#define x (dec->hor_MCU_count)
#define h (dec->ver_MCU_num*16)
#define w (dec->hor_MCU_num*16)
int temp[6][64];
for (int a = 0; a < 64; a++)
{
block[i][a]*=dec->qtable[(dec->frame_components[dec->MCU_comp_id[i]]).qtable][a];
block[j][a]*=dec->qtable[(dec->frame_components[dec->MCU_comp_id[j]]).qtable][a];
block[k][a]*=dec->qtable[(dec->frame_components[dec->MCU_comp_id[k]]).qtable][a];
}
for (int b = 0; b < 64; b++)
{
temp[0][zigzad_reverse_order[b]] = block[i][b];
temp[1][zigzad_reverse_order[b]] = block[j][b];
temp[2][zigzad_reverse_order[b]] = block[k][b];
}
IDCT2(temp[0]);
IDCT2(temp[1]);
IDCT2(temp[2]);
// for( size_t y = 0; y < W; ++y )
// {
// for( size_t x = 0; x < H; ++x )
// {
// data[0][x][y] = ( rand() % 255 ) * 255 * 255 * 255;
// data[1][x][y] = ( rand() % 255 ) * 255 * 255 * 255;
// data[2][x][y] = ( rand() % 255 ) * 255 * 255 * 255;
// }
// }
int indexX = 0;
int indexY = 0;
switch (i) {
case 0:
indexX = 16*x;
indexY = 16*y;
break;
case 1:
indexX = 16*x + 8;
indexY = 16*y;
break;
case 2:
indexX = 16*x;
indexY = 16*y + 8;
break;
case 3:
indexX = 16*x + 8;
indexY = 16*y + 8;
break;
default:
break;
}
for(int a = 0, t = 0; a < 8; a++)
{
for(int b = 0; b < 8; b++)
{
t = a*8 + b;
(dec->decodedata)[3 * ((indexY+a) * w + (indexX+b)) + 0] = (uint8_t)(temp[0][t] + 1.14*temp[2][t] + 128);
(dec->decodedata)[3 * ((indexY+a) * w + (indexX+b)) + 1] = (uint8_t)(temp[0][t] - 0.395*temp[1][t] - 0.581*temp[2][t] + 128);
(dec->decodedata)[3 * ((indexY+a) * w + (indexX+b)) + 2] = (uint8_t)(temp[0][t] + 1.772*temp[1][t] + 128);
}
}
// for(int a = 0; a < 64; a++)
// {
// temp[3][a] = temp[0][a] + 1.14*temp[2][a] + 128;
// temp[4][a] = temp[0][a] - 0.395*temp[1][a] - 0.581*temp[2][a] + 128;
// temp[5][a] = temp[0][a] + 1.772*temp[1][a] + 128;
// }
return JPEG_OK;
#undef x
#undef y
#undef w
#undef h
}
void ma_jpeg_codec::IDCT2(int *data)
{
static const int c1=251 ; /* cos(pi/16)<<8 */
static const int s1=50 ; /* sin(pi/16)<<8 */
static const int c3=213 ; /* cos(3pi/16)<<8 */
static const int s3=142 ; /* sin(3pi/16)<<8 */
static const int r2c6=277; /* cos(6pi/16)*sqrt(2)<<9 */
static const int r2s6=669;
static const int r2=181; /* sqrt(2)<<7 */
int i;
int x0,x1,x2,x3,x4,x5,x6,x7,x8;
/* Stage 4 */
for(i=0;i<8;i++){
x0=data[0]<<9;
x1=data[1]<<7;
x2=data[2];
x3=data[3]*r2;
x4=data[4]<<9;
x5=data[5]*r2;
x6=data[6];
x7=data[7]<<7;
x8=x7+x1;
x1 -= x7;
/* Stage 3 */
x7=x0+x4;
x0-=x4;
x4=x1+x5;
x1-=x5;
x5=x3+x8;
x8-=x3;
x3=r2c6*(x2+x6);
x6=x3+(-r2c6-r2s6)*x6;
x2=x3+(-r2c6+r2s6)*x2;
/* Stage 2 */
x3=x7+x2;
x7-=x2;
x2=x0+x6;
x0-= x6;
x6=c3*(x4+x5);
x5=(x6+(-c3-s3)*x5)>>6;
x4=(x6+(-c3+s3)*x4)>>6;
x6=c1*(x1+x8);
x1=(x6+(-c1-s1)*x1)>>6;
x8=(x6+(-c1+s1)*x8)>>6;
/* Stage 1, rounding and output */
x7+=512; x2+=512;x0+=512;x3+=512;
*data++=(x3+x4)>>10; *data++=(x2+x8)>>10;
*data++=(x0+x1)>>10; *data++=(x7+x5)>>10;
*data++=(x7-x5)>>10; *data++=(x0-x1)>>10;
*data++=(x2-x8)>>10; *data++=(x3-x4)>>10;
}
data -= 64;
for(i=0;i<8;i++){
x0=data[0]<<9, x1=data[8]<<7, x2=data[16],
x3=data[24]*r2, x4=data[32]<<9, x5=data[40]*r2,
x6=data[48], x7=data[56]<<7;
x8=x7+x1; x1 -= x7;
/* Stage 3 */
x7=x0+x4; x0-=x4; x4=x1+x5; x1-=x5; x5=x3+x8; x8-=x3;
x3=r2c6*(x2+x6);x6=x3+(-r2c6-r2s6)*x6;x2=x3+(-r2c6+r2s6)*x2;
/* Stage 2 */
x3=x7+x2; x7-=x2; x2=x0+x6; x0-= x6;
x6=c3*(x4+x5);x5=(x6+(-c3-s3)*x5)>>6;x4=(x6+(-c3+s3)*x4)>>6;
x6=c1*(x1+x8);x1=(x6+(-c1-s1)*x1)>>6;x8=(x6+(-c1+s1)*x8)>>6;
/* Stage 1, rounding and output */
x7+=512; x2+=512;x0+=512;x3+=512;
data[0]=(x3+x4)>>11; data[8]=(x2+x8)>>11;
data[16]=(x0+x1)>>11; data[24]=(x7+x5)>>11;
data[32]=(x7-x5)>>11; data[40]=(x0-x1)>>11;
data[48]=(x2-x8)>>11; data[56]=(x3-x4)>>11;
data ++;
}
data -=8;
}
ma_jpeg_codec::JPEG_CODE
ma_jpeg_codec::jpeg_decode(
QByteArray *src,
uint8_t *dst)
{
Decode * dec = new Decode();
dec->count = 0;
char * pCur = src->data();
uint16_t marker;
if(JPEG_OK != jpeg_parse_SOI(&pCur,dec))
{ return JPEG_SOI_ERROR; }
jpeg_parse_tableORmis(&pCur,dec);
marker = get_ptr_16bits_data(pCur);
// parse frame/SOF
if(true == isMarkerFrameStart(marker))
{
jpeg_parse_DHP(&pCur,dec);
goto jpeg_parse_frame_header;
}
//Parse DHP.Hierarchical mode
else if(JPEG_MARKER_DHP == marker)
{
goto jpeg_parse_frame_loop_start;
}
//Parse EOI.only has SOI,table,EOI. Abbreviated format for table-specification data
else if(JPEG_MARKER_EOI == (marker & 0xffff))
{
jpeg_parse_EOI(&pCur,dec);
goto jpeg_parse_complete;
}
jpeg_parse_frame_loop_start:
jpeg_parse_tableORmis(&pCur,dec);
jpeg_parse_EXP(&pCur,dec);
jpeg_parse_frame_header:
jpeg_parse_SOF(&pCur,dec);
jpeg_parse_scan_loop_start:
jpeg_parse_tableORmis(&pCur,dec);
jpeg_parse_SOS(&pCur,dec);
jpeg_parse_ECS(&pCur,dec);
//jpeg_parse_DNL(&pCur,dec);
//--jpeg_parse_scan_loop_end:
//--jpeg_parse_frame_loop_end:
marker = get_ptr_16bits_data(pCur);
// parse next frame/Multiframe
if(true == isMarkerFrameStart(marker))
{
goto jpeg_parse_frame_loop_start;
}
//parse next scan/Multiscan
else if(true == isMarkerScanStart(marker))
{
goto jpeg_parse_frame_loop_start;
}
else if(JPEG_MARKER_EOI == (marker & 0xffff))
{
jpeg_parse_EOI(&pCur,dec);
goto jpeg_parse_complete;
}
dst = dec->decodedata;
jpeg_parse_complete:
return JPEG_OK;
}
void ma_jpeg_codec::jpeg_encode(
QByteArray *src,
QByteArray *dst)
{
}
ma_jpeg_codec::ma_jpeg_codec()
: file(new QByteArray)
{
}
void ma_jpeg_codec::setFile(QByteArray *file)
{
this->file = file;
}
void ma_jpeg_codec::sl_in_file(QByteArray *file)
{
this->setFile(file);
this->decode();
}
void ma_jpeg_codec::decode()
{
uint8_t* decodeData;
jpeg_decode(this->file,decodeData);
emit this->sg_decode_complete(decodeData);
}
// By Thomas G. Lane.
// http://developer.download.nvidia.com/SDK/9.5/Samples/vidimaging_samples.html#gpgpu_dct
// float data[64]
void ma_jpeg_codec::jpeg_fdct(float *data)
{
float tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
float tmp10, tmp11, tmp12, tmp13;
float z1, z2, z3, z4, z5, z11, z13;
float *dataptr;
int ctr;
/* Pass 1: process rows. */
dataptr = data;
for ( ctr = 7; ctr >= 0; ctr-- ) {
tmp0 = dataptr[0] + dataptr[7];
tmp7 = dataptr[0] - dataptr[7];
tmp1 = dataptr[1] + dataptr[6];
tmp6 = dataptr[1] - dataptr[6];
tmp2 = dataptr[2] + dataptr[5];
tmp5 = dataptr[2] - dataptr[5];
tmp3 = dataptr[3] + dataptr[4];
tmp4 = dataptr[3] - dataptr[4];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
dataptr[0] = tmp10 + tmp11; /* phase 3 */
dataptr[4] = tmp10 - tmp11;
z1 = (tmp12 + tmp13) * ((float) 0.707106781); /* c4 */
dataptr[2] = tmp13 + z1; /* phase 5 */
dataptr[6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = (tmp10 - tmp12) * ((float) 0.382683433); /* c6 */
z2 = ((float) 0.541196100) * tmp10 + z5; /* c2-c6 */
z4 = ((float) 1.306562965) * tmp12 + z5; /* c2+c6 */
z3 = tmp11 * ((float) 0.707106781); /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
dataptr[5] = z13 + z2; /* phase 6 */
dataptr[3] = z13 - z2;
dataptr[1] = z11 + z4;
dataptr[7] = z11 - z4;
dataptr += 8; /* advance pointer to next row */
}
/* Pass 2: process columns. */
dataptr = data;
for ( ctr = 8-1; ctr >= 0; ctr-- ) {
tmp0 = dataptr[8*0] + dataptr[8*7];
tmp7 = dataptr[8*0] - dataptr[8*7];
tmp1 = dataptr[8*1] + dataptr[8*6];
tmp6 = dataptr[8*1] - dataptr[8*6];
tmp2 = dataptr[8*2] + dataptr[8*5];
tmp5 = dataptr[8*2] - dataptr[8*5];
tmp3 = dataptr[8*3] + dataptr[8*4];
tmp4 = dataptr[8*3] - dataptr[8*4];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
dataptr[8*0] = tmp10 + tmp11; /* phase 3 */
dataptr[8*4] = tmp10 - tmp11;
z1 = (tmp12 + tmp13) * ((float) 0.707106781); /* c4 */
dataptr[8*2] = tmp13 + z1; /* phase 5 */
dataptr[8*6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = (tmp10 - tmp12) * ((float) 0.382683433); /* c6 */
z2 = ((float) 0.541196100) * tmp10 + z5; /* c2-c6 */
z4 = ((float) 1.306562965) * tmp12 + z5; /* c2+c6 */
z3 = tmp11 * ((float) 0.707106781); /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
dataptr[8*5] = z13 + z2; /* phase 6 */
dataptr[8*3] = z13 - z2;
dataptr[8*1] = z11 + z4;
dataptr[8*7] = z11 - z4;
dataptr++; /* advance pointer to next column */
}
}
void ma_jpeg_codec::jpeg_idct(long *src,
long *dst
)
{
}
#define W1 2841 /* 2048*sqrt(2)*cos(1*pi/16) */
#define W2 2676 /* 2048*sqrt(2)*cos(2*pi/16) */
#define W3 2408 /* 2048*sqrt(2)*cos(3*pi/16) */
#define W5 1609 /* 2048*sqrt(2)*cos(5*pi/16) */
#define W6 1108 /* 2048*sqrt(2)*cos(6*pi/16) */
#define W7 565 /* 2048*sqrt(2)*cos(7*pi/16) */
/* global declarations */
//void init_idct _ANSI_ARGS_((void));
//void idct _ANSI_ARGS_((short *block));
void init_idct (void);
void idct (short *block);
/* private data */
static short iclip[1024]; /* clipping table */
static short *iclp;
/* private prototypes */
//static void idctrow _ANSI_ARGS_((short *blk));
//static void idctcol _ANSI_ARGS_((short *blk));
static void idctrow (short *blk);
static void idctcol (short *blk);
/* row (horizontal) IDCT
*
* 7 pi 1
* dst[k] = sum c[l] * src[l] * cos( -- * ( k + - ) * l )
* l=0 8 2
*
* where: c[0] = 128
* c[1..7] = 128*sqrt(2)
*/
static void idctrow(short *blk)
{
int x0, x1, x2, x3, x4, x5, x6, x7, x8;
/* shortcut */
if (!((x1 = blk[4]<<11) | (x2 = blk[6]) | (x3 = blk[2]) |
(x4 = blk[1]) | (x5 = blk[7]) | (x6 = blk[5]) | (x7 = blk[3])))
{
blk[0]=blk[1]=blk[2]=blk[3]=blk[4]=blk[5]=blk[6]=blk[7]=blk[0]<<3;
return;
}
x0 = (blk[0]<<11) + 128; /* for proper rounding in the fourth stage */
/* first stage */
x8 = W7*(x4+x5);
x4 = x8 + (W1-W7)*x4;
x5 = x8 - (W1+W7)*x5;
x8 = W3*(x6+x7);
x6 = x8 - (W3-W5)*x6;
x7 = x8 - (W3+W5)*x7;
/* second stage */
x8 = x0 + x1;
x0 -= x1;
x1 = W6*(x3+x2);
x2 = x1 - (W2+W6)*x2;
x3 = x1 + (W2-W6)*x3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
/* third stage */
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181*(x4+x5)+128)>>8;
x4 = (181*(x4-x5)+128)>>8;
/* fourth stage */
blk[0] = (x7+x1)>>8;
blk[1] = (x3+x2)>>8;
blk[2] = (x0+x4)>>8;
blk[3] = (x8+x6)>>8;
blk[4] = (x8-x6)>>8;
blk[5] = (x0-x4)>>8;
blk[6] = (x3-x2)>>8;
blk[7] = (x7-x1)>>8;
}
/* column (vertical) IDCT
*
* 7 pi 1
* dst[8*k] = sum c[l] * src[8*l] * cos( -- * ( k + - ) * l )
* l=0 8 2
*
* where: c[0] = 1/1024
* c[1..7] = (1/1024)*sqrt(2)
*/
static void idctcol(short *blk)
{
int x0, x1, x2, x3, x4, x5, x6, x7, x8;
/* shortcut */
if (!((x1 = (blk[8*4]<<8)) | (x2 = blk[8*6]) | (x3 = blk[8*2]) |
(x4 = blk[8*1]) | (x5 = blk[8*7]) | (x6 = blk[8*5]) | (x7 = blk[8*3])))
{
blk[8*0]=blk[8*1]=blk[8*2]=blk[8*3]=blk[8*4]=blk[8*5]=blk[8*6]=blk[8*7]=
iclp[(blk[8*0]+32)>>6];
return;
}
x0 = (blk[8*0]<<8) + 8192;
/* first stage */
x8 = W7*(x4+x5) + 4;
x4 = (x8+(W1-W7)*x4)>>3;
x5 = (x8-(W1+W7)*x5)>>3;
x8 = W3*(x6+x7) + 4;
x6 = (x8-(W3-W5)*x6)>>3;
x7 = (x8-(W3+W5)*x7)>>3;
/* second stage */
x8 = x0 + x1;
x0 -= x1;
x1 = W6*(x3+x2) + 4;
x2 = (x1-(W2+W6)*x2)>>3;
x3 = (x1+(W2-W6)*x3)>>3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
/* third stage */
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181*(x4+x5)+128)>>8;
x4 = (181*(x4-x5)+128)>>8;
/* fourth stage */
blk[8*0] = iclp[(x7+x1)>>14];
blk[8*1] = iclp[(x3+x2)>>14];
blk[8*2] = iclp[(x0+x4)>>14];
blk[8*3] = iclp[(x8+x6)>>14];
blk[8*4] = iclp[(x8-x6)>>14];
blk[8*5] = iclp[(x0-x4)>>14];
blk[8*6] = iclp[(x3-x2)>>14];
blk[8*7] = iclp[(x7-x1)>>14];
}
/* two dimensional inverse discrete cosine transform */
void idct(short *block)
{
int i;
for (i=0; i<8; i++)
idctrow(block+8*i);
for (i=0; i<8; i++)
idctcol(block+i);
for(i = 0;i < 64; i++)
{
qDebug("%d",block[i]);
}
}
void init_idct()
{
int i;
iclp = iclip+512;
for (i= -512; i<512; i++)
iclp[i] = (i<-256) ? -256 : ((i>255) ? 255 : i);
}
|
//=================================================================================================
/*!
// \file src/mathtest/operations/smatsmatsub/DCaMIb.cpp
// \brief Source file for the DCaMIb sparse matrix/sparse matrix subtraction math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/IdentityMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/operations/smatsmatsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'DCaMIb'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using DCa = blaze::DiagonalMatrix< blaze::CompressedMatrix<TypeA> >;
using MIb = blaze::IdentityMatrix<TypeB>;
// Creator type definitions
using CDCa = blazetest::Creator<DCa>;
using CMIb = blazetest::Creator<MIb>;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i; ++j ) {
RUN_SMATSMATSUB_OPERATION_TEST( CDCa( i, j ), CMIb( i ) );
}
}
// Running tests with large matrices
RUN_SMATSMATSUB_OPERATION_TEST( CDCa( 67UL, 7UL ), CMIb( 67UL ) );
RUN_SMATSMATSUB_OPERATION_TEST( CDCa( 128UL, 16UL ), CMIb( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#include "Carla.h"
#include "CarlaGameModeBase.h"
#include "Game/CarlaGameInstance.h"
#include "Game/CarlaHUD.h"
#include "Game/CarlaPlayerState.h"
#include "Game/Tagger.h"
#include "Game/TaggerDelegate.h"
#include "Sensor/Sensor.h"
#include "Sensor/SensorFactory.h"
#include "Settings/CarlaSettings.h"
#include "Settings/CarlaSettingsDelegate.h"
#include "Util/RandomEngine.h"
#include "Vehicle/CarlaVehicleController.h"
#include "ConstructorHelpers.h"
#include "Engine/PlayerStartPIE.h"
#include "EngineUtils.h"
#include "GameFramework/PlayerStart.h"
#include "SceneViewport.h"
ACarlaGameModeBase::ACarlaGameModeBase(const FObjectInitializer& ObjectInitializer) :
Super(ObjectInitializer),
GameController(nullptr),
PlayerController(nullptr)
{
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.TickGroup = TG_PrePhysics;
bAllowTickBeforeBeginPlay = false;
PlayerControllerClass = ACarlaVehicleController::StaticClass();
PlayerStateClass = ACarlaPlayerState::StaticClass();
HUDClass = ACarlaHUD::StaticClass();
TaggerDelegate = CreateDefaultSubobject<UTaggerDelegate>(TEXT("TaggerDelegate"));
CarlaSettingsDelegate = CreateDefaultSubobject<UCarlaSettingsDelegate>(TEXT("CarlaSettingsDelegate"));
}
void ACarlaGameModeBase::InitGame(
const FString &MapName,
const FString &Options,
FString &ErrorMessage)
{
Super::InitGame(MapName, Options, ErrorMessage);
GameInstance = Cast<UCarlaGameInstance>(GetGameInstance());
checkf(
GameInstance != nullptr,
TEXT("GameInstance is not a UCarlaGameInstance, did you forget to set it in the project settings?"));
GameInstance->InitializeGameControllerIfNotPresent(MockGameControllerSettings);
GameController = &GameInstance->GetGameController();
auto &CarlaSettings = GameInstance->GetCarlaSettings();
UWorld *world = GetWorld();
{ // Load weather descriptions and initialize game controller.
#if WITH_EDITOR
{
// Hack to be able to test level-specific weather descriptions in editor.
// When playing in editor the map name gets an extra prefix, here we
// remove it.
FString CorrectedMapName = MapName;
constexpr auto PIEPrefix = TEXT("UEDPIE_0_");
CorrectedMapName.RemoveFromStart(PIEPrefix);
UE_LOG(LogCarla, Log, TEXT("Corrected map name from %s to %s"), *MapName, *CorrectedMapName);
CarlaSettings.LoadWeatherDescriptions(CorrectedMapName);
}
#else
CarlaSettings.LoadWeatherDescriptions(MapName);
#endif // WITH_EDITOR
GameController->Initialize(CarlaSettings);
CarlaSettings.ValidateWeatherId();
CarlaSettings.LogSettings();
}
// Set default pawn class.
if (!CarlaSettings.PlayerVehicle.IsEmpty()) {
auto Class = FindObject<UClass>(ANY_PACKAGE, *CarlaSettings.PlayerVehicle);
if (Class) {
DefaultPawnClass = Class;
} else {
UE_LOG(LogCarla, Error, TEXT("Failed to load player pawn class \"%s\""), *CarlaSettings.PlayerVehicle)
}
}
if (TaggerDelegate != nullptr) {
TaggerDelegate->RegisterSpawnHandler(world);
} else {
UE_LOG(LogCarla, Error, TEXT("Missing TaggerDelegate!"));
}
if(CarlaSettingsDelegate!=nullptr) {
//apply quality settings
CarlaSettingsDelegate->ApplyQualitySettingsLevelPostRestart();
//assign settings delegate for every new actor from now on
CarlaSettingsDelegate->RegisterSpawnHandler(world);
} else {
UE_LOG(LogCarla, Error, TEXT("Missing CarlaSettingsDelegate!"));
}
if (DynamicWeatherClass != nullptr) {
DynamicWeather = world->SpawnActor<ADynamicWeather>(DynamicWeatherClass);
}
if (VehicleSpawnerClass != nullptr) {
VehicleSpawner = world->SpawnActor<AVehicleSpawnerBase>(VehicleSpawnerClass);
}
if (WalkerSpawnerClass != nullptr) {
WalkerSpawner = world->SpawnActor<AWalkerSpawnerBase>(WalkerSpawnerClass);
}
}
void ACarlaGameModeBase::RestartPlayer(AController* NewPlayer)
{
check(NewPlayer != nullptr);
TArray<APlayerStart *> UnOccupiedStartPoints;
APlayerStart *PlayFromHere = FindUnOccupiedStartPoints(NewPlayer, UnOccupiedStartPoints);
if (PlayFromHere != nullptr) {
RestartPlayerAtPlayerStart(NewPlayer, PlayFromHere);
RegisterPlayer(*NewPlayer);
return;
} else if (UnOccupiedStartPoints.Num() > 0u) {
check(GameController != nullptr);
APlayerStart *StartSpot = GameController->ChoosePlayerStart(UnOccupiedStartPoints);
if (StartSpot != nullptr) {
RestartPlayerAtPlayerStart(NewPlayer, StartSpot);
RegisterPlayer(*NewPlayer);
return;
}
}
UE_LOG(LogCarla, Error, TEXT("No start spot found!"));
}
void ACarlaGameModeBase::BeginPlay()
{
Super::BeginPlay();
const auto &CarlaSettings = GameInstance->GetCarlaSettings();
// Setup semantic segmentation if necessary.
if (CarlaSettings.bSemanticSegmentationEnabled) {
TagActorsForSemanticSegmentation();
TaggerDelegate->SetSemanticSegmentationEnabled();
}
// Change weather.
if (DynamicWeather != nullptr) {
const auto *Weather = CarlaSettings.GetActiveWeatherDescription();
if (Weather != nullptr) {
UE_LOG(LogCarla, Log, TEXT("Changing weather settings to \"%s\""), *Weather->Name);
DynamicWeather->SetWeatherDescription(*Weather);
DynamicWeather->RefreshWeather();
}
} else {
UE_LOG(LogCarla, Error, TEXT("Missing dynamic weather actor!"));
}
// Find road map.
TActorIterator<ACityMapGenerator> It(GetWorld());
URoadMap *RoadMap = (It ? It->GetRoadMap() : nullptr);
if (PlayerController != nullptr) {
PlayerController->SetRoadMap(RoadMap);
} else {
UE_LOG(LogCarla, Error, TEXT("Player controller is not a AWheeledVehicleAIController!"));
}
// Setup other vehicles.
if (VehicleSpawner != nullptr) {
VehicleSpawner->SetNumberOfVehicles(CarlaSettings.NumberOfVehicles);
VehicleSpawner->SetSeed(CarlaSettings.SeedVehicles);
VehicleSpawner->SetRoadMap(RoadMap);
if (PlayerController != nullptr) {
PlayerController->GetRandomEngine()->Seed(
VehicleSpawner->GetRandomEngine()->GenerateSeed());
}
} else {
UE_LOG(LogCarla, Error, TEXT("Missing vehicle spawner actor!"));
}
// Setup walkers.
if (WalkerSpawner != nullptr) {
WalkerSpawner->SetNumberOfWalkers(CarlaSettings.NumberOfPedestrians);
WalkerSpawner->SetSeed(CarlaSettings.SeedPedestrians);
} else {
UE_LOG(LogCarla, Error, TEXT("Missing walker spawner actor!"));
}
GameController->BeginPlay();
}
void ACarlaGameModeBase::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
if (CarlaSettingsDelegate != nullptr && EndPlayReason!=EEndPlayReason::EndPlayInEditor)
{
CarlaSettingsDelegate->Reset();
}
}
void ACarlaGameModeBase::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
GameController->Tick(DeltaSeconds);
}
void ACarlaGameModeBase::RegisterPlayer(AController &NewPlayer)
{
check(GameController != nullptr);
AddTickPrerequisiteActor(&NewPlayer);
PlayerController = Cast<ACarlaVehicleController>(&NewPlayer);
if (PlayerController != nullptr) {
GetDataRouter().RegisterPlayer(*PlayerController);
GameController->RegisterPlayer(*PlayerController);
AttachSensorsToPlayer();
} else {
UE_LOG(LogCarla, Error, TEXT("ACarlaGameModeBase: Player is not a ACarlaVehicleController"));
}
}
void ACarlaGameModeBase::AttachSensorsToPlayer()
{
check(PlayerController != nullptr);
const auto &Settings = GameInstance->GetCarlaSettings();
const auto *Weather = Settings.GetActiveWeatherDescription();
for (auto &Item : Settings.SensorDescriptions)
{
check(Item.Value != nullptr);
auto &SensorDescription = *Item.Value;
if (Weather != nullptr)
{
SensorDescription.AdjustToWeather(*Weather);
}
auto *Sensor = FSensorFactory::Make(SensorDescription, *GetWorld());
check(Sensor != nullptr);
Sensor->AttachToActor(PlayerController->GetPawn());
GetDataRouter().RegisterSensor(*Sensor);
}
}
void ACarlaGameModeBase::TagActorsForSemanticSegmentation()
{
check(GetWorld() != nullptr);
ATagger::TagActorsInLevel(*GetWorld(), true);
}
APlayerStart *ACarlaGameModeBase::FindUnOccupiedStartPoints(
AController *Player,
TArray<APlayerStart *> &UnOccupiedStartPoints)
{
APlayerStart* FoundPlayerStart = nullptr;
UClass* PawnClass = GetDefaultPawnClassForController(Player);
APawn* PawnToFit = PawnClass ? PawnClass->GetDefaultObject<APawn>() : nullptr;
for (TActorIterator<APlayerStart> It(GetWorld()); It; ++It) {
APlayerStart* PlayerStart = *It;
if (PlayerStart->IsA<APlayerStartPIE>()) {
FoundPlayerStart = PlayerStart;
break;
} else {
FVector ActorLocation = PlayerStart->GetActorLocation();
const FRotator ActorRotation = PlayerStart->GetActorRotation();
if (!GetWorld()->EncroachingBlockingGeometry(PawnToFit, ActorLocation, ActorRotation)) {
UnOccupiedStartPoints.Add(PlayerStart);
}
#if WITH_EDITOR
else if (GetWorld()->FindTeleportSpot(PawnToFit, ActorLocation, ActorRotation)) {
UE_LOG(
LogCarla,
Warning,
TEXT("Player start cannot be used, occupied location: %s"),
*PlayerStart->GetActorLocation().ToString());
}
#endif // WITH_EDITOR
}
}
return FoundPlayerStart;
}
|
/*
* Copyright (c) 2021, Krisna Pranav
*
* SPDX-License-Identifier: BSD-2-Clause
*/
// includes
#include <base/ByteReader.h>
#include <base/Optional.h>
#include <base/StringView.h>
#include <kernel/arch/x86/InterruptDisabler.h>
#include <kernel/bus/pci/WindowedMMIOAccess.h>
#include <kernel/Debug.h>
#include <kernel/memory/MemoryManager.h>
#include <kernel/Sections.h>
namespace Kernel {
namespace PCI {
UNMAP_AFTER_INIT DeviceConfigurationSpaceMapping::DeviceConfigurationSpaceMapping(Address device_address, const MMIOAccess::MMIOSegment& mmio_segment)
: m_device_address(device_address)
, m_mapped_region(MM.allocate_kernel_region(Memory::page_round_up(PCI_MMIO_CONFIG_SPACE_SIZE), "PCI MMIO Device Access", Memory::Region::Access::ReadWrite).release_nonnull())
{
PhysicalAddress segment_lower_addr = mmio_segment.get_paddr();
PhysicalAddress device_physical_mmio_space = segment_lower_addr.offset(
PCI_MMIO_CONFIG_SPACE_SIZE * m_device_address.function() + (PCI_MMIO_CONFIG_SPACE_SIZE * PCI_MAX_FUNCTIONS_PER_DEVICE) * m_device_address.device() + (PCI_MMIO_CONFIG_SPACE_SIZE * PCI_MAX_FUNCTIONS_PER_DEVICE * PCI_MAX_DEVICES_PER_BUS) * (m_device_address.bus() - mmio_segment.get_start_bus()));
m_mapped_region->physical_page_slot(0) = Memory::PhysicalPage::create(device_physical_mmio_space, Memory::MayReturnToFreeList::No);
m_mapped_region->remap();
}
UNMAP_AFTER_INIT void WindowedMMIOAccess::initialize(PhysicalAddress mcfg)
{
if (!Access::is_initialized()) {
new WindowedMMIOAccess(mcfg);
dbgln_if(PCI_DEBUG, "PCI: MMIO access initialised.");
}
}
UNMAP_AFTER_INIT WindowedMMIOAccess::WindowedMMIOAccess(PhysicalAddress p_mcfg)
: MMIOAccess(p_mcfg)
{
dmesgln("PCI: Using MMIO (mapping per device) for PCI configuration space access");
InterruptDisabler disabler;
enumerate_hardware([&](const Address& address, ID) {
m_mapped_device_regions.append(make<DeviceConfigurationSpaceMapping>(address, m_segments.get(address.seg()).value()));
});
}
Optional<VirtualAddress> WindowedMMIOAccess::get_device_configuration_space(Address address)
{
dbgln_if(PCI_DEBUG, "PCI: Getting device configuration space for {}", address);
for (auto& mapping : m_mapped_device_regions) {
auto checked_address = mapping.address();
dbgln_if(PCI_DEBUG, "PCI Device Configuration Space Mapping: Check if {} was requested", checked_address);
if (address.seg() == checked_address.seg()
&& address.bus() == checked_address.bus()
&& address.device() == checked_address.device()
&& address.function() == checked_address.function()) {
dbgln_if(PCI_DEBUG, "PCI Device Configuration Space Mapping: Found {}", checked_address);
return mapping.vaddr();
}
}
dbgln_if(PCI_DEBUG, "PCI: No device configuration space found for {}", address);
return {};
}
u8 WindowedMMIOAccess::read8_field(Address address, u32 field)
{
InterruptDisabler disabler;
VERIFY(field <= 0xfff);
dbgln_if(PCI_DEBUG, "PCI: MMIO Reading 8-bit field {:#08x} for {}", field, address);
return *((u8*)(get_device_configuration_space(address).value().get() + (field & 0xfff)));
}
u16 WindowedMMIOAccess::read16_field(Address address, u32 field)
{
InterruptDisabler disabler;
VERIFY(field < 0xfff);
dbgln_if(PCI_DEBUG, "PCI: MMIO Reading 16-bit field {:#08x} for {}", field, address);
u16 data = 0;
ByteReader::load<u16>(get_device_configuration_space(address).value().offset(field & 0xfff).as_ptr(), data);
return data;
}
u32 WindowedMMIOAccess::read32_field(Address address, u32 field)
{
InterruptDisabler disabler;
VERIFY(field <= 0xffc);
dbgln_if(PCI_DEBUG, "PCI: MMIO Reading 32-bit field {:#08x} for {}", field, address);
u32 data = 0;
ByteReader::load<u32>(get_device_configuration_space(address).value().offset(field & 0xfff).as_ptr(), data);
return data;
}
void WindowedMMIOAccess::write8_field(Address address, u32 field, u8 value)
{
InterruptDisabler disabler;
VERIFY(field <= 0xfff);
dbgln_if(PCI_DEBUG, "PCI: MMIO Writing 8-bit field {:#08x}, value={:#02x} for {}", field, value, address);
*((u8*)(get_device_configuration_space(address).value().get() + (field & 0xfff))) = value;
}
void WindowedMMIOAccess::write16_field(Address address, u32 field, u16 value)
{
InterruptDisabler disabler;
VERIFY(field < 0xfff);
dbgln_if(PCI_DEBUG, "PCI: MMIO Writing 16-bit field {:#08x}, value={:#02x} for {}", field, value, address);
ByteReader::store<u16>(get_device_configuration_space(address).value().offset(field & 0xfff).as_ptr(), value);
}
void WindowedMMIOAccess::write32_field(Address address, u32 field, u32 value)
{
InterruptDisabler disabler;
VERIFY(field <= 0xffc);
dbgln_if(PCI_DEBUG, "PCI: MMIO Writing 32-bit field {:#08x}, value={:#02x} for {}", field, value, address);
ByteReader::store<u32>(get_device_configuration_space(address).value().offset(field & 0xfff).as_ptr(), value);
}
}
}
|
// Copyright (c) 2012 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 "extensions/browser/api/web_request/upload_data_presenter.h"
#include <utility>
#include "base/files/file_path.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "extensions/browser/api/web_request/form_data_parser.h"
#include "extensions/browser/api/web_request/web_request_api_constants.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/url_request/url_request.h"
using base::BinaryValue;
using base::DictionaryValue;
using base::ListValue;
using base::StringValue;
using base::Value;
namespace keys = extension_web_request_api_constants;
namespace {
// Takes |dictionary| of <string, list of strings> pairs, and gets the list
// for |key|, creating it if necessary.
base::ListValue* GetOrCreateList(base::DictionaryValue* dictionary,
const std::string& key) {
base::ListValue* list = nullptr;
if (!dictionary->GetList(key, &list)) {
list = new base::ListValue();
dictionary->SetWithoutPathExpansion(key, base::WrapUnique(list));
}
return list;
}
} // namespace
namespace extensions {
namespace subtle {
void AppendKeyValuePair(const char* key,
std::unique_ptr<base::Value> value,
base::ListValue* list) {
std::unique_ptr<base::DictionaryValue> dictionary(new base::DictionaryValue);
dictionary->SetWithoutPathExpansion(key, std::move(value));
list->Append(std::move(dictionary));
}
} // namespace subtle
UploadDataPresenter::~UploadDataPresenter() {}
RawDataPresenter::RawDataPresenter()
: success_(true),
list_(new base::ListValue) {
}
RawDataPresenter::~RawDataPresenter() {}
void RawDataPresenter::FeedNext(const net::UploadElementReader& reader) {
if (!success_)
return;
if (reader.AsBytesReader()) {
const net::UploadBytesElementReader* bytes_reader = reader.AsBytesReader();
FeedNextBytes(bytes_reader->bytes(), bytes_reader->length());
} else if (reader.AsFileReader()) {
// Insert the file path instead of the contents, which may be too large.
const net::UploadFileElementReader* file_reader = reader.AsFileReader();
FeedNextFile(file_reader->path().AsUTF8Unsafe());
} else {
NOTIMPLEMENTED();
}
}
bool RawDataPresenter::Succeeded() {
return success_;
}
std::unique_ptr<base::Value> RawDataPresenter::Result() {
if (!success_)
return nullptr;
return std::move(list_);
}
void RawDataPresenter::FeedNextBytes(const char* bytes, size_t size) {
subtle::AppendKeyValuePair(keys::kRequestBodyRawBytesKey,
BinaryValue::CreateWithCopiedBuffer(bytes, size),
list_.get());
}
void RawDataPresenter::FeedNextFile(const std::string& filename) {
// Insert the file path instead of the contents, which may be too large.
subtle::AppendKeyValuePair(keys::kRequestBodyRawFileKey,
base::MakeUnique<base::StringValue>(filename),
list_.get());
}
ParsedDataPresenter::ParsedDataPresenter(const net::URLRequest& request)
: parser_(FormDataParser::Create(request)),
success_(parser_.get() != NULL),
dictionary_(success_ ? new base::DictionaryValue() : NULL) {
}
ParsedDataPresenter::~ParsedDataPresenter() {}
void ParsedDataPresenter::FeedNext(const net::UploadElementReader& reader) {
if (!success_)
return;
const net::UploadBytesElementReader* bytes_reader = reader.AsBytesReader();
if (!bytes_reader) {
return;
}
if (!parser_->SetSource(base::StringPiece(bytes_reader->bytes(),
bytes_reader->length()))) {
Abort();
return;
}
FormDataParser::Result result;
while (parser_->GetNextNameValue(&result)) {
GetOrCreateList(dictionary_.get(), result.name())
->AppendString(result.value());
}
}
bool ParsedDataPresenter::Succeeded() {
if (success_ && !parser_->AllDataReadOK())
Abort();
return success_;
}
std::unique_ptr<base::Value> ParsedDataPresenter::Result() {
if (!success_)
return nullptr;
return std::move(dictionary_);
}
// static
std::unique_ptr<ParsedDataPresenter> ParsedDataPresenter::CreateForTests() {
const std::string form_type("application/x-www-form-urlencoded");
return std::unique_ptr<ParsedDataPresenter>(
new ParsedDataPresenter(form_type));
}
ParsedDataPresenter::ParsedDataPresenter(const std::string& form_type)
: parser_(FormDataParser::CreateFromContentTypeHeader(&form_type)),
success_(parser_.get() != NULL),
dictionary_(success_ ? new base::DictionaryValue() : NULL) {
}
void ParsedDataPresenter::Abort() {
success_ = false;
dictionary_.reset();
parser_.reset();
}
} // namespace extensions
|
#include <cstdlib>
#include <iostream>
using namespace std;
inline void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int test_cases;
cin >> test_cases;
for (unsigned int i {0}; i < test_cases; ++i)
{
int number;
cin >> number;
number = (number * 567 / 9 + 7492) * 235 / 47 - 498;
cout << abs(number) / 10 % 10 << '\n';
}
return 0;
}
|
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapDevice.h"
#include "SkConfig8888.h"
#include "SkDraw.h"
#include "SkPixelRef.h"
#include "SkRasterClip.h"
#include "SkShader.h"
#include "SkSurface.h"
#define CHECK_FOR_ANNOTATION(paint) \
do { if (paint.getAnnotation()) { return; } } while (0)
static bool valid_for_bitmap_device(const SkImageInfo& info,
SkAlphaType* newAlphaType) {
if (info.width() < 0 || info.height() < 0) {
return false;
}
// TODO: can we stop supporting kUnknown in SkBitmkapDevice?
if (kUnknown_SkColorType == info.colorType()) {
if (newAlphaType) {
*newAlphaType = kUnknown_SkAlphaType;
}
return true;
}
switch (info.alphaType()) {
case kPremul_SkAlphaType:
case kOpaque_SkAlphaType:
break;
default:
return false;
}
SkAlphaType canonicalAlphaType = info.alphaType();
switch (info.colorType()) {
case kAlpha_8_SkColorType:
break;
case kRGB_565_SkColorType:
canonicalAlphaType = kOpaque_SkAlphaType;
break;
case kN32_SkColorType:
break;
default:
return false;
}
if (newAlphaType) {
*newAlphaType = canonicalAlphaType;
}
return true;
}
SkBitmapDevice::SkBitmapDevice(const SkBitmap& bitmap)
: INHERITED(SkSurfaceProps(SkSurfaceProps::kLegacyFontHost_InitType))
, fBitmap(bitmap) {
SkASSERT(valid_for_bitmap_device(bitmap.info(), NULL));
}
SkBitmapDevice* SkBitmapDevice::Create(const SkImageInfo& info) {
return Create(info, SkSurfaceProps(SkSurfaceProps::kLegacyFontHost_InitType));
}
SkBitmapDevice::SkBitmapDevice(const SkBitmap& bitmap, const SkSurfaceProps& surfaceProps)
: INHERITED(surfaceProps)
, fBitmap(bitmap) {
SkASSERT(valid_for_bitmap_device(bitmap.info(), NULL));
}
SkBitmapDevice* SkBitmapDevice::Create(const SkImageInfo& origInfo,
const SkSurfaceProps& surfaceProps) {
SkAlphaType newAT = origInfo.alphaType();
if (!valid_for_bitmap_device(origInfo, &newAT)) {
return NULL;
}
const SkImageInfo info = origInfo.makeAlphaType(newAT);
SkBitmap bitmap;
if (kUnknown_SkColorType == info.colorType()) {
if (!bitmap.setInfo(info)) {
return NULL;
}
} else {
if (!bitmap.tryAllocPixels(info)) {
return NULL;
}
if (!bitmap.info().isOpaque()) {
bitmap.eraseColor(SK_ColorTRANSPARENT);
}
}
return SkNEW_ARGS(SkBitmapDevice, (bitmap, surfaceProps));
}
SkImageInfo SkBitmapDevice::imageInfo() const {
return fBitmap.info();
}
void SkBitmapDevice::setNewSize(const SkISize& size) {
SkASSERT(!fBitmap.pixelRef());
fBitmap.setInfo(fBitmap.info().makeWH(size.fWidth, size.fHeight));
}
void SkBitmapDevice::replaceBitmapBackendForRasterSurface(const SkBitmap& bm) {
SkASSERT(bm.width() == fBitmap.width());
SkASSERT(bm.height() == fBitmap.height());
fBitmap = bm; // intent is to use bm's pixelRef (and rowbytes/config)
fBitmap.lockPixels();
}
SkBaseDevice* SkBitmapDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint*) {
const SkSurfaceProps surfaceProps(this->surfaceProps().flags(), cinfo.fPixelGeometry);
return SkBitmapDevice::Create(cinfo.fInfo, surfaceProps);
}
const SkBitmap& SkBitmapDevice::onAccessBitmap() {
return fBitmap;
}
bool SkBitmapDevice::onAccessPixels(SkPixmap* pmap) {
if (fBitmap.lockPixelsAreWritable() && this->onPeekPixels(pmap)) {
fBitmap.notifyPixelsChanged();
return true;
}
return false;
}
bool SkBitmapDevice::onPeekPixels(SkPixmap* pmap) {
const SkImageInfo info = fBitmap.info();
if (fBitmap.getPixels() && (kUnknown_SkColorType != info.colorType())) {
SkColorTable* ctable = NULL;
pmap->reset(fBitmap.info(), fBitmap.getPixels(), fBitmap.rowBytes(), ctable);
return true;
}
return false;
}
bool SkBitmapDevice::onWritePixels(const SkImageInfo& srcInfo, const void* srcPixels,
size_t srcRowBytes, int x, int y) {
// since we don't stop creating un-pixeled devices yet, check for no pixels here
if (NULL == fBitmap.getPixels()) {
return false;
}
const SkImageInfo dstInfo = fBitmap.info().makeWH(srcInfo.width(), srcInfo.height());
void* dstPixels = fBitmap.getAddr(x, y);
size_t dstRowBytes = fBitmap.rowBytes();
if (SkPixelInfo::CopyPixels(dstInfo, dstPixels, dstRowBytes, srcInfo, srcPixels, srcRowBytes)) {
fBitmap.notifyPixelsChanged();
return true;
}
return false;
}
bool SkBitmapDevice::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
int x, int y) {
return fBitmap.readPixels(dstInfo, dstPixels, dstRowBytes, x, y);
}
void SkBitmapDevice::onAttachToCanvas(SkCanvas* canvas) {
INHERITED::onAttachToCanvas(canvas);
if (fBitmap.lockPixelsAreWritable()) {
fBitmap.lockPixels();
}
}
void SkBitmapDevice::onDetachFromCanvas() {
INHERITED::onDetachFromCanvas();
if (fBitmap.lockPixelsAreWritable()) {
fBitmap.unlockPixels();
}
}
///////////////////////////////////////////////////////////////////////////////
void SkBitmapDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) {
draw.drawPaint(paint);
}
void SkBitmapDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode, size_t count,
const SkPoint pts[], const SkPaint& paint) {
CHECK_FOR_ANNOTATION(paint);
draw.drawPoints(mode, count, pts, paint);
}
void SkBitmapDevice::drawRect(const SkDraw& draw, const SkRect& r, const SkPaint& paint) {
CHECK_FOR_ANNOTATION(paint);
draw.drawRect(r, paint);
}
void SkBitmapDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
CHECK_FOR_ANNOTATION(paint);
SkPath path;
path.addOval(oval);
// call the VIRTUAL version, so any subclasses who do handle drawPath aren't
// required to override drawOval.
this->drawPath(draw, path, paint, NULL, true);
}
void SkBitmapDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
CHECK_FOR_ANNOTATION(paint);
#ifdef SK_IGNORE_BLURRED_RRECT_OPT
SkPath path;
path.addRRect(rrect);
// call the VIRTUAL version, so any subclasses who do handle drawPath aren't
// required to override drawRRect.
this->drawPath(draw, path, paint, NULL, true);
#else
draw.drawRRect(rrect, paint);
#endif
}
void SkBitmapDevice::drawPath(const SkDraw& draw, const SkPath& path,
const SkPaint& paint, const SkMatrix* prePathMatrix,
bool pathIsMutable) {
CHECK_FOR_ANNOTATION(paint);
draw.drawPath(path, paint, prePathMatrix, pathIsMutable);
}
void SkBitmapDevice::drawBitmap(const SkDraw& draw, const SkBitmap& bitmap,
const SkMatrix& matrix, const SkPaint& paint) {
draw.drawBitmap(bitmap, matrix, NULL, paint);
}
void SkBitmapDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
const SkRect* src, const SkRect& dst,
const SkPaint& paint,
SkCanvas::DrawBitmapRectFlags flags) {
SkMatrix matrix;
SkRect bitmapBounds, tmpSrc, tmpDst;
SkBitmap tmpBitmap;
bitmapBounds.isetWH(bitmap.width(), bitmap.height());
// Compute matrix from the two rectangles
if (src) {
tmpSrc = *src;
} else {
tmpSrc = bitmapBounds;
}
matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
const SkRect* dstPtr = &dst;
const SkBitmap* bitmapPtr = &bitmap;
// clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
// needed (if the src was clipped). No check needed if src==null.
if (src) {
if (!bitmapBounds.contains(*src)) {
if (!tmpSrc.intersect(bitmapBounds)) {
return; // nothing to draw
}
// recompute dst, based on the smaller tmpSrc
matrix.mapRect(&tmpDst, tmpSrc);
dstPtr = &tmpDst;
}
// since we may need to clamp to the borders of the src rect within
// the bitmap, we extract a subset.
const SkIRect srcIR = tmpSrc.roundOut();
if(bitmap.pixelRef()->getTexture()) {
// Accelerated source canvas, don't use extractSubset but readPixels to get the subset.
// This way, the pixels are copied in CPU memory instead of GPU memory.
bitmap.pixelRef()->readPixels(&tmpBitmap, &srcIR);
} else {
if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
return;
}
}
bitmapPtr = &tmpBitmap;
// Since we did an extract, we need to adjust the matrix accordingly
SkScalar dx = 0, dy = 0;
if (srcIR.fLeft > 0) {
dx = SkIntToScalar(srcIR.fLeft);
}
if (srcIR.fTop > 0) {
dy = SkIntToScalar(srcIR.fTop);
}
if (dx || dy) {
matrix.preTranslate(dx, dy);
}
SkRect extractedBitmapBounds;
extractedBitmapBounds.isetWH(bitmapPtr->width(), bitmapPtr->height());
if (extractedBitmapBounds == tmpSrc) {
// no fractional part in src, we can just call drawBitmap
goto USE_DRAWBITMAP;
}
} else {
USE_DRAWBITMAP:
// We can go faster by just calling drawBitmap, which will concat the
// matrix with the CTM, and try to call drawSprite if it can. If not,
// it will make a shader and call drawRect, as we do below.
draw.drawBitmap(*bitmapPtr, matrix, dstPtr, paint);
return;
}
// construct a shader, so we can call drawRect with the dst
SkShader* s = SkShader::CreateBitmapShader(*bitmapPtr,
SkShader::kClamp_TileMode,
SkShader::kClamp_TileMode,
&matrix);
if (NULL == s) {
return;
}
SkPaint paintWithShader(paint);
paintWithShader.setStyle(SkPaint::kFill_Style);
paintWithShader.setShader(s)->unref();
// Call ourself, in case the subclass wanted to share this setup code
// but handle the drawRect code themselves.
this->drawRect(draw, *dstPtr, paintWithShader);
}
void SkBitmapDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
int x, int y, const SkPaint& paint) {
draw.drawSprite(bitmap, x, y, paint);
}
void SkBitmapDevice::drawText(const SkDraw& draw, const void* text, size_t len,
SkScalar x, SkScalar y, const SkPaint& paint) {
draw.drawText((const char*)text, len, x, y, paint);
}
void SkBitmapDevice::drawPosText(const SkDraw& draw, const void* text, size_t len,
const SkScalar xpos[], int scalarsPerPos,
const SkPoint& offset, const SkPaint& paint) {
draw.drawPosText((const char*)text, len, xpos, scalarsPerPos, offset, paint);
}
void SkBitmapDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
int vertexCount,
const SkPoint verts[], const SkPoint textures[],
const SkColor colors[], SkXfermode* xmode,
const uint16_t indices[], int indexCount,
const SkPaint& paint) {
draw.drawVertices(vmode, vertexCount, verts, textures, colors, xmode,
indices, indexCount, paint);
}
void SkBitmapDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
int x, int y, const SkPaint& paint) {
draw.drawSprite(static_cast<SkBitmapDevice*>(device)->fBitmap, x, y, paint);
}
SkSurface* SkBitmapDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
return SkSurface::NewRaster(info, &props);
}
SkImageFilter::Cache* SkBitmapDevice::getImageFilterCache() {
SkImageFilter::Cache* cache = SkImageFilter::Cache::Get();
cache->ref();
return cache;
}
///////////////////////////////////////////////////////////////////////////////
bool SkBitmapDevice::onShouldDisableLCD(const SkPaint& paint) const {
if (kN32_SkColorType != fBitmap.colorType() ||
paint.getRasterizer() ||
paint.getPathEffect() ||
paint.isFakeBoldText() ||
paint.getStyle() != SkPaint::kFill_Style ||
!SkXfermode::IsMode(paint.getXfermode(), SkXfermode::kSrcOver_Mode))
{
return true;
}
return false;
}
|
/*
* Pearson.cpp
*
* Created on: Jul 14, 2010
* Author: jbard,wklai2
*/
#include <math.h>
#include "Pearson.h"
/**
* Concrete implemenatation of this Metrix. MUST TAKE IN THESE VARIABLES, AND RETURN A DOUBLE
*/
double Pearson::Correlation(const double *x, const double *y, int length) {
double xmean = 0, ymean = 0, s = 0, xv = 0, yv = 0;
double t1, t2;
// Mean
for (int i = 0; i < length; i++) {
xmean += x[i];
ymean += y[i];
}
xmean /= length;
ymean /= length;
// numerator and denominator
for (int i = 0; i < length; i++) {
t1 = x[i] - xmean;
t2 = y[i] - ymean;
xv += pow(t1, 2);
yv += pow(t2, 2);
s += (t1 * t2);
}
if (xv == 0 || yv == 0) {
return 0;
} else {
return (s / (sqrt(xv) * sqrt(yv)));
}
}
|
// Copyright 2020 Thomas Schöps
// This file is part of CIDE, licensed under the new BSD license.
// See the COPYING file in the project root for the license text.
#include "cide/create_class.h"
#include <QBoxLayout>
#include <QCheckBox>
#include <QComboBox>
#include <QDebug>
#include <QDialogButtonBox>
#include <QIcon>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QTextEdit>
#include "cide/cpp_utils.h"
#include "cide/main_window.h"
#include "cide/settings.h"
CreateClassDialog::CreateClassDialog(const QDir& parentFolder, const std::shared_ptr<Project>& project, MainWindow* mainWindow, QWidget* parent)
: QDialog(parent),
parentFolder(parentFolder),
project(project),
mainWindow(mainWindow) {
setWindowTitle(tr("Create class"));
setWindowIcon(QIcon(":/cide/cide.png"));
QLabel* nameLabel = new QLabel(tr("Name: "));
nameEdit = new QLineEdit();
// TODO: Add options to create a default constructor / destructor
// TODO: Add an option to create a singleton class
headerOnlyCheck = new QCheckBox(tr("Create header-only class"));
addHeaderToCMakeListsCheck = new QCheckBox(tr("Add header to CMakeLists.txt file (heuristically)"));
addSourceToCMakeListsCheck = new QCheckBox(tr("Add source to CMakeLists.txt file (heuristically)"));
addSourceToCMakeListsCheck->setChecked(true);
QLabel* addToTargetLabel = new QLabel(tr("Add to target: "));
addToTargetCombo = new QComboBox();
// TODO: Select the current target by default instead of the target with the most source files?
int largestTargetSize = 0;
for (int i = 0; i < project->GetNumTargets(); ++ i) {
const auto& target = project->GetTarget(i);
if (!target.name.isEmpty()) {
addToTargetCombo->addItem(target.name, i);
if (target.sources.size() > largestTargetSize) {
largestTargetSize = target.sources.size();
addToTargetCombo->setCurrentIndex(addToTargetCombo->count() - 1);
}
}
}
QLabel* headerPathLabel = new QLabel(tr("Header path: "));
headerPathEdit = new QLineEdit();
QLabel* sourcePathLabel = new QLabel(tr("Source path: "));
sourcePathEdit = new QLineEdit();
QLabel* cmakePreviewLabel = new QLabel(tr("Preview of CMakeLists.txt change (edit to correct if necessary):"));
cmakePreview = new QTextEdit();
cmakePreview->setFont(Settings::Instance().GetDefaultFont());
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
// --- Layout ---
QVBoxLayout* layout = new QVBoxLayout();
QHBoxLayout* nameLayout = new QHBoxLayout();
nameLayout->addWidget(nameLabel);
nameLayout->addWidget(nameEdit);
QHBoxLayout* addToTargetLayout = new QHBoxLayout();
addToTargetLayout->addWidget(addToTargetLabel);
addToTargetLayout->addWidget(addToTargetCombo);
QGridLayout* pathsLayout = new QGridLayout();
pathsLayout->addWidget(headerPathLabel, 0, 0);
pathsLayout->addWidget(headerPathEdit, 0, 1);
pathsLayout->addWidget(sourcePathLabel, 1, 0);
pathsLayout->addWidget(sourcePathEdit, 1, 1);
layout->addLayout(nameLayout);
layout->addWidget(headerOnlyCheck);
layout->addWidget(addHeaderToCMakeListsCheck);
layout->addWidget(addSourceToCMakeListsCheck);
layout->addLayout(addToTargetLayout);
layout->addLayout(pathsLayout);
layout->addWidget(cmakePreviewLabel);
layout->addWidget(cmakePreview);
layout->addWidget(buttonBox);
setLayout(layout);
nameEdit->setFocus();
// --- Connections ---
connect(nameEdit, &QLineEdit::textChanged, this, &CreateClassDialog::ClassNameChanged);
connect(headerOnlyCheck, &QCheckBox::stateChanged, [&](int state) {
sourcePathEdit->setEnabled(state == Qt::Unchecked);
addSourceToCMakeListsCheck->setEnabled(state == Qt::Unchecked);
UpdateCMakePreview();
});
connect(addHeaderToCMakeListsCheck, &QCheckBox::stateChanged, this, &CreateClassDialog::UpdateCMakePreview);
connect(addSourceToCMakeListsCheck, &QCheckBox::stateChanged, this, &CreateClassDialog::UpdateCMakePreview);
connect(headerPathEdit, &QLineEdit::textChanged, this, &CreateClassDialog::UpdateCMakePreview);
connect(sourcePathEdit, &QLineEdit::textChanged, this, &CreateClassDialog::UpdateCMakePreview);
connect(addToTargetCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &CreateClassDialog::UpdateCMakePreview);
}
void CreateClassDialog::accept() {
QString className = nameEdit->text();
QString headerPath = headerPathEdit->text();
QString headerFilename = QFileInfo(headerPath).fileName();
// Check for whether the files exist already and ask about overwriting in this case.
if (QFileInfo(headerPath).exists()) {
if (QMessageBox::question(this, tr("Overwrite existing file?"), tr("The header file %1 exists already. Overwrite it?").arg(headerPath)) == QMessageBox::No) {
return;
}
}
if (!headerOnlyCheck->isChecked()) {
QString sourcePath = sourcePathEdit->text();
if (QFileInfo(sourcePath).exists()) {
if (QMessageBox::question(this, tr("Overwrite existing file?"), tr("The source file %1 exists already. Overwrite it?").arg(sourcePath)) == QMessageBox::No) {
return;
}
}
}
// Create the source file
if (!headerOnlyCheck->isChecked()) {
QString sourcePath = sourcePathEdit->text();
QString sourceFilename = QFileInfo(sourcePath).fileName();
QFile source(sourcePath);
if (!source.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
QMessageBox::warning(this, tr("Error"), tr("Could not create source file: %1.").arg(sourcePath));
return;
}
QString sourceText = project->GetFileTemplate(static_cast<int>(Project::FileTemplate::SourceFile));
ApplyFileTemplateReplacements(&sourceText, className, headerFilename);
if (mainWindow->GetDefaultNewlineFormat() == NewlineFormat::CrLf) {
sourceText.replace(QStringLiteral("\n"), QStringLiteral("\r\n"));
}
source.write(sourceText.toUtf8());
source.close();
mainWindow->Open(sourcePath);
}
// Create the header file
QFile header(headerPath);
if (!header.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
QMessageBox::warning(this, tr("Error"), tr("Could not create header file: %1.").arg(headerPath));
return;
}
QString headerText = project->GetFileTemplate(static_cast<int>(Project::FileTemplate::HeaderFile));
ApplyFileTemplateReplacements(&headerText, className, headerFilename);
if (mainWindow->GetDefaultNewlineFormat() == NewlineFormat::CrLf) {
headerText.replace(QStringLiteral("\n"), QStringLiteral("\r\n"));
}
header.write(headerText.toUtf8());
header.close();
mainWindow->Open(headerPath);
// Update the CMake file if enabled
// NOTE: Do not call UpdateCMakePreview() here, as it would override changes made by the user
if ((addHeaderToCMakeListsCheck->isChecked() ||
(!headerOnlyCheck->isChecked() && addSourceToCMakeListsCheck->isChecked())) &&
cmakePreviewSuccessful) {
Document* document;
DocumentWidget* widget;
if (mainWindow->GetDocumentAndWidgetForPath(cmakeListsPath, &document, &widget)) {
widget->SelectAll();
widget->InsertText(cmakePreview->toPlainText());
// Here, we do not reconfigure the project, since the user would need to save this file first.
} else {
QFile cmakeFile(cmakeListsPath);
if (!cmakeFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
QMessageBox::warning(this, tr("Error"), tr("Could not open CMakeLists.txt file: %1.").arg(cmakeListsPath));
return;
}
cmakeFile.write(cmakePreview->toPlainText().toUtf8());
cmakeFile.close();
// Automatically reconfigure the project after changing CMakeLists.txt on disk
mainWindow->ReconfigureProject(project, this);
}
}
QDialog::accept();
}
void CreateClassDialog::ClassNameChanged() {
QString className = nameEdit->text();
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!className.isEmpty());
if (className.isEmpty()) {
return;
}
// Split the class name into "words" heuristically
QStringList words;
QString currentWord = className.at(0);
for (int i = 1; i < className.size(); ++ i) {
// Start a new word?
if (className[i].isLetter() && className[i].isUpper() &&
className[i - 1].isLetter() && className[i - 1].isLower()) {
words.push_back(currentWord);
currentWord = "";
}
currentWord += className[i];
}
if (!currentWord.isEmpty()) {
words.push_back(currentWord);
}
// Build the filename with the words using the selected filename style
QString filename;
if (project->GetFilenameStyle() == Project::FilenameStyle::CamelCase) {
for (const QString& word : words) {
filename += word[0].toUpper() + word.mid(1).toLower();
}
} else if (project->GetFilenameStyle() == Project::FilenameStyle::LowercaseWithUnderscores) {
for (const QString& word : words) {
if (!filename.isEmpty()) {
filename += QStringLiteral("_");
}
filename += word.toLower();
}
} else if (project->GetFilenameStyle() == Project::FilenameStyle::NotConfigured) {
filename = className;
} else {
qDebug() << "Error: Unhandled filename style: " << static_cast<int>(project->GetFilenameStyle());
}
// Update the filename in the UI
QString headerFileExtension;
if (!project->GetHeaderFileExtension().isEmpty()) {
headerFileExtension = project->GetHeaderFileExtension();
} else {
headerFileExtension = QStringLiteral("h"); // set default value
}
QString sourceFileExtension;
if (!project->GetSourceFileExtension().isEmpty()) {
sourceFileExtension = project->GetSourceFileExtension();
} else {
sourceFileExtension = QStringLiteral("cpp"); // set default value
}
headerPathEdit->setText(parentFolder.filePath(filename + "." + headerFileExtension));
sourcePathEdit->setText(parentFolder.filePath(filename + "." + sourceFileExtension));
// Update the CMake preview
UpdateCMakePreview();
}
void GetPathPrefixAndIndentation(int existingFilePos, const QString& fileText, QString* pathPrefix, QString* newlineAndIndentation) {
for (int i = existingFilePos - 1; i >= 0; -- i) {
if (IsWhitespace(fileText[i])) {
*pathPrefix = fileText.mid(i + 1, existingFilePos - i - 1);
// We need to cut off everything after the last slash. This is because
// we might have been looking for "settings.cc", but actually found
// "project_settings.cc". So to get the path prefix, we have to cut
// off the "project_".
// TODO: This will not work in case the files are listed without a path prefix.
// We could thus improve the heuristics even more by forcing a suitable
// character before the found filename, e.g., whitespace or a slash,
// to handle this case as well.
int lastSlashPos = pathPrefix->lastIndexOf('/');
if (lastSlashPos >= 0) {
pathPrefix->chop(pathPrefix->size() - (lastSlashPos + 1));
}
break;
}
}
int newlinePos = fileText.lastIndexOf('\n', existingFilePos);
if (newlinePos >= 0) {
while (IsWhitespace(fileText[newlinePos])) {
*newlineAndIndentation += fileText[newlinePos];
++ newlinePos;
if (newlinePos >= existingFilePos) {
break;
}
}
}
}
bool CreateClassDialog::UpdateCMakePreview() {
addToTargetCombo->setEnabled(
addHeaderToCMakeListsCheck->isChecked() ||
(!headerOnlyCheck->isChecked() && addSourceToCMakeListsCheck->isChecked()));
auto disablePreview = [&](const QString& errorReason) {
cmakePreviewSuccessful = false;
cmakePreview->setEnabled(false);
cmakePreview->setPlainText(errorReason);
};
if (!addHeaderToCMakeListsCheck->isChecked() &&
(headerOnlyCheck->isChecked() || !addSourceToCMakeListsCheck->isChecked())) {
disablePreview("");
return false;
}
// Starting from the source path, search for the first directory
// that contains a CMakeLists.txt file.
QDir cmakelistsDir = QFileInfo(headerOnlyCheck->isChecked() ? headerPathEdit->text() : sourcePathEdit->text()).dir();
while (true) {
QString cmakePath = cmakelistsDir.filePath("CMakeLists.txt");
if (QFile::exists(cmakePath)) {
break;
}
// If we are at the project root or cannot go further up, abort.
if (QFileInfo(cmakelistsDir.path()).canonicalFilePath() == project->GetDir() ||
!cmakelistsDir.cdUp()) {
disablePreview(tr("(could not find CMakeLists.txt)"));
return false;
}
}
// // Search for other source files in the source file directory, get the one with the longest filename
// QDir fileDir = QFileInfo(headerOnlyCheck->isChecked() ? headerPathEdit->text() : sourcePathEdit->text()).dir();
// QString longestCFilename = "";
// for (const QString& filename : fileDir.entryList(QDir::NoDotAndDotDot | QDir::Files)) {
// if (GuessIsCFile(fileDir.filePath(filename))) {
// if (filename.size() > longestCFilename.size()) {
// longestCFilename = filename;
// }
// }
// }
// Read the CMakeLists.txt file.
cmakeListsPath = QFileInfo(cmakelistsDir.filePath("CMakeLists.txt")).canonicalFilePath();
QFile cmakeListsFile(cmakeListsPath);
if (!cmakeListsFile.open(QIODevice::ReadOnly)) {
disablePreview(tr("(could not open %1)").arg(cmakeListsPath));
return false;
}
QString cmakeText = QString::fromUtf8(cmakeListsFile.readAll());
cmakeListsFile.close();
// Heuristically search for the correct insertion point in the CMakeLists.txt file:
// First, check where to insert the files, assuming alphabetical ordering.
int targetIndex = addToTargetCombo->currentData().toInt();
const Target& target = project->GetTarget(targetIndex);
std::vector<std::pair<std::string, bool>> orderedSources; // <filename, isNew>
for (const SourceFile& existingSource : target.sources) {
orderedSources.emplace_back(QFileInfo(existingSource.path).fileName().toStdString(), false);
}
if (addHeaderToCMakeListsCheck->isChecked()) {
orderedSources.emplace_back(QFileInfo(headerPathEdit->text()).fileName().toStdString(), true);
}
if (!headerOnlyCheck->isChecked() && addSourceToCMakeListsCheck->isChecked()) {
orderedSources.emplace_back(QFileInfo(sourcePathEdit->text()).fileName().toStdString(), true);
}
std::sort(orderedSources.begin(), orderedSources.end(), [&](const std::pair<std::string, bool>& a, const std::pair<std::string, bool>& b) {
return a.first < b.first;
});
// Find the "surrounding" existing filenames in the CMakeLists.txt file to insert the new files next to them.
// Use the same path prefix (parent directories) as for the existing files.
std::vector<DocumentRange> insertedRanges;
for (int i = 0; i < orderedSources.size(); ++ i) {
const std::pair<std::string, bool>& item = orderedSources[i];
if (!item.second) {
// For existing files, do nothing.
continue;
}
// Try to find the previous existing source to insert the new one afterwards.
if (i > 0) {
const std::string& existingFilename = orderedSources[i - 1].first;
int existingFilePos = cmakeText.indexOf(QString::fromStdString(existingFilename));
if (existingFilePos >= 0) {
QString pathPrefix;
QString newlineAndIndentation;
GetPathPrefixAndIndentation(existingFilePos, cmakeText, &pathPrefix, &newlineAndIndentation);
QString insertion = newlineAndIndentation + pathPrefix + QString::fromStdString(item.first);
int insertionPos = existingFilePos + existingFilename.size();
cmakeText.insert(insertionPos, insertion);
for (DocumentRange& range : insertedRanges) {
if (range.start >= insertionPos) {
range.start += insertion.size();
range.end += insertion.size();
}
}
insertedRanges.push_back(DocumentRange(
insertionPos,
insertionPos + insertion.size()));
continue;
}
}
// If that did not work, try to find the next existing source to insert the new one before,
// and if that fails as well, try all others.
bool inserted = false;
for (int attempt = 0; attempt < orderedSources.size() + 1; ++ attempt) {
int existingIndex;
if (attempt == 0) {
existingIndex = i + 1;
} else {
existingIndex = attempt - 1;
if (orderedSources[existingIndex].second) {
continue;
}
}
if (existingIndex >= 0 && existingIndex < orderedSources.size()) {
const std::string& existingFilename = orderedSources[existingIndex].first;
int existingFilePos = cmakeText.indexOf(QString::fromStdString(existingFilename));
if (existingFilePos >= 0) {
QString pathPrefix;
QString newlineAndIndentation;
GetPathPrefixAndIndentation(existingFilePos, cmakeText, &pathPrefix, &newlineAndIndentation);
QString insertion = newlineAndIndentation + pathPrefix + QString::fromStdString(item.first);
int newlinePos = cmakeText.lastIndexOf('\n', existingFilePos);
if (newlinePos < 0) {
newlinePos = 0;
}
if (cmakeText[newlinePos] == '\r') {
newlinePos = std::max(0, newlinePos - 1);
}
cmakeText.insert(newlinePos, insertion);
for (DocumentRange& range : insertedRanges) {
if (range.start >= newlinePos) {
range.start += insertion.size();
range.end += insertion.size();
}
}
insertedRanges.push_back(DocumentRange(
newlinePos,
newlinePos + insertion.size()));
inserted = true;
break;
}
}
}
if (inserted) {
continue;
}
// If that also failed, give up.
disablePreview(tr("(could not find the correct place to insert new files for the selected target in %1)").arg(cmakeListsPath));
return false;
}
cmakePreview->setPlainText(cmakeText);
QTextCursor cursor = cmakePreview->textCursor();
int minOffset = std::numeric_limits<int>::max();
int maxOffset = 0;
for (const DocumentRange& range : insertedRanges) {
minOffset = std::min(minOffset, range.start.offset);
maxOffset = std::max(maxOffset, range.end.offset);
// NOTE: Attempt to color the inserted ranges; this colored all ranges instead.
// cursor.setPosition(range.start.offset, QTextCursor::MoveAnchor);
// cursor.setPosition(range.end.offset, QTextCursor::KeepAnchor);
// QTextCharFormat format = cursor.charFormat();
// format.setForeground(QBrush(qRgb(255, 80, 80)));
// cursor.setCharFormat(format);
}
cursor.setPosition(minOffset, QTextCursor::MoveAnchor);
cursor.setPosition(maxOffset, QTextCursor::KeepAnchor);
cmakePreview->setTextCursor(cursor);
cmakePreview->ensureCursorVisible();
cmakePreview->setEnabled(true);
cmakePreviewSuccessful = true;
return true;
}
void CreateClassDialog::ApplyFileTemplateReplacements(QString* text, const QString& className, const QString& headerFilename) {
text->replace(
"${LicenseHeader}",
project->GetFileTemplate(static_cast<int>(Project::FileTemplate::LicenseHeader)));
text->replace(
"${ClassName}",
className);
text->replace(
"${HeaderFilename}",
headerFilename);
}
|
#include <bits/stdc++.h>
#include <time.h>
#define int long long int
#define pb push_back
#define all(a) a.begin(), a.end()
#define scnarr(a, n) for (int i = 0; i < n; ++i) cin >> a[i]
#define vi vector<int>
#define si set<int>
#define pii pair <int, int>
#define sii set<pii>
#define vii vector<pii>
#define mii map <int, int>
#define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
using namespace std;
using namespace chrono;
/*
Things to remember : check for coners n = 1, pass references instead
*/
/* -------------------------------Solution Sarted--------------------------------------*/
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
//Constants
const int MOD = 1000000007; // 1e9 + 7
const int MAXN = 200005; // 1e6 +5
const int INF = 100000000000005; // 1e15 +5
vi size, arr, w;
void init(int n){
for(int i = 1; i <= n; ++i){
size[i] = 1;
arr[i] = i;
}
return;
}
int find(int u){
if(arr[u] == u){
return u;
}
return arr[u] = find(arr[u]);
}
void _union(int u, int v){
if(size[u] > size[v]){
size[u] += size[v];
arr[v] = u;
}else{
size[v] += size[u];
arr[u] = v;
}
return;
}
bool parity_check(int x){
return (__builtin_popcount(x)&1);
}
void solve(){
int n, m, q, x, y, ty;
cin >> n >> m;
size.assign(n +5, 1);
arr.resize(n +5);
w.resize(n +5);
init(n);
for(int i = 1; i <= n; ++i){
cin >> w[i];
}
for(int i = 0; i < m; ++i){
cin >> x >> y;
if(parity_check(w[x]) == parity_check(w[y])){
x = find(x);
y = find(y);
if(x != y){
_union(x, y);
}
}
}
int odd = 0, even = 0;
for(int i = 1; i <= n; ++i){
if(parity_check(w[i])){
odd = max(odd, size[i]);
}else{
even = max(even, size[i]);
}
}
cin >> q;
while(q--){
cin >> ty >> x;
if(ty&1){
if(parity_check(x)){
cout << even << endl;
}else{
cout << odd << endl;
}
}else{
if(parity_check(x)){
cout << odd << endl;
}else{
cout << even << endl;
}
}
}
return;
}
signed main()
{
faster;
#ifndef ONLINE_JUDGE
freopen("ip.txt", "r", stdin);
freopen("op.txt", "w", stdout);
#endif
int t; cin >> t; while(t--)
solve();
return 0;
}
//Author : Ankit Raj
//Problem Link :
/*Snippets*/
/*
sieve - prime factorization using sieve and primes in range
zpower - pow with mod
plate - Initial template
bfs
dfs
fenwik - BIT
binary_search
segment_tree
*/
|
#include "shared.h"
using namespace scene_graph;
using detail::ISceneAttachment;
/*
Описание реализации контекста сцены
*/
namespace
{
typedef xtl::shared_ptr<ISceneAttachment> AttachmentPtr;
typedef stl::hash_map<stl::hash_key<const char*>, AttachmentPtr> AttachmentMap;
///Реестр присоединенных данных
struct AttachmentRegistry: public xtl::reference_counter
{
AttachmentPtr anonymous_attachment;
AttachmentMap named_attachments;
};
typedef xtl::intrusive_ptr<AttachmentRegistry> AttachmentRegistryPtr;
typedef stl::hash_map<const std::type_info*, AttachmentRegistryPtr> AttachmentRegistryMap;
typedef xtl::signal<bool (const char*)> ExceptionFilterSignal;
}
struct SceneContext::Impl: public xtl::reference_counter, public xtl::instance_counter<SceneContext>
{
common::PropertyMap properties; //свойства контекста
AttachmentRegistryMap attachments; //присоединенные данные
ExceptionFilterSignal exception_filter; //фильтр ислючений
LogFunction log_handler; //обработчик событий протоколирования
};
/*
Конструкторы / деструктор / присваивание
*/
SceneContext::SceneContext ()
: impl (new Impl)
{
}
SceneContext::SceneContext (const SceneContext& context)
: impl (context.impl)
{
addref (impl);
}
SceneContext::~SceneContext ()
{
release (impl);
}
SceneContext& SceneContext::operator = (const SceneContext& context)
{
SceneContext (context).Swap (*this);
return *this;
}
/*
Свойства
*/
common::PropertyMap SceneContext::Properties () const
{
return impl->properties;
}
void SceneContext::SetProperties (const common::PropertyMap& properties)
{
impl->properties = properties;
}
/*
Работа с присоединенными данными
*/
void SceneContext::RaiseAttachmentError (const char* name, const std::type_info& type)
{
static const char* METHOD_NAME = "scene_graph::SceneContext::Attachment(const char*)";
if (!name)
throw xtl::make_null_argument_exception (METHOD_NAME, "name");
throw xtl::format_operation_exception (METHOD_NAME, "Can't find attachment '%s' of type '%s'", name, type.name ());
}
void SceneContext::RaiseAttachmentError (const std::type_info& type)
{
throw xtl::format_operation_exception ("scene_graph::SceneContext::Attachment", "Can't find attachment of type '%s'", type.name ());
}
void SceneContext::AttachCore (ISceneAttachment* in_attachment)
{
static const char* METHOD_NAME = "scene_graph::SceneContext::Attach(T&)";
if (!in_attachment)
throw xtl::make_null_argument_exception (METHOD_NAME, "attachment");
AttachmentPtr attachment (in_attachment);
AttachmentRegistryMap::iterator iter = impl->attachments.find (&attachment->ValueType ());
if (iter != impl->attachments.end () && iter->second->anonymous_attachment)
throw xtl::format_operation_exception (METHOD_NAME, "Attachment of type '%s' has already defined", attachment->ValueType ().name ());
AttachmentRegistryPtr registry;
if (iter == impl->attachments.end ())
{
registry = AttachmentRegistryPtr (new AttachmentRegistry, false);
impl->attachments.insert_pair (&attachment->ValueType (), registry);
}
else
{
registry = iter->second.get ();
}
registry->anonymous_attachment = attachment;
}
void SceneContext::AttachCore (const char* name, ISceneAttachment* in_attachment)
{
static const char* METHOD_NAME = "scene_graph::SceneContext::Attach(const char*,T&)";
if (!in_attachment)
throw xtl::make_null_argument_exception (METHOD_NAME, "attachment");
AttachmentPtr attachment (in_attachment);
if (!name)
throw xtl::make_null_argument_exception (METHOD_NAME, "name");
AttachmentRegistryMap::iterator iter = impl->attachments.find (&attachment->ValueType ());
AttachmentRegistryPtr registry;
if (iter == impl->attachments.end ())
{
registry = AttachmentRegistryPtr (new AttachmentRegistry, false);
impl->attachments.insert_pair (&attachment->ValueType (), registry);
}
else
{
registry = iter->second.get ();
}
AttachmentMap::iterator iter1 = registry->named_attachments.find (name);
if (iter1 != registry->named_attachments.end ())
throw xtl::format_operation_exception (METHOD_NAME, "Attachment '%s' of type '%s' has already defined", name, attachment->ValueType ().name ());
registry->named_attachments.insert_pair (name, attachment);
}
void SceneContext::DetachCore (const std::type_info& type)
{
AttachmentRegistryMap::iterator iter = impl->attachments.find (&type);
if (iter == impl->attachments.end ())
return;
iter->second->anonymous_attachment.reset ();
}
void SceneContext::DetachCore (const char* name, const std::type_info& type)
{
if (!name)
return;
AttachmentRegistryMap::iterator iter = impl->attachments.find (&type);
if (iter == impl->attachments.end ())
return;
iter->second->named_attachments.erase (name);
}
ISceneAttachment* SceneContext::FindAttachmentCore (const std::type_info& type) const
{
AttachmentRegistryMap::iterator iter = impl->attachments.find (&type);
if (iter == impl->attachments.end ())
return 0;
AttachmentRegistry& registry = *iter->second;
return registry.anonymous_attachment.get ();
}
ISceneAttachment* SceneContext::FindAttachmentCore (const char* name, const std::type_info& type) const
{
if (!name)
return 0;
AttachmentRegistryMap::iterator iter = impl->attachments.find (&type);
if (iter == impl->attachments.end ())
return 0;
AttachmentRegistry& registry = *iter->second;
AttachmentMap::iterator iter1 = registry.named_attachments.find (name);
if (iter1 == registry.named_attachments.end ())
return 0;
return iter1->second.get ();
}
/*
Отсоединение всех данных
*/
void SceneContext::DetachAllCore (const std::type_info& type)
{
impl->attachments.erase (&type);
}
void SceneContext::DetachAll ()
{
impl->attachments.clear ();
}
/*
Очистка
*/
void SceneContext::Clear ()
{
DetachAll ();
impl->properties.Clear ();
impl->exception_filter.disconnect_all ();
}
/*
Обработчик ошибок создания сцены
*/
namespace
{
struct ExceptionFilter
{
stl::string mask;
SceneContext::ExceptionHandler filter;
ExceptionFilter (const char* in_mask, const SceneContext::ExceptionHandler& in_filter)
: mask (in_mask)
, filter (in_filter)
{
}
bool operator () (const char* message) const
{
if (!message || !common::wcimatch (message, mask.c_str ()))
return false;
return filter (message);
}
};
}
xtl::connection SceneContext::RegisterErrorHandler (const char* error_wc_mask, const ExceptionHandler& handler)
{
if (!error_wc_mask)
throw xtl::make_null_argument_exception ("scene_graph::SceneContext::RegisterErrorHandler", "error_wc_mask");
return impl->exception_filter.connect (ExceptionFilter (error_wc_mask, handler));
}
bool SceneContext::FilterError (const char* error_message) const
{
if (!error_message)
return false;
return impl->exception_filter (error_message);
}
/*
Поток протоколирования
*/
void SceneContext::SetLogHandler (const LogFunction& handler)
{
impl->log_handler = handler;
}
const SceneContext::LogFunction& SceneContext::LogHandler () const
{
return impl->log_handler;
}
/*
Обмен
*/
void SceneContext::Swap (SceneContext& context)
{
stl::swap (impl, context.impl);
}
namespace scene_graph
{
void swap (SceneContext& context1, SceneContext& context2)
{
context1.Swap (context2);
}
}
|
//===-- crtbegin.c - Start of constructors and destructors ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#if 0
#define DBG(...) DebugLog(2, __VA_ARGS__)
#else
#define DBG(...)
#endif
extern "C" {
// #include <stddef.h>
}
#include "globals_ctor.h"
#include <Platform/Platform.h>
typedef void (ctor)(void);
typedef ctor* ctor_ptr;
#if defined(__clang__)
void construct_globals_objects()
{
UINT32 PeCoffHeaderOffset = 0;
EFI_IMAGE_DOS_HEADER* DosHdr = (EFI_IMAGE_DOS_HEADER*)SelfLoadedImage->ImageBase;
if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
// DOS image header is present, so read the PE header after the DOS image header
PeCoffHeaderOffset = DosHdr->e_lfanew;
}
DBG("ImageContext.PeCoffHeaderOffset: %08x %d\n", PeCoffHeaderOffset, PeCoffHeaderOffset);
EFI_IMAGE_OPTIONAL_HEADER_UNION* ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *) ((UINTN) (SelfLoadedImage->ImageBase) + PeCoffHeaderOffset);
EFI_IMAGE_SECTION_HEADER* SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINTN) ImgHdr + sizeof(UINT32) + sizeof(EFI_IMAGE_FILE_HEADER) + ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader);
for (int Index = 0; Index < ImgHdr->Pe32.FileHeader.NumberOfSections; Index++, SectionHeader++)
{
DBG("SectionHeader->Name=%a\n", SectionHeader->Name);
// DBG("SectionHeader->PointerToRawData=%8x\n", SectionHeader->PointerToRawData);
// DBG("SectionHeader->SizeOfRawData=%8x\n", SectionHeader->SizeOfRawData);
DBG("SectionHeader->VirtualSize=%8x\n", SectionHeader->Misc.VirtualSize);
if (AsciiStrCmp((CONST CHAR8*) SectionHeader->Name, ".ctorss") == 0)
{
ctor_ptr* currentCtor = (ctor_ptr*) (((UINTN) (SelfLoadedImage->ImageBase)) + SectionHeader->PointerToRawData);
ctor_ptr* ctorend = (ctor_ptr*) (((UINTN) (SelfLoadedImage->ImageBase)) + SectionHeader->PointerToRawData + SectionHeader->Misc.VirtualSize);
while (currentCtor < ctorend)
{
DBG("¤tCtor %x %d\n", (UINTN) (currentCtor), (UINTN) (currentCtor));
DBG("currentCtor %x %d\n", (UINTN) (*currentCtor), (UINTN) (*currentCtor));
if (*currentCtor != NULL) (*currentCtor)();
currentCtor++;
}
}
}
}
#elif defined(__GNUC__)
__attribute__((visibility("hidden"))) void *__dso_handle = &__dso_handle;
extern int __beginning_of_section_ctors, __end_of_section_ctors;
ctor_ptr* p = (ctor_ptr*)&__beginning_of_section_ctors;
ctor_ptr* pend = (ctor_ptr*)&__end_of_section_ctors;
void construct_globals_objects() {
DBG("CTOR %x %d\n", (UINTN)p, (UINTN)p);
// DBG("CTOR %x %d\n", (UINTN)p[0], (UINTN)p[0]);
while ( p < pend ) {
DBG("CTOR %x %d\n", (UINTN)p[0], (UINTN)p[0]);
(*p)();
p++;
}
// DBG("CTOR %x %d\n", (UINTN)__CTOR_LIST__, (UINTN)__CTOR_LIST__);
// __do_init();
// const size_t n = __CTOR_LIST_END__ - __CTOR_LIST__ - 1;
// size_t n = 10;
// for (size_t i = 0; i < n; i++) {
// DBG("CTOR %x %d\n", (UINTN)__CTOR_LIST__[i], (UINTN)__CTOR_LIST__[i]);
// }
// __CTOR_LIST__[0]();
}
#elif defined(_MSC_VER)
void construct_globals_objects()
{
DBG("Work in progress\n");
UINT32 PeCoffHeaderOffset = 0;
EFI_IMAGE_DOS_HEADER* DosHdr = (EFI_IMAGE_DOS_HEADER*)SelfLoadedImage->ImageBase;
if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
// DOS image header is present, so read the PE header after the DOS image header
PeCoffHeaderOffset = DosHdr->e_lfanew;
}
DBG("ImageContext.PeCoffHeaderOffset: %08x %d\n", PeCoffHeaderOffset, PeCoffHeaderOffset);
EFI_IMAGE_OPTIONAL_HEADER_UNION* ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *) ((UINTN) (SelfLoadedImage->ImageBase) + PeCoffHeaderOffset);
EFI_IMAGE_SECTION_HEADER* SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINTN) ImgHdr + sizeof(UINT32) + sizeof(EFI_IMAGE_FILE_HEADER) + ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader);
for (int Index = 0; Index < ImgHdr->Pe32.FileHeader.NumberOfSections; Index++, SectionHeader++)
{
DBG("SectionHeader->Name=%a\n", SectionHeader->Name);
// DBG("SectionHeader->PointerToRawData=%8x\n", SectionHeader->PointerToRawData);
// DBG("SectionHeader->SizeOfRawData=%8x\n", SectionHeader->SizeOfRawData);
DBG("SectionHeader->VirtualSize=%8x\n", SectionHeader->Misc.VirtualSize);
if (AsciiStrCmp((CONST CHAR8*) SectionHeader->Name, ".CRT") == 0)
{
ctor_ptr* currentCtor = (ctor_ptr*) (((UINTN) (SelfLoadedImage->ImageBase)) + SectionHeader->PointerToRawData);
ctor_ptr* ctorend = (ctor_ptr*) (((UINTN) (SelfLoadedImage->ImageBase)) + SectionHeader->PointerToRawData + SectionHeader->Misc.VirtualSize);
while (currentCtor < ctorend)
{
DBG("¤tCtor %x %d\n", (UINTN) (currentCtor), (UINTN) (currentCtor));
DBG("currentCtor %x %d\n", (UINTN) (*currentCtor), (UINTN) (*currentCtor));
if (*currentCtor != NULL) (*currentCtor)();
currentCtor++;
}
}
}
}
#endif
|
// make sure the average includes decimal digits
#include <iostream>
int main()
{
// TODO#1: use the "static_cast" operator to cast the character to a short
// then print both the char and the short
char my_char1 = 'J';
short my_short1 = 74;
std::cout << "The ASCII value for " << my_char1 << " is " << static_cast<short>(my_char1) << my_short1 << std::endl;
std::cout << std::endl; // blank line to separate output from the different exercises
// TODO#2: add one to the character to see what gets printed out
char my_char2 = 'C';
my_char2 = my_char2 + 1;
std::cout << "Char1: " << my_char2 << std::endl;
std::cout << std::endl; // blank line to separate output from the different exercises
// TODO#3: again add one to the character to see what gets printed out
// and add a comment explaining why the value of the character is no
// longer alphabetic
char my_char3 = 'z';
my_char3 = my_char3 + 1;
std::cout << "Char2: " << my_char3 << std::endl;
// The value of the character is no longer alphabetic because the symbol
// character for the new value is {.
std::cout << std::endl; // blank line to separate output from the different exercises
// TODO#4: print each number, then add one to each number and print it again
// also add a comment to explain why my_short2 value became negative after
// adding one, but my_int2 did not
// note: std::dec and std::hex indicate the format of the output, decimal
// versus hexadecimal
short my_short2 = 32767; // maximum value for a short
int my_int2 = my_short2;
std::cout << "Short (" << sizeof(my_short2) << " bytes): "
<< std::dec << my_short2 << std::hex << " (0x" << my_short2 << ')';
my_short2 = my_short2 + 1;
std::cout << ", after adding 1: " << std::dec << my_short2
<< std::hex << " (0x" << my_short2 << ")\n";
// The short became a negative number because it was already at the maximum
// value for the data type. Adding 1 to the value caused it to overflow and
// become the minimum value.
std::cout << "Int (" << sizeof(my_short2) << " bytes): "
<< std::dec << my_int2 << std::hex << " (0x" << my_int2 << ')';
my_int2 = my_int2 + 1;
std::cout << ", after adding 1: " << std::dec << my_int2
<< std::hex << " (0x" << my_int2 << ")\n";
// The int did not overflow because the maximum value is higher and has not
// been reached.
std::cout << std::endl; // blank line to separate output from the different exercises
// TODO#5: print each number, then add one to each number and print it again
// also add a comment to explain why my_short3 value became zero after
// adding one, but my_int3 did not
unsigned short my_short3 = 65535; // maximum value for an unsigned short
int my_int3 = my_short3;
std::cout << "Unsigned short (" << sizeof(my_short3) << " bytes): "
<< std::dec << my_short3 << std::hex << " (0x" << my_short3 << ')';
my_short3 = my_short3 + 1;
std::cout << ", after adding 1: " << std::dec << my_short3
<< std::hex << " (0x" << my_short3 << ")\n";
// The short reverted to zero because it is unsigned and does not include any
// negative values, causing it'soverflow to result in a zero (the minimum for
// an unsigned short).
std::cout << "Same value as int (" << sizeof(my_int3) << " bytes): "
<< std::dec << my_int3 << std::hex << " (0x" << my_int3 << ')';
my_int3 = my_int3 + 1;
std::cout << ", after adding 1: " << std::dec << my_int3
<< std::hex << " (0x" << my_int3 << ")\n";
// The int did not overflow because the maximum value is higher and has not
// been reached.
// ** not required, but for more practice, feel free to add code below which **
// ** tests underflow and overflow using other data types **
return 0;
}
|
#include "Stdafx.h"
#include "YaraExceptions.h"
namespace YaraSharp
{
// Code 1 is handled by OutOfMemoryException
// Code 2
YaraAttachToProcessFailure::YaraAttachToProcessFailure() : Exception(String::Format("{0} - Code {1}", "ERROR_COULD_NOT_ATTACH_TO_PROCESS", ERROR_COULD_NOT_ATTACH_TO_PROCESS)) {}
// Code 3
YaraOpenFileFailure::YaraOpenFileFailure() : Exception(String::Format("{0} - Code {1}", "ERROR_COULD_NOT_OPEN_FILE", ERROR_COULD_NOT_OPEN_FILE)) {}
// Code 4
YaraMapFileFailure::YaraMapFileFailure() : Exception(String::Format("{0} - Code {1}", "ERROR_COULD_NOT_MAP_FILE", ERROR_COULD_NOT_MAP_FILE)) {}
// Code 6
YaraInvalidFile::YaraInvalidFile() : Exception(String::Format("{0} - Code {1}", "ERROR_INVALID_FILE", ERROR_INVALID_FILE)) {}
// Code 7
YaraCorruptFile::YaraCorruptFile() : Exception(String::Format("{0} - Code {1}", "ERROR_CORRUPT_FILE", ERROR_CORRUPT_FILE)) {}
// Code 8
YaraUnsupportedFileVersion::YaraUnsupportedFileVersion() : Exception(String::Format("{0} - Code {1}", "ERROR_UNSUPPORTED_FILE_VERSION", ERROR_UNSUPPORTED_FILE_VERSION)) {}
// Code 9
YaraInvalidRegularExpression::YaraInvalidRegularExpression() : Exception(String::Format("{0} - Code {1}", "ERROR_INVALID_REGULAR_EXPRESSION", ERROR_INVALID_REGULAR_EXPRESSION)) {}
// Code 10
YaraInvalidHexString::YaraInvalidHexString() : Exception(String::Format("{0} - Code {1}", "ERROR_INVALID_HEX_STRING", ERROR_INVALID_HEX_STRING)) {}
// Code 11
YaraSyntaxError::YaraSyntaxError() : Exception(String::Format("{0} - Code {1}", "ERROR_SYNTAX_ERROR", ERROR_SYNTAX_ERROR)) {}
// Code 12
YaraLoopNestingLimitExceeded::YaraLoopNestingLimitExceeded() : Exception(String::Format("{0} - Code {1}", "ERROR_LOOP_NESTING_LIMIT_EXCEEDED", ERROR_LOOP_NESTING_LIMIT_EXCEEDED)) {}
// Code 13
YaraDuplicatedLoopIdentifier::YaraDuplicatedLoopIdentifier() : Exception(String::Format("{0} - Code {1}", "ERROR_DUPLICATED_LOOP_IDENTIFIER", ERROR_DUPLICATED_LOOP_IDENTIFIER)) {}
// Code 14
YaraDuplicatedIdentifier::YaraDuplicatedIdentifier() : Exception(String::Format("{0} - Code {1}", "ERROR_DUPLICATED_IDENTIFIER", ERROR_DUPLICATED_IDENTIFIER)) {}
// Code 15
YaraDuplicatedTagIdentifier::YaraDuplicatedTagIdentifier() : Exception(String::Format("{0} - Code {1}", "ERROR_DUPLICATED_TAG_IDENTIFIER", ERROR_DUPLICATED_TAG_IDENTIFIER)) {}
// Code 16
YaraDuplicatedMetaIdentifier::YaraDuplicatedMetaIdentifier() : Exception(String::Format("{0} - Code {1}", "ERROR_DUPLICATED_META_IDENTIFIER", ERROR_DUPLICATED_META_IDENTIFIER)) {}
// Code 17
YaraDuplicatedStringIdentifier::YaraDuplicatedStringIdentifier() : Exception(String::Format("{0} - Code {1}", "ERROR_DUPLICATED_STRING_IDENTIFIER", ERROR_DUPLICATED_STRING_IDENTIFIER)) {}
// Code 18
YaraUnreferencedString::YaraUnreferencedString() : Exception(String::Format("{0} - Code {1}", "ERROR_UNREFERENCED_STRING", ERROR_UNREFERENCED_STRING)) {}
// Code 19
YaraUndefinedString::YaraUndefinedString() : Exception(String::Format("{0} - Code {1}", "ERROR_UNDEFINED_STRING", ERROR_UNDEFINED_STRING)) {}
// Code 20
YaraUndefinedIdentifier::YaraUndefinedIdentifier() : Exception(String::Format("{0} - Code {1}", "ERROR_UNDEFINED_IDENTIFIER", ERROR_UNDEFINED_IDENTIFIER)) {}
// Code 21
YaraMisplacedAnonymousString::YaraMisplacedAnonymousString() : Exception(String::Format("{0} - Code {1}", "ERROR_MISPLACED_ANONYMOUS_STRING", ERROR_MISPLACED_ANONYMOUS_STRING)) {}
// Code 22
YaraCircularReference::YaraCircularReference() : Exception(String::Format("{0} - Code {1}", "ERROR_INCLUDES_CIRCULAR_REFERENCE", ERROR_INCLUDES_CIRCULAR_REFERENCE)) {}
// Code 23
YaraDepthExceeded::YaraDepthExceeded() : Exception(String::Format("{0} - Code {1}", "ERROR_INCLUDE_DEPTH_EXCEEDED", ERROR_INCLUDE_DEPTH_EXCEEDED)) {}
// Code 24
YaraWrongType::YaraWrongType() : Exception(String::Format("{0} - Code {1}", "ERROR_WRONG_TYPE", ERROR_WRONG_TYPE)) {}
// Code 25
YaraExecStackOverflow::YaraExecStackOverflow() : Exception(String::Format("{0} - Code {1}", "ERROR_EXEC_STACK_OVERFLOW", ERROR_EXEC_STACK_OVERFLOW)) {}
// Code 26
YaraScanTimeout::YaraScanTimeout() : Exception(String::Format("{0} - Code {1}", "ERROR_SCAN_TIMEOUT", ERROR_SCAN_TIMEOUT)) {}
// Code 27
YaraTooManyScanThreads::YaraTooManyScanThreads() : Exception(String::Format("{0} - Code {1}", "ERROR_TOO_MANY_SCAN_THREADS", ERROR_TOO_MANY_SCAN_THREADS)) {}
// Code 28
YaraCallbackError::YaraCallbackError() : Exception(String::Format("{0} - Code {1}", "ERROR_CALLBACK_ERROR", ERROR_CALLBACK_ERROR)) {}
// Code 29
YaraInvalidArgument::YaraInvalidArgument() : Exception(String::Format("{0} - Code {1}", "ERROR_INVALID_ARGUMENT", ERROR_INVALID_ARGUMENT)) {}
// Code 30
YaraTooManyMatches::YaraTooManyMatches() : Exception(String::Format("{0} - Code {1}", "ERROR_TOO_MANY_MATCHES", ERROR_TOO_MANY_MATCHES)) {}
// Code 31
YaraInternalFatalError::YaraInternalFatalError() : Exception(String::Format("{0} - Code {1}", "ERROR_INTERNAL_FATAL_ERROR", ERROR_INTERNAL_FATAL_ERROR)) {}
// Code 32
YaraNestedForOfLoop::YaraNestedForOfLoop() : Exception(String::Format("{0} - Code {1}", "ERROR_NESTED_FOR_OF_LOOP", ERROR_NESTED_FOR_OF_LOOP)) {}
// Code 33
YaraInvalidFieldName::YaraInvalidFieldName() : Exception(String::Format("{0} - Code {1}", "ERROR_INVALID_FIELD_NAME", ERROR_INVALID_FIELD_NAME)) {}
// Code 34
YaraUnknownModule::YaraUnknownModule() : Exception(String::Format("{0} - Code {1}", "ERROR_UNKNOWN_MODULE", ERROR_UNKNOWN_MODULE)) {}
// Code 35
YaraNotAStructure::YaraNotAStructure() : Exception(String::Format("{0} - Code {1}", "ERROR_NOT_A_STRUCTURE", ERROR_NOT_A_STRUCTURE)) {}
// Code 36
YaraNotIndexable::YaraNotIndexable() : Exception(String::Format("{0} - Code {1}", "ERROR_NOT_INDEXABLE", ERROR_NOT_INDEXABLE)) {}
// Code 37
YaraNotAFunction::YaraNotAFunction() : Exception(String::Format("{0} - Code {1}", "ERROR_NOT_A_FUNCTION", ERROR_NOT_A_FUNCTION)) {}
// Code 38
YaraInvalidFormat::YaraInvalidFormat() : Exception(String::Format("{0} - Code {1}", "ERROR_INVALID_FORMAT", ERROR_INVALID_FORMAT)) {}
// Code 39
YaraTooManyArguments::YaraTooManyArguments() : Exception(String::Format("{0} - Code {1}", "ERROR_TOO_MANY_ARGUMENTS", ERROR_TOO_MANY_ARGUMENTS)) {}
// Code 40
YaraWrongArguments::YaraWrongArguments() : Exception(String::Format("{0} - Code {1}", "ERROR_WRONG_ARGUMENTS", ERROR_WRONG_ARGUMENTS)) {}
// Code 41
YaraWrongReturnType::YaraWrongReturnType() : Exception(String::Format("{0} - Code {1}", "ERROR_WRONG_RETURN_TYPE", ERROR_WRONG_RETURN_TYPE)) {}
// Code 42
YaraDuplicatedStructureMember::YaraDuplicatedStructureMember() : Exception(String::Format("{0} - Code {1}", "ERROR_DUPLICATED_STRUCTURE_MEMBER", ERROR_DUPLICATED_STRUCTURE_MEMBER)) {}
// Code 43
YaraEmptyString::YaraEmptyString() : Exception(String::Format("{0} - Code {1}", "ERROR_EMPTY_STRING", ERROR_EMPTY_STRING)) {}
// Code 44
YaraDivisionByZero::YaraDivisionByZero() : Exception(String::Format("{0} - Code {1}", "ERROR_DIVISION_BY_ZERO", ERROR_DIVISION_BY_ZERO)) {}
// Code 45
YaraRegularExpressionTooLarge::YaraRegularExpressionTooLarge() : Exception(String::Format("{0} - Code {1}", "ERROR_REGULAR_EXPRESSION_TOO_LARGE", ERROR_REGULAR_EXPRESSION_TOO_LARGE)) {}
// Code 46
YaraTooManyReFibers::YaraTooManyReFibers() : Exception(String::Format("{0} - Code {1}", "ERROR_TOO_MANY_RE_FIBERS", ERROR_TOO_MANY_RE_FIBERS)) {}
// Code 47
YaraCouldNotReadProcessMemory::YaraCouldNotReadProcessMemory() : Exception(String::Format("{0} - Code {1}", "ERROR_COULD_NOT_READ_PROCESS_MEMORY", ERROR_COULD_NOT_READ_PROCESS_MEMORY)) {}
// Code 48
YaraInvalidExternalVariableType::YaraInvalidExternalVariableType() : Exception(String::Format("{0} - Code {1}", "ERROR_INVALID_EXTERNAL_VARIABLE_TYPE", ERROR_INVALID_EXTERNAL_VARIABLE_TYPE)) {}
}
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Math/Matrix3x4.h>
#include <RHI/RayTracingTlas.h>
#include <RHI/RayTracingBlas.h>
#include <RHI/Buffer.h>
#include <RHI/BufferView.h>
#include <RHI/Device.h>
#include <Atom/RHI/Factory.h>
#include <Atom/RHI/BufferPool.h>
#include <Atom/RHI/RayTracingBufferPools.h>
namespace AZ
{
namespace Vulkan
{
RHI::Ptr<RayTracingTlas> RayTracingTlas::Create()
{
return aznew RayTracingTlas;
}
RHI::ResultCode RayTracingTlas::CreateBuffersInternal(RHI::Device& deviceBase, const RHI::RayTracingTlasDescriptor* descriptor, const RHI::RayTracingBufferPools& bufferPools)
{
auto& device = static_cast<Device&>(deviceBase);
auto& physicalDevice = static_cast<const PhysicalDevice&>(device.GetPhysicalDevice());
const VkPhysicalDeviceAccelerationStructurePropertiesKHR& accelerationStructureProperties = physicalDevice.GetPhysicalDeviceAccelerationStructureProperties();
// advance to the next buffer
m_currentBufferIndex = (m_currentBufferIndex + 1) % BufferCount;
TlasBuffers& buffers = m_buffers[m_currentBufferIndex];
if (buffers.m_accelerationStructure)
{
vkDestroyAccelerationStructureKHR(device.GetNativeDevice(), buffers.m_accelerationStructure, nullptr);
buffers.m_accelerationStructure = nullptr;
}
const RHI::RayTracingTlasInstanceVector& instances = descriptor->GetInstances();
if (instances.empty())
{
// no instances in the scene, clear the TLAS buffers
buffers.m_tlasBuffer = nullptr;
buffers.m_tlasInstancesBuffer = nullptr;
buffers.m_scratchBuffer = nullptr;
return RHI::ResultCode::Success;
}
VkDeviceAddress tlasInstancesGpuAddress = 0;
if (descriptor->GetInstancesBuffer() == nullptr)
{
buffers.m_instanceCount = aznumeric_caster(instances.size());
uint64_t instanceDescsSizeInBytes = aznumeric_cast<uint32_t>(sizeof(VkAccelerationStructureInstanceKHR) * instances.size());
// create instances buffer
buffers.m_tlasInstancesBuffer = RHI::Factory::Get().CreateBuffer();
AZ::RHI::BufferDescriptor tlasInstancesBufferDescriptor;
tlasInstancesBufferDescriptor.m_bindFlags = RHI::BufferBindFlags::ShaderRead | RHI::BufferBindFlags::RayTracingAccelerationStructure;
tlasInstancesBufferDescriptor.m_byteCount = instanceDescsSizeInBytes;
AZ::RHI::BufferInitRequest tlasInstancesBufferRequest;
tlasInstancesBufferRequest.m_buffer = buffers.m_tlasInstancesBuffer.get();
tlasInstancesBufferRequest.m_descriptor = tlasInstancesBufferDescriptor;
RHI::ResultCode resultCode = bufferPools.GetTlasInstancesBufferPool()->InitBuffer(tlasInstancesBufferRequest);
AZ_Assert(resultCode == RHI::ResultCode::Success, "failed to create TLAS instances buffer");
BufferMemoryView* tlasInstancesMemoryView = static_cast<Buffer*>(buffers.m_tlasInstancesBuffer.get())->GetBufferMemoryView();
tlasInstancesMemoryView->SetName("TLAS Instance");
RHI::BufferMapResponse mapResponse;
resultCode = bufferPools.GetTlasInstancesBufferPool()->MapBuffer(RHI::BufferMapRequest(*buffers.m_tlasInstancesBuffer, 0, instanceDescsSizeInBytes), mapResponse);
AZ_Assert(resultCode == RHI::ResultCode::Success, "failed to map TLAS instances buffer");
VkAccelerationStructureInstanceKHR* mappedData = reinterpret_cast<VkAccelerationStructureInstanceKHR*>(mapResponse.m_data);
memset(mappedData, 0, instanceDescsSizeInBytes);
// create each VkAccelerationStructureInstanceKHR structure
for (uint32_t i = 0; i < instances.size(); ++i)
{
const RHI::RayTracingTlasInstance& instance = instances[i];
mappedData[i].instanceCustomIndex = instance.m_instanceID;
mappedData[i].instanceShaderBindingTableRecordOffset = instance.m_hitGroupIndex;
AZ::Matrix3x4 matrix3x4 = AZ::Matrix3x4::CreateFromTransform(instance.m_transform);
matrix3x4.MultiplyByScale(instance.m_nonUniformScale);
matrix3x4.StoreToRowMajorFloat12(&mappedData[i].transform.matrix[0][0]);
RayTracingBlas* blas = static_cast<RayTracingBlas*>(instance.m_blas.get());
VkAccelerationStructureDeviceAddressInfoKHR addressInfo = {};
addressInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR;
addressInfo.pNext = nullptr;
addressInfo.accelerationStructure = blas->GetBuffers().m_accelerationStructure;
mappedData[i].accelerationStructureReference = vkGetAccelerationStructureDeviceAddressKHR(device.GetNativeDevice(), &addressInfo);
// [GFX TODO][ATOM-5270] Add ray tracing TLAS instance mask support
mappedData[i].mask = 0x1;
}
bufferPools.GetTlasInstancesBufferPool()->UnmapBuffer(*buffers.m_tlasInstancesBuffer);
VkBufferDeviceAddressInfo addressInfo = {};
addressInfo.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO;
addressInfo.pNext = nullptr;
addressInfo.buffer = tlasInstancesMemoryView->GetNativeBuffer();
tlasInstancesGpuAddress = vkGetBufferDeviceAddress(device.GetNativeDevice(), &addressInfo);
}
else
{
AZ_Assert(descriptor->GetNumInstancesInBuffer(), "TLAS InstancesBuffer set but instances count is zero");
VkBufferDeviceAddressInfo addressInfo = {};
addressInfo.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO;
addressInfo.pNext = nullptr;
addressInfo.buffer = static_cast<Buffer*>(descriptor->GetInstancesBuffer().get())->GetBufferMemoryView()->GetNativeBuffer();
tlasInstancesGpuAddress = vkGetBufferDeviceAddress(device.GetNativeDevice(), &addressInfo);
buffers.m_instanceCount = descriptor->GetNumInstancesInBuffer();
}
buffers.m_geometry = {};
buffers.m_geometry.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR;
buffers.m_geometry.pNext = nullptr;
buffers.m_geometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR;
buffers.m_geometry.geometry.instances.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR;
buffers.m_geometry.geometry.instances.arrayOfPointers = VK_FALSE;
buffers.m_geometry.geometry.instances.data.deviceAddress = tlasInstancesGpuAddress;
buffers.m_buildInfo = {};
buffers.m_buildInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR;
buffers.m_buildInfo.flags = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR;
buffers.m_buildInfo.geometryCount = 1;
buffers.m_buildInfo.pGeometries = &buffers.m_geometry;
buffers.m_buildInfo.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR;
buffers.m_buildInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
buffers.m_buildInfo.srcAccelerationStructure = nullptr;
VkAccelerationStructureBuildSizesInfoKHR buildSizesInfo = {};
buildSizesInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR;
vkGetAccelerationStructureBuildSizesKHR(
device.GetNativeDevice(),
VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR,
&buffers.m_buildInfo,
&buffers.m_instanceCount,
&buildSizesInfo);
buildSizesInfo.accelerationStructureSize = RHI::AlignUp(buildSizesInfo.accelerationStructureSize, 256);
buildSizesInfo.buildScratchSize = RHI::AlignUp(buildSizesInfo.buildScratchSize, accelerationStructureProperties.minAccelerationStructureScratchOffsetAlignment);
// create scratch buffer
buffers.m_scratchBuffer = RHI::Factory::Get().CreateBuffer();
AZ::RHI::BufferDescriptor scratchBufferDescriptor;
scratchBufferDescriptor.m_bindFlags = RHI::BufferBindFlags::ShaderReadWrite;
scratchBufferDescriptor.m_byteCount = buildSizesInfo.buildScratchSize;
AZ::RHI::BufferInitRequest scratchBufferRequest;
scratchBufferRequest.m_buffer = buffers.m_scratchBuffer.get();
scratchBufferRequest.m_descriptor = scratchBufferDescriptor;
RHI::ResultCode resultCode = bufferPools.GetScratchBufferPool()->InitBuffer(scratchBufferRequest);
AZ_Assert(resultCode == RHI::ResultCode::Success, "failed to create TLAS scratch buffer");
BufferMemoryView* scratchMemoryView = static_cast<Buffer*>(buffers.m_scratchBuffer.get())->GetBufferMemoryView();
scratchMemoryView->SetName("TLAS Scratch");
// create TLAS buffer
buffers.m_tlasBuffer = RHI::Factory::Get().CreateBuffer();
AZ::RHI::BufferDescriptor tlasBufferDescriptor;
tlasBufferDescriptor.m_bindFlags = RHI::BufferBindFlags::RayTracingAccelerationStructure;
tlasBufferDescriptor.m_byteCount = buildSizesInfo.accelerationStructureSize;
AZ::RHI::BufferInitRequest tlasBufferRequest;
tlasBufferRequest.m_buffer = buffers.m_tlasBuffer.get();
tlasBufferRequest.m_descriptor = tlasBufferDescriptor;
resultCode = bufferPools.GetTlasBufferPool()->InitBuffer(tlasBufferRequest);
AZ_Assert(resultCode == RHI::ResultCode::Success, "failed to create TLAS buffer");
BufferMemoryView* tlasMemoryView = static_cast<Buffer*>(buffers.m_tlasBuffer.get())->GetBufferMemoryView();
tlasMemoryView->SetName("TLAS");
// create acceleration structure
VkAccelerationStructureCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR;
createInfo.pNext = nullptr;
createInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
createInfo.size = buildSizesInfo.accelerationStructureSize;
createInfo.offset = 0;
createInfo.buffer = tlasMemoryView->GetNativeBuffer();
VkResult vkResult = vkCreateAccelerationStructureKHR(device.GetNativeDevice(), &createInfo, nullptr, &buffers.m_accelerationStructure);
AssertSuccess(vkResult);
buffers.m_buildInfo.dstAccelerationStructure = buffers.m_accelerationStructure;
VkBufferDeviceAddressInfo addressInfo = {};
addressInfo.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO;
addressInfo.pNext = nullptr;
addressInfo.buffer = scratchMemoryView->GetNativeBuffer();
buffers.m_buildInfo.scratchData.deviceAddress = vkGetBufferDeviceAddress(device.GetNativeDevice(), &addressInfo);
buffers.m_offsetInfo = {};
buffers.m_offsetInfo.primitiveCount = buffers.m_instanceCount;
// store the VkAccelerationStructureKHR in the TLAS Buffer, this is necessary since we need it to
// setup the TLAS in the DescriptorSet when the Srg is compiled
static_cast<Buffer*>(buffers.m_tlasBuffer.get())->SetNativeAccelerationStructure(buffers.m_accelerationStructure);
return RHI::ResultCode::Success;
}
}
}
|
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "vision-precomp.h" // Precompiled headers
#include <mrpt/vision/CFeatureExtraction.h>
// Universal include for all versions of OpenCV
#include <mrpt/3rdparty/do_opencv_includes.h>
#include <numeric> // iota
#if MRPT_HAS_OPENCV
#include "faster_corner_prototypes.h"
#endif
using namespace mrpt;
using namespace mrpt::vision;
using namespace mrpt::img;
using namespace mrpt::img;
using namespace mrpt::system;
using namespace std;
// ------------ SSE2-optimized implementations of FASTER -------------
void CFeatureExtraction::detectFeatures_SSE2_FASTER9(
const CImage& img, TKeyPointList& corners, const int threshold,
bool append_to_list, uint8_t octave,
std::vector<size_t>* out_feats_index_by_row)
{
#if MRPT_HAS_OPENCV
ASSERT_(!img.isColor());
if (!append_to_list) corners.clear();
fast_corner_detect_9(
img.asCvMat<cv::Mat>(SHALLOW_COPY), corners, threshold, octave,
out_feats_index_by_row);
#else
THROW_EXCEPTION("MRPT built without OpenCV support!");
#endif
}
void CFeatureExtraction::detectFeatures_SSE2_FASTER10(
const CImage& img, TKeyPointList& corners, const int threshold,
bool append_to_list, uint8_t octave,
std::vector<size_t>* out_feats_index_by_row)
{
#if MRPT_HAS_OPENCV
ASSERT_(!img.isColor());
if (!append_to_list) corners.clear();
fast_corner_detect_10(
img.asCvMat<cv::Mat>(SHALLOW_COPY), corners, threshold, octave,
out_feats_index_by_row);
#else
THROW_EXCEPTION("MRPT built without OpenCV support!");
#endif
}
void CFeatureExtraction::detectFeatures_SSE2_FASTER12(
const CImage& img, TKeyPointList& corners, const int threshold,
bool append_to_list, uint8_t octave,
std::vector<size_t>* out_feats_index_by_row)
{
#if MRPT_HAS_OPENCV
ASSERT_(!img.isColor());
if (!append_to_list) corners.clear();
fast_corner_detect_12(
img.asCvMat<cv::Mat>(SHALLOW_COPY), corners, threshold, octave,
out_feats_index_by_row);
#else
THROW_EXCEPTION("MRPT built without OpenCV support!");
#endif
}
// N_fast = 9, 10, 12
void CFeatureExtraction::extractFeaturesFASTER_N(
const int N_fast, const mrpt::img::CImage& inImg, CFeatureList& feats,
unsigned int init_ID, unsigned int nDesiredFeatures, const TImageROI& ROI)
{
MRPT_UNUSED_PARAM(ROI);
MRPT_START
CTimeLoggerEntry tle(profiler, "extractFeaturesFASTER_N");
#if MRPT_HAS_OPENCV
// Make sure we operate on a gray-scale version of the image:
const CImage inImg_gray(inImg, FAST_REF_OR_CONVERT_TO_GRAY);
const cv::Mat& img = inImg_gray.asCvMatRef();
TKeyPointList corners;
TKeyPointMethod type_of_this_feature;
switch (N_fast)
{
case 9:
fast_corner_detect_9(
img, corners, options.FASTOptions.threshold, 0, nullptr);
type_of_this_feature = featFASTER9;
break;
case 10:
fast_corner_detect_10(
img, corners, options.FASTOptions.threshold, 0, nullptr);
type_of_this_feature = featFASTER10;
break;
case 12:
fast_corner_detect_12(
img, corners, options.FASTOptions.threshold, 0, nullptr);
type_of_this_feature = featFASTER12;
break;
default:
THROW_EXCEPTION(
"Only the 9,10,12 FASTER detectors are implemented.");
};
CTimeLoggerEntry tle2(profiler, "extractFeaturesFASTER_N.fillFeatsStruct");
// *All* the features have been extracted.
const size_t N = corners.size();
// Now:
// 1) Sort them by "response": It's ~100 times faster to sort a list of
// indices "sorted_indices" than sorting directly the actual list of
// features "corners"
std::vector<size_t> sorted_indices(N);
std::iota(sorted_indices.begin(), sorted_indices.end(), 0);
// Use KLT response
// If the user wants us to limit the number of features, we need to do it
// according to some quality measure
if (options.FASTOptions.use_KLT_response || nDesiredFeatures != 0)
{
const auto KLT_half_win =
options.FASTOptions.KLT_response_half_win_size;
const auto max_x =
static_cast<int>(inImg_gray.getWidth() - 1 - KLT_half_win);
const auto max_y =
static_cast<int>(inImg_gray.getHeight() - 1 - KLT_half_win);
for (size_t i = 0; i < N; i++)
{
const auto x = corners[i].pt.x;
const auto y = corners[i].pt.y;
if (x > KLT_half_win && y > KLT_half_win && x <= max_x &&
y <= max_y)
corners[i].response =
inImg_gray.KLT_response(x, y, KLT_half_win);
else
corners[i].response = -100;
}
std::sort(
sorted_indices.begin(), sorted_indices.end(),
KeypointResponseSorter<TKeyPointList>(corners));
}
else
{
for (size_t i = 0; i < N; i++) corners[i].response = 0;
}
// 2) Filter by "min-distance" (in options.FASTOptions.min_distance)
// 3) Convert to MRPT CFeatureList format.
// Steps 2 & 3 are done together in the while() below.
// The "min-distance" filter is done by means of a 2D binary matrix where
// each cell is marked when one
// feature falls within it. This is not exactly the same than a pure
// "min-distance" but is pretty close
// and for large numbers of features is much faster than brute force search
// of kd-trees.
// (An intermediate approach would be the creation of a mask image updated
// for each accepted feature, etc.)
const bool do_filter_min_dist = options.FASTOptions.min_distance > 1;
// Used half the min-distance since we'll later mark as occupied the ranges
// [i-1,i+1] for a feature at "i"
const unsigned int occupied_grid_cell_size =
options.FASTOptions.min_distance / 2.0;
const float occupied_grid_cell_size_inv = 1.0f / occupied_grid_cell_size;
unsigned int grid_lx =
!do_filter_min_dist
? 1
: (unsigned int)(1 + inImg.getWidth() * occupied_grid_cell_size_inv);
unsigned int grid_ly =
!do_filter_min_dist
? 1
: (unsigned int)(1 + inImg.getHeight() * occupied_grid_cell_size_inv);
// See the comments above for an explanation.
mrpt::math::CMatrixBool occupied_sections(grid_lx, grid_ly);
occupied_sections.fill(false);
unsigned int nMax =
(nDesiredFeatures != 0 && N > nDesiredFeatures) ? nDesiredFeatures : N;
const int offset = (int)this->options.patchSize / 2 + 1;
const int size_2 = options.patchSize / 2;
const size_t imgH = inImg.getHeight();
const size_t imgW = inImg.getWidth();
unsigned int i = 0;
unsigned int cont = 0;
TFeatureID nextID = init_ID;
if (!options.addNewFeatures) feats.clear();
while (cont != nMax && i != N)
{
// Take the next feature from the ordered list of good features:
const TKeyPoint& feat = corners[sorted_indices[i]];
i++;
// Patch out of the image??
const int xBorderInf = feat.pt.x - size_2;
const int xBorderSup = feat.pt.x + size_2;
const int yBorderInf = feat.pt.y - size_2;
const int yBorderSup = feat.pt.y + size_2;
if (!(xBorderSup < (int)imgW && xBorderInf > 0 &&
yBorderSup < (int)imgH && yBorderInf > 0))
continue; // nope, skip.
if (do_filter_min_dist)
{
// Check the min-distance:
const auto sect_ix =
size_t(feat.pt.x * occupied_grid_cell_size_inv);
const auto sect_iy =
size_t(feat.pt.y * occupied_grid_cell_size_inv);
if (occupied_sections(sect_ix, sect_iy))
continue; // Already occupied! skip.
// Mark section as occupied
occupied_sections(sect_ix, sect_iy) = true;
if (sect_ix > 0) occupied_sections(sect_ix - 1, sect_iy) = true;
if (sect_iy > 0) occupied_sections(sect_ix, sect_iy - 1) = true;
if (sect_ix < grid_lx - 1)
occupied_sections(sect_ix + 1, sect_iy) = true;
if (sect_iy < grid_ly - 1)
occupied_sections(sect_ix, sect_iy + 1) = true;
}
// All tests passed: add new feature:
CFeature ft;
ft.type = type_of_this_feature;
ft.keypoint.ID = nextID++;
ft.keypoint.pt.x = feat.pt.x;
ft.keypoint.pt.y = feat.pt.y;
ft.response = feat.response;
ft.orientation = 0;
ft.keypoint.octave = 1;
ft.patchSize = options.patchSize; // The size of the feature patch
if (options.patchSize > 0)
{
ft.patch.emplace();
inImg.extract_patch(
*ft.patch, round(feat.pt.x) - offset, round(feat.pt.y) - offset,
options.patchSize,
options.patchSize); // Image patch surronding the feature
}
feats.push_back(ft);
++cont;
}
#endif
MRPT_END
}
|
// Copyright 2018 The Chromium OS 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 "smbprovider/read_dir_progress.h"
#include <algorithm>
#include <base/logging.h>
#include <dbus/smbprovider/dbus-constants.h>
#include "smbprovider/constants.h"
#include "smbprovider/metadata_cache.h"
namespace smbprovider {
ReadDirProgress::ReadDirProgress(SambaInterface* samba_interface)
: ReadDirProgress(samba_interface, kReadDirectoryInitialBatchSize) {}
ReadDirProgress::ReadDirProgress(SambaInterface* samba_interface,
uint32_t initial_batch_size)
: samba_interface_(samba_interface), batch_size_(initial_batch_size) {}
ReadDirProgress::~ReadDirProgress() = default;
bool ReadDirProgress::StartReadDir(const std::string& directory_path,
MetadataCache* cache,
int32_t* error,
DirectoryEntryListProto* out_entries) {
DCHECK(cache);
DCHECK(error);
DCHECK(out_entries);
DCHECK(!is_started_);
is_started_ = true;
// Purge the cache of expired entries before reading next directory.
cache->PurgeExpiredEntries();
DCHECK(!iterator_);
iterator_ = std::make_unique<CachingIterator>(directory_path,
samba_interface_, cache);
*error = iterator_->Init();
if (*error != 0) {
return false;
}
return ContinueReadDir(error, out_entries);
}
bool ReadDirProgress::ContinueReadDir(int32_t* error,
DirectoryEntryListProto* out_entries) {
DCHECK(error);
DCHECK(out_entries);
DCHECK(is_started_);
out_entries->clear_entries();
*error = 0;
uint32_t num_read = 0;
while (*error == 0 && num_read < batch_size_) {
if (iterator_->IsDone()) {
return false;
}
AddDirectoryEntry(iterator_->Get(), out_entries);
++num_read;
*error = iterator_->Next();
}
// The while-loop is exited from if |batch_size_| has been met or there was an
// error.
if (*error != 0) {
return false;
}
IncreaseBatchSize();
return true;
}
void ReadDirProgress::IncreaseBatchSize() {
batch_size_ = std::min(batch_size_ * 2, kReadDirectoryMaxBatchSize);
}
} // namespace smbprovider
|
/*******************************************************************************
* Copyright 2016-2018 Intel Corporation
*
* 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.
*******************************************************************************/
#include <assert.h>
#include "mkldnn_types.h"
#include "c_types_map.hpp"
#include "memory_desc_wrapper.hpp"
#include "memory_pd.hpp"
#include "type_helpers.hpp"
#include "utils.hpp"
namespace mkldnn {
namespace impl {
memory_desc_wrapper::memory_desc_wrapper(const memory_pd_t *m_pd)
: _md(m_pd == nullptr ? nullptr : m_pd->desc()) {}
namespace {
using namespace mkldnn::impl::utils;
using namespace mkldnn::impl::status;
using namespace mkldnn::impl::memory_format;
status_t fill_x(memory_desc_t &md) {
const int ndims = md.ndims;
if (ndims != 1) return invalid_arguments;
blocking_desc_t &blk = md.layout_desc.blocking;
array_set(blk.block_dims, 1, ndims);
array_set(blk.strides[1], 1, ndims);
blk.strides[0][0] = 1;
array_copy(blk.padding_dims, md.dims, ndims);
array_set(blk.offset_padding_to_data, 0, ndims);
blk.offset_padding = 0;
return success;
}
/* TODO: improve me maybe... and put this to utils */
inline void set_default_strides(strides_t strides, const dims_t dims,
int ndims, const int *perm = NULL) {
int id_perm[TENSOR_MAX_DIMS] = {0};
for (int i = 0; i < ndims; ++i)
id_perm[i] = i;
if (perm == NULL)
perm = id_perm;
strides[perm[ndims - 1]] = 1;
for (int d = 1; d < ndims; ++d) {
const int prev_idx = perm[ndims - d];
const int curr_idx = perm[ndims - 1 - d];
strides[curr_idx] = dims[curr_idx] == 0
? 1
: strides[prev_idx] * nstl::max(1, dims[prev_idx]);
}
}
status_t fill_nonblocked(memory_desc_t &md, const int perm[]) {
const int ndims = md.ndims;
blocking_desc_t &blk = md.layout_desc.blocking;
array_set(blk.block_dims, 1, ndims);
array_set(blk.strides[1], 1, ndims);
set_default_strides(blk.strides[0], md.dims, ndims, perm);
array_copy(blk.padding_dims, md.dims, ndims);
array_set(blk.offset_padding_to_data, 0, ndims);
blk.offset_padding = 0;
return success;
}
status_t fill_contiguous_blocked(memory_desc_t &md, const dims_t block_dims,
const int perm[]) {
const int ndims = md.ndims;
blocking_desc_t &blk = md.layout_desc.blocking;
array_copy(blk.block_dims, block_dims, ndims);
dim_t unrolled_dims[2*TENSOR_MAX_DIMS];
stride_t unrolled_strides[2*TENSOR_MAX_DIMS];
dims_t padding_dims;
for (int d = 0; d < ndims; ++d) {
unrolled_dims[d] = div_up(md.dims[d], block_dims[d]);
unrolled_dims[ndims + d] = block_dims[d];
padding_dims[d] = rnd_up(md.dims[d], block_dims[d]);
}
set_default_strides(unrolled_strides, unrolled_dims, 2*ndims, perm);
array_copy(blk.strides[0], &unrolled_strides[0], ndims);
array_copy(blk.strides[1], &unrolled_strides[ndims], ndims);
array_copy(blk.padding_dims, padding_dims, ndims);
array_set(blk.offset_padding_to_data, 0, ndims);
blk.offset_padding = 0;
return success;
}
status_t fill_nc(memory_desc_t &md) {
if (md.ndims != 2) return invalid_arguments;
const int perm[2] = {0, 1};
return fill_nonblocked(md, perm);
}
status_t fill_ncw(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const int perm[3] = {0, 1, 2};
return fill_nonblocked(md, perm);
}
status_t fill_nwc(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const int perm[3] = {0, 2, 1};
return fill_nonblocked(md, perm);
}
status_t fill_nCw8c(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {1, 8, 1, 1};
const int perm[] = {
0, 1, 2,
3, 4, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_nCw16c(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {1, 16, 1};
const int perm[] = {
0, 1, 2,
3, 4, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_nchw(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const int perm[4] = {0, 1, 2, 3};
return fill_nonblocked(md, perm);
}
status_t fill_ncdhw(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const int perm[5] = {0, 1, 2, 3, 4};
return fill_nonblocked(md, perm);
}
status_t fill_oidhw(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const int perm[5] = {0, 1, 2, 3, 4};
return fill_nonblocked(md, perm);
}
status_t fill_goidhw(memory_desc_t &md) {
if (md.ndims != 6) return invalid_arguments;
const int perm[6] = {0, 1, 2, 3, 4, 5};
return fill_nonblocked(md, perm);
}
status_t fill_nhwc(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const int perm[4] = {0, 2, 3, 1};
return fill_nonblocked(md, perm);
}
status_t fill_ndhwc(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const int perm[5] = {0, 2, 3, 4, 1};
return fill_nonblocked(md, perm);
}
status_t fill_chwn(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const int perm[4] = {1, 2, 3, 0};
return fill_nonblocked(md, perm);
}
status_t fill_nChw8c(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 8, 1, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_nChw16c(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_nCdhw16c(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 16, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_nCdhw8c(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 8, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_oi(memory_desc_t &md) {
if (md.ndims != 2) return invalid_arguments;
const int perm[2] = {0, 1};
return fill_nonblocked(md, perm);
}
status_t fill_io(memory_desc_t &md) {
if (md.ndims != 2) return invalid_arguments;
const int perm[2] = {1, 0};
return fill_nonblocked(md, perm);
}
status_t fill_oiw(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const int perm[3] = {0, 1, 2};
return fill_nonblocked(md, perm);
}
status_t fill_wio(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const int perm[3] = {2, 1, 0};
return fill_nonblocked(md, perm);
}
status_t fill_Owi8o(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {8, 1, 1};
const int perm[] = {
0, 2, 1,
3, 4, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIw8o8i(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {8, 8, 1};
const int perm[] = {
0, 1, 2,
3, 4, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIw8i8o(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {8, 8, 1};
const int perm[] = {
0, 1, 2,
4, 3, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIw16i16o(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {16, 16, 1};
const int perm[] = {
0, 1, 2,
4, 3, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIw16o16i(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {16, 16, 1};
const int perm[] = {
0, 1, 2,
3, 4, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Oiw16o(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {16, 1, 1};
const int perm[] = {
0, 1, 2,
3, 4, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Owi16o(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {16, 1, 1};
const int perm[] = {
0, 2, 1,
3, 4, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIw8i16o2i(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {16, 16, 1};
const int perm[] = {
0, 1, 2,
4, 3, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_IOw16o16i(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {16, 16, 1};
const int perm[] = {
1, 0, 2,
3, 4, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIw8o16i2o(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const dims_t block_dims = {16, 16, 1};
const int perm[] = {
0, 1, 2,
3, 4, 5};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_oihw(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const int perm[4] = {0, 1, 2, 3};
return fill_nonblocked(md, perm);
}
status_t fill_ihwo(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const int perm[4] = {1, 2, 3, 0};
return fill_nonblocked(md, perm);
}
status_t fill_hwio(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const int perm[4] = {2, 3, 1, 0};
return fill_nonblocked(md, perm);
}
status_t fill_dhwio(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const int perm[5] = {2, 3, 4, 1, 0};
return fill_nonblocked(md, perm);
}
status_t fill_OIhw8i8o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {8, 8, 1, 1};
const int perm[] = {
0, 1, 2, 3,
5, 4, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIhw16i16o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3,
5, 4, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIdhw16i16o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {16, 16, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
6, 5, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIdhw8i8o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {8, 8, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
6, 5, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIhw4i16o4i(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3,
5, 4, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIhw8i16o2i(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3,
5, 4, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIdhw8i16o2i(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {16, 16, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
6, 5, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIhw8o8i(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {8, 8, 1, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIhw16o16i(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIdhw16o16i(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {16, 16, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIdhw8o8i(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {8, 8, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_IOhw16o16i(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {16, 16, 1, 1};
const int perm[] = {
1, 0, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_OIhw8o16i2o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Oihw16o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {16, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Oidhw16o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {16, 1, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Ohwi8o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {8, 1, 1, 1};
const int perm[] = {
0, 2, 3, 1,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Ohwi16o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {16, 1, 1, 1};
const int perm[] = {
0, 2, 3, 1,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Odhwi16o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {16, 1, 1, 1, 1};
const int perm[] = {
0, 2, 3, 4, 1,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Odhwi8o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {8, 1, 1, 1, 1};
const int perm[] = {
0, 2, 3, 4, 1,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_goiw(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const int perm[4] = {0, 1, 2, 3};
return fill_nonblocked(md, perm);
}
status_t fill_gOwi8o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 8, 1, 1};
const int perm[] = {
0, 1, 3, 2,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIw8o8i(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 8, 8, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIw8i8o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 8, 8, 1};
const int perm[] = {
0, 1, 2, 3,
4, 6, 5, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIw16i16o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1};
const int perm[] = {
0, 1, 2, 3,
4, 6, 5, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIw16o16i(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOiw16o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOwi16o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 16, 1, 1};
const int perm[] = {
0, 1, 3, 2,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIw8i16o2i(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1};
const int perm[] = {
0, 1, 2, 3,
4, 6, 5, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIw8o16i2o(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1};
const int perm[] = {
0, 1, 2, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gIOw16o16i(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1};
const int perm[] = {
0, 2, 1, 3,
4, 5, 6, 7};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_goihw(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const int perm[5] = {0, 1, 2, 3, 4};
return fill_nonblocked(md, perm);
}
status_t fill_hwigo(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const int perm[5] = {3, 4, 2, 0, 1};
return fill_nonblocked(md, perm);
}
status_t fill_gOIhw8i8o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 8, 8, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 7, 6, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIhw16i16o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 7, 6, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIdhw16i16o(memory_desc_t &md) {
if (md.ndims != 6) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4, 5,
6, 8, 7, 9, 10, 11};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIdhw8i8o(memory_desc_t &md) {
if (md.ndims != 6) return invalid_arguments;
const dims_t block_dims = {1, 8, 8, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4, 5,
6, 8, 7, 9, 10, 11};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOihw16o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 16, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOidhw16o(memory_desc_t &md) {
if (md.ndims != 6) return invalid_arguments;
const dims_t block_dims = {1, 16, 1, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOhwi8o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 8, 1, 1, 1};
const int perm[] = {
0, 1, 3, 4, 2,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOhwi16o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 16, 1, 1, 1};
const int perm[] = {
0, 1, 3, 4, 2,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOdhwi16o(memory_desc_t &md) {
if (md.ndims != 6) return invalid_arguments;
const dims_t block_dims = {1, 16, 1, 1, 1, 1};
const int perm[] = {
0, 1, 3, 4, 5, 2,
6, 7, 8, 9, 10, 11};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOdhwi8o(memory_desc_t &md) {
if (md.ndims != 6) return invalid_arguments;
const dims_t block_dims = {1, 8, 1, 1, 1, 1};
const int perm[] = {
0, 1, 3, 4, 5, 2,
6, 7, 8, 9, 10, 11};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIhw4i16o4i(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 7, 6, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Goihw8g(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {8, 1, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_Goihw16g(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {16, 1, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIhw8i16o2i(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 7, 6, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIdhw8i16o2i(memory_desc_t &md) {
if (md.ndims != 6) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4, 5,
6, 8, 7, 9, 10, 11};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIhw8o8i(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 8, 8, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIhw16o16i(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIdhw16o16i(memory_desc_t &md) {
if (md.ndims != 6) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIdhw8o8i(memory_desc_t &md) {
if (md.ndims != 6) return invalid_arguments;
const dims_t block_dims = {1, 8, 8, 1, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gIOhw16o16i(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1, 1};
const int perm[] = {
0, 2, 1, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_gOIhw8o16i2o(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const dims_t block_dims = {1, 16, 16, 1, 1};
const int perm[] = {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9};
return fill_contiguous_blocked(md, block_dims, perm);
}
status_t fill_ntc(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const int perm[3] = { 1, 0, 2 };
return fill_nonblocked(md, perm);
}
status_t fill_tnc(memory_desc_t &md) {
if (md.ndims != 3) return invalid_arguments;
const int perm[3] = { 0, 1, 2 };
return fill_nonblocked(md, perm);
}
status_t fill_ldsnc(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const int perm[5] = { 0, 1, 2, 3, 4 };
return fill_nonblocked(md, perm);
}
status_t fill_ldigo(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const int perm[5] = { 0, 1, 2, 3, 4 };
return fill_nonblocked(md, perm);
}
status_t fill_ldgoi(memory_desc_t &md) {
if (md.ndims != 5) return invalid_arguments;
const int perm[5] = { 0, 1, 3, 4, 2 };
return fill_nonblocked(md, perm);
}
status_t fill_ldgo(memory_desc_t &md) {
if (md.ndims != 4) return invalid_arguments;
const int perm[4] = { 0, 1, 2, 3 };
return fill_nonblocked(md, perm);
}
}
status_t memory_desc_wrapper::compute_blocking(memory_desc_t &memory_desc)
{
if (memory_desc.ndims == 0) return invalid_arguments;
switch (memory_desc.format) {
case x: return fill_x(memory_desc);
case nc: return fill_nc(memory_desc);
case ncw: return fill_ncw(memory_desc);
case nwc: return fill_nwc(memory_desc);
case nCw8c: return fill_nCw8c(memory_desc);
case nCw16c: return fill_nCw16c(memory_desc);
case nchw: return fill_nchw(memory_desc);
case nhwc: return fill_nhwc(memory_desc);
case chwn: return fill_chwn(memory_desc);
case nChw8c: case oIhw8i: return fill_nChw8c(memory_desc);
case nChw16c: case oIhw16i: return fill_nChw16c(memory_desc);
case oi: return fill_oi(memory_desc);
case io: return fill_io(memory_desc);
case oiw: return fill_oiw(memory_desc);
case wio: return fill_wio(memory_desc);
case Owi8o: return fill_Owi8o(memory_desc);
case OIw8o8i: return fill_OIw8o8i(memory_desc);
case OIw8i8o: return fill_OIw8i8o(memory_desc);
case OIw16i16o: return fill_OIw16i16o(memory_desc);
case OIw16o16i: return fill_OIw16o16i(memory_desc);
case Oiw16o: return fill_Oiw16o(memory_desc);
case Owi16o: return fill_Owi16o(memory_desc);
case OIw8i16o2i: return fill_OIw8i16o2i(memory_desc);
case OIw8o16i2o: return fill_OIw8o16i2o(memory_desc);
case IOw16o16i: return fill_IOw16o16i(memory_desc);
case oihw: return fill_oihw(memory_desc);
case ihwo: return fill_ihwo(memory_desc);
case hwio: return fill_hwio(memory_desc);
case hwio_s8s8: return fill_hwio(memory_desc);
case dhwio: return fill_dhwio(memory_desc);
case OIhw8i8o: return fill_OIhw8i8o(memory_desc);
case OIhw16i16o: return fill_OIhw16i16o(memory_desc);
case OIhw4i16o4i: return fill_OIhw4i16o4i(memory_desc);
case OIhw4i16o4i_s8s8: return fill_OIhw4i16o4i(memory_desc);
case OIhw8i16o2i: return fill_OIhw8i16o2i(memory_desc);
case OIdhw8i16o2i: return fill_OIdhw8i16o2i(memory_desc);
case OIhw8o16i2o: return fill_OIhw8o16i2o(memory_desc);
case OIhw8o8i: return fill_OIhw8o8i(memory_desc);
case OIhw16o16i: return fill_OIhw16o16i(memory_desc);
case IOhw16o16i: return fill_IOhw16o16i(memory_desc);
case Oihw16o: return fill_Oihw16o(memory_desc);
case Ohwi8o: return fill_Ohwi8o(memory_desc);
case Ohwi16o: return fill_Ohwi16o(memory_desc);
case goiw: return fill_goiw(memory_desc);
case gOwi8o: return fill_gOwi8o(memory_desc);
case gOIw8o8i: return fill_gOIw8o8i(memory_desc);
case gOIw8i8o: return fill_gOIw8i8o(memory_desc);
case gOIw16i16o: return fill_gOIw16i16o(memory_desc);
case gOIw16o16i: return fill_gOIw16o16i(memory_desc);
case gOiw16o: return fill_gOiw16o(memory_desc);
case gOwi16o: return fill_gOwi16o(memory_desc);
case gOIw8i16o2i: return fill_gOIw8i16o2i(memory_desc);
case gOIw8o16i2o: return fill_gOIw8o16i2o(memory_desc);
case gIOw16o16i: return fill_gIOw16o16i(memory_desc);
case goihw: return fill_goihw(memory_desc);
case hwigo: return fill_hwigo(memory_desc);
case hwigo_s8s8: return fill_hwigo(memory_desc);
case gOIhw8i8o: return fill_gOIhw8i8o(memory_desc);
case gOIhw16i16o: return fill_gOIhw16i16o(memory_desc);
case gOIhw4i16o4i: return fill_gOIhw4i16o4i(memory_desc);
case gOIhw4i16o4i_s8s8: return fill_gOIhw4i16o4i(memory_desc);
case gOIhw8i16o2i: return fill_gOIhw8i16o2i(memory_desc);
case gOIdhw8i16o2i: return fill_gOIdhw8i16o2i(memory_desc);
case gOIhw8o16i2o: return fill_gOIhw8o16i2o(memory_desc);
case gOIhw8o8i: return fill_gOIhw8o8i(memory_desc);
case gOIhw16o16i: return fill_gOIhw16o16i(memory_desc);
case gIOhw16o16i: return fill_gIOhw16o16i(memory_desc);
case gOihw16o: return fill_gOihw16o(memory_desc);
case gOhwi8o: return fill_gOhwi8o(memory_desc);
case gOhwi16o: return fill_gOhwi16o(memory_desc);
case Goihw8g: return fill_Goihw8g(memory_desc);
case Goihw16g: return fill_Goihw16g(memory_desc);
case ncdhw: return fill_ncdhw(memory_desc);
case ndhwc: return fill_ndhwc(memory_desc);
case oidhw: return fill_oidhw(memory_desc);
case goidhw: return fill_goidhw(memory_desc);
case nCdhw8c: case oIdhw8i: return fill_nCdhw8c(memory_desc);
case nCdhw16c: case oIdhw16i: return fill_nCdhw16c(memory_desc);
case OIdhw16i16o: return fill_OIdhw16i16o(memory_desc);
case gOIdhw16i16o: return fill_gOIdhw16i16o(memory_desc);
case OIdhw8i8o: return fill_OIdhw8i8o(memory_desc);
case gOIdhw8i8o: return fill_gOIdhw8i8o(memory_desc);
case OIdhw16o16i: return fill_OIdhw16o16i(memory_desc);
case gOIdhw16o16i: return fill_gOIdhw16o16i(memory_desc);
case OIdhw8o8i: return fill_OIdhw8o8i(memory_desc);
case gOIdhw8o8i: return fill_gOIdhw8o8i(memory_desc);
case Oidhw16o: return fill_Oidhw16o(memory_desc);
case Odhwi16o: return fill_Odhwi16o(memory_desc);
case Odhwi8o: return fill_Odhwi8o(memory_desc);
case gOidhw16o: return fill_gOidhw16o(memory_desc);
case gOdhwi16o: return fill_gOdhwi16o(memory_desc);
case gOdhwi8o: return fill_gOdhwi8o(memory_desc);
case ntc: return fill_ntc(memory_desc);
case tnc: return fill_tnc(memory_desc);
case ldsnc: return fill_ldsnc(memory_desc);
case ldigo: return fill_ldigo(memory_desc);
case ldgoi: return fill_ldgoi(memory_desc);
case ldgo: return fill_ldgo(memory_desc);
case wino_fmt: return success;
default: break;
}
return invalid_arguments;
}
}
}
// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
|
//==============================================================================
/*
Software License Agreement (BSD License)
Copyright (c) 2003-2016, CHAI3D.
(www.chai3d.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of CHAI3D nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"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
COPYRIGHT OWNER OR CONTRIBUTORS 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.
\author <http://www.chai3d.org>
\author Francois Conti
\version 3.2.0 $Rev: 1869 $
*/
//==============================================================================
//------------------------------------------------------------------------------
#include "chai3d.h"
//------------------------------------------------------------------------------
#include <GLFW/glfw3.h>
//------------------------------------------------------------------------------
using namespace chai3d;
using namespace std;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// GENERAL SETTINGS
//------------------------------------------------------------------------------
// stereo Mode
/*
C_STEREO_DISABLED: Stereo is disabled
C_STEREO_ACTIVE: Active stereo for OpenGL NVDIA QUADRO cards
C_STEREO_PASSIVE_LEFT_RIGHT: Passive stereo where L/R images are rendered next to each other
C_STEREO_PASSIVE_TOP_BOTTOM: Passive stereo where L/R images are rendered above each other
*/
cStereoMode stereoMode = C_STEREO_DISABLED;
// fullscreen mode
bool fullscreen = false;
// mirrored display
bool mirroredDisplay = false;
//------------------------------------------------------------------------------
// DECLARED VARIABLES
//------------------------------------------------------------------------------
// a world that contains all objects of the virtual environment
cWorld* world;
// a camera to render the world in the window display
cCamera* camera;
// a light source to illuminate the objects in the world
cDirectionalLight *light;
// a haptic device handler
cHapticDeviceHandler* handler;
// a pointer to the current haptic device
cGenericHapticDevicePtr hapticDevice;
// a label to display the haptic device model
cLabel* labelHapticDeviceModel;
// a label to display the position [m] of the haptic device
cLabel* labelHapticDevicePosition;
// a global variable to store the position [m] of the haptic device
cVector3d hapticDevicePosition;
// a global variable to store the velocity [m/s] of the haptic device
cVector3d hapticDeviceVelocity;
// a font for rendering text
cFontPtr font;
// a label to display the rate [Hz] at which the simulation is running
cLabel* labelRates;
// a small sphere (cursor) representing the haptic device
cShapeSphere* cursor;
// a line representing the velocity of the haptic device
cShapeLine* velocity;
// a scope to monitor position values of haptic device
cScope* scope;
// a level widget to display velocity
cLevel* levelVelocity;
// three dials to display position information
cDial* dialPosX;
cDial* dialPosY;
cDial* dialPosZ;
// a flag for using damping (ON/OFF)
bool useDamping = false;
// a flag for using force field (ON/OFF)
bool useForceField = true;
// a flag to indicate if the haptic simulation currently running
bool simulationRunning = false;
// a flag to indicate if the haptic simulation has terminated
bool simulationFinished = true;
// a frequency counter to measure the simulation graphic rate
cFrequencyCounter freqCounterGraphics;
// a frequency counter to measure the simulation haptic rate
cFrequencyCounter freqCounterHaptics;
// haptic thread
cThread* hapticsThread;
// a handle to window display context
GLFWwindow* window = NULL;
// current width of window
int width = 0;
// current height of window
int height = 0;
// swap interval for the display context (vertical synchronization)
int swapInterval = 1;
//------------------------------------------------------------------------------
// DECLARED FUNCTIONS
//------------------------------------------------------------------------------
// callback when the window display is resized
void windowSizeCallback(GLFWwindow* a_window, int a_width, int a_height);
// callback when an error GLFW occurs
void errorCallback(int error, const char* a_description);
// callback when a key is pressed
void keyCallback(GLFWwindow* a_window, int a_key, int a_scancode, int a_action, int a_mods);
// this function renders the scene
void updateGraphics(void);
// this function contains the main haptics simulation loop
void updateHaptics(void);
// this function closes the application
void close(void);
//==============================================================================
/*
DEMO: 03-analytics.cpp
This application illustrates how to program forces, torques and gripper
forces to your haptic device.
In this example the application opens an OpenGL window and displays a
3D cursor for the device connected to your computer. Several widgets are
used to demonstrate several possible approaches for to display signal data.
*/
//==============================================================================
int main(int argc, char* argv[])
{
//--------------------------------------------------------------------------
// INITIALIZATION
//--------------------------------------------------------------------------
cout << endl;
cout << "-----------------------------------" << endl;
cout << "CHAI3D" << endl;
cout << "Demo: 03-analytics" << endl;
cout << "Copyright 2003-2016" << endl;
cout << "-----------------------------------" << endl << endl << endl;
cout << "Keyboard Options:" << endl << endl;
cout << "[1] - Enable/Disable potential field" << endl;
cout << "[2] - Enable/Disable damping" << endl;
cout << "[f] - Enable/Disable full screen mode" << endl;
cout << "[m] - Enable/Disable vertical mirroring" << endl;
cout << "[q] - Exit application" << endl;
cout << endl << endl;
//--------------------------------------------------------------------------
// OPEN GL - WINDOW DISPLAY
//--------------------------------------------------------------------------
// initialize GLFW library
if (!glfwInit())
{
cout << "failed initialization" << endl;
cSleepMs(1000);
return 1;
}
// set error callback
glfwSetErrorCallback(errorCallback);
// compute desired size of window
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
int w = 0.8 * mode->height;
int h = 0.5 * mode->height;
int x = 0.5 * (mode->width - w);
int y = 0.5 * (mode->height - h);
// set OpenGL version
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
// set active stereo mode
if (stereoMode == C_STEREO_ACTIVE)
{
glfwWindowHint(GLFW_STEREO, GL_TRUE);
}
else
{
glfwWindowHint(GLFW_STEREO, GL_FALSE);
}
// create display context
window = glfwCreateWindow(w, h, "CHAI3D", NULL, NULL);
if (!window)
{
cout << "failed to create window" << endl;
cSleepMs(1000);
glfwTerminate();
return 1;
}
// get width and height of window
glfwGetWindowSize(window, &width, &height);
// set position of window
glfwSetWindowPos(window, x, y);
// set key callback
glfwSetKeyCallback(window, keyCallback);
// set resize callback
glfwSetWindowSizeCallback(window, windowSizeCallback);
// set current display context
glfwMakeContextCurrent(window);
// sets the swap interval for the current display context
glfwSwapInterval(swapInterval);
#ifdef GLEW_VERSION
// initialize GLEW library
if (glewInit() != GLEW_OK)
{
cout << "failed to initialize GLEW library" << endl;
glfwTerminate();
return 1;
}
#endif
//--------------------------------------------------------------------------
// WORLD - CAMERA - LIGHTING
//--------------------------------------------------------------------------
// create a new world.
world = new cWorld();
// set the background color of the environment
world->m_backgroundColor.setBlack();
// create a camera and insert it into the virtual world
camera = new cCamera(world);
world->addChild(camera);
// position and orient the camera
camera->set(cVector3d(0.5, 0.0, 0.0), // camera position (eye)
cVector3d(0.0, 0.0, 0.0), // look at position (target)
cVector3d(0.0, 0.0, 1.0)); // direction of the (up) vector
// set the near and far clipping planes of the camera
camera->setClippingPlanes(0.01, 10.0);
// set stereo mode
camera->setStereoMode(stereoMode);
// set stereo eye separation and focal length (applies only if stereo is enabled)
camera->setStereoEyeSeparation(0.005);
camera->setStereoFocalLength(0.5);
// set vertical mirrored display mode
camera->setMirrorVertical(mirroredDisplay);
// create a directional light source
light = new cDirectionalLight(world);
// insert light source inside world
world->addChild(light);
// enable light source
light->setEnabled(true);
// define direction of light beam
light->setDir(-1.0, 0.0, 0.0);
// create a sphere (cursor) to represent the haptic device
cursor = new cShapeSphere(0.01);
// insert cursor inside world
world->addChild(cursor);
// create small line to illustrate the velocity of the haptic device
velocity = new cShapeLine(cVector3d(0,0,0), cVector3d(0,0,0));
// insert line inside world
world->addChild(velocity);
//--------------------------------------------------------------------------
// HAPTIC DEVICE
//--------------------------------------------------------------------------
// create a haptic device handler
handler = new cHapticDeviceHandler();
// get a handle to the first haptic device
handler->getDevice(hapticDevice, 0);
// open a connection with the haptic device
hapticDevice->open();
// retrieve information about the current haptic device
cHapticDeviceInfo info = hapticDevice->getSpecifications();
// if the haptic device provides orientation sensing (stylus),
// a reference frame is displayed
if (info.m_sensedRotation == true)
{
// display a reference frame
cursor->setShowFrame(true);
// set the size of the reference frame
cursor->setFrameSize(0.05);
}
// if the device has a gripper, enable the gripper to behave like a user switch
hapticDevice->setEnableGripperUserSwitch(true);
//--------------------------------------------------------------------------
// WIDGETS
//--------------------------------------------------------------------------
// create a font
font = NEW_CFONTCALIBRI20();
// create a label to display the haptic device model
labelHapticDeviceModel = new cLabel(font);
camera->m_frontLayer->addChild(labelHapticDeviceModel);
labelHapticDeviceModel->setText(info.m_modelName);
// create a label to display the position of haptic device
labelHapticDevicePosition = new cLabel(font);
camera->m_frontLayer->addChild(labelHapticDevicePosition);
// create a label to display the haptic and graphic rate of the simulation
labelRates = new cLabel(font);
camera->m_frontLayer->addChild(labelRates);
////////////////////////////////////////////////////////////////////////////
// In the following lines we set up several widgets to display position
// and velocity data coming from the haptic device. For each widget we
// define a range of values to expect from the haptic device. In this
// example the units are meters (as we are tracking a position signal!) and
// have a set a default range between -0.1 to 0.1 meters. If you are using
// devices with a small or larger workspace, you may want to adjust these
// values accordingly. The other settings will modify the visual appearance
// of the widgets. Have fun playing with these values!
////////////////////////////////////////////////////////////////////////////
// create a scope to plot haptic device position data
scope = new cScope();
camera->m_frontLayer->addChild(scope);
scope->setLocalPos(100,60);
scope->setRange(-0.1, 0.1);
scope->setSignalEnabled(true, true, true, false);
scope->setTransparencyLevel(0.7);
// create a level to display velocity data
levelVelocity = new cLevel();
camera->m_frontLayer->addChild(levelVelocity);
levelVelocity->setLocalPos(20, 60);
levelVelocity->setRange(0.0, 1.0);
levelVelocity->setWidth(40);
levelVelocity->setNumIncrements(46);
levelVelocity->setSingleIncrementDisplay(false);
levelVelocity->setTransparencyLevel(0.5);
// three dials to display position data
dialPosX = new cDial();
camera->m_frontLayer->addChild(dialPosX);
dialPosX->setLocalPos(750, 200);
dialPosX->setRange(-0.1, 0.1);
dialPosX->setSize(40);
dialPosX->setSingleIncrementDisplay(true);
dialPosY = new cDial();
camera->m_frontLayer->addChild(dialPosY);
dialPosY->setLocalPos(750, 140);
dialPosY->setRange(-0.1, 0.1);
dialPosY->setSize(40);
dialPosY->setSingleIncrementDisplay(true);
dialPosZ = new cDial();
camera->m_frontLayer->addChild(dialPosZ);
dialPosZ->setLocalPos(750, 80);
dialPosZ->setRange(-0.1, 0.1);
dialPosZ->setSize(40);
dialPosZ->setSingleIncrementDisplay(true);
//--------------------------------------------------------------------------
// START SIMULATION
//--------------------------------------------------------------------------
// create a thread which starts the main haptics rendering loop
hapticsThread = new cThread();
hapticsThread->start(updateHaptics, CTHREAD_PRIORITY_HAPTICS);
// setup callback when application exits
atexit(close);
//--------------------------------------------------------------------------
// MAIN GRAPHIC LOOP
//--------------------------------------------------------------------------
// call window size callback at initialization
windowSizeCallback(window, width, height);
while (!glfwWindowShouldClose(window))
{
// get width and height of window
glfwGetWindowSize(window, &width, &height);
// render graphics
updateGraphics();
// swap buffers
glfwSwapBuffers(window);
// process events
glfwPollEvents();
// signal frequency counter
freqCounterGraphics.signal(1);
}
// close window
glfwDestroyWindow(window);
// terminate GLFW library
glfwTerminate();
// exit
return (0);
}
//------------------------------------------------------------------------------
void windowSizeCallback(GLFWwindow* a_window, int a_width, int a_height)
{
// update window size
width = a_width;
height = a_height;
// update position of label
labelHapticDevicePosition->setLocalPos(20, width - 60, 0);
// update position of label
labelHapticDeviceModel->setLocalPos(20, height - 40, 0);
// update position of scope
scope->setSize(width - 200, 180);
// update position of dials
dialPosX->setLocalPos(width - 50, 210);
dialPosY->setLocalPos(width - 50, 150);
dialPosZ->setLocalPos(width - 50, 90);
}
//------------------------------------------------------------------------------
void errorCallback(int a_error, const char* a_description)
{
cout << "Error: " << a_description << endl;
}
//------------------------------------------------------------------------------
void keyCallback(GLFWwindow* a_window, int a_key, int a_scancode, int a_action, int a_mods)
{
// filter calls that only include a key press
if ((a_action != GLFW_PRESS) && (a_action != GLFW_REPEAT))
{
return;
}
// option - exit
if ((a_key == GLFW_KEY_ESCAPE) || (a_key == GLFW_KEY_Q))
{
glfwSetWindowShouldClose(a_window, GLFW_TRUE);
}
// option - enable/disable force field
if (a_key == GLFW_KEY_1)
{
useForceField = !useForceField;
if (useForceField)
cout << "> Enable force field \r";
else
cout << "> Disable force field \r";
}
// option - enable/disable damping
if (a_key == GLFW_KEY_2)
{
useDamping = !useDamping;
if (useDamping)
cout << "> Enable damping \r";
else
cout << "> Disable damping \r";
}
// option - toggle fullscreen
if (a_key == GLFW_KEY_F)
{
// toggle state variable
fullscreen = !fullscreen;
// get handle to monitor
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
// get information about monitor
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
// set fullscreen or window mode
if (fullscreen)
{
glfwSetWindowMonitor(window, monitor, 0, 0, mode->width, mode->height, mode->refreshRate);
glfwSwapInterval(swapInterval);
}
else
{
int w = 0.8 * mode->height;
int h = 0.5 * mode->height;
int x = 0.5 * (mode->width - w);
int y = 0.5 * (mode->height - h);
glfwSetWindowMonitor(window, NULL, x, y, w, h, mode->refreshRate);
glfwSwapInterval(swapInterval);
}
}
// option - toggle vertical mirroring
if (a_key == GLFW_KEY_M)
{
mirroredDisplay = !mirroredDisplay;
camera->setMirrorVertical(mirroredDisplay);
}
}
//------------------------------------------------------------------------------
void close(void)
{
// stop the simulation
simulationRunning = false;
// wait for graphics and haptics loops to terminate
while (!simulationFinished) { cSleepMs(100); }
// close haptic device
hapticDevice->close();
// delete resources
delete hapticsThread;
delete world;
delete handler;
}
//------------------------------------------------------------------------------
void updateGraphics(void)
{
/////////////////////////////////////////////////////////////////////
// UPDATE WIDGETS
/////////////////////////////////////////////////////////////////////
// update position data
labelHapticDevicePosition->setText( hapticDevicePosition.str(3));
// update haptic and graphic rate data
labelRates->setText(cStr(freqCounterGraphics.getFrequency(), 0) + " Hz / " +
cStr(freqCounterHaptics.getFrequency(), 0) + " Hz");
// update position of label
labelRates->setLocalPos((int)(0.5 * (width - labelRates->getWidth())), 15);
// update information to scope
scope->setSignalValues(hapticDevicePosition.x(),
hapticDevicePosition.y(),
hapticDevicePosition.z());
// update information to dials
dialPosX->setValue(hapticDevicePosition.x());
dialPosY->setValue(hapticDevicePosition.y());
dialPosZ->setValue(hapticDevicePosition.z());
// update velocity information to level
levelVelocity->setValue(hapticDeviceVelocity.length());
/////////////////////////////////////////////////////////////////////
// RENDER SCENE
/////////////////////////////////////////////////////////////////////
// update shadow maps (if any)
world->updateShadowMaps(false, mirroredDisplay);
// render world
camera->renderView(width, height);
// wait until all OpenGL commands are completed
glFinish();
// check for any OpenGL errors
GLenum err;
err = glGetError();
if (err != GL_NO_ERROR) cout << "Error: %s\n" << gluErrorString(err);
}
//------------------------------------------------------------------------------
void updateHaptics(void)
{
// simulation in now running
simulationRunning = true;
simulationFinished = false;
// main haptic simulation loop
while(simulationRunning)
{
/////////////////////////////////////////////////////////////////////
// READ HAPTIC DEVICE
/////////////////////////////////////////////////////////////////////
// read position
cVector3d position;
hapticDevice->getPosition(position);
// read orientation
cMatrix3d rotation;
hapticDevice->getRotation(rotation);
// read gripper position
double gripperAngle;
hapticDevice->getGripperAngleRad(gripperAngle);
// read linear velocity
cVector3d linearVelocity;
hapticDevice->getLinearVelocity(linearVelocity);
// read angular velocity
cVector3d angularVelocity;
hapticDevice->getAngularVelocity(angularVelocity);
// read gripper angular velocity
double gripperAngularVelocity;
hapticDevice->getGripperAngularVelocity(gripperAngularVelocity);
// read user-switch status (button 0)
bool button0, button1, button2, button3;
button0 = false;
button1 = false;
button2 = false;
button3 = false;
hapticDevice->getUserSwitch(0, button0);
hapticDevice->getUserSwitch(1, button1);
hapticDevice->getUserSwitch(2, button2);
hapticDevice->getUserSwitch(3, button3);
/////////////////////////////////////////////////////////////////////
// UPDATE 3D CURSOR MODEL
/////////////////////////////////////////////////////////////////////
// update arrow
velocity->m_pointA = position;
velocity->m_pointB = cAdd(position, linearVelocity);
// update position and orientation of cursor
cursor->setLocalPos(position);
cursor->setLocalRot(rotation);
// adjust the color of the cursor according to the status of
// the user-switch (ON = TRUE / OFF = FALSE)
if (button0)
{
cursor->m_material->setGreenMediumAquamarine();
}
else if (button1)
{
cursor->m_material->setYellowGold();
}
else if (button2)
{
cursor->m_material->setOrangeCoral();
}
else if (button3)
{
cursor->m_material->setPurpleLavender();
}
else
{
cursor->m_material->setBlueRoyal();
}
// update global variable for graphic display update
hapticDevicePosition = position;
hapticDeviceVelocity = linearVelocity;
/////////////////////////////////////////////////////////////////////
// COMPUTE AND APPLY FORCES
/////////////////////////////////////////////////////////////////////
cVector3d force (0,0,0);
cVector3d torque (0,0,0);
double gripperForce = 0.0;
// apply force field
if (useForceField)
{
// compute linear force
double Kp = 25; // [N/m]
cVector3d forceField = -Kp * position;
force.add(forceField);
// compute angular torque
double Kr = 0.05; // [N/m.rad]
cVector3d axis;
double angle;
rotation.toAxisAngle(axis, angle);
torque = (-Kr * angle) * axis;
}
// apply damping term
if (useDamping)
{
cHapticDeviceInfo info = hapticDevice->getSpecifications();
// compute linear damping force
double Kv = 1.0 * info.m_maxLinearDamping;
cVector3d forceDamping = -Kv * linearVelocity;
force.add(forceDamping);
// compute angular damping force
double Kvr = 1.0 * info.m_maxAngularDamping;
cVector3d torqueDamping = -Kvr * angularVelocity;
torque.add(torqueDamping);
// compute gripper angular damping force
double Kvg = 1.0 * info.m_maxGripperAngularDamping;
gripperForce = gripperForce - Kvg * gripperAngularVelocity;
}
// send computed force, torque, and gripper force to haptic device
hapticDevice->setForceAndTorqueAndGripperForce(force, torque, gripperForce);
// update frequency counter
freqCounterHaptics.signal(1);
}
// exit haptics thread
simulationFinished = true;
}
//------------------------------------------------------------------------------
|
// (C) Copyright Beman Dawes 2008
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for more information.
// MACRO: BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
// TITLE: C++0x explicit conversion operators unavailable
// DESCRIPTION: The compiler does not support C++0x explicit conversion operators
#if defined(__GNUC__) && !defined(__GXX_EXPERIMENTAL_CXX0X__) && !defined(BOOST_INTEL_STDCXX0X)
# error This feature is not available in non-C++0x mode
#endif
namespace boost_no_cxx11_explicit_conversion_operators {
void quiet_warning(int){}
struct foo {
explicit operator int() { return 1; }
};
int test()
{
foo f;
int i = int(f);
quiet_warning(i);
return 0;
}
}
|
/*******************************************************************************
* Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II
* Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI
*
* Distributed under the Boost Software License, Version 1.0.
* See accompanying file LICENSE.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt
******************************************************************************/
#ifndef NT2_CORE_SETTINGS_SIZE_HPP_INCLUDED
#define NT2_CORE_SETTINGS_SIZE_HPP_INCLUDED
#include <cstddef>
#include <boost/array.hpp>
#include <boost/mpl/vector_c.hpp>
#include <nt2/extension/parameters.hpp>
#include <nt2/sdk/details/preprocessor.hpp>
#include <nt2/core/settings/meta/option.hpp>
////////////////////////////////////////////////////////////////////////////////
// Defines size options
////////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace options
{
struct size_ { typedef void nt2_is_option_type; };
} }
////////////////////////////////////////////////////////////////////////////////
// Helper macro
////////////////////////////////////////////////////////////////////////////////
#define M0(z,n,t) \
template< BOOST_PP_ENUM_PARAMS(n, std::ptrdiff_t D) > \
struct of_size_<BOOST_PP_ENUM_PARAMS(n,D)> \
: BOOST_PP_CAT(BOOST_PP_CAT(boost::mpl::vector,n),_c) \
<std::ptrdiff_t, BOOST_PP_ENUM_PARAMS(n,D)> \
{ \
static const std::size_t dimensions = n; \
}; \
/**/
#define M1(z,n,t) \
typedef of_size_<NT2_PP_ENUM_VALUE(n,-1)> BOOST_PP_CAT(BOOST_PP_CAT(_,n),D); \
/**/
////////////////////////////////////////////////////////////////////////////////
// of_size_<D0,..,Dn> is a mixed CT/RT size value containing up to n
// dimensions spans in either a CT or RT storage
////////////////////////////////////////////////////////////////////////////////
namespace nt2
{
template< BOOST_PP_ENUM_BINARY_PARAMS ( NT2_MAX_DIMENSIONS
, std::ptrdiff_t D
, = -2 BOOST_PP_INTERCEPT
)
>
struct of_size_
: BOOST_PP_CAT(BOOST_PP_CAT(boost::mpl::vector,NT2_MAX_DIMENSIONS),_c)
<std::ptrdiff_t, BOOST_PP_ENUM_PARAMS(NT2_MAX_DIMENSIONS,D)>
{
static const std::size_t dimensions = NT2_MAX_DIMENSIONS;
};
//////////////////////////////////////////////////////////////////////////////
// Total specialization for 0D elements
//////////////////////////////////////////////////////////////////////////////
template<>
struct of_size_<NT2_PP_ENUM_VALUE(NT2_MAX_DIMENSIONS,-2)>
: boost::mpl::vector0_c<std::ptrdiff_t>
{
static const std::size_t dimensions = 0;
};
//////////////////////////////////////////////////////////////////////////////
// Other dimensions of_size_
//////////////////////////////////////////////////////////////////////////////
BOOST_PP_REPEAT_FROM_TO(1,NT2_MAX_DIMENSIONS,M0,~)
}
////////////////////////////////////////////////////////////////////////////////
// Register of_size has a valid options::id_ type
////////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace meta
{
template< BOOST_PP_ENUM_PARAMS(NT2_MAX_DIMENSIONS, std::ptrdiff_t D)
, class Default
>
struct option < of_size_<BOOST_PP_ENUM_PARAMS(NT2_MAX_DIMENSIONS,D)>
, options::size_
, Default
, void
>
{
typedef of_size_<BOOST_PP_ENUM_PARAMS(NT2_MAX_DIMENSIONS,D)> type;
};
} }
////////////////////////////////////////////////////////////////////////////////
// Defines some usual short-cut for runtime of_size_
////////////////////////////////////////////////////////////////////////////////
namespace nt2
{
BOOST_PP_REPEAT_FROM_TO(0,BOOST_PP_INC(NT2_MAX_DIMENSIONS),M1,~)
}
////////////////////////////////////////////////////////////////////////////////
// Macro clean-up
////////////////////////////////////////////////////////////////////////////////
#undef M0
#undef M1
#endif
|
// Copyright 2014 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 "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h"
#include <stddef.h>
#include <stdint.h>
#include <vector>
#include "base/command_line.h"
#include "base/macros.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_samples.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/simple_test_clock.h"
#include "base/test/task_environment.h"
#include "base/time/clock.h"
#include "base/time/default_clock.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_switches.h"
#include "components/prefs/pref_registry_simple.h"
#include "net/base/proxy_server.h"
#include "net/http/http_util.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace data_reduction_proxy {
class DataReductionProxySettingsTest
: public ConcreteDataReductionProxySettingsTest<
DataReductionProxySettings> {
public:
void CheckMaybeActivateDataReductionProxy(bool initially_enabled,
bool request_succeeded,
bool expected_enabled,
bool expected_restricted,
bool expected_fallback_restricted) {
test_context_->SetDataReductionProxyEnabled(initially_enabled);
ExpectSetProxyPrefs(expected_enabled, false);
settings_->MaybeActivateDataReductionProxy(false);
test_context_->RunUntilIdle();
}
};
TEST_F(DataReductionProxySettingsTest, TestResetDataReductionStatistics) {
int64_t original_content_length;
int64_t received_content_length;
int64_t last_update_time;
settings_->ResetDataReductionStatistics();
settings_->GetContentLengths(kNumDaysInHistory,
&original_content_length,
&received_content_length,
&last_update_time);
EXPECT_EQ(0L, original_content_length);
EXPECT_EQ(0L, received_content_length);
EXPECT_EQ(last_update_time_.ToInternalValue(), last_update_time);
}
TEST_F(DataReductionProxySettingsTest, TestContentLengths) {
int64_t original_content_length;
int64_t received_content_length;
int64_t last_update_time;
// Request |kNumDaysInHistory| days.
settings_->GetContentLengths(kNumDaysInHistory,
&original_content_length,
&received_content_length,
&last_update_time);
const unsigned int days = kNumDaysInHistory;
// Received content length history values are 0 to |kNumDaysInHistory - 1|.
int64_t expected_total_received_content_length = (days - 1L) * days / 2;
// Original content length history values are 0 to
// |2 * (kNumDaysInHistory - 1)|.
long expected_total_original_content_length = (days - 1L) * days;
EXPECT_EQ(expected_total_original_content_length, original_content_length);
EXPECT_EQ(expected_total_received_content_length, received_content_length);
EXPECT_EQ(last_update_time_.ToInternalValue(), last_update_time);
// Request |kNumDaysInHistory - 1| days.
settings_->GetContentLengths(kNumDaysInHistory - 1,
&original_content_length,
&received_content_length,
&last_update_time);
expected_total_received_content_length -= (days - 1);
expected_total_original_content_length -= 2 * (days - 1);
EXPECT_EQ(expected_total_original_content_length, original_content_length);
EXPECT_EQ(expected_total_received_content_length, received_content_length);
// Request 0 days.
settings_->GetContentLengths(0,
&original_content_length,
&received_content_length,
&last_update_time);
expected_total_received_content_length = 0;
expected_total_original_content_length = 0;
EXPECT_EQ(expected_total_original_content_length, original_content_length);
EXPECT_EQ(expected_total_received_content_length, received_content_length);
// Request 1 day. First day had 0 bytes so should be same as 0 days.
settings_->GetContentLengths(1,
&original_content_length,
&received_content_length,
&last_update_time);
EXPECT_EQ(expected_total_original_content_length, original_content_length);
EXPECT_EQ(expected_total_received_content_length, received_content_length);
}
TEST(DataReductionProxySettingsStandaloneTest, TestOnProxyEnabledPrefChange) {
base::test::SingleThreadTaskEnvironment task_environment{
base::test::SingleThreadTaskEnvironment::MainThreadType::IO};
std::unique_ptr<DataReductionProxyTestContext> drp_test_context =
DataReductionProxyTestContext::Builder()
.WithMockConfig()
.WithMockDataReductionProxyService()
.SkipSettingsInitialization()
.Build();
drp_test_context->InitSettings();
MockDataReductionProxyService* mock_service =
static_cast<MockDataReductionProxyService*>(
drp_test_context->data_reduction_proxy_service());
// The pref is disabled, so correspondingly should be the proxy.
EXPECT_CALL(*mock_service, SetProxyPrefs(false, false));
drp_test_context->SetDataReductionProxyEnabled(false);
// The pref is enabled, so correspondingly should be the proxy.
EXPECT_CALL(*mock_service, SetProxyPrefs(true, false));
drp_test_context->SetDataReductionProxyEnabled(true);
}
TEST(DataReductionProxySettingsStandaloneTest, TestIsProxyEnabledOrManaged) {
base::test::SingleThreadTaskEnvironment task_environment{
base::test::SingleThreadTaskEnvironment::MainThreadType::IO};
std::unique_ptr<DataReductionProxyTestContext> drp_test_context =
DataReductionProxyTestContext::Builder()
.WithMockConfig()
.WithMockDataReductionProxyService()
.SkipSettingsInitialization()
.Build();
drp_test_context->InitSettings();
DataReductionProxySettings* settings = drp_test_context->settings();
drp_test_context->SetDataReductionProxyEnabled(true);
EXPECT_TRUE(settings->IsDataReductionProxyEnabled());
EXPECT_FALSE(settings->IsDataReductionProxyManaged());
drp_test_context->SetDataReductionProxyEnabled(false);
EXPECT_FALSE(settings->IsDataReductionProxyEnabled());
EXPECT_FALSE(settings->IsDataReductionProxyManaged());
drp_test_context->SetDataReductionProxyEnabled(false);
drp_test_context->pref_service()->SetManagedPref(
prefs::kDataSaverEnabled, std::make_unique<base::Value>(false));
EXPECT_FALSE(settings->IsDataReductionProxyEnabled());
EXPECT_TRUE(settings->IsDataReductionProxyManaged());
drp_test_context->SetDataReductionProxyEnabled(true);
drp_test_context->pref_service()->SetManagedPref(
prefs::kDataSaverEnabled, std::make_unique<base::Value>(true));
EXPECT_TRUE(settings->IsDataReductionProxyEnabled());
EXPECT_TRUE(settings->IsDataReductionProxyManaged());
drp_test_context->RunUntilIdle();
}
TEST(DataReductionProxySettingsStandaloneTest, TestCanUseDataReductionProxy) {
base::test::SingleThreadTaskEnvironment task_environment{
base::test::SingleThreadTaskEnvironment::MainThreadType::IO};
std::unique_ptr<DataReductionProxyTestContext> drp_test_context =
DataReductionProxyTestContext::Builder()
.WithMockConfig()
.WithMockDataReductionProxyService()
.SkipSettingsInitialization()
.Build();
drp_test_context->InitSettings();
MockDataReductionProxyService* mock_service =
static_cast<MockDataReductionProxyService*>(
drp_test_context->data_reduction_proxy_service());
DataReductionProxySettings* settings = drp_test_context->settings();
GURL http_gurl("http://url.com/");
GURL https_gurl("https://url.com/");
// The pref is disabled, so correspondingly should be the proxy.
EXPECT_CALL(*mock_service, SetProxyPrefs(false, false));
drp_test_context->SetDataReductionProxyEnabled(false);
EXPECT_FALSE(settings->CanUseDataReductionProxy(http_gurl));
EXPECT_FALSE(settings->CanUseDataReductionProxy(https_gurl));
// The pref is enabled, so correspondingly should be the proxy.
EXPECT_CALL(*mock_service, SetProxyPrefs(true, false));
drp_test_context->SetDataReductionProxyEnabled(true);
EXPECT_TRUE(settings->CanUseDataReductionProxy(http_gurl));
EXPECT_FALSE(settings->CanUseDataReductionProxy(https_gurl));
drp_test_context->RunUntilIdle();
}
TEST_F(DataReductionProxySettingsTest, TestMaybeActivateDataReductionProxy) {
// Initialize the pref member in |settings_| without the usual callback
// so it won't trigger MaybeActivateDataReductionProxy when the pref value
// is set.
// TODO(bengr): Test enabling/disabling while a secure proxy check is
// outstanding.
// The proxy is enabled and unrestricted initially.
// Request succeeded but with bad response, expect proxy to be restricted.
CheckMaybeActivateDataReductionProxy(true, true, true, true, false);
// Request succeeded with valid response, expect proxy to be unrestricted.
CheckMaybeActivateDataReductionProxy(true, true, true, false, false);
// Request failed, expect proxy to be enabled but restricted.
CheckMaybeActivateDataReductionProxy(true, false, true, true, false);
// The proxy is disabled initially. No secure proxy checks should take place,
// and so the state should not change.
CheckMaybeActivateDataReductionProxy(false, true, false, false, false);
}
TEST_F(DataReductionProxySettingsTest, TestInitDataReductionProxyOn) {
MockSettings* settings = static_cast<MockSettings*>(settings_.get());
EXPECT_CALL(*settings, RecordStartupState(PROXY_ENABLED));
test_context_->SetDataReductionProxyEnabled(true);
InitDataReductionProxy(true);
CheckDataReductionProxySyntheticTrial(true);
}
TEST_F(DataReductionProxySettingsTest, TestInitDataReductionProxyOff) {
// InitDataReductionProxySettings with the preference off will directly call
// LogProxyState.
MockSettings* settings = static_cast<MockSettings*>(settings_.get());
EXPECT_CALL(*settings, RecordStartupState(PROXY_DISABLED));
test_context_->SetDataReductionProxyEnabled(false);
InitDataReductionProxy(false);
CheckDataReductionProxySyntheticTrial(false);
}
TEST_F(DataReductionProxySettingsTest, TestEnableProxyFromCommandLine) {
MockSettings* settings = static_cast<MockSettings*>(settings_.get());
EXPECT_CALL(*settings, RecordStartupState(PROXY_ENABLED));
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableDataReductionProxy);
InitDataReductionProxy(true);
CheckDataReductionProxySyntheticTrial(true);
}
TEST_F(DataReductionProxySettingsTest, TestSetDataReductionProxyEnabled) {
MockSettings* settings = static_cast<MockSettings*>(settings_.get());
EXPECT_CALL(*settings, RecordStartupState(PROXY_ENABLED));
test_context_->SetDataReductionProxyEnabled(true);
InitDataReductionProxy(true);
test_context_->SetDataReductionProxyEnabled(false);
test_context_->RunUntilIdle();
CheckDataReductionProxySyntheticTrial(false);
test_context_->SetDataReductionProxyEnabled(true);
test_context_->RunUntilIdle();
CheckDataReductionProxySyntheticTrial(true);
}
TEST_F(DataReductionProxySettingsTest, TestSettingsEnabledStateHistograms) {
const char kUMAEnabledState[] = "DataReductionProxy.EnabledState";
base::HistogramTester histogram_tester;
// No settings state histograms should be recorded during startup.
test_context_->RunUntilIdle();
histogram_tester.ExpectTotalCount(kUMAEnabledState, 0);
test_context_->SetDataReductionProxyEnabled(true);
settings_->MaybeActivateDataReductionProxy(false);
test_context_->RunUntilIdle();
histogram_tester.ExpectBucketCount(
kUMAEnabledState, DATA_REDUCTION_SETTINGS_ACTION_OFF_TO_ON, 1);
histogram_tester.ExpectBucketCount(
kUMAEnabledState, DATA_REDUCTION_SETTINGS_ACTION_ON_TO_OFF, 0);
test_context_->SetDataReductionProxyEnabled(false);
settings_->MaybeActivateDataReductionProxy(false);
test_context_->RunUntilIdle();
histogram_tester.ExpectBucketCount(
kUMAEnabledState, DATA_REDUCTION_SETTINGS_ACTION_OFF_TO_ON, 1);
histogram_tester.ExpectBucketCount(
kUMAEnabledState, DATA_REDUCTION_SETTINGS_ACTION_ON_TO_OFF, 1);
}
// Verify that the UMA metric and the pref is recorded correctly when the user
// enables the data reduction proxy.
TEST_F(DataReductionProxySettingsTest, TestDaysSinceEnabledWithTestClock) {
const char kUMAEnabledState[] = "DataReductionProxy.DaysSinceEnabled";
base::SimpleTestClock clock;
clock.Advance(base::TimeDelta::FromDays(1));
ResetSettings(&clock);
base::Time last_enabled_time = clock.Now();
{
base::HistogramTester histogram_tester;
test_context_->RunUntilIdle();
histogram_tester.ExpectTotalCount(kUMAEnabledState, 0);
// Enable data reduction proxy. The metric should be recorded.
test_context_->SetDataReductionProxyEnabled(true);
settings_->MaybeActivateDataReductionProxy(false);
test_context_->RunUntilIdle();
last_enabled_time = clock.Now();
EXPECT_EQ(
last_enabled_time,
base::Time::FromInternalValue(test_context_->pref_service()->GetInt64(
prefs::kDataReductionProxyLastEnabledTime)));
histogram_tester.ExpectUniqueSample(kUMAEnabledState, 0, 1);
}
{
// Simulate turning off and on of data reduction proxy while Chromium is
// running.
test_context_->SetDataReductionProxyEnabled(false);
settings_->MaybeActivateDataReductionProxy(false);
clock.Advance(base::TimeDelta::FromDays(1));
last_enabled_time = clock.Now();
test_context_->SetDataReductionProxyEnabled(true);
base::HistogramTester histogram_tester;
settings_->MaybeActivateDataReductionProxy(false /* at_startup */);
test_context_->RunUntilIdle();
histogram_tester.ExpectUniqueSample(kUMAEnabledState, 0, 1);
EXPECT_EQ(
last_enabled_time,
base::Time::FromInternalValue(test_context_->pref_service()->GetInt64(
prefs::kDataReductionProxyLastEnabledTime)));
}
{
// Advance clock by a random number of days.
int advance_clock_days = 42;
clock.Advance(base::TimeDelta::FromDays(advance_clock_days));
base::HistogramTester histogram_tester;
// Simulate Chromium start up. Data reduction proxy was enabled
// |advance_clock_days| ago.
settings_->MaybeActivateDataReductionProxy(true /* at_startup */);
test_context_->RunUntilIdle();
histogram_tester.ExpectUniqueSample(kUMAEnabledState, advance_clock_days,
1);
EXPECT_EQ(
last_enabled_time,
base::Time::FromInternalValue(test_context_->pref_service()->GetInt64(
prefs::kDataReductionProxyLastEnabledTime)));
}
}
// Verify that the pref and the UMA metric are not recorded for existing users
// that already have data reduction proxy on.
TEST(DataReductionProxySettingsStandaloneTest,
TestDaysSinceEnabledExistingUser) {
base::test::SingleThreadTaskEnvironment task_environment{
base::test::SingleThreadTaskEnvironment::MainThreadType::IO};
std::unique_ptr<DataReductionProxyTestContext> drp_test_context =
DataReductionProxyTestContext::Builder()
.WithMockConfig()
.WithMockDataReductionProxyService()
.SkipSettingsInitialization()
.Build();
drp_test_context->InitSettings();
base::HistogramTester histogram_tester;
// Simulate Chromium startup with data reduction proxy already enabled.
drp_test_context->settings()->MaybeActivateDataReductionProxy(
true /* at_startup */);
drp_test_context->RunUntilIdle();
histogram_tester.ExpectTotalCount("DataReductionProxy.DaysSinceEnabled", 0);
EXPECT_EQ(0, drp_test_context->pref_service()->GetInt64(
prefs::kDataReductionProxyLastEnabledTime));
}
TEST_F(DataReductionProxySettingsTest, TestGetDailyContentLengths) {
ContentLengthList result =
settings_->GetDailyContentLengths(prefs::kDailyHttpOriginalContentLength);
ASSERT_FALSE(result.empty());
ASSERT_EQ(kNumDaysInHistory, result.size());
for (size_t i = 0; i < kNumDaysInHistory; ++i) {
long expected_length =
static_cast<long>((kNumDaysInHistory - 1 - i) * 2);
ASSERT_EQ(expected_length, result[i]);
}
}
} // namespace data_reduction_proxy
|
#include "curl_easy.h"
#include "curl_form.h"
#include "curl_header.h"
using curl::curl_header;
using curl::curl_easy;
using curl::curl_easy_exception;
using curl::curlcpp_traceback;
/*
* This example shows how to add custom headers to a simple
* curl request.
*/
int main() {
// Let's create an object which will contain a list of headers.
curl_header header;
// Easy object to handle the connection.
curl_easy easy;
// Add custom headers.
header.add("Accept:");
header.add("Another:yes");
header.add("Host: example.com");
// Add the headers to the easy object.
easy.add<CURLOPT_HTTPHEADER>(header.get());
easy.add<CURLOPT_URL>("localhost");
easy.add<CURLOPT_VERBOSE>(1L);
try {
// Request execution
easy.perform();
} catch (curl_easy_exception error) {
// If you want to get the entire error stack we can do:
curlcpp_traceback errors = error.get_traceback();
// Otherwise we could print the stack like this:
error.print_traceback();
}
return 0;
}
|
#include <eve/function/diff/sub.hpp>
#include <eve/wide.hpp>
#include <eve/constant/inf.hpp>
#include <eve/constant/minf.hpp>
#include <eve/constant/nan.hpp>
#include <iostream>
using wide_ft = eve::wide<float, eve::fixed<8>>;
int main()
{
wide_ft pf = {2.0f, 3.0f, -4.0f, 2.0f, 2.0f,
eve::inf(eve::as<float>()), eve::minf(eve::as<float>()), eve::nan(eve::as<float>())};
wide_ft qf = {4.0f, 1.0f, -1.0f, 0.5f, 0.0f,
-2.0f, -3.0f, 2.5f};
std::cout << "---- simd" << '\n'
<< "<- pf = " << pf << '\n'
<< "<- qf = " << qf << '\n'
<< "-> sub(pf, qf) = " << eve::sub(pf, qf) << '\n'
<< "-> diff_1st(sub)(pf, qf) = " << eve::diff_1st(eve::sub)(pf, qf) << std::endl
<< "-> diff_2nd(sub)(pf, qf) = " << eve::diff_2nd(eve::sub)(pf, qf) << std::endl
<< "-> diff(sub)(pf, qf, 0u, 2u) = " << eve::diff(eve::sub)(pf, qf, 0u, 2u) << std::endl
<< "-> diff(sub)(pf, qf, 2u, 0u) = " << eve::diff(eve::sub)(pf, qf, 2u, 0u) << std::endl;
float xf = 4.0f;
float yf = -1.0f;
std::cout << "---- scalar" << '\n'
<< "<- xf = " << xf << '\n'
<< "<- yf = " << yf << '\n'
<< "-> sub(xf, yf) = " << eve::sub(xf, yf) << '\n'
<< "-> diff_1st(sub)(xf, yf) = " << eve::diff_1st(eve::sub)(xf, yf) << std::endl
<< "-> diff_2nd(sub)(xf, yf) = " << eve::diff_2nd(eve::sub)(xf, yf) << std::endl;
return 0;
}
|
// Copyright 2014 Samsung Electronics. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Define those macros _before_ you include the utc_blink_ewk.h header file. */
#include "utc_blink_ewk_base.h"
class utc_blink_ewk_context_web_storage_origin_delete: public utc_blink_ewk_base {
protected:
utc_blink_ewk_context_web_storage_origin_delete()
: utc_blink_ewk_base()
, origins(NULL)
, ctx(NULL)
{
}
~utc_blink_ewk_context_web_storage_origin_delete()
{
SetOrigins(NULL);
}
void PostSetUp()
{
ctx = ewk_view_context_get(GetEwkWebView());
ASSERT_TRUE(ctx != NULL);
// we want empty web storage at test start
ASSERT_EQ(EINA_TRUE, ewk_context_web_storage_delete_all(ctx));
GetOrigins(0);
ASSERT_TRUE(origins == NULL);
}
void LoadFinished(Evas_Object* webview)
{
EventLoopStop(Success);
}
static void origins_get_cb(Eina_List* origins, void* user_data)
{
utc_message("origins_get_cb: %p, %p", origins, user_data);
if (!user_data) {
ewk_context_origins_free(origins);
FAIL();
}
utc_blink_ewk_context_web_storage_origin_delete* owner = static_cast<utc_blink_ewk_context_web_storage_origin_delete*>(user_data);
owner->SetOrigins(origins);
owner->EventLoopStop(Success);
}
Ewk_Security_Origin* FindSecurityOrigin(const char* origin_host)
{
utc_message("FindSecurityOrigin: %s in %p", origin_host, origins);
Ewk_Security_Origin* retval = NULL;
if(origins && origin_host) {
Eina_List* it;
void *vorigin = NULL;
EINA_LIST_FOREACH(origins, it, vorigin) {
Ewk_Security_Origin* origin = static_cast<Ewk_Security_Origin*>(vorigin);
const char* host = ewk_security_origin_host_get(origin);
if (host && strcmp(host, origin_host) == 0) {
retval = origin;
break;
}
}
}
return retval;
}
void SetOrigins(Eina_List* new_origins)
{
if (new_origins != origins) {
if (origins) {
ewk_context_origins_free(origins);
}
origins = new_origins;
}
}
void GetOrigins(int expected_count)
{
// web storage operations are async, we must wait for changes to propagate
for (int i = 0; i < 3; ++i) {
if (EINA_TRUE != ewk_context_web_storage_origins_get(ctx, origins_get_cb, this)) {
break;
}
if (Success != EventLoopStart()) {
break;
}
if (expected_count == eina_list_count(origins)) {
break;
}
if (!EventLoopWait(3.0)) {
break;
}
}
}
protected:
static const char* const web_storage_sample_resource;
static const char* const web_storage_sample_url;
static const char* const sample_origin;
protected:
Eina_List* origins;
Ewk_Context* ctx;
};
const char* const utc_blink_ewk_context_web_storage_origin_delete::web_storage_sample_resource = "ewk_context_web_storage/web_storage_create_simple.html";
const char* const utc_blink_ewk_context_web_storage_origin_delete::web_storage_sample_url = "http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_webstorage_local";
const char* const utc_blink_ewk_context_web_storage_origin_delete::sample_origin = "www.w3schools.com";
/**
* @brief Tests if can delete all web storages
*/
TEST_F(utc_blink_ewk_context_web_storage_origin_delete, POS_TEST)
{
// load some pages with web storage
std::string resurl = GetResourceUrl(web_storage_sample_resource);
utc_message("Loading resource: %s", resurl.c_str());
ASSERT_EQ(EINA_TRUE, ewk_view_url_set(GetEwkWebView(), resurl.c_str()));
ASSERT_EQ(Success, EventLoopStart());
utc_message("Loading web page: %s", web_storage_sample_url);
ASSERT_EQ(EINA_TRUE, ewk_view_url_set(GetEwkWebView(), web_storage_sample_url));
ASSERT_EQ(Success, EventLoopStart());
GetOrigins(2);
ASSERT_TRUE(origins != NULL);
ASSERT_EQ(2, eina_list_count(origins));
// remove sample origin
Ewk_Security_Origin* origin = FindSecurityOrigin(sample_origin);
ASSERT_TRUE(origin != NULL);
ASSERT_EQ(EINA_TRUE, ewk_context_web_storage_origin_delete(ctx, origin));
GetOrigins(1);
ASSERT_TRUE(origins != NULL);
ASSERT_EQ(1, eina_list_count(origins));
// verify security origin was removed
origin = FindSecurityOrigin(sample_origin);
ASSERT_TRUE(origin == NULL);
}
/**
* @brief Tests if returns false when context is null.
*/
TEST_F(utc_blink_ewk_context_web_storage_origin_delete, invalid_args)
{
EXPECT_EQ(EINA_FALSE, ewk_context_web_storage_origin_delete(NULL, NULL));
EXPECT_EQ(EINA_FALSE, ewk_context_web_storage_origin_delete(ctx, NULL));
}
|
//////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#define NT2_UNIT_MODULE "nt2 trigonometric toolbox - fast_tand/scalar Mode"
//////////////////////////////////////////////////////////////////////////////
// Test behavior of trigonometric components in scalar mode
//////////////////////////////////////////////////////////////////////////////
/// created by jt the 11/02/2011
/// modified by jt the 23/03/2011
#include <boost/type_traits/is_same.hpp>
#include <nt2/sdk/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/memory/buffer.hpp>
#include <nt2/sdk/constant/real.hpp>
#include <nt2/sdk/constant/infinites.hpp>
#include <nt2/include/functions/ulpdist.hpp>
#include <nt2/toolbox/trigonometric/include/fast_tand.hpp>
// specific includes for arity 1 tests
#include <nt2/toolbox/trigonometric/include/constants.hpp>
extern "C" {extern long double cephes_tanl(long double);}
NT2_TEST_CASE_TPL ( fast_tand_real__1_0, NT2_REAL_TYPES)
{
using nt2::fast_tand;
using nt2::tag::fast_tand_;
typedef typename nt2::meta::as_integer<T>::type iT;
typedef typename nt2::meta::call<fast_tand_(T)>::type r_t;
typedef typename nt2::meta::upgrade<T>::type u_t;
typedef typename boost::result_of<nt2::meta::floating(T)>::type wished_r_t;
// return type conformity test
NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );
std::cout << std::endl;
double ulpd;
ulpd=0.0;
// specific values tests
NT2_TEST_ULP_EQUAL(fast_tand(-nt2::_180<T>()), nt2::Nan<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(-nt2::_45<T>()), nt2::Mone<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(-nt2::_90<T>()), nt2::Nan<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::Inf<T>()), nt2::Nan<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::Minf<T>()), nt2::Nan<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::Nan<T>()), nt2::Nan<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::Zero<T>()), nt2::Zero<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::_180<T>()), nt2::Nan<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::_45<T>()), nt2::One<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::_90<T>()), nt2::Nan<r_t>(), 1.0);
// random verifications
static const uint32_t NR = NT2_NB_RANDOM_TEST;
{
NT2_CREATE_BUF(tab_a0,T, NR, T(-45), T(45));
double ulp0, ulpd ; ulpd=ulp0=0.0;
T a0;
for (uint32_t j =0; j < NR; ++j )
{
std::cout << "for param "
<< " a0 = "<< u_t(a0 = tab_a0[j])
<< std::endl;
NT2_TEST_ULP_EQUAL( nt2::fast_tand(a0),::cephes_tanl(a0*nt2::long_deginrad),2.5);
ulp0=nt2::max(ulpd,ulp0);
}
std::cout << "max ulp found is: " << ulp0 << std::endl;
}
} // end of test for real_
NT2_TEST_CASE_TPL ( fast_tand_unsigned_int__1_0, NT2_UNSIGNED_TYPES)
{
using nt2::fast_tand;
using nt2::tag::fast_tand_;
typedef typename nt2::meta::as_integer<T>::type iT;
typedef typename nt2::meta::call<fast_tand_(T)>::type r_t;
typedef typename nt2::meta::upgrade<T>::type u_t;
typedef typename boost::result_of<nt2::meta::floating(T)>::type wished_r_t;
// return type conformity test
NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );
std::cout << std::endl;
double ulpd;
ulpd=0.0;
// specific values tests
NT2_TEST_ULP_EQUAL(fast_tand(nt2::Zero<T>()), nt2::Zero<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::_45<T>()), nt2::One<r_t>(), 1.0);
} // end of test for unsigned_int_
NT2_TEST_CASE_TPL ( fast_tand_signed_int__1_0, NT2_INTEGRAL_SIGNED_TYPES)
{
using nt2::fast_tand;
using nt2::tag::fast_tand_;
typedef typename nt2::meta::as_integer<T>::type iT;
typedef typename nt2::meta::call<fast_tand_(T)>::type r_t;
typedef typename nt2::meta::upgrade<T>::type u_t;
typedef typename boost::result_of<nt2::meta::floating(T)>::type wished_r_t;
// return type conformity test
NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );
std::cout << std::endl;
double ulpd;
ulpd=0.0;
// specific values tests
NT2_TEST_ULP_EQUAL(fast_tand(-nt2::_45<T>()), nt2::Mone<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::Zero<T>()), nt2::Zero<r_t>(), 1.0);
NT2_TEST_ULP_EQUAL(fast_tand(nt2::_45<T>()), nt2::One<r_t>(), 1.0);
} // end of test for signed_int_
|
/*
Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
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, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
@file
@brief
This file implements classes defined in field.h
*/
#ifdef USE_PRAGMA_IMPLEMENTATION
#pragma implementation // gcc: Class implementation
#endif
#include "mysql_priv.h"
#include "sql_select.h"
#include "rpl_rli.h" // Pull in Relay_log_info
#include "slave.h" // Pull in rpl_master_has_bug()
#include <m_ctype.h>
#include <errno.h>
#ifdef HAVE_FCONVERT
#include <floatingpoint.h>
#endif
// Maximum allowed exponent value for converting string to decimal
#define MAX_EXPONENT 1024
/*****************************************************************************
Instansiate templates and static variables
*****************************************************************************/
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
template class List<Create_field>;
template class List_iterator<Create_field>;
#endif
uchar Field_null::null[1]={1};
const char field_separator=',';
#define DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE 320
#define LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE 128
#define DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE 128
#define BLOB_PACK_LENGTH_TO_MAX_LENGH(arg) \
((ulong) ((LL(1) << min(arg, 4) * 8) - LL(1)))
#define ASSERT_COLUMN_MARKED_FOR_READ DBUG_ASSERT(!table || (!table->read_set || bitmap_is_set(table->read_set, field_index)))
#define ASSERT_COLUMN_MARKED_FOR_WRITE DBUG_ASSERT(!table || (!table->write_set || bitmap_is_set(table->write_set, field_index)))
/*
Rules for merging different types of fields in UNION
NOTE: to avoid 256*256 table, gap in table types numeration is skiped
following #defines describe that gap and how to canculate number of fields
and index of field in thia array.
*/
#define FIELDTYPE_TEAR_FROM (MYSQL_TYPE_BIT + 1)
#define FIELDTYPE_TEAR_TO (MYSQL_TYPE_NEWDECIMAL - 1)
#define FIELDTYPE_NUM (FIELDTYPE_TEAR_FROM + (255 - FIELDTYPE_TEAR_TO))
inline int field_type2index (enum_field_types field_type)
{
return (field_type < FIELDTYPE_TEAR_FROM ?
field_type :
((int)FIELDTYPE_TEAR_FROM) + (field_type - FIELDTYPE_TEAR_TO) - 1);
}
static enum_field_types field_types_merge_rules [FIELDTYPE_NUM][FIELDTYPE_NUM]=
{
/* MYSQL_TYPE_DECIMAL -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_DECIMAL, MYSQL_TYPE_DECIMAL,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_TINY -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_TINY,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_TINY, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_SHORT -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_SHORT,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_SHORT, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_SHORT,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_LONG -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_LONG,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_LONG, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_LONG, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_LONG,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_FLOAT -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_FLOAT,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_FLOAT, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_FLOAT, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_FLOAT,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_DOUBLE -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_NULL -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_TINY,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_TIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_BIT,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_ENUM,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_SET, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_GEOMETRY
},
/* MYSQL_TYPE_TIMESTAMP -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_TIMESTAMP, MYSQL_TYPE_TIMESTAMP,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_DATETIME, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_LONGLONG -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_LONGLONG,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_LONGLONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_LONG,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_LONGLONG,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_INT24 -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_INT24,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_INT24, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_INT24, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_INT24,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_DATE -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_TIME -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_DATETIME, MYSQL_TYPE_TIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_DATETIME -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_DATETIME, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_DATETIME, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_YEAR -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_YEAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_YEAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_NEWDATE -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_VARCHAR -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_BIT -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_BIT, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_BIT,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_NEWDECIMAL -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_ENUM -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_ENUM, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_SET -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_SET, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_TINY_BLOB -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB
},
/* MYSQL_TYPE_MEDIUM_BLOB -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB
},
/* MYSQL_TYPE_LONG_BLOB -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB
},
/* MYSQL_TYPE_BLOB -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_BLOB,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB
},
/* MYSQL_TYPE_VAR_STRING -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_STRING -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_STRING,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_STRING, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING
},
/* MYSQL_TYPE_GEOMETRY -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_GEOMETRY, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<245>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_GEOMETRY
}
};
/**
Return type of which can carry value of both given types in UNION result.
@param a type for merging
@param b type for merging
@return
type of field
*/
enum_field_types Field::field_type_merge(enum_field_types a,
enum_field_types b)
{
DBUG_ASSERT(a < FIELDTYPE_TEAR_FROM || a > FIELDTYPE_TEAR_TO);
DBUG_ASSERT(b < FIELDTYPE_TEAR_FROM || b > FIELDTYPE_TEAR_TO);
return field_types_merge_rules[field_type2index(a)]
[field_type2index(b)];
}
static Item_result field_types_result_type [FIELDTYPE_NUM]=
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
DECIMAL_RESULT, INT_RESULT,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
INT_RESULT, INT_RESULT,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
REAL_RESULT, REAL_RESULT,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
INT_RESULT, INT_RESULT,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
STRING_RESULT, INT_RESULT,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_BIT <16>-<245>
STRING_RESULT,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
DECIMAL_RESULT, STRING_RESULT,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
STRING_RESULT, STRING_RESULT
};
/*
Test if the given string contains important data:
not spaces for character string,
or any data for binary string.
SYNOPSIS
test_if_important_data()
cs Character set
str String to test
strend String end
RETURN
FALSE - If string does not have important data
TRUE - If string has some important data
*/
static bool
test_if_important_data(CHARSET_INFO *cs, const char *str, const char *strend)
{
if (cs != &my_charset_bin)
str+= cs->cset->scan(cs, str, strend, MY_SEQ_SPACES);
return (str < strend);
}
/**
Detect Item_result by given field type of UNION merge result.
@param field_type given field type
@return
Item_result (type of internal MySQL expression result)
*/
Item_result Field::result_merge_type(enum_field_types field_type)
{
DBUG_ASSERT(field_type < FIELDTYPE_TEAR_FROM || field_type
> FIELDTYPE_TEAR_TO);
return field_types_result_type[field_type2index(field_type)];
}
/*****************************************************************************
Static help functions
*****************************************************************************/
/**
Check whether a field type can be partially indexed by a key.
This is a static method, rather than a virtual function, because we need
to check the type of a non-Field in mysql_alter_table().
@param type field type
@retval
TRUE Type can have a prefixed key
@retval
FALSE Type can not have a prefixed key
*/
bool Field::type_can_have_key_part(enum enum_field_types type)
{
switch (type) {
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_GEOMETRY:
return TRUE;
default:
return FALSE;
}
}
/**
Numeric fields base class constructor.
*/
Field_num::Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
uchar null_bit_arg, utype unireg_check_arg,
const char *field_name_arg,
uint8 dec_arg, bool zero_arg, bool unsigned_arg)
:Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg),
dec(dec_arg),zerofill(zero_arg),unsigned_flag(unsigned_arg)
{
if (zerofill)
flags|=ZEROFILL_FLAG;
if (unsigned_flag)
flags|=UNSIGNED_FLAG;
}
void Field_num::prepend_zeros(String *value)
{
int diff;
if ((diff= (int) (field_length - value->length())) > 0)
{
bmove_upp((uchar*) value->ptr()+field_length,
(uchar*) value->ptr()+value->length(),
value->length());
bfill((uchar*) value->ptr(),diff,'0');
value->length(field_length);
(void) value->c_ptr_quick(); // Avoid warnings in purify
}
}
/**
Test if given number is a int.
@todo
Make this multi-byte-character safe
@param str String to test
@param length Length of 'str'
@param int_end Pointer to char after last used digit
@param cs Character set
@note
This is called after one has called strntoull10rnd() function.
@retval
0 OK
@retval
1 error: empty string or wrong integer.
@retval
2 error: garbage at the end of string.
*/
int Field_num::check_int(CHARSET_INFO *cs, const char *str, int length,
const char *int_end, int error)
{
/* Test if we get an empty string or wrong integer */
if (str == int_end || error == MY_ERRNO_EDOM)
{
char buff[128];
String tmp(buff, (uint32) sizeof(buff), system_charset_info);
tmp.copy(str, length, system_charset_info);
push_warning_printf(table->in_use, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
"integer", tmp.c_ptr(), field_name,
(ulong) table->in_use->row_count);
return 1;
}
/* Test if we have garbage at the end of the given string. */
if (test_if_important_data(cs, int_end, str + length))
{
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
return 2;
}
return 0;
}
/*
Conver a string to an integer then check bounds.
SYNOPSIS
Field_num::get_int
cs Character set
from String to convert
len Length of the string
rnd OUT longlong value
unsigned_max max unsigned value
signed_min min signed value
signed_max max signed value
DESCRIPTION
The function calls strntoull10rnd() to get an integer value then
check bounds and errors returned. In case of any error a warning
is raised.
RETURN
0 ok
1 error
*/
bool Field_num::get_int(CHARSET_INFO *cs, const char *from, uint len,
longlong *rnd, ulonglong unsigned_max,
longlong signed_min, longlong signed_max)
{
char *end;
int error;
*rnd= (longlong) cs->cset->strntoull10rnd(cs, from, len,
unsigned_flag, &end,
&error);
if (unsigned_flag)
{
if ((((ulonglong) *rnd > unsigned_max) && (*rnd= (longlong) unsigned_max)) ||
error == MY_ERRNO_ERANGE)
{
goto out_of_range;
}
}
else
{
if (*rnd < signed_min)
{
*rnd= signed_min;
goto out_of_range;
}
else if (*rnd > signed_max)
{
*rnd= signed_max;
goto out_of_range;
}
}
if (table->in_use->count_cuted_fields &&
check_int(cs, from, len, end, error))
return 1;
return 0;
out_of_range:
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
return 1;
}
/**
Process decimal library return codes and issue warnings for overflow and
truncation.
@param op_result decimal library return code (E_DEC_* see include/decimal.h)
@retval
1 there was overflow
@retval
0 no error or some other errors except overflow
*/
int Field::warn_if_overflow(int op_result)
{
if (op_result == E_DEC_OVERFLOW)
{
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
return 1;
}
if (op_result == E_DEC_TRUNCATED)
{
set_warning(MYSQL_ERROR::WARN_LEVEL_NOTE, WARN_DATA_TRUNCATED, 1);
/* We return 0 here as this is not a critical issue */
}
return 0;
}
#ifdef NOT_USED
static bool test_if_real(const char *str,int length, CHARSET_INFO *cs)
{
cs= system_charset_info; // QQ move test_if_real into CHARSET_INFO struct
while (length && my_isspace(cs,*str))
{ // Allow start space
length--; str++;
}
if (!length)
return 0;
if (*str == '+' || *str == '-')
{
length--; str++;
if (!length || !(my_isdigit(cs,*str) || *str == '.'))
return 0;
}
while (length && my_isdigit(cs,*str))
{
length--; str++;
}
if (!length)
return 1;
if (*str == '.')
{
length--; str++;
while (length && my_isdigit(cs,*str))
{
length--; str++;
}
}
if (!length)
return 1;
if (*str == 'E' || *str == 'e')
{
if (length < 3 || (str[1] != '+' && str[1] != '-') ||
!my_isdigit(cs,str[2]))
return 0;
length-=3;
str+=3;
while (length && my_isdigit(cs,*str))
{
length--; str++;
}
}
for (; length ; length--, str++)
{ // Allow end space
if (!my_isspace(cs,*str))
return 0;
}
return 1;
}
#endif
/**
Interpret field value as an integer but return the result as a string.
This is used for printing bit_fields as numbers while debugging.
*/
String *Field::val_int_as_str(String *val_buffer, my_bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_READ;
CHARSET_INFO *cs= &my_charset_bin;
uint length;
longlong value= val_int();
if (val_buffer->alloc(MY_INT64_NUM_DECIMAL_DIGITS))
return 0;
length= (uint) (*cs->cset->longlong10_to_str)(cs, (char*) val_buffer->ptr(),
MY_INT64_NUM_DECIMAL_DIGITS,
unsigned_val ? 10 : -10,
value);
val_buffer->length(length);
return val_buffer;
}
/// This is used as a table name when the table structure is not set up
Field::Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg,
uchar null_bit_arg,
utype unireg_check_arg, const char *field_name_arg)
:ptr(ptr_arg), null_ptr(null_ptr_arg),
table(0), orig_table(0), table_name(0),
field_name(field_name_arg),
key_start(0), part_of_key(0), part_of_key_not_clustered(0),
part_of_sortkey(0), unireg_check(unireg_check_arg),
field_length(length_arg), null_bit(null_bit_arg),
is_created_from_null_item(FALSE)
{
flags=null_ptr ? 0: NOT_NULL_FLAG;
comment.str= (char*) "";
comment.length=0;
field_index= 0;
}
void Field::hash(ulong *nr, ulong *nr2)
{
if (is_null())
{
*nr^= (*nr << 1) | 1;
}
else
{
uint len= pack_length();
CHARSET_INFO *cs= charset();
cs->coll->hash_sort(cs, ptr, len, nr, nr2);
}
}
size_t
Field::do_last_null_byte() const
{
DBUG_ASSERT(null_ptr == NULL || null_ptr >= table->record[0]);
if (null_ptr)
return (size_t) (null_ptr - table->record[0]) + 1;
return LAST_NULL_BYTE_UNDEF;
}
void Field::copy_from_tmp(int row_offset)
{
memcpy(ptr,ptr+row_offset,pack_length());
if (null_ptr)
{
*null_ptr= (uchar) ((null_ptr[0] & (uchar) ~(uint) null_bit) |
(null_ptr[row_offset] & (uchar) null_bit));
}
}
bool Field::send_binary(Protocol *protocol)
{
char buff[MAX_FIELD_WIDTH];
String tmp(buff,sizeof(buff),charset());
val_str(&tmp);
return protocol->store(tmp.ptr(), tmp.length(), tmp.charset());
}
/**
Check to see if field size is compatible with destination.
This method is used in row-based replication to verify that the slave's
field size is less than or equal to the master's field size. The
encoded field metadata (from the master or source) is decoded and compared
to the size of this field (the slave or destination).
@param field_metadata Encoded size in field metadata
@param mflags Flags from the table map event for the table.
@retval 0 if this field's size is < the source field's size
@retval 1 if this field's size is >= the source field's size
*/
int Field::compatible_field_size(uint field_metadata,
const Relay_log_info *rli_arg __attribute__((unused)),
uint16 mflags __attribute__((unused)))
{
uint const source_size= pack_length_from_metadata(field_metadata);
uint const destination_size= row_pack_length();
return (source_size <= destination_size);
}
int Field::store(const char *to, uint length, CHARSET_INFO *cs,
enum_check_fields check_level)
{
int res;
enum_check_fields old_check_level= table->in_use->count_cuted_fields;
table->in_use->count_cuted_fields= check_level;
res= store(to, length, cs);
table->in_use->count_cuted_fields= old_check_level;
return res;
}
/**
Pack the field into a format suitable for storage and transfer.
To implement packing functionality, only the virtual function
should be overridden. The other functions are just convenience
functions and hence should not be overridden.
The value of <code>low_byte_first</code> is dependent on how the
packed data is going to be used: for local use, e.g., temporary
store on disk or in memory, use the native format since that is
faster. For data that is going to be transfered to other machines
(e.g., when writing data to the binary log), data should always be
stored in little-endian format.
@note The default method for packing fields just copy the raw bytes
of the record into the destination, but never more than
<code>max_length</code> characters.
@param to
Pointer to memory area where representation of field should be put.
@param from
Pointer to memory area where record representation of field is
stored.
@param max_length
Maximum length of the field, as given in the column definition. For
example, for <code>CHAR(1000)</code>, the <code>max_length</code>
is 1000. This information is sometimes needed to decide how to pack
the data.
@param low_byte_first
@c TRUE if integers should be stored little-endian, @c FALSE if
native format should be used. Note that for little-endian machines,
the value of this flag is a moot point since the native format is
little-endian.
*/
uchar *
Field::pack(uchar *to, const uchar *from, uint max_length,
bool low_byte_first __attribute__((unused)))
{
uint32 length= pack_length();
set_if_smaller(length, max_length);
memcpy(to, from, length);
return to+length;
}
/**
Unpack a field from row data.
This method is used to unpack a field from a master whose size of
the field is less than that of the slave.
The <code>param_data</code> parameter is a two-byte integer (stored
in the least significant 16 bits of the unsigned integer) usually
consisting of two parts: the real type in the most significant byte
and a original pack length in the least significant byte.
The exact layout of the <code>param_data</code> field is given by
the <code>Table_map_log_event::save_field_metadata()</code>.
This is the default method for unpacking a field. It just copies
the memory block in byte order (of original pack length bytes or
length of field, whichever is smaller).
@param to Destination of the data
@param from Source of the data
@param param_data Real type and original pack length of the field
data
@param low_byte_first
If this flag is @c true, all composite entities (e.g., lengths)
should be unpacked in little-endian format; otherwise, the entities
are unpacked in native order.
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field::unpack(uchar* to, const uchar *from, uint param_data,
bool low_byte_first __attribute__((unused)))
{
uint length=pack_length();
int from_type= 0;
/*
If from length is > 255, it has encoded data in the upper bits. Need
to mask it out.
*/
if (param_data > 255)
{
from_type= (param_data & 0xff00) >> 8U; // real_type.
param_data= param_data & 0x00ff; // length.
}
if ((param_data == 0) ||
(length == param_data) ||
(from_type != real_type()))
{
memcpy(to, from, length);
return from+length;
}
uint len= (param_data && (param_data < length)) ?
param_data : length;
memcpy(to, from, param_data > length ? length : len);
return from+len;
}
my_decimal *Field::val_decimal(my_decimal *decimal)
{
/* This never have to be called */
DBUG_ASSERT(0);
return 0;
}
void Field_num::add_zerofill_and_unsigned(String &res) const
{
if (unsigned_flag)
res.append(STRING_WITH_LEN(" unsigned"));
if (zerofill)
res.append(STRING_WITH_LEN(" zerofill"));
}
void Field::make_field(Send_field *field)
{
if (orig_table && orig_table->s->db.str && *orig_table->s->db.str)
{
field->db_name= orig_table->s->db.str;
field->org_table_name= orig_table->s->table_name.str;
}
else
field->org_table_name= field->db_name= "";
if (orig_table && orig_table->alias)
{
field->table_name= orig_table->alias;
field->org_col_name= field_name;
}
else
{
field->table_name= "";
field->org_col_name= "";
}
field->col_name= field_name;
field->charsetnr= charset()->number;
field->length=field_length;
field->type=type();
field->flags=table->maybe_null ? (flags & ~NOT_NULL_FLAG) : flags;
field->decimals= 0;
}
/**
Conversion from decimal to longlong with checking overflow and
setting correct value (min/max) in case of overflow.
@param val value which have to be converted
@param unsigned_flag type of integer in which we convert val
@param err variable to pass error code
@return
value converted from val
*/
longlong Field::convert_decimal2longlong(const my_decimal *val,
bool unsigned_flag, int *err)
{
longlong i;
if (unsigned_flag)
{
if (val->sign())
{
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
i= 0;
*err= 1;
}
else if (warn_if_overflow(my_decimal2int(E_DEC_ERROR &
~E_DEC_OVERFLOW & ~E_DEC_TRUNCATED,
val, TRUE, &i)))
{
i= ~(longlong) 0;
*err= 1;
}
}
else if (warn_if_overflow(my_decimal2int(E_DEC_ERROR &
~E_DEC_OVERFLOW & ~E_DEC_TRUNCATED,
val, FALSE, &i)))
{
i= (val->sign() ? LONGLONG_MIN : LONGLONG_MAX);
*err= 1;
}
return i;
}
/**
Storing decimal in integer fields.
@param val value for storing
@note
This method is used by all integer fields, real/decimal redefine it
@retval
0 OK
@retval
!=0 error
*/
int Field_num::store_decimal(const my_decimal *val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int err= 0;
longlong i= convert_decimal2longlong(val, unsigned_flag, &err);
return test(err | store(i, unsigned_flag));
}
/**
Return decimal value of integer field.
@param decimal_value buffer for storing decimal value
@note
This method is used by all integer fields, real/decimal redefine it.
All longlong values fit in our decimal buffer which cal store 8*9=72
digits of integer number
@return
pointer to decimal buffer with value of field
*/
my_decimal* Field_num::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ASSERT(result_type() == INT_RESULT);
longlong nr= val_int();
int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
return decimal_value;
}
Field_str::Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
uchar null_bit_arg, utype unireg_check_arg,
const char *field_name_arg, CHARSET_INFO *charset_arg)
:Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg)
{
field_charset= charset_arg;
if (charset_arg->state & MY_CS_BINSORT)
flags|=BINARY_FLAG;
field_derivation= DERIVATION_IMPLICIT;
}
void Field_num::make_field(Send_field *field)
{
Field::make_field(field);
field->decimals= dec;
}
/**
Decimal representation of Field_str.
@param d value for storing
@note
Field_str is the base class for fields like Field_enum,
Field_date and some similar. Some dates use fraction and also
string value should be converted to floating point value according
our rules, so we use double to store value of decimal in string.
@todo
use decimal2string?
@retval
0 OK
@retval
!=0 error
*/
int Field_str::store_decimal(const my_decimal *d)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
double val;
/* TODO: use decimal2string? */
int err= warn_if_overflow(my_decimal2double(E_DEC_FATAL_ERROR &
~E_DEC_OVERFLOW, d, &val));
return err | store(val);
}
my_decimal *Field_str::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
longlong nr= val_int();
int2my_decimal(E_DEC_FATAL_ERROR, nr, 0, decimal_value);
return decimal_value;
}
uint Field::fill_cache_field(CACHE_FIELD *copy)
{
uint store_length;
copy->str=ptr;
copy->length=pack_length();
copy->field= this;
if (flags & BLOB_FLAG)
{
copy->type= CACHE_BLOB;
copy->length-= table->s->blob_ptr_size;
return copy->length;
}
else if (!zero_pack() &&
(type() == MYSQL_TYPE_STRING && copy->length >= 4 &&
copy->length < 256))
{
copy->type= CACHE_STRIPPED;
store_length= 2;
}
else
{
copy->type= 0;
store_length= 0;
}
return copy->length + store_length;
}
bool Field::get_date(MYSQL_TIME *ltime,uint fuzzydate)
{
char buff[40];
String tmp(buff,sizeof(buff),&my_charset_bin),*res;
if (!(res=val_str(&tmp)) ||
str_to_datetime_with_warn(res->ptr(), res->length(),
ltime, fuzzydate) <= MYSQL_TIMESTAMP_ERROR)
return 1;
return 0;
}
bool Field::get_time(MYSQL_TIME *ltime)
{
char buff[40];
String tmp(buff,sizeof(buff),&my_charset_bin),*res;
if (!(res=val_str(&tmp)) ||
str_to_time_with_warn(res->ptr(), res->length(), ltime))
return 1;
return 0;
}
/**
This is called when storing a date in a string.
@note
Needs to be changed if/when we want to support different time formats.
*/
int Field::store_time(MYSQL_TIME *ltime, timestamp_type type_arg)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char buff[MAX_DATE_STRING_REP_LENGTH];
uint length= (uint) my_TIME_to_str(ltime, buff);
return store(buff, length, &my_charset_bin);
}
bool Field::optimize_range(uint idx, uint part)
{
return test(table->file->index_flags(idx, part, 1) & HA_READ_RANGE);
}
Field *Field::new_field(MEM_ROOT *root, struct st_table *new_table,
bool keep_type __attribute__((unused)))
{
Field *tmp;
if (!(tmp= (Field*) memdup_root(root,(char*) this,size_of())))
return 0;
if (tmp->table->maybe_null)
tmp->flags&= ~NOT_NULL_FLAG;
tmp->table= new_table;
tmp->key_start.init(0);
tmp->part_of_key.init(0);
tmp->part_of_sortkey.init(0);
tmp->unireg_check= Field::NONE;
tmp->flags&= (NOT_NULL_FLAG | BLOB_FLAG | UNSIGNED_FLAG |
ZEROFILL_FLAG | BINARY_FLAG | ENUM_FLAG | SET_FLAG);
tmp->reset_fields();
return tmp;
}
Field *Field::new_key_field(MEM_ROOT *root, struct st_table *new_table,
uchar *new_ptr, uchar *new_null_ptr,
uint new_null_bit)
{
Field *tmp;
if ((tmp= new_field(root, new_table, table == new_table)))
{
tmp->ptr= new_ptr;
tmp->null_ptr= new_null_ptr;
tmp->null_bit= new_null_bit;
}
return tmp;
}
/* This is used to generate a field in TABLE from TABLE_SHARE */
Field *Field::clone(MEM_ROOT *root, struct st_table *new_table)
{
Field *tmp;
if ((tmp= (Field*) memdup_root(root,(char*) this,size_of())))
{
tmp->init(new_table);
tmp->move_field_offset((my_ptrdiff_t) (new_table->record[0] -
new_table->s->default_values));
}
return tmp;
}
/****************************************************************************
Field_null, a field that always return NULL
****************************************************************************/
void Field_null::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("null"));
}
/****************************************************************************
Functions for the Field_decimal class
This is an number stored as a pre-space (or pre-zero) string
****************************************************************************/
int
Field_decimal::reset(void)
{
Field_decimal::store(STRING_WITH_LEN("0"),&my_charset_bin);
return 0;
}
void Field_decimal::overflow(bool negative)
{
uint len=field_length;
uchar *to=ptr, filler= '9';
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
if (negative)
{
if (!unsigned_flag)
{
/* Put - sign as a first digit so we'll have -999..999 or 999..999 */
*to++ = '-';
len--;
}
else
{
filler= '0'; // Fill up with 0
if (!zerofill)
{
/*
Handle unsigned integer without zerofill, in which case
the number should be of format ' 0' or ' 0.000'
*/
uint whole_part=field_length- (dec ? dec+2 : 1);
// Fill with spaces up to the first digit
bfill(to, whole_part, ' ');
to+= whole_part;
len-= whole_part;
// The main code will also handle the 0 before the decimal point
}
}
}
bfill(to, len, filler);
if (dec)
ptr[field_length-dec-1]='.';
return;
}
int Field_decimal::store(const char *from_arg, uint len, CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char buff[STRING_BUFFER_USUAL_SIZE];
String tmp(buff,sizeof(buff), &my_charset_bin);
const uchar *from= (uchar*) from_arg;
/* Convert character set if the old one is multi uchar */
if (cs->mbmaxlen > 1)
{
uint dummy_errors;
tmp.copy((char*) from, len, cs, &my_charset_bin, &dummy_errors);
from= (uchar*) tmp.ptr();
len= tmp.length();
}
const uchar *end= from+len;
/* The pointer where the field value starts (i.e., "where to write") */
uchar *to= ptr;
uint tmp_dec, tmp_uint;
/*
The sign of the number : will be 0 (means positive but sign not
specified), '+' or '-'
*/
uchar sign_char=0;
/* The pointers where prezeros start and stop */
const uchar *pre_zeros_from, *pre_zeros_end;
/* The pointers where digits at the left of '.' start and stop */
const uchar *int_digits_from, *int_digits_end;
/* The pointers where digits at the right of '.' start and stop */
const uchar *frac_digits_from, *frac_digits_end;
/* The sign of the exponent : will be 0 (means no exponent), '+' or '-' */
char expo_sign_char=0;
uint exponent=0; // value of the exponent
/*
Pointers used when digits move from the left of the '.' to the
right of the '.' (explained below)
*/
const uchar *UNINIT_VAR(int_digits_tail_from);
/* Number of 0 that need to be added at the left of the '.' (1E3: 3 zeros) */
uint UNINIT_VAR(int_digits_added_zeros);
/*
Pointer used when digits move from the right of the '.' to the left
of the '.'
*/
const uchar *UNINIT_VAR(frac_digits_head_end);
/* Number of 0 that need to be added at the right of the '.' (for 1E-3) */
uint UNINIT_VAR(frac_digits_added_zeros);
uchar *pos,*tmp_left_pos,*tmp_right_pos;
/* Pointers that are used as limits (begin and end of the field buffer) */
uchar *left_wall,*right_wall;
uchar tmp_char;
/*
To remember if table->in_use->cuted_fields has already been incremented,
to do that only once
*/
bool is_cuted_fields_incr=0;
/*
There are three steps in this function :
- parse the input string
- modify the position of digits around the decimal dot '.'
according to the exponent value (if specified)
- write the formatted number
*/
if ((tmp_dec=dec))
tmp_dec++;
/* skip pre-space */
while (from != end && my_isspace(&my_charset_bin,*from))
from++;
if (from == end)
{
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
is_cuted_fields_incr=1;
}
else if (*from == '+' || *from == '-') // Found some sign ?
{
sign_char= *from++;
/*
We allow "+" for unsigned decimal unless defined different
Both options allowed as one may wish not to have "+" for unsigned numbers
because of data processing issues
*/
if (unsigned_flag)
{
if (sign_char=='-')
{
Field_decimal::overflow(1);
return 1;
}
/*
Defining this will not store "+" for unsigned decimal type even if
it is passed in numeric string. This will make some tests to fail
*/
#ifdef DONT_ALLOW_UNSIGNED_PLUS
else
sign_char=0;
#endif
}
}
pre_zeros_from= from;
for (; from!=end && *from == '0'; from++) ; // Read prezeros
pre_zeros_end=int_digits_from=from;
/* Read non zero digits at the left of '.'*/
for (; from != end && my_isdigit(&my_charset_bin, *from) ; from++) ;
int_digits_end=from;
if (from!=end && *from == '.') // Some '.' ?
from++;
frac_digits_from= from;
/* Read digits at the right of '.' */
for (;from!=end && my_isdigit(&my_charset_bin, *from); from++) ;
frac_digits_end=from;
// Some exponentiation symbol ?
if (from != end && (*from == 'e' || *from == 'E'))
{
from++;
if (from != end && (*from == '+' || *from == '-')) // Some exponent sign ?
expo_sign_char= *from++;
else
expo_sign_char= '+';
/*
Read digits of the exponent and compute its value. We must care about
'exponent' overflow, because as unsigned arithmetic is "modulo", big
exponents will become small (e.g. 1e4294967296 will become 1e0, and the
field will finally contain 1 instead of its max possible value).
*/
for (;from!=end && my_isdigit(&my_charset_bin, *from); from++)
{
exponent=10*exponent+(*from-'0');
if (exponent>MAX_EXPONENT)
break;
}
}
/*
We only have to generate warnings if count_cuted_fields is set.
This is to avoid extra checks of the number when they are not needed.
Even if this flag is not set, it's OK to increment warnings, if
it makes the code easer to read.
*/
if (table->in_use->count_cuted_fields)
{
// Skip end spaces
for (;from != end && my_isspace(&my_charset_bin, *from); from++) ;
if (from != end) // If still something left, warn
{
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
is_cuted_fields_incr=1;
}
}
/*
Now "move" digits around the decimal dot according to the exponent value,
and add necessary zeros.
Examples :
- 1E+3 : needs 3 more zeros at the left of '.' (int_digits_added_zeros=3)
- 1E-3 : '1' moves at the right of '.', and 2 more zeros are needed
between '.' and '1'
- 1234.5E-3 : '234' moves at the right of '.'
These moves are implemented with pointers which point at the begin
and end of each moved segment. Examples :
- 1234.5E-3 : before the code below is executed, the int_digits part is
from '1' to '4' and the frac_digits part from '5' to '5'. After the code
below, the int_digits part is from '1' to '1', the frac_digits_head
part is from '2' to '4', and the frac_digits part from '5' to '5'.
- 1234.5E3 : before the code below is executed, the int_digits part is
from '1' to '4' and the frac_digits part from '5' to '5'. After the code
below, the int_digits part is from '1' to '4', the int_digits_tail
part is from '5' to '5', the frac_digits part is empty, and
int_digits_added_zeros=2 (to make 1234500).
*/
/*
Below tmp_uint cannot overflow with small enough MAX_EXPONENT setting,
as int_digits_added_zeros<=exponent<4G and
(int_digits_end-int_digits_from)<=max_allowed_packet<=2G and
(frac_digits_from-int_digits_tail_from)<=max_allowed_packet<=2G
*/
if (!expo_sign_char)
tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);
else if (expo_sign_char == '-')
{
tmp_uint=min(exponent,(uint)(int_digits_end-int_digits_from));
frac_digits_added_zeros=exponent-tmp_uint;
int_digits_end -= tmp_uint;
frac_digits_head_end=int_digits_end+tmp_uint;
tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);
}
else // (expo_sign_char=='+')
{
tmp_uint=min(exponent,(uint)(frac_digits_end-frac_digits_from));
int_digits_added_zeros=exponent-tmp_uint;
int_digits_tail_from=frac_digits_from;
frac_digits_from=frac_digits_from+tmp_uint;
/*
We "eat" the heading zeros of the
int_digits.int_digits_tail.int_digits_added_zeros concatenation
(for example 0.003e3 must become 3 and not 0003)
*/
if (int_digits_from == int_digits_end)
{
/*
There was nothing in the int_digits part, so continue
eating int_digits_tail zeros
*/
for (; int_digits_tail_from != frac_digits_from &&
*int_digits_tail_from == '0'; int_digits_tail_from++) ;
if (int_digits_tail_from == frac_digits_from)
{
// there were only zeros in int_digits_tail too
int_digits_added_zeros=0;
}
}
tmp_uint= (uint) (tmp_dec+(int_digits_end-int_digits_from)+
(uint)(frac_digits_from-int_digits_tail_from)+
int_digits_added_zeros);
}
/*
Now write the formated number
First the digits of the int_% parts.
Do we have enough room to write these digits ?
If the sign is defined and '-', we need one position for it
*/
if (field_length < tmp_uint + (int) (sign_char == '-'))
{
// too big number, change to max or min number
Field_decimal::overflow(sign_char == '-');
return 1;
}
/*
Tmp_left_pos is the position where the leftmost digit of
the int_% parts will be written
*/
tmp_left_pos=pos=to+(uint)(field_length-tmp_uint);
// Write all digits of the int_% parts
while (int_digits_from != int_digits_end)
*pos++ = *int_digits_from++ ;
if (expo_sign_char == '+')
{
while (int_digits_tail_from != frac_digits_from)
*pos++= *int_digits_tail_from++;
while (int_digits_added_zeros-- >0)
*pos++= '0';
}
/*
Note the position where the rightmost digit of the int_% parts has been
written (this is to later check if the int_% parts contained nothing,
meaning an extra 0 is needed).
*/
tmp_right_pos=pos;
/*
Step back to the position of the leftmost digit of the int_% parts,
to write sign and fill with zeros or blanks or prezeros.
*/
pos=tmp_left_pos-1;
if (zerofill)
{
left_wall=to-1;
while (pos > left_wall) // Fill with zeros
*pos--='0';
}
else
{
left_wall=to+(sign_char != 0)-1;
if (!expo_sign_char) // If exponent was specified, ignore prezeros
{
for (;pos > left_wall && pre_zeros_from !=pre_zeros_end;
pre_zeros_from++)
*pos--= '0';
}
if (pos == tmp_right_pos-1)
*pos--= '0'; // no 0 has ever been written, so write one
left_wall= to-1;
if (sign_char && pos != left_wall)
{
/* Write sign if possible (it is if sign is '-') */
*pos--= sign_char;
}
while (pos != left_wall)
*pos--=' '; //fill with blanks
}
/*
Write digits of the frac_% parts ;
Depending on table->in_use->count_cutted_fields, we may also want
to know if some non-zero tail of these parts will
be truncated (for example, 0.002->0.00 will generate a warning,
while 0.000->0.00 will not)
(and 0E1000000000 will not, while 1E-1000000000 will)
*/
pos=to+(uint)(field_length-tmp_dec); // Calculate post to '.'
right_wall=to+field_length;
if (pos != right_wall)
*pos++='.';
if (expo_sign_char == '-')
{
while (frac_digits_added_zeros-- > 0)
{
if (pos == right_wall)
{
if (table->in_use->count_cuted_fields && !is_cuted_fields_incr)
break; // Go on below to see if we lose non zero digits
return 0;
}
*pos++='0';
}
while (int_digits_end != frac_digits_head_end)
{
tmp_char= *int_digits_end++;
if (pos == right_wall)
{
if (tmp_char != '0') // Losing a non zero digit ?
{
if (!is_cuted_fields_incr)
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
WARN_DATA_TRUNCATED, 1);
return 0;
}
continue;
}
*pos++= tmp_char;
}
}
for (;frac_digits_from!=frac_digits_end;)
{
tmp_char= *frac_digits_from++;
if (pos == right_wall)
{
if (tmp_char != '0') // Losing a non zero digit ?
{
if (!is_cuted_fields_incr)
{
/*
This is a note, not a warning, as we don't want to abort
when we cut decimals in strict mode
*/
set_warning(MYSQL_ERROR::WARN_LEVEL_NOTE, WARN_DATA_TRUNCATED, 1);
}
return 0;
}
continue;
}
*pos++= tmp_char;
}
while (pos != right_wall)
*pos++='0'; // Fill with zeros at right of '.'
return 0;
}
int Field_decimal::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
if (unsigned_flag && nr < 0)
{
overflow(1);
return 1;
}
if (!isfinite(nr)) // Handle infinity as special case
{
overflow(nr < 0.0);
return 1;
}
reg4 uint i;
size_t length;
uchar fyllchar,*to;
char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
fyllchar = zerofill ? (char) '0' : (char) ' ';
#ifdef HAVE_SNPRINTF
buff[sizeof(buff)-1]=0; // Safety
snprintf(buff,sizeof(buff)-1, "%.*f",(int) dec,nr);
length= strlen(buff);
#else
length= sprintf(buff, "%.*f", dec, nr);
#endif
if (length > field_length)
{
overflow(nr < 0.0);
return 1;
}
else
{
to=ptr;
for (i=field_length-length ; i-- > 0 ;)
*to++ = fyllchar;
memcpy(to,buff,length);
return 0;
}
}
int Field_decimal::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char buff[22];
uint length, int_part;
char fyllchar;
uchar *to;
if (nr < 0 && unsigned_flag && !unsigned_val)
{
overflow(1);
return 1;
}
length= (uint) (longlong10_to_str(nr,buff,unsigned_val ? 10 : -10) - buff);
int_part= field_length- (dec ? dec+1 : 0);
if (length > int_part)
{
overflow(!unsigned_val && nr < 0L); /* purecov: inspected */
return 1;
}
fyllchar = zerofill ? (char) '0' : (char) ' ';
to= ptr;
for (uint i=int_part-length ; i-- > 0 ;)
*to++ = fyllchar;
memcpy(to,buff,length);
if (dec)
{
to[length]='.';
bfill(to+length+1,dec,'0');
}
return 0;
}
double Field_decimal::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
char *end_not_used;
return my_strntod(&my_charset_bin, (char*) ptr, field_length, &end_not_used,
¬_used);
}
longlong Field_decimal::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
if (unsigned_flag)
return my_strntoull(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
¬_used);
return my_strntoll(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
¬_used);
}
String *Field_decimal::val_str(String *val_buffer __attribute__((unused)),
String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
uchar *str;
size_t tmp_length;
for (str=ptr ; *str == ' ' ; str++) ;
val_ptr->set_charset(&my_charset_bin);
tmp_length= (size_t) (str-ptr);
if (field_length < tmp_length) // Error in data
val_ptr->length(0);
else
val_ptr->set_ascii((const char*) str, field_length-tmp_length);
return val_ptr;
}
/**
Should be able to handle at least the following fixed decimal formats:
5.00 , -1.0, 05, -05, +5 with optional pre/end space
*/
int Field_decimal::cmp(const uchar *a_ptr,const uchar *b_ptr)
{
const uchar *end;
int swap=0;
/* First remove prefixes '0', ' ', and '-' */
for (end=a_ptr+field_length;
a_ptr != end &&
(*a_ptr == *b_ptr ||
((my_isspace(&my_charset_bin,*a_ptr) || *a_ptr == '+' ||
*a_ptr == '0') &&
(my_isspace(&my_charset_bin,*b_ptr) || *b_ptr == '+' ||
*b_ptr == '0')));
a_ptr++,b_ptr++)
{
if (*a_ptr == '-') // If both numbers are negative
swap= -1 ^ 1; // Swap result
}
if (a_ptr == end)
return 0;
if (*a_ptr == '-')
return -1;
if (*b_ptr == '-')
return 1;
while (a_ptr != end)
{
if (*a_ptr++ != *b_ptr++)
return swap ^ (a_ptr[-1] < b_ptr[-1] ? -1 : 1); // compare digits
}
return 0;
}
void Field_decimal::sort_string(uchar *to,uint length)
{
uchar *str,*end;
for (str=ptr,end=ptr+length;
str != end &&
((my_isspace(&my_charset_bin,*str) || *str == '+' ||
*str == '0')) ;
str++)
*to++=' ';
if (str == end)
return; /* purecov: inspected */
if (*str == '-')
{
*to++=1; // Smaller than any number
str++;
while (str != end)
if (my_isdigit(&my_charset_bin,*str))
*to++= (char) ('9' - *str++);
else
*to++= *str++;
}
else memcpy(to,str,(uint) (end-str));
}
void Field_decimal::sql_type(String &res) const
{
CHARSET_INFO *cs=res.charset();
uint tmp=field_length;
if (!unsigned_flag)
tmp--;
if (dec)
tmp--;
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"decimal(%d,%d)",tmp,dec));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
** Field_new_decimal
****************************************************************************/
Field_new_decimal::Field_new_decimal(uchar *ptr_arg,
uint32 len_arg, uchar *null_ptr_arg,
uchar null_bit_arg,
enum utype unireg_check_arg,
const char *field_name_arg,
uint8 dec_arg,bool zero_arg,
bool unsigned_arg)
:Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg, dec_arg, zero_arg, unsigned_arg)
{
precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
set_if_smaller(precision, DECIMAL_MAX_PRECISION);
DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
(dec <= DECIMAL_MAX_SCALE));
bin_size= my_decimal_get_binary_size(precision, dec);
}
Field_new_decimal::Field_new_decimal(uint32 len_arg,
bool maybe_null_arg,
const char *name,
uint8 dec_arg,
bool unsigned_arg)
:Field_num((uchar*) 0, len_arg,
maybe_null_arg ? (uchar*) "": 0, 0,
NONE, name, dec_arg, 0, unsigned_arg)
{
precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
set_if_smaller(precision, DECIMAL_MAX_PRECISION);
DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
(dec <= DECIMAL_MAX_SCALE));
bin_size= my_decimal_get_binary_size(precision, dec);
}
Field *Field_new_decimal::create_from_item (Item *item)
{
uint8 dec= item->decimals;
uint8 intg= item->decimal_precision() - dec;
uint32 len= item->max_length;
DBUG_ASSERT (item->result_type() == DECIMAL_RESULT);
/*
Trying to put too many digits overall in a DECIMAL(prec,dec)
will always throw a warning. We must limit dec to
DECIMAL_MAX_SCALE however to prevent an assert() later.
*/
if (dec > 0)
{
signed int overflow;
dec= min(dec, DECIMAL_MAX_SCALE);
/*
If the value still overflows the field with the corrected dec,
we'll throw out decimals rather than integers. This is still
bad and of course throws a truncation warning.
+1: for decimal point
*/
const int required_length=
my_decimal_precision_to_length(intg + dec, dec,
item->unsigned_flag);
overflow= required_length - len;
if (overflow > 0)
dec= max(0, dec - overflow); // too long, discard fract
else
/* Corrected value fits. */
len= required_length;
}
return new Field_new_decimal(len, item->maybe_null, item->name,
dec, item->unsigned_flag);
}
int Field_new_decimal::reset(void)
{
store_value(&decimal_zero);
return 0;
}
/**
Generate max/min decimal value in case of overflow.
@param decimal_value buffer for value
@param sign sign of value which caused overflow
*/
void Field_new_decimal::set_value_on_overflow(my_decimal *decimal_value,
bool sign)
{
DBUG_ENTER("Field_new_decimal::set_value_on_overflow");
max_my_decimal(decimal_value, precision, decimals());
if (sign)
{
if (unsigned_flag)
my_decimal_set_zero(decimal_value);
else
decimal_value->sign(TRUE);
}
DBUG_VOID_RETURN;
}
/**
Store decimal value in the binary buffer.
Checks if decimal_value fits into field size.
If it does, stores the decimal in the buffer using binary format.
Otherwise sets maximal number that can be stored in the field.
@param decimal_value my_decimal
@retval
0 ok
@retval
1 error
*/
bool Field_new_decimal::store_value(const my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
DBUG_ENTER("Field_new_decimal::store_value");
#ifndef DBUG_OFF
{
char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
DBUG_PRINT("enter", ("value: %s", dbug_decimal_as_string(dbug_buff, decimal_value)));
}
#endif
/* check that we do not try to write negative value in unsigned field */
if (unsigned_flag && decimal_value->sign())
{
DBUG_PRINT("info", ("unsigned overflow"));
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
decimal_value= &decimal_zero;
}
#ifndef DBUG_OFF
{
char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
DBUG_PRINT("info", ("saving with precision %d scale: %d value %s",
(int)precision, (int)dec,
dbug_decimal_as_string(dbug_buff, decimal_value)));
}
#endif
if (warn_if_overflow(my_decimal2binary(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
decimal_value, ptr, precision, dec)))
{
my_decimal buff;
DBUG_PRINT("info", ("overflow"));
set_value_on_overflow(&buff, decimal_value->sign());
my_decimal2binary(E_DEC_FATAL_ERROR, &buff, ptr, precision, dec);
error= 1;
}
DBUG_EXECUTE("info", print_decimal_buff(decimal_value, (uchar *) ptr,
bin_size););
DBUG_RETURN(error);
}
int Field_new_decimal::store(const char *from, uint length,
CHARSET_INFO *charset_arg)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int err;
my_decimal decimal_value;
DBUG_ENTER("Field_new_decimal::store(char*)");
if ((err= str2my_decimal(E_DEC_FATAL_ERROR &
~(E_DEC_OVERFLOW | E_DEC_BAD_NUM),
from, length, charset_arg,
&decimal_value)) &&
table->in_use->abort_on_warning)
{
/* Because "from" is not NUL-terminated and we use %s in the ER() */
String from_as_str;
from_as_str.copy(from, length, &my_charset_bin);
push_warning_printf(table->in_use, MYSQL_ERROR::WARN_LEVEL_ERROR,
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
"decimal", from_as_str.c_ptr(), field_name,
(ulong) table->in_use->row_count);
DBUG_RETURN(err);
}
switch (err) {
case E_DEC_TRUNCATED:
set_warning(MYSQL_ERROR::WARN_LEVEL_NOTE, WARN_DATA_TRUNCATED, 1);
break;
case E_DEC_OVERFLOW:
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
set_value_on_overflow(&decimal_value, decimal_value.sign());
break;
case E_DEC_BAD_NUM:
{
/* Because "from" is not NUL-terminated and we use %s in the ER() */
String from_as_str;
from_as_str.copy(from, length, &my_charset_bin);
push_warning_printf(table->in_use, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
"decimal", from_as_str.c_ptr(), field_name,
(ulong) table->in_use->row_count);
my_decimal_set_zero(&decimal_value);
break;
}
}
#ifndef DBUG_OFF
char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
DBUG_PRINT("enter", ("value: %s",
dbug_decimal_as_string(dbug_buff, &decimal_value)));
#endif
store_value(&decimal_value);
DBUG_RETURN(err);
}
/**
@todo
Fix following when double2my_decimal when double2decimal
will return E_DEC_TRUNCATED always correctly
*/
int Field_new_decimal::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
my_decimal decimal_value;
int err;
DBUG_ENTER("Field_new_decimal::store(double)");
err= double2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, nr,
&decimal_value);
/*
TODO: fix following when double2my_decimal when double2decimal
will return E_DEC_TRUNCATED always correctly
*/
if (!err)
{
double nr2;
my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &nr2);
if (nr2 != nr)
err= E_DEC_TRUNCATED;
}
if (err)
{
if (check_overflow(err))
set_value_on_overflow(&decimal_value, decimal_value.sign());
/* Only issue a warning if store_value doesn't issue an warning */
table->in_use->got_warning= 0;
}
if (store_value(&decimal_value))
err= 1;
else if (err && !table->in_use->got_warning)
err= warn_if_overflow(err);
DBUG_RETURN(err);
}
int Field_new_decimal::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
my_decimal decimal_value;
int err;
if ((err= int2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
nr, unsigned_val, &decimal_value)))
{
if (check_overflow(err))
set_value_on_overflow(&decimal_value, decimal_value.sign());
/* Only issue a warning if store_value doesn't issue an warning */
table->in_use->got_warning= 0;
}
if (store_value(&decimal_value))
err= 1;
else if (err && !table->in_use->got_warning)
err= warn_if_overflow(err);
return err;
}
int Field_new_decimal::store_decimal(const my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
return store_value(decimal_value);
}
int Field_new_decimal::store_time(MYSQL_TIME *ltime, timestamp_type t_type)
{
my_decimal decimal_value;
return store_value(date2my_decimal(ltime, &decimal_value));
}
double Field_new_decimal::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
double dbl;
my_decimal decimal_value;
my_decimal2double(E_DEC_FATAL_ERROR, val_decimal(&decimal_value), &dbl);
return dbl;
}
longlong Field_new_decimal::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
longlong i;
my_decimal decimal_value;
my_decimal2int(E_DEC_FATAL_ERROR, val_decimal(&decimal_value),
unsigned_flag, &i);
return i;
}
my_decimal* Field_new_decimal::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ENTER("Field_new_decimal::val_decimal");
binary2my_decimal(E_DEC_FATAL_ERROR, ptr, decimal_value,
precision, dec);
DBUG_EXECUTE("info", print_decimal_buff(decimal_value, (uchar *) ptr,
bin_size););
DBUG_RETURN(decimal_value);
}
String *Field_new_decimal::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
my_decimal decimal_value;
uint fixed_precision= zerofill ? precision : 0;
my_decimal2string(E_DEC_FATAL_ERROR, val_decimal(&decimal_value),
fixed_precision, dec, '0', val_buffer);
return val_buffer;
}
int Field_new_decimal::cmp(const uchar *a,const uchar*b)
{
return memcmp(a, b, bin_size);
}
void Field_new_decimal::sort_string(uchar *buff,
uint length __attribute__((unused)))
{
memcpy(buff, ptr, bin_size);
}
void Field_new_decimal::sql_type(String &str) const
{
CHARSET_INFO *cs= str.charset();
str.length(cs->cset->snprintf(cs, (char*) str.ptr(), str.alloced_length(),
"decimal(%d,%d)", precision, (int)dec));
add_zerofill_and_unsigned(str);
}
/**
Save the field metadata for new decimal fields.
Saves the precision in the first byte and decimals() in the second
byte of the field metadata array at index of *metadata_ptr and
*(metadata_ptr + 1).
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_new_decimal::do_save_field_metadata(uchar *metadata_ptr)
{
*metadata_ptr= precision;
*(metadata_ptr + 1)= decimals();
return 2;
}
/**
Returns the number of bytes field uses in row-based replication
row packed size.
This method is used in row-based replication to determine the number
of bytes that the field consumes in the row record format. This is
used to skip fields in the master that do not exist on the slave.
@param field_metadata Encoded size in field metadata
@returns The size of the field based on the field metadata.
*/
uint Field_new_decimal::pack_length_from_metadata(uint field_metadata)
{
uint const source_precision= (field_metadata >> 8U) & 0x00ff;
uint const source_decimal= field_metadata & 0x00ff;
uint const source_size= my_decimal_get_binary_size(source_precision,
source_decimal);
return (source_size);
}
/**
Check to see if field size is compatible with destination.
This method is used in row-based replication to verify that the slave's
field size is less than or equal to the master's field size. The
encoded field metadata (from the master or source) is decoded and compared
to the size of this field (the slave or destination).
@param field_metadata Encoded size in field metadata
@retval 0 if this field's size is < the source field's size
@retval 1 if this field's size is >= the source field's size
*/
int Field_new_decimal::compatible_field_size(uint field_metadata,
const Relay_log_info * __attribute__((unused)),
uint16 mflags __attribute__((unused)))
{
int compatible= 0;
uint const source_precision= (field_metadata >> 8U) & 0x00ff;
uint const source_decimal= field_metadata & 0x00ff;
uint const source_size= my_decimal_get_binary_size(source_precision,
source_decimal);
uint const destination_size= row_pack_length();
compatible= (source_size <= destination_size);
if (compatible)
compatible= (source_precision <= precision) &&
(source_decimal <= decimals());
return (compatible);
}
uint Field_new_decimal::is_equal(Create_field *new_field)
{
return ((new_field->sql_type == real_type()) &&
((new_field->flags & UNSIGNED_FLAG) ==
(uint) (flags & UNSIGNED_FLAG)) &&
((new_field->flags & AUTO_INCREMENT_FLAG) ==
(uint) (flags & AUTO_INCREMENT_FLAG)) &&
(new_field->length == max_display_length()) &&
(new_field->decimals == dec));
}
/**
Unpack a decimal field from row data.
This method is used to unpack a decimal or numeric field from a master
whose size of the field is less than that of the slave.
@param to Destination of the data
@param from Source of the data
@param param_data Precision (upper) and decimal (lower) values
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field_new_decimal::unpack(uchar* to,
const uchar *from,
uint param_data,
bool low_byte_first)
{
if (param_data == 0)
return Field::unpack(to, from, param_data, low_byte_first);
uint from_precision= (param_data & 0xff00) >> 8U;
uint from_decimal= param_data & 0x00ff;
uint length=pack_length();
uint from_pack_len= my_decimal_get_binary_size(from_precision, from_decimal);
uint len= (param_data && (from_pack_len < length)) ?
from_pack_len : length;
if ((from_pack_len && (from_pack_len < length)) ||
(from_precision < precision) ||
(from_decimal < decimals()))
{
/*
If the master's data is smaller than the slave, we need to convert
the binary to decimal then resize the decimal converting it back to
a decimal and write that to the raw data buffer.
*/
decimal_digit_t dec_buf[DECIMAL_MAX_PRECISION];
decimal_t dec_val;
dec_val.len= from_precision;
dec_val.buf= dec_buf;
/*
Note: bin2decimal does not change the length of the field. So it is
just the first step the resizing operation. The second step does the
resizing using the precision and decimals from the slave.
*/
bin2decimal((uchar *)from, &dec_val, from_precision, from_decimal);
decimal2bin(&dec_val, to, precision, decimals());
}
else
memcpy(to, from, len); // Sizes are the same, just copy the data.
return from+len;
}
/****************************************************************************
** tiny int
****************************************************************************/
int Field_tiny::store(const char *from,uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error;
longlong rnd;
error= get_int(cs, from, len, &rnd, 255, -128, 127);
ptr[0]= unsigned_flag ? (char) (ulonglong) rnd : (char) rnd;
return error;
}
int Field_tiny::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
nr=rint(nr);
if (unsigned_flag)
{
if (nr < 0.0)
{
*ptr=0;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (nr > 255.0)
{
*ptr=(char) 255;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
*ptr=(char) nr;
}
else
{
if (nr < -128.0)
{
*ptr= (char) -128;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (nr > 127.0)
{
*ptr=127;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
*ptr=(char) (int) nr;
}
return error;
}
int Field_tiny::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
if (unsigned_flag)
{
if (nr < 0 && !unsigned_val)
{
*ptr= 0;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if ((ulonglong) nr > (ulonglong) 255)
{
*ptr= (char) 255;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
*ptr=(char) nr;
}
else
{
if (nr < 0 && unsigned_val)
nr= 256; // Generate overflow
if (nr < -128)
{
*ptr= (char) -128;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (nr > 127)
{
*ptr=127;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
*ptr=(char) nr;
}
return error;
}
double Field_tiny::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int tmp= unsigned_flag ? (int) ptr[0] :
(int) ((signed char*) ptr)[0];
return (double) tmp;
}
longlong Field_tiny::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int tmp= unsigned_flag ? (int) ptr[0] :
(int) ((signed char*) ptr)[0];
return (longlong) tmp;
}
String *Field_tiny::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
CHARSET_INFO *cs= &my_charset_bin;
uint length;
uint mlength=max(field_length+1,5*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
if (unsigned_flag)
length= (uint) cs->cset->long10_to_str(cs,to,mlength, 10,
(long) *ptr);
else
length= (uint) cs->cset->long10_to_str(cs,to,mlength,-10,
(long) *((signed char*) ptr));
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer);
return val_buffer;
}
bool Field_tiny::send_binary(Protocol *protocol)
{
return protocol->store_tiny((longlong) (int8) ptr[0]);
}
int Field_tiny::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
signed char a,b;
a=(signed char) a_ptr[0]; b= (signed char) b_ptr[0];
if (unsigned_flag)
return ((uchar) a < (uchar) b) ? -1 : ((uchar) a > (uchar) b) ? 1 : 0;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_tiny::sort_string(uchar *to,uint length __attribute__((unused)))
{
if (unsigned_flag)
*to= *ptr;
else
to[0] = (char) (ptr[0] ^ (uchar) 128); /* Revers signbit */
}
void Field_tiny::sql_type(String &res) const
{
CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"tinyint(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
Field type short int (2 byte)
****************************************************************************/
int Field_short::store(const char *from,uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int store_tmp;
int error;
longlong rnd;
error= get_int(cs, from, len, &rnd, UINT_MAX16, INT_MIN16, INT_MAX16);
store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int2store(ptr, store_tmp);
}
else
#endif
shortstore(ptr, (short) store_tmp);
return error;
}
int Field_short::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
int16 res;
nr=rint(nr);
if (unsigned_flag)
{
if (nr < 0)
{
res=0;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (nr > (double) UINT_MAX16)
{
res=(int16) UINT_MAX16;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
res=(int16) (uint16) nr;
}
else
{
if (nr < (double) INT_MIN16)
{
res=INT_MIN16;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (nr > (double) INT_MAX16)
{
res=INT_MAX16;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
res=(int16) (int) nr;
}
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int2store(ptr,res);
}
else
#endif
shortstore(ptr,res);
return error;
}
int Field_short::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
int16 res;
if (unsigned_flag)
{
if (nr < 0L && !unsigned_val)
{
res=0;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if ((ulonglong) nr > (ulonglong) UINT_MAX16)
{
res=(int16) UINT_MAX16;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
res=(int16) (uint16) nr;
}
else
{
if (nr < 0 && unsigned_val)
nr= UINT_MAX16+1; // Generate overflow
if (nr < INT_MIN16)
{
res=INT_MIN16;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (nr > (longlong) INT_MAX16)
{
res=INT_MAX16;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
res=(int16) nr;
}
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int2store(ptr,res);
}
else
#endif
shortstore(ptr,res);
return error;
}
double Field_short::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
short j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint2korr(ptr);
else
#endif
shortget(j,ptr);
return unsigned_flag ? (double) (unsigned short) j : (double) j;
}
longlong Field_short::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
short j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint2korr(ptr);
else
#endif
shortget(j,ptr);
return unsigned_flag ? (longlong) (unsigned short) j : (longlong) j;
}
String *Field_short::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
CHARSET_INFO *cs= &my_charset_bin;
uint length;
uint mlength=max(field_length+1,7*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
short j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint2korr(ptr);
else
#endif
shortget(j,ptr);
if (unsigned_flag)
length=(uint) cs->cset->long10_to_str(cs, to, mlength, 10,
(long) (uint16) j);
else
length=(uint) cs->cset->long10_to_str(cs, to, mlength,-10, (long) j);
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer);
return val_buffer;
}
bool Field_short::send_binary(Protocol *protocol)
{
return protocol->store_short(Field_short::val_int());
}
int Field_short::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
short a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
a=sint2korr(a_ptr);
b=sint2korr(b_ptr);
}
else
#endif
{
shortget(a,a_ptr);
shortget(b,b_ptr);
}
if (unsigned_flag)
return ((unsigned short) a < (unsigned short) b) ? -1 :
((unsigned short) a > (unsigned short) b) ? 1 : 0;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_short::sort_string(uchar *to,uint length __attribute__((unused)))
{
#ifdef WORDS_BIGENDIAN
if (!table->s->db_low_byte_first)
{
if (unsigned_flag)
to[0] = ptr[0];
else
to[0] = (char) (ptr[0] ^ 128); /* Revers signbit */
to[1] = ptr[1];
}
else
#endif
{
if (unsigned_flag)
to[0] = ptr[1];
else
to[0] = (char) (ptr[1] ^ 128); /* Revers signbit */
to[1] = ptr[0];
}
}
void Field_short::sql_type(String &res) const
{
CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"smallint(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
Field type medium int (3 byte)
****************************************************************************/
int Field_medium::store(const char *from,uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int store_tmp;
int error;
longlong rnd;
error= get_int(cs, from, len, &rnd, UINT_MAX24, INT_MIN24, INT_MAX24);
store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
int3store(ptr, store_tmp);
return error;
}
int Field_medium::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
nr=rint(nr);
if (unsigned_flag)
{
if (nr < 0)
{
int3store(ptr,0);
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (nr >= (double) (long) (1L << 24))
{
uint32 tmp=(uint32) (1L << 24)-1L;
int3store(ptr,tmp);
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
int3store(ptr,(uint32) nr);
}
else
{
if (nr < (double) INT_MIN24)
{
long tmp=(long) INT_MIN24;
int3store(ptr,tmp);
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (nr > (double) INT_MAX24)
{
long tmp=(long) INT_MAX24;
int3store(ptr,tmp);
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
int3store(ptr,(long) nr);
}
return error;
}
int Field_medium::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
if (unsigned_flag)
{
if (nr < 0 && !unsigned_val)
{
int3store(ptr,0);
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if ((ulonglong) nr >= (ulonglong) (long) (1L << 24))
{
long tmp= (long) (1L << 24)-1L;
int3store(ptr,tmp);
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
int3store(ptr,(uint32) nr);
}
else
{
if (nr < 0 && unsigned_val)
nr= (ulonglong) (long) (1L << 24); // Generate overflow
if (nr < (longlong) INT_MIN24)
{
long tmp= (long) INT_MIN24;
int3store(ptr,tmp);
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (nr > (longlong) INT_MAX24)
{
long tmp=(long) INT_MAX24;
int3store(ptr,tmp);
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
int3store(ptr,(long) nr);
}
return error;
}
double Field_medium::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
return (double) j;
}
longlong Field_medium::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
return (longlong) j;
}
String *Field_medium::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
CHARSET_INFO *cs= &my_charset_bin;
uint length;
uint mlength=max(field_length+1,10*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
length=(uint) cs->cset->long10_to_str(cs,to,mlength,-10,j);
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer); /* purecov: inspected */
return val_buffer;
}
bool Field_medium::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
return protocol->store_long(Field_medium::val_int());
}
int Field_medium::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
long a,b;
if (unsigned_flag)
{
a=uint3korr(a_ptr);
b=uint3korr(b_ptr);
}
else
{
a=sint3korr(a_ptr);
b=sint3korr(b_ptr);
}
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_medium::sort_string(uchar *to,uint length __attribute__((unused)))
{
if (unsigned_flag)
to[0] = ptr[2];
else
to[0] = (uchar) (ptr[2] ^ 128); /* Revers signbit */
to[1] = ptr[1];
to[2] = ptr[0];
}
void Field_medium::sql_type(String &res) const
{
CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"mediumint(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
** long int
****************************************************************************/
int Field_long::store(const char *from,uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
long store_tmp;
int error;
longlong rnd;
error= get_int(cs, from, len, &rnd, UINT_MAX32, INT_MIN32, INT_MAX32);
store_tmp= unsigned_flag ? (long) (ulonglong) rnd : (long) rnd;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int4store(ptr, store_tmp);
}
else
#endif
longstore(ptr, store_tmp);
return error;
}
int Field_long::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
int32 res;
nr=rint(nr);
if (unsigned_flag)
{
if (nr < 0)
{
res=0;
error= 1;
}
else if (nr > (double) UINT_MAX32)
{
res= UINT_MAX32;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else
res=(int32) (ulong) nr;
}
else
{
if (nr < (double) INT_MIN32)
{
res=(int32) INT_MIN32;
error= 1;
}
else if (nr > (double) INT_MAX32)
{
res=(int32) INT_MAX32;
error= 1;
}
else
res=(int32) (longlong) nr;
}
if (error)
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int4store(ptr,res);
}
else
#endif
longstore(ptr,res);
return error;
}
int Field_long::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
int32 res;
if (unsigned_flag)
{
if (nr < 0 && !unsigned_val)
{
res=0;
error= 1;
}
else if ((ulonglong) nr >= (LL(1) << 32))
{
res=(int32) (uint32) ~0L;
error= 1;
}
else
res=(int32) (uint32) nr;
}
else
{
if (nr < 0 && unsigned_val)
nr= ((longlong) INT_MAX32) + 1; // Generate overflow
if (nr < (longlong) INT_MIN32)
{
res=(int32) INT_MIN32;
error= 1;
}
else if (nr > (longlong) INT_MAX32)
{
res=(int32) INT_MAX32;
error= 1;
}
else
res=(int32) nr;
}
if (error)
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int4store(ptr,res);
}
else
#endif
longstore(ptr,res);
return error;
}
double Field_long::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int32 j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint4korr(ptr);
else
#endif
longget(j,ptr);
return unsigned_flag ? (double) (uint32) j : (double) j;
}
longlong Field_long::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int32 j;
/* See the comment in Field_long::store(long long) */
DBUG_ASSERT(table->in_use == current_thd);
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint4korr(ptr);
else
#endif
longget(j,ptr);
return unsigned_flag ? (longlong) (uint32) j : (longlong) j;
}
String *Field_long::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
CHARSET_INFO *cs= &my_charset_bin;
uint length;
uint mlength=max(field_length+1,12*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
int32 j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint4korr(ptr);
else
#endif
longget(j,ptr);
if (unsigned_flag)
length=cs->cset->long10_to_str(cs,to,mlength, 10,(long) (uint32)j);
else
length=cs->cset->long10_to_str(cs,to,mlength,-10,(long) j);
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer);
return val_buffer;
}
bool Field_long::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
return protocol->store_long(Field_long::val_int());
}
int Field_long::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
int32 a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
a=sint4korr(a_ptr);
b=sint4korr(b_ptr);
}
else
#endif
{
longget(a,a_ptr);
longget(b,b_ptr);
}
if (unsigned_flag)
return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_long::sort_string(uchar *to,uint length __attribute__((unused)))
{
#ifdef WORDS_BIGENDIAN
if (!table->s->db_low_byte_first)
{
if (unsigned_flag)
to[0] = ptr[0];
else
to[0] = (char) (ptr[0] ^ 128); /* Revers signbit */
to[1] = ptr[1];
to[2] = ptr[2];
to[3] = ptr[3];
}
else
#endif
{
if (unsigned_flag)
to[0] = ptr[3];
else
to[0] = (char) (ptr[3] ^ 128); /* Revers signbit */
to[1] = ptr[2];
to[2] = ptr[1];
to[3] = ptr[0];
}
}
void Field_long::sql_type(String &res) const
{
CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"int(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
Field type longlong int (8 bytes)
****************************************************************************/
int Field_longlong::store(const char *from,uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
char *end;
ulonglong tmp;
tmp= cs->cset->strntoull10rnd(cs,from,len,unsigned_flag,&end,&error);
if (error == MY_ERRNO_ERANGE)
{
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
else if (table->in_use->count_cuted_fields &&
check_int(cs, from, len, end, error))
error= 1;
else
error= 0;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int8store(ptr,tmp);
}
else
#endif
longlongstore(ptr,tmp);
return error;
}
int Field_longlong::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
longlong res;
nr= rint(nr);
if (unsigned_flag)
{
if (nr < 0)
{
res=0;
error= 1;
}
else if (nr >= (double) ULONGLONG_MAX)
{
res= ~(longlong) 0;
error= 1;
}
else
res=(longlong) double2ulonglong(nr);
}
else
{
if (nr <= (double) LONGLONG_MIN)
{
res= LONGLONG_MIN;
error= (nr < (double) LONGLONG_MIN);
}
else if (nr >= (double) (ulonglong) LONGLONG_MAX)
{
res= LONGLONG_MAX;
error= (nr > (double) LONGLONG_MAX);
}
else
res=(longlong) nr;
}
if (error)
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int8store(ptr,res);
}
else
#endif
longlongstore(ptr,res);
return error;
}
int Field_longlong::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
if (nr < 0) // Only possible error
{
/*
if field is unsigned and value is signed (< 0) or
if field is signed and value is unsigned we have an overflow
*/
if (unsigned_flag != unsigned_val)
{
nr= unsigned_flag ? (ulonglong) 0 : (ulonglong) LONGLONG_MAX;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= 1;
}
}
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int8store(ptr,nr);
}
else
#endif
longlongstore(ptr,nr);
return error;
}
double Field_longlong::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
longlong j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
j=sint8korr(ptr);
}
else
#endif
longlongget(j,ptr);
/* The following is open coded to avoid a bug in gcc 3.3 */
if (unsigned_flag)
{
ulonglong tmp= (ulonglong) j;
return ulonglong2double(tmp);
}
return (double) j;
}
longlong Field_longlong::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
longlong j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint8korr(ptr);
else
#endif
longlongget(j,ptr);
return j;
}
String *Field_longlong::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
CHARSET_INFO *cs= &my_charset_bin;
uint length;
uint mlength=max(field_length+1,22*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
longlong j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint8korr(ptr);
else
#endif
longlongget(j,ptr);
length=(uint) (cs->cset->longlong10_to_str)(cs,to,mlength,
unsigned_flag ? 10 : -10, j);
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer);
return val_buffer;
}
bool Field_longlong::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
return protocol->store_longlong(Field_longlong::val_int(), unsigned_flag);
}
int Field_longlong::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
longlong a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
a=sint8korr(a_ptr);
b=sint8korr(b_ptr);
}
else
#endif
{
longlongget(a,a_ptr);
longlongget(b,b_ptr);
}
if (unsigned_flag)
return ((ulonglong) a < (ulonglong) b) ? -1 :
((ulonglong) a > (ulonglong) b) ? 1 : 0;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_longlong::sort_string(uchar *to,uint length __attribute__((unused)))
{
#ifdef WORDS_BIGENDIAN
if (!table->s->db_low_byte_first)
{
if (unsigned_flag)
to[0] = ptr[0];
else
to[0] = (char) (ptr[0] ^ 128); /* Revers signbit */
to[1] = ptr[1];
to[2] = ptr[2];
to[3] = ptr[3];
to[4] = ptr[4];
to[5] = ptr[5];
to[6] = ptr[6];
to[7] = ptr[7];
}
else
#endif
{
if (unsigned_flag)
to[0] = ptr[7];
else
to[0] = (char) (ptr[7] ^ 128); /* Revers signbit */
to[1] = ptr[6];
to[2] = ptr[5];
to[3] = ptr[4];
to[4] = ptr[3];
to[5] = ptr[2];
to[6] = ptr[1];
to[7] = ptr[0];
}
}
void Field_longlong::sql_type(String &res) const
{
CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"bigint(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/*
Floating-point numbers
*/
uchar *
Field_real::pack(uchar *to, const uchar *from,
uint max_length, bool low_byte_first)
{
DBUG_ENTER("Field_real::pack");
DBUG_ASSERT(max_length >= pack_length());
#ifdef WORDS_BIGENDIAN
if (low_byte_first != table->s->db_low_byte_first)
{
const uchar *dptr= from + pack_length();
while (dptr-- > from)
*to++ = *dptr;
DBUG_RETURN(to);
}
else
#endif
DBUG_RETURN(Field::pack(to, from, max_length, low_byte_first));
}
const uchar *
Field_real::unpack(uchar *to, const uchar *from,
uint param_data, bool low_byte_first)
{
DBUG_ENTER("Field_real::unpack");
#ifdef WORDS_BIGENDIAN
if (low_byte_first != table->s->db_low_byte_first)
{
const uchar *dptr= from + pack_length();
while (dptr-- > from)
*to++ = *dptr;
DBUG_RETURN(from + pack_length());
}
else
#endif
DBUG_RETURN(Field::unpack(to, from, param_data, low_byte_first));
}
/****************************************************************************
single precision float
****************************************************************************/
int Field_float::store(const char *from,uint len,CHARSET_INFO *cs)
{
int error;
char *end;
double nr= my_strntod(cs,(char*) from,len,&end,&error);
if (error || (!len || ((uint) (end-from) != len &&
table->in_use->count_cuted_fields)))
{
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
(error ? ER_WARN_DATA_OUT_OF_RANGE : WARN_DATA_TRUNCATED), 1);
error= error ? 1 : 2;
}
Field_float::store(nr);
return error;
}
int Field_float::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= truncate(&nr, FLT_MAX);
float j= (float)nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4store(ptr,j);
}
else
#endif
memcpy_fixed(ptr,(uchar*) &j,sizeof(j));
return error;
}
int Field_float::store(longlong nr, bool unsigned_val)
{
return Field_float::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
(double) nr);
}
double Field_float::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
float j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(j,ptr);
}
else
#endif
memcpy_fixed((uchar*) &j,ptr,sizeof(j));
return ((double) j);
}
longlong Field_float::val_int(void)
{
float j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(j,ptr);
}
else
#endif
memcpy_fixed((uchar*) &j,ptr,sizeof(j));
return (longlong) rint(j);
}
String *Field_float::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
float nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(nr,ptr);
}
else
#endif
memcpy_fixed((uchar*) &nr,ptr,sizeof(nr));
uint to_length=max(field_length,70);
val_buffer->alloc(to_length);
char *to=(char*) val_buffer->ptr();
if (dec >= NOT_FIXED_DEC)
{
sprintf(to,"%-*.*g",(int) field_length,FLT_DIG,nr);
to=strcend(to,' ');
*to=0;
}
else
{
#ifdef HAVE_FCONVERT
char buff[70],*pos=buff;
int decpt,sign,tmp_dec=dec;
VOID(sfconvert(&nr,tmp_dec,&decpt,&sign,buff));
if (sign)
{
*to++='-';
}
if (decpt < 0)
{ /* val_buffer is < 0 */
*to++='0';
if (!tmp_dec)
goto end;
*to++='.';
if (-decpt > tmp_dec)
decpt= - (int) tmp_dec;
tmp_dec=(uint) ((int) tmp_dec+decpt);
while (decpt++ < 0)
*to++='0';
}
else if (decpt == 0)
{
*to++= '0';
if (!tmp_dec)
goto end;
*to++='.';
}
else
{
while (decpt-- > 0)
*to++= *pos++;
if (!tmp_dec)
goto end;
*to++='.';
}
while (tmp_dec--)
*to++= *pos++;
#else
#ifdef HAVE_SNPRINTF
to[to_length-1]=0; // Safety
snprintf(to,to_length-1,"%.*f",dec,nr);
to=strend(to);
#else
to+= sprintf(to, "%.*f", dec, nr);
#endif
#endif
}
#ifdef HAVE_FCONVERT
end:
#endif
val_buffer->length((uint) (to-val_buffer->ptr()));
if (zerofill)
prepend_zeros(val_buffer);
return val_buffer;
}
int Field_float::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
float a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(a,a_ptr);
float4get(b,b_ptr);
}
else
#endif
{
memcpy_fixed(&a,a_ptr,sizeof(float));
memcpy_fixed(&b,b_ptr,sizeof(float));
}
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
#define FLT_EXP_DIG (sizeof(float)*8-FLT_MANT_DIG)
void Field_float::sort_string(uchar *to,uint length __attribute__((unused)))
{
float nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(nr,ptr);
}
else
#endif
memcpy_fixed(&nr,ptr,sizeof(float));
uchar *tmp= to;
if (nr == (float) 0.0)
{ /* Change to zero string */
tmp[0]=(uchar) 128;
bzero((char*) tmp+1,sizeof(nr)-1);
}
else
{
#ifdef WORDS_BIGENDIAN
memcpy_fixed(tmp,&nr,sizeof(nr));
#else
tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0];
#endif
if (tmp[0] & 128) /* Negative */
{ /* make complement */
uint i;
for (i=0 ; i < sizeof(nr); i++)
tmp[i]= (uchar) (tmp[i] ^ (uchar) 255);
}
else
{
ushort exp_part=(((ushort) tmp[0] << 8) | (ushort) tmp[1] |
(ushort) 32768);
exp_part+= (ushort) 1 << (16-1-FLT_EXP_DIG);
tmp[0]= (uchar) (exp_part >> 8);
tmp[1]= (uchar) exp_part;
}
}
}
bool Field_float::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
return protocol->store((float) Field_float::val_real(), dec, (String*) 0);
}
/**
Save the field metadata for float fields.
Saves the pack length in the first byte.
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_float::do_save_field_metadata(uchar *metadata_ptr)
{
*metadata_ptr= pack_length();
return 1;
}
void Field_float::sql_type(String &res) const
{
if (dec == NOT_FIXED_DEC)
{
res.set_ascii(STRING_WITH_LEN("float"));
}
else
{
CHARSET_INFO *cs= res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"float(%d,%d)",(int) field_length,dec));
}
add_zerofill_and_unsigned(res);
}
/****************************************************************************
double precision floating point numbers
****************************************************************************/
int Field_double::store(const char *from,uint len,CHARSET_INFO *cs)
{
int error;
char *end;
double nr= my_strntod(cs,(char*) from, len, &end, &error);
if (error || (!len || ((uint) (end-from) != len &&
table->in_use->count_cuted_fields)))
{
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
(error ? ER_WARN_DATA_OUT_OF_RANGE : WARN_DATA_TRUNCATED), 1);
error= error ? 1 : 2;
}
Field_double::store(nr);
return error;
}
int Field_double::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= truncate(&nr, DBL_MAX);
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8store(ptr,nr);
}
else
#endif
doublestore(ptr,nr);
return error;
}
int Field_double::store(longlong nr, bool unsigned_val)
{
return Field_double::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
(double) nr);
}
/*
If a field has fixed length, truncate the double argument pointed to by 'nr'
appropriately.
Also ensure that the argument is within [-max_value; max_value] range.
*/
int Field_real::truncate(double *nr, double max_value)
{
int error= 1;
double res= *nr;
if (isnan(res))
{
res= 0;
set_null();
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
goto end;
}
else if (unsigned_flag && res < 0)
{
res= 0;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
goto end;
}
if (!not_fixed)
{
uint order= field_length - dec;
uint step= array_elements(log_10) - 1;
max_value= 1.0;
for (; order > step; order-= step)
max_value*= log_10[step];
max_value*= log_10[order];
max_value-= 1.0 / log_10[dec];
double tmp= rint((res - floor(res)) * log_10[dec]) / log_10[dec];
res= floor(res) + tmp;
}
if (res < -max_value)
{
res= -max_value;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
}
else if (res > max_value)
{
res= max_value;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
}
else
error= 0;
end:
*nr= res;
return error;
}
int Field_real::store_decimal(const my_decimal *dm)
{
double dbl;
my_decimal2double(E_DEC_FATAL_ERROR, dm, &dbl);
return store(dbl);
}
double Field_double::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
double j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(j,ptr);
}
else
#endif
doubleget(j,ptr);
return j;
}
longlong Field_double::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
double j;
longlong res;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(j,ptr);
}
else
#endif
doubleget(j,ptr);
/* Check whether we fit into longlong range */
if (j <= (double) LONGLONG_MIN)
{
res= (longlong) LONGLONG_MIN;
goto warn;
}
if (j >= (double) (ulonglong) LONGLONG_MAX)
{
res= (longlong) LONGLONG_MAX;
goto warn;
}
return (longlong) rint(j);
warn:
{
char buf[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
String tmp(buf, sizeof(buf), &my_charset_latin1), *str;
str= val_str(&tmp, 0);
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_TRUNCATED_WRONG_VALUE,
ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
str->c_ptr());
}
return res;
}
my_decimal *Field_real::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
double2my_decimal(E_DEC_FATAL_ERROR, val_real(), decimal_value);
return decimal_value;
}
String *Field_double::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
double nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(nr,ptr);
}
else
#endif
doubleget(nr,ptr);
uint to_length= DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE;
val_buffer->alloc(to_length);
char *to=(char*) val_buffer->ptr();
if (dec >= NOT_FIXED_DEC)
{
sprintf(to,"%-*.*g",(int) field_length,DBL_DIG,nr);
to=strcend(to,' ');
}
else
{
#ifdef HAVE_FCONVERT
char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
char *pos= buff;
int decpt,sign,tmp_dec=dec;
VOID(fconvert(nr,tmp_dec,&decpt,&sign,buff));
if (sign)
{
*to++='-';
}
if (decpt < 0)
{ /* val_buffer is < 0 */
*to++='0';
if (!tmp_dec)
goto end;
*to++='.';
if (-decpt > tmp_dec)
decpt= - (int) tmp_dec;
tmp_dec=(uint) ((int) tmp_dec+decpt);
while (decpt++ < 0)
*to++='0';
}
else if (decpt == 0)
{
*to++= '0';
if (!tmp_dec)
goto end;
*to++='.';
}
else
{
while (decpt-- > 0)
*to++= *pos++;
if (!tmp_dec)
goto end;
*to++='.';
}
while (tmp_dec--)
*to++= *pos++;
#else
#ifdef HAVE_SNPRINTF
to[to_length-1]=0; // Safety
snprintf(to,to_length-1,"%.*f",dec,nr);
to=strend(to);
#else
to+= sprintf(to, "%.*f", dec, nr);
#endif
#endif
}
#ifdef HAVE_FCONVERT
end:
#endif
val_buffer->length((uint) (to-val_buffer->ptr()));
if (zerofill)
prepend_zeros(val_buffer);
return val_buffer;
}
bool Field_double::send_binary(Protocol *protocol)
{
return protocol->store((double) Field_double::val_real(), dec, (String*) 0);
}
int Field_double::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
double a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(a,a_ptr);
float8get(b,b_ptr);
}
else
#endif
{
doubleget(a, a_ptr);
doubleget(b, b_ptr);
}
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
#define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG)
/* The following should work for IEEE */
void Field_double::sort_string(uchar *to,uint length __attribute__((unused)))
{
double nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(nr,ptr);
}
else
#endif
doubleget(nr,ptr);
change_double_for_sort(nr, to);
}
/**
Save the field metadata for double fields.
Saves the pack length in the first byte of the field metadata array
at index of *metadata_ptr.
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_double::do_save_field_metadata(uchar *metadata_ptr)
{
*metadata_ptr= pack_length();
return 1;
}
void Field_double::sql_type(String &res) const
{
CHARSET_INFO *cs=res.charset();
if (dec == NOT_FIXED_DEC)
{
res.set_ascii(STRING_WITH_LEN("double"));
}
else
{
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"double(%d,%d)",(int) field_length,dec));
}
add_zerofill_and_unsigned(res);
}
/**
TIMESTAMP type holds datetime values in range from 1970-01-01 00:00:01 UTC to
2038-01-01 00:00:00 UTC stored as number of seconds since Unix
Epoch in UTC.
Up to one of timestamps columns in the table can be automatically
set on row update and/or have NOW() as default value.
TABLE::timestamp_field points to Field object for such timestamp with
auto-set-on-update. TABLE::time_stamp holds offset in record + 1 for this
field, and is used by handler code which performs updates required.
Actually SQL-99 says that we should allow niladic functions (like NOW())
as defaults for any field. Current limitations (only NOW() and only
for one TIMESTAMP field) are because of restricted binary .frm format
and should go away in the future.
Also because of this limitation of binary .frm format we use 5 different
unireg_check values with TIMESTAMP field to distinguish various cases of
DEFAULT or ON UPDATE values. These values are:
TIMESTAMP_OLD_FIELD - old timestamp, if there was not any fields with
auto-set-on-update (or now() as default) in this table before, then this
field has NOW() as default and is updated when row changes, else it is
field which has 0 as default value and is not automatically updated.
TIMESTAMP_DN_FIELD - field with NOW() as default but not set on update
automatically (TIMESTAMP DEFAULT NOW())
TIMESTAMP_UN_FIELD - field which is set on update automatically but has not
NOW() as default (but it may has 0 or some other const timestamp as
default) (TIMESTAMP ON UPDATE NOW()).
TIMESTAMP_DNUN_FIELD - field which has now() as default and is auto-set on
update. (TIMESTAMP DEFAULT NOW() ON UPDATE NOW())
NONE - field which is not auto-set on update with some other than NOW()
default value (TIMESTAMP DEFAULT 0).
Note that TIMESTAMP_OLD_FIELDs are never created explicitly now, they are
left only for preserving ability to read old tables. Such fields replaced
with their newer analogs in CREATE TABLE and in SHOW CREATE TABLE. This is
because we want to prefer NONE unireg_check before TIMESTAMP_OLD_FIELD for
"TIMESTAMP DEFAULT 'Const'" field. (Old timestamps allowed such
specification too but ignored default value for first timestamp, which of
course is non-standard.) In most cases user won't notice any change, only
exception is different behavior of old/new timestamps during ALTER TABLE.
*/
Field_timestamp::Field_timestamp(uchar *ptr_arg, uint32 len_arg,
uchar *null_ptr_arg, uchar null_bit_arg,
enum utype unireg_check_arg,
const char *field_name_arg,
TABLE_SHARE *share,
CHARSET_INFO *cs)
:Field_str(ptr_arg, MAX_DATETIME_WIDTH, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg, cs)
{
/* For 4.0 MYD and 4.0 InnoDB compatibility */
flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
if (!share->timestamp_field && unireg_check != NONE)
{
/* This timestamp has auto-update */
share->timestamp_field= this;
flags|= TIMESTAMP_FLAG;
if (unireg_check != TIMESTAMP_DN_FIELD)
flags|= ON_UPDATE_NOW_FLAG;
}
}
Field_timestamp::Field_timestamp(bool maybe_null_arg,
const char *field_name_arg,
CHARSET_INFO *cs)
:Field_str((uchar*) 0, MAX_DATETIME_WIDTH,
maybe_null_arg ? (uchar*) "": 0, 0,
NONE, field_name_arg, cs)
{
/* For 4.0 MYD and 4.0 InnoDB compatibility */
flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
if (unireg_check != TIMESTAMP_DN_FIELD)
flags|= ON_UPDATE_NOW_FLAG;
}
/**
Get auto-set type for TIMESTAMP field.
Returns value indicating during which operations this TIMESTAMP field
should be auto-set to current timestamp.
*/
timestamp_auto_set_type Field_timestamp::get_auto_set_type() const
{
switch (unireg_check)
{
case TIMESTAMP_DN_FIELD:
return TIMESTAMP_AUTO_SET_ON_INSERT;
case TIMESTAMP_UN_FIELD:
return TIMESTAMP_AUTO_SET_ON_UPDATE;
case TIMESTAMP_OLD_FIELD:
/*
Although we can have several such columns in legacy tables this
function should be called only for first of them (i.e. the one
having auto-set property).
*/
DBUG_ASSERT(table->timestamp_field == this);
/* Fall-through */
case TIMESTAMP_DNUN_FIELD:
return TIMESTAMP_AUTO_SET_ON_BOTH;
default:
/*
Normally this function should not be called for TIMESTAMPs without
auto-set property.
*/
DBUG_ASSERT(0);
return TIMESTAMP_NO_AUTO_SET;
}
}
int Field_timestamp::store(const char *from,uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
MYSQL_TIME l_time;
my_time_t tmp= 0;
int error;
bool have_smth_to_conv;
my_bool in_dst_time_gap;
THD *thd= table ? table->in_use : current_thd;
/* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
have_smth_to_conv= (str_to_datetime(from, len, &l_time,
(thd->variables.sql_mode &
MODE_NO_ZERO_DATE) |
MODE_NO_ZERO_IN_DATE, &error) >
MYSQL_TIMESTAMP_ERROR);
if (error || !have_smth_to_conv)
{
error= 1;
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
from, len, MYSQL_TIMESTAMP_DATETIME, 1);
}
/* Only convert a correct date (not a zero date) */
if (have_smth_to_conv && l_time.month)
{
if (!(tmp= TIME_to_timestamp(thd, &l_time, &in_dst_time_gap)))
{
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE,
from, len, MYSQL_TIMESTAMP_DATETIME, !error);
error= 1;
}
else if (in_dst_time_gap)
{
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_INVALID_TIMESTAMP,
from, len, MYSQL_TIMESTAMP_DATETIME, !error);
error= 1;
}
}
store_timestamp(tmp);
return error;
}
int Field_timestamp::store(double nr)
{
int error= 0;
if (nr < 0 || nr > 99991231235959.0)
{
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE,
nr, MYSQL_TIMESTAMP_DATETIME);
nr= 0; // Avoid overflow on buff
error= 1;
}
error|= Field_timestamp::store((longlong) rint(nr), FALSE);
return error;
}
int Field_timestamp::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
MYSQL_TIME l_time;
my_time_t timestamp= 0;
int error;
my_bool in_dst_time_gap;
THD *thd= table ? table->in_use : current_thd;
/* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
longlong tmp= number_to_datetime(nr, &l_time, (thd->variables.sql_mode &
MODE_NO_ZERO_DATE) |
MODE_NO_ZERO_IN_DATE, &error);
if (tmp == LL(-1))
{
error= 2;
}
if (!error && tmp)
{
if (!(timestamp= TIME_to_timestamp(thd, &l_time, &in_dst_time_gap)))
{
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE,
nr, MYSQL_TIMESTAMP_DATETIME, 1);
error= 1;
}
if (in_dst_time_gap)
{
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_INVALID_TIMESTAMP,
nr, MYSQL_TIMESTAMP_DATETIME, 1);
error= 1;
}
} else if (error)
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
WARN_DATA_TRUNCATED,
nr, MYSQL_TIMESTAMP_DATETIME, 1);
store_timestamp(timestamp);
return error;
}
double Field_timestamp::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
return (double) Field_timestamp::val_int();
}
longlong Field_timestamp::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
uint32 temp;
MYSQL_TIME time_tmp;
THD *thd= table ? table->in_use : current_thd;
thd->time_zone_used= 1;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
temp=uint4korr(ptr);
else
#endif
longget(temp,ptr);
if (temp == 0L) // No time
return(0); /* purecov: inspected */
thd->variables.time_zone->gmt_sec_to_TIME(&time_tmp, (my_time_t)temp);
return time_tmp.year * LL(10000000000) + time_tmp.month * LL(100000000) +
time_tmp.day * 1000000L + time_tmp.hour * 10000L +
time_tmp.minute * 100 + time_tmp.second;
}
String *Field_timestamp::val_str(String *val_buffer, String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
uint32 temp, temp2;
MYSQL_TIME time_tmp;
THD *thd= table ? table->in_use : current_thd;
char *to;
val_buffer->alloc(field_length+1);
to= (char*) val_buffer->ptr();
val_buffer->length(field_length);
thd->time_zone_used= 1;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
temp=uint4korr(ptr);
else
#endif
longget(temp,ptr);
if (temp == 0L)
{ /* Zero time is "000000" */
val_ptr->set(STRING_WITH_LEN("0000-00-00 00:00:00"), &my_charset_bin);
return val_ptr;
}
val_buffer->set_charset(&my_charset_bin); // Safety
thd->variables.time_zone->gmt_sec_to_TIME(&time_tmp,(my_time_t)temp);
temp= time_tmp.year % 100;
if (temp < YY_PART_YEAR - 1)
{
*to++= '2';
*to++= '0';
}
else
{
*to++= '1';
*to++= '9';
}
temp2=temp/10; temp=temp-temp2*10;
*to++= (char) ('0'+(char) (temp2));
*to++= (char) ('0'+(char) (temp));
*to++= '-';
temp=time_tmp.month;
temp2=temp/10; temp=temp-temp2*10;
*to++= (char) ('0'+(char) (temp2));
*to++= (char) ('0'+(char) (temp));
*to++= '-';
temp=time_tmp.day;
temp2=temp/10; temp=temp-temp2*10;
*to++= (char) ('0'+(char) (temp2));
*to++= (char) ('0'+(char) (temp));
*to++= ' ';
temp=time_tmp.hour;
temp2=temp/10; temp=temp-temp2*10;
*to++= (char) ('0'+(char) (temp2));
*to++= (char) ('0'+(char) (temp));
*to++= ':';
temp=time_tmp.minute;
temp2=temp/10; temp=temp-temp2*10;
*to++= (char) ('0'+(char) (temp2));
*to++= (char) ('0'+(char) (temp));
*to++= ':';
temp=time_tmp.second;
temp2=temp/10; temp=temp-temp2*10;
*to++= (char) ('0'+(char) (temp2));
*to++= (char) ('0'+(char) (temp));
*to= 0;
return val_buffer;
}
bool Field_timestamp::get_date(MYSQL_TIME *ltime, uint fuzzydate)
{
long temp;
THD *thd= table ? table->in_use : current_thd;
thd->time_zone_used= 1;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
temp=uint4korr(ptr);
else
#endif
longget(temp,ptr);
if (temp == 0L)
{ /* Zero time is "000000" */
if (fuzzydate & TIME_NO_ZERO_DATE)
return 1;
bzero((char*) ltime,sizeof(*ltime));
}
else
{
thd->variables.time_zone->gmt_sec_to_TIME(ltime, (my_time_t)temp);
}
return 0;
}
bool Field_timestamp::get_time(MYSQL_TIME *ltime)
{
return Field_timestamp::get_date(ltime,0);
}
bool Field_timestamp::send_binary(Protocol *protocol)
{
MYSQL_TIME tm;
Field_timestamp::get_date(&tm, 0);
return protocol->store(&tm);
}
int Field_timestamp::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
int32 a,b;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
a=sint4korr(a_ptr);
b=sint4korr(b_ptr);
}
else
#endif
{
longget(a,a_ptr);
longget(b,b_ptr);
}
return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
}
void Field_timestamp::sort_string(uchar *to,uint length __attribute__((unused)))
{
#ifdef WORDS_BIGENDIAN
if (!table || !table->s->db_low_byte_first)
{
to[0] = ptr[0];
to[1] = ptr[1];
to[2] = ptr[2];
to[3] = ptr[3];
}
else
#endif
{
to[0] = ptr[3];
to[1] = ptr[2];
to[2] = ptr[1];
to[3] = ptr[0];
}
}
void Field_timestamp::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("timestamp"));
}
void Field_timestamp::set_time()
{
THD *thd= table ? table->in_use : current_thd;
long tmp= (long) thd->query_start();
set_notnull();
store_timestamp(tmp);
}
/****************************************************************************
** time type
** In string context: HH:MM:SS
** In number context: HHMMSS
** Stored as a 3 byte unsigned int
****************************************************************************/
int Field_time::store(const char *from,uint len,CHARSET_INFO *cs)
{
MYSQL_TIME ltime;
long tmp;
int error= 0;
int warning;
if (str_to_time(from, len, <ime, &warning))
{
tmp=0L;
error= 2;
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
from, len, MYSQL_TIMESTAMP_TIME, 1);
}
else
{
if (warning & MYSQL_TIME_WARN_TRUNCATED)
{
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
WARN_DATA_TRUNCATED,
from, len, MYSQL_TIMESTAMP_TIME, 1);
error= 1;
}
if (warning & MYSQL_TIME_WARN_OUT_OF_RANGE)
{
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE,
from, len, MYSQL_TIMESTAMP_TIME, !error);
error= 1;
}
if (ltime.month)
ltime.day=0;
tmp=(ltime.day*24L+ltime.hour)*10000L+(ltime.minute*100+ltime.second);
}
if (ltime.neg)
tmp= -tmp;
int3store(ptr,tmp);
return error;
}
int Field_time::store_time(MYSQL_TIME *ltime, timestamp_type time_type)
{
long tmp= ((ltime->month ? 0 : ltime->day * 24L) + ltime->hour) * 10000L +
(ltime->minute * 100 + ltime->second);
if (ltime->neg)
tmp= -tmp;
return Field_time::store((longlong) tmp, FALSE);
}
int Field_time::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
long tmp;
int error= 0;
if (nr > (double)TIME_MAX_VALUE)
{
tmp= TIME_MAX_VALUE;
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE, nr, MYSQL_TIMESTAMP_TIME);
error= 1;
}
else if (nr < (double)-TIME_MAX_VALUE)
{
tmp= -TIME_MAX_VALUE;
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE, nr, MYSQL_TIMESTAMP_TIME);
error= 1;
}
else
{
tmp=(long) floor(fabs(nr)); // Remove fractions
if (nr < 0)
tmp= -tmp;
if (tmp % 100 > 59 || tmp/100 % 100 > 59)
{
tmp=0;
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE, nr,
MYSQL_TIMESTAMP_TIME);
error= 1;
}
}
int3store(ptr,tmp);
return error;
}
int Field_time::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
long tmp;
int error= 0;
if (nr < (longlong) -TIME_MAX_VALUE && !unsigned_val)
{
tmp= -TIME_MAX_VALUE;
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE, nr,
MYSQL_TIMESTAMP_TIME, 1);
error= 1;
}
else if (nr > (longlong) TIME_MAX_VALUE || (nr < 0 && unsigned_val))
{
tmp= TIME_MAX_VALUE;
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE, nr,
MYSQL_TIMESTAMP_TIME, 1);
error= 1;
}
else
{
tmp=(long) nr;
if (tmp % 100 > 59 || tmp/100 % 100 > 59)
{
tmp=0;
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE, nr,
MYSQL_TIMESTAMP_TIME, 1);
error= 1;
}
}
int3store(ptr,tmp);
return error;
}
double Field_time::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
uint32 j= (uint32) uint3korr(ptr);
return (double) j;
}
longlong Field_time::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
return (longlong) sint3korr(ptr);
}
/**
@note
This function is multi-byte safe as the result string is always of type
my_charset_bin
*/
String *Field_time::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
val_buffer->alloc(MAX_DATE_STRING_REP_LENGTH);
long tmp=(long) sint3korr(ptr);
ltime.neg= 0;
if (tmp < 0)
{
tmp= -tmp;
ltime.neg= 1;
}
ltime.day= (uint) 0;
ltime.hour= (uint) (tmp/10000);
ltime.minute= (uint) (tmp/100 % 100);
ltime.second= (uint) (tmp % 100);
make_time((DATE_TIME_FORMAT*) 0, <ime, val_buffer);
return val_buffer;
}
/**
@note
Normally we would not consider 'time' as a valid date, but we allow
get_date() here to be able to do things like
DATE_FORMAT(time, "%l.%i %p")
*/
bool Field_time::get_date(MYSQL_TIME *ltime, uint fuzzydate)
{
THD *thd= table ? table->in_use : current_thd;
if (!(fuzzydate & TIME_FUZZY_DATE))
{
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE,
ER(ER_WARN_DATA_OUT_OF_RANGE), field_name,
thd->row_count);
return 1;
}
return Field_time::get_time(ltime);
}
bool Field_time::get_time(MYSQL_TIME *ltime)
{
long tmp=(long) sint3korr(ptr);
ltime->neg=0;
if (tmp < 0)
{
ltime->neg= 1;
tmp=-tmp;
}
ltime->year= ltime->month= ltime->day= 0;
ltime->hour= (int) (tmp/10000);
tmp-=ltime->hour*10000;
ltime->minute= (int) tmp/100;
ltime->second= (int) tmp % 100;
ltime->second_part=0;
ltime->time_type= MYSQL_TIMESTAMP_TIME;
return 0;
}
bool Field_time::send_binary(Protocol *protocol)
{
MYSQL_TIME tm;
Field_time::get_time(&tm);
tm.day= tm.hour/24; // Move hours to days
tm.hour-= tm.day*24;
return protocol->store_time(&tm);
}
int Field_time::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
int32 a,b;
a=(int32) sint3korr(a_ptr);
b=(int32) sint3korr(b_ptr);
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_time::sort_string(uchar *to,uint length __attribute__((unused)))
{
to[0] = (uchar) (ptr[2] ^ 128);
to[1] = ptr[1];
to[2] = ptr[0];
}
void Field_time::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("time"));
}
/****************************************************************************
** year type
** Save in a byte the year 0, 1901->2155
** Can handle 2 byte or 4 byte years!
****************************************************************************/
int Field_year::store(const char *from, uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char *end;
int error;
longlong nr= cs->cset->strntoull10rnd(cs, from, len, 0, &end, &error);
if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155 ||
error == MY_ERRNO_ERANGE)
{
*ptr=0;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
return 1;
}
if (table->in_use->count_cuted_fields &&
(error= check_int(cs, from, len, end, error)))
{
if (error == 1) /* empty or incorrect string */
{
*ptr= 0;
return 1;
}
error= 1;
}
if (nr != 0 || len != 4)
{
if (nr < YY_PART_YEAR)
nr+=100; // 2000 - 2069
else if (nr > 1900)
nr-= 1900;
}
*ptr= (char) (uchar) nr;
return error;
}
int Field_year::store(double nr)
{
if (nr < 0.0 || nr >= 2155.0)
{
(void) Field_year::store((longlong) -1, FALSE);
return 1;
}
return Field_year::store((longlong) nr, FALSE);
}
int Field_year::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155)
{
*ptr= 0;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
return 1;
}
if (nr != 0 || field_length != 4) // 0000 -> 0; 00 -> 2000
{
if (nr < YY_PART_YEAR)
nr+=100; // 2000 - 2069
else if (nr > 1900)
nr-= 1900;
}
*ptr= (char) (uchar) nr;
return 0;
}
bool Field_year::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
ulonglong tmp= Field_year::val_int();
return protocol->store_short(tmp);
}
double Field_year::val_real(void)
{
return (double) Field_year::val_int();
}
longlong Field_year::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ASSERT(field_length == 2 || field_length == 4);
int tmp= (int) ptr[0];
if (field_length != 4)
tmp%=100; // Return last 2 char
else if (tmp)
tmp+=1900;
return (longlong) tmp;
}
String *Field_year::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
DBUG_ASSERT(field_length < 5);
val_buffer->alloc(5);
val_buffer->length(field_length);
char *to=(char*) val_buffer->ptr();
sprintf(to,field_length == 2 ? "%02d" : "%04d",(int) Field_year::val_int());
return val_buffer;
}
void Field_year::sql_type(String &res) const
{
CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*)res.ptr(),res.alloced_length(),
"year(%d)",(int) field_length));
}
/****************************************************************************
** date type
** In string context: YYYY-MM-DD
** In number context: YYYYMMDD
** Stored as a 4 byte unsigned int
****************************************************************************/
int Field_date::store(const char *from, uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
MYSQL_TIME l_time;
uint32 tmp;
int error;
THD *thd= table ? table->in_use : current_thd;
if (str_to_datetime(from, len, &l_time, TIME_FUZZY_DATE |
(thd->variables.sql_mode &
(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
MODE_INVALID_DATES)),
&error) <= MYSQL_TIMESTAMP_ERROR)
{
tmp= 0;
error= 2;
}
else
tmp=(uint32) l_time.year*10000L + (uint32) (l_time.month*100+l_time.day);
if (error)
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
from, len, MYSQL_TIMESTAMP_DATE, 1);
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
int4store(ptr,tmp);
}
else
#endif
longstore(ptr,tmp);
return error;
}
int Field_date::store(double nr)
{
longlong tmp;
if (nr >= 19000000000000.0 && nr <= 99991231235959.0)
nr=floor(nr/1000000.0); // Timestamp to date
if (nr < 0.0 || nr > 99991231.0)
{
tmp= LL(0);
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE,
nr, MYSQL_TIMESTAMP_DATE);
}
else
tmp= (longlong) rint(nr);
return Field_date::store(tmp, TRUE);
}
int Field_date::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
MYSQL_TIME not_used;
int error;
longlong initial_nr= nr;
THD *thd= table ? table->in_use : current_thd;
nr= number_to_datetime(nr, ¬_used, (TIME_FUZZY_DATE |
(thd->variables.sql_mode &
(MODE_NO_ZERO_IN_DATE |
MODE_NO_ZERO_DATE |
MODE_INVALID_DATES))), &error);
if (nr == LL(-1))
{
nr= 0;
error= 2;
}
if (nr >= 19000000000000.0 && nr <= 99991231235959.0)
nr= (longlong) floor(nr/1000000.0); // Timestamp to date
if (error)
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
error == 2 ? ER_WARN_DATA_OUT_OF_RANGE :
WARN_DATA_TRUNCATED, initial_nr,
MYSQL_TIMESTAMP_DATETIME, 1);
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
int4store(ptr, nr);
}
else
#endif
longstore(ptr, nr);
return error;
}
bool Field_date::send_binary(Protocol *protocol)
{
longlong tmp= Field_date::val_int();
MYSQL_TIME tm;
tm.year= (uint32) tmp/10000L % 10000;
tm.month= (uint32) tmp/100 % 100;
tm.day= (uint32) tmp % 100;
return protocol->store_date(&tm);
}
double Field_date::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int32 j;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
j=sint4korr(ptr);
else
#endif
longget(j,ptr);
return (double) (uint32) j;
}
longlong Field_date::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int32 j;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
j=sint4korr(ptr);
else
#endif
longget(j,ptr);
return (longlong) (uint32) j;
}
String *Field_date::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
val_buffer->alloc(field_length);
int32 tmp;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
tmp=sint4korr(ptr);
else
#endif
longget(tmp,ptr);
ltime.neg= 0;
ltime.year= (int) ((uint32) tmp/10000L % 10000);
ltime.month= (int) ((uint32) tmp/100 % 100);
ltime.day= (int) ((uint32) tmp % 100);
make_date((DATE_TIME_FORMAT *) 0, <ime, val_buffer);
return val_buffer;
}
bool Field_date::get_time(MYSQL_TIME *ltime)
{
bzero((char *)ltime, sizeof(MYSQL_TIME));
return 0;
}
int Field_date::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
int32 a,b;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
a=sint4korr(a_ptr);
b=sint4korr(b_ptr);
}
else
#endif
{
longget(a,a_ptr);
longget(b,b_ptr);
}
return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
}
void Field_date::sort_string(uchar *to,uint length __attribute__((unused)))
{
#ifdef WORDS_BIGENDIAN
if (!table || !table->s->db_low_byte_first)
{
to[0] = ptr[0];
to[1] = ptr[1];
to[2] = ptr[2];
to[3] = ptr[3];
}
else
#endif
{
to[0] = ptr[3];
to[1] = ptr[2];
to[2] = ptr[1];
to[3] = ptr[0];
}
}
void Field_date::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("date"));
}
/****************************************************************************
** The new date type
** This is identical to the old date type, but stored on 3 bytes instead of 4
** In number context: YYYYMMDD
****************************************************************************/
/*
Store string into a date field
SYNOPSIS
Field_newdate::store()
from Date string
len Length of date field
cs Character set (not used)
RETURN
0 ok
1 Value was cut during conversion
2 Wrong date string
3 Datetime value that was cut (warning level NOTE)
This is used by opt_range.cc:get_mm_leaf(). Note that there is a
nearly-identical class Field_date doesn't ever return 3 from its
store function.
*/
int Field_newdate::store(const char *from,uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
long tmp;
MYSQL_TIME l_time;
int error;
THD *thd= table ? table->in_use : current_thd;
enum enum_mysql_timestamp_type ret;
if ((ret= str_to_datetime(from, len, &l_time,
(TIME_FUZZY_DATE |
(thd->variables.sql_mode &
(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
MODE_INVALID_DATES))),
&error)) <= MYSQL_TIMESTAMP_ERROR)
{
tmp= 0;
error= 2;
}
else
{
tmp= l_time.day + l_time.month*32 + l_time.year*16*32;
if (!error && (ret != MYSQL_TIMESTAMP_DATE) &&
(l_time.hour || l_time.minute || l_time.second || l_time.second_part))
error= 3; // Datetime was cut (note)
}
if (error)
set_datetime_warning(error == 3 ? MYSQL_ERROR::WARN_LEVEL_NOTE :
MYSQL_ERROR::WARN_LEVEL_WARN,
WARN_DATA_TRUNCATED,
from, len, MYSQL_TIMESTAMP_DATE, 1);
int3store(ptr, tmp);
return error;
}
int Field_newdate::store(double nr)
{
if (nr < 0.0 || nr > 99991231235959.0)
{
int3store(ptr,(int32) 0);
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
WARN_DATA_TRUNCATED, nr, MYSQL_TIMESTAMP_DATE);
return 1;
}
return Field_newdate::store((longlong) rint(nr), FALSE);
}
int Field_newdate::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
MYSQL_TIME l_time;
longlong tmp;
int error;
THD *thd= table ? table->in_use : current_thd;
if (number_to_datetime(nr, &l_time,
(TIME_FUZZY_DATE |
(thd->variables.sql_mode &
(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
MODE_INVALID_DATES))),
&error) == LL(-1))
{
tmp= 0L;
error= 2;
}
else
tmp= l_time.day + l_time.month*32 + l_time.year*16*32;
if (!error && l_time.time_type != MYSQL_TIMESTAMP_DATE &&
(l_time.hour || l_time.minute || l_time.second || l_time.second_part))
error= 3;
if (error)
set_datetime_warning(error == 3 ? MYSQL_ERROR::WARN_LEVEL_NOTE :
MYSQL_ERROR::WARN_LEVEL_WARN,
error == 2 ?
ER_WARN_DATA_OUT_OF_RANGE : WARN_DATA_TRUNCATED,
nr,MYSQL_TIMESTAMP_DATE, 1);
int3store(ptr,tmp);
return error;
}
int Field_newdate::store_time(MYSQL_TIME *ltime,timestamp_type time_type)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
long tmp;
int error= 0;
if (time_type == MYSQL_TIMESTAMP_DATE ||
time_type == MYSQL_TIMESTAMP_DATETIME)
{
tmp=ltime->year*16*32+ltime->month*32+ltime->day;
if (check_date(ltime, tmp != 0,
(TIME_FUZZY_DATE |
(current_thd->variables.sql_mode &
(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
MODE_INVALID_DATES))), &error))
{
char buff[MAX_DATE_STRING_REP_LENGTH];
String str(buff, sizeof(buff), &my_charset_latin1);
tmp= 0;
make_date((DATE_TIME_FORMAT *) 0, ltime, &str);
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
str.ptr(), str.length(), MYSQL_TIMESTAMP_DATE, 1);
}
if (!error && ltime->time_type != MYSQL_TIMESTAMP_DATE &&
(ltime->hour || ltime->minute || ltime->second || ltime->second_part))
{
char buff[MAX_DATE_STRING_REP_LENGTH];
String str(buff, sizeof(buff), &my_charset_latin1);
make_datetime((DATE_TIME_FORMAT *) 0, ltime, &str);
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_NOTE,
WARN_DATA_TRUNCATED,
str.ptr(), str.length(), MYSQL_TIMESTAMP_DATE, 1);
error= 3;
}
}
else
{
tmp=0;
error= 1;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
}
int3store(ptr,tmp);
return error;
}
bool Field_newdate::send_binary(Protocol *protocol)
{
MYSQL_TIME tm;
Field_newdate::get_date(&tm,0);
return protocol->store_date(&tm);
}
double Field_newdate::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
return (double) Field_newdate::val_int();
}
longlong Field_newdate::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
ulong j= uint3korr(ptr);
j= (j % 32L)+(j / 32L % 16L)*100L + (j/(16L*32L))*10000L;
return (longlong) j;
}
String *Field_newdate::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
val_buffer->alloc(field_length);
val_buffer->length(field_length);
uint32 tmp=(uint32) uint3korr(ptr);
int part;
char *pos=(char*) val_buffer->ptr()+10;
/* Open coded to get more speed */
*pos--=0; // End NULL
part=(int) (tmp & 31);
*pos--= (char) ('0'+part%10);
*pos--= (char) ('0'+part/10);
*pos--= '-';
part=(int) (tmp >> 5 & 15);
*pos--= (char) ('0'+part%10);
*pos--= (char) ('0'+part/10);
*pos--= '-';
part=(int) (tmp >> 9);
*pos--= (char) ('0'+part%10); part/=10;
*pos--= (char) ('0'+part%10); part/=10;
*pos--= (char) ('0'+part%10); part/=10;
*pos= (char) ('0'+part);
return val_buffer;
}
bool Field_newdate::get_date(MYSQL_TIME *ltime,uint fuzzydate)
{
uint32 tmp=(uint32) uint3korr(ptr);
ltime->day= tmp & 31;
ltime->month= (tmp >> 5) & 15;
ltime->year= (tmp >> 9);
ltime->time_type= MYSQL_TIMESTAMP_DATE;
ltime->hour= ltime->minute= ltime->second= ltime->second_part= ltime->neg= 0;
return ((!(fuzzydate & TIME_FUZZY_DATE) && (!ltime->month || !ltime->day)) ?
1 : 0);
}
bool Field_newdate::get_time(MYSQL_TIME *ltime)
{
return Field_newdate::get_date(ltime,0);
}
int Field_newdate::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
uint32 a,b;
a=(uint32) uint3korr(a_ptr);
b=(uint32) uint3korr(b_ptr);
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_newdate::sort_string(uchar *to,uint length __attribute__((unused)))
{
to[0] = ptr[2];
to[1] = ptr[1];
to[2] = ptr[0];
}
void Field_newdate::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("date"));
}
/****************************************************************************
** datetime type
** In string context: YYYY-MM-DD HH:MM:DD
** In number context: YYYYMMDDHHMMDD
** Stored as a 8 byte unsigned int. Should sometimes be change to a 6 byte int.
****************************************************************************/
int Field_datetime::store(const char *from,uint len,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
MYSQL_TIME time_tmp;
int error;
ulonglong tmp= 0;
enum enum_mysql_timestamp_type func_res;
THD *thd= table ? table->in_use : current_thd;
func_res= str_to_datetime(from, len, &time_tmp,
(TIME_FUZZY_DATE |
(thd->variables.sql_mode &
(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
MODE_INVALID_DATES))),
&error);
if ((int) func_res > (int) MYSQL_TIMESTAMP_ERROR)
tmp= TIME_to_ulonglong_datetime(&time_tmp);
else
error= 1; // Fix if invalid zero date
if (error)
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE,
from, len, MYSQL_TIMESTAMP_DATETIME, 1);
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
int8store(ptr,tmp);
}
else
#endif
longlongstore(ptr,tmp);
return error;
}
int Field_datetime::store(double nr)
{
int error= 0;
if (nr < 0.0 || nr > 99991231235959.0)
{
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE,
nr, MYSQL_TIMESTAMP_DATETIME);
nr= 0.0;
error= 1;
}
error|= Field_datetime::store((longlong) rint(nr), FALSE);
return error;
}
int Field_datetime::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
MYSQL_TIME not_used;
int error;
longlong initial_nr= nr;
THD *thd= table ? table->in_use : current_thd;
nr= number_to_datetime(nr, ¬_used, (TIME_FUZZY_DATE |
(thd->variables.sql_mode &
(MODE_NO_ZERO_IN_DATE |
MODE_NO_ZERO_DATE |
MODE_INVALID_DATES))), &error);
if (nr == LL(-1))
{
nr= 0;
error= 2;
}
if (error)
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
error == 2 ? ER_WARN_DATA_OUT_OF_RANGE :
WARN_DATA_TRUNCATED, initial_nr,
MYSQL_TIMESTAMP_DATETIME, 1);
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
int8store(ptr,nr);
}
else
#endif
longlongstore(ptr,nr);
return error;
}
int Field_datetime::store_time(MYSQL_TIME *ltime,timestamp_type time_type)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
longlong tmp;
int error= 0;
/*
We don't perform range checking here since values stored in TIME
structure always fit into DATETIME range.
*/
if (time_type == MYSQL_TIMESTAMP_DATE ||
time_type == MYSQL_TIMESTAMP_DATETIME)
{
tmp=((ltime->year*10000L+ltime->month*100+ltime->day)*LL(1000000)+
(ltime->hour*10000L+ltime->minute*100+ltime->second));
if (check_date(ltime, tmp != 0,
(TIME_FUZZY_DATE |
(current_thd->variables.sql_mode &
(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
MODE_INVALID_DATES))), &error))
{
char buff[MAX_DATE_STRING_REP_LENGTH];
String str(buff, sizeof(buff), &my_charset_latin1);
tmp= 0;
make_datetime((DATE_TIME_FORMAT *) 0, ltime, &str);
set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
str.ptr(), str.length(), MYSQL_TIMESTAMP_DATETIME,1);
}
}
else
{
tmp=0;
error= 1;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
}
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
int8store(ptr,tmp);
}
else
#endif
longlongstore(ptr,tmp);
return error;
}
bool Field_datetime::send_binary(Protocol *protocol)
{
MYSQL_TIME tm;
Field_datetime::get_date(&tm, TIME_FUZZY_DATE);
return protocol->store(&tm);
}
double Field_datetime::val_real(void)
{
return (double) Field_datetime::val_int();
}
longlong Field_datetime::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
longlong j;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
j=sint8korr(ptr);
else
#endif
longlongget(j,ptr);
return j;
}
String *Field_datetime::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
val_buffer->alloc(field_length);
val_buffer->length(field_length);
ulonglong tmp;
long part1,part2;
char *pos;
int part3;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
tmp=sint8korr(ptr);
else
#endif
longlongget(tmp,ptr);
/*
Avoid problem with slow longlong arithmetic and sprintf
*/
part1=(long) (tmp/LL(1000000));
part2=(long) (tmp - (ulonglong) part1*LL(1000000));
pos=(char*) val_buffer->ptr() + MAX_DATETIME_WIDTH;
*pos--=0;
*pos--= (char) ('0'+(char) (part2%10)); part2/=10;
*pos--= (char) ('0'+(char) (part2%10)); part3= (int) (part2 / 10);
*pos--= ':';
*pos--= (char) ('0'+(char) (part3%10)); part3/=10;
*pos--= (char) ('0'+(char) (part3%10)); part3/=10;
*pos--= ':';
*pos--= (char) ('0'+(char) (part3%10)); part3/=10;
*pos--= (char) ('0'+(char) part3);
*pos--= ' ';
*pos--= (char) ('0'+(char) (part1%10)); part1/=10;
*pos--= (char) ('0'+(char) (part1%10)); part1/=10;
*pos--= '-';
*pos--= (char) ('0'+(char) (part1%10)); part1/=10;
*pos--= (char) ('0'+(char) (part1%10)); part3= (int) (part1/10);
*pos--= '-';
*pos--= (char) ('0'+(char) (part3%10)); part3/=10;
*pos--= (char) ('0'+(char) (part3%10)); part3/=10;
*pos--= (char) ('0'+(char) (part3%10)); part3/=10;
*pos=(char) ('0'+(char) part3);
return val_buffer;
}
bool Field_datetime::get_date(MYSQL_TIME *ltime, uint fuzzydate)
{
longlong tmp=Field_datetime::val_int();
uint32 part1,part2;
part1=(uint32) (tmp/LL(1000000));
part2=(uint32) (tmp - (ulonglong) part1*LL(1000000));
ltime->time_type= MYSQL_TIMESTAMP_DATETIME;
ltime->neg= 0;
ltime->second_part= 0;
ltime->second= (int) (part2%100);
ltime->minute= (int) (part2/100%100);
ltime->hour= (int) (part2/10000);
ltime->day= (int) (part1%100);
ltime->month= (int) (part1/100%100);
ltime->year= (int) (part1/10000);
return (!(fuzzydate & TIME_FUZZY_DATE) && (!ltime->month || !ltime->day)) ? 1 : 0;
}
bool Field_datetime::get_time(MYSQL_TIME *ltime)
{
return Field_datetime::get_date(ltime,0);
}
int Field_datetime::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
longlong a,b;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
a=sint8korr(a_ptr);
b=sint8korr(b_ptr);
}
else
#endif
{
longlongget(a,a_ptr);
longlongget(b,b_ptr);
}
return ((ulonglong) a < (ulonglong) b) ? -1 :
((ulonglong) a > (ulonglong) b) ? 1 : 0;
}
void Field_datetime::sort_string(uchar *to,uint length __attribute__((unused)))
{
#ifdef WORDS_BIGENDIAN
if (!table || !table->s->db_low_byte_first)
{
to[0] = ptr[0];
to[1] = ptr[1];
to[2] = ptr[2];
to[3] = ptr[3];
to[4] = ptr[4];
to[5] = ptr[5];
to[6] = ptr[6];
to[7] = ptr[7];
}
else
#endif
{
to[0] = ptr[7];
to[1] = ptr[6];
to[2] = ptr[5];
to[3] = ptr[4];
to[4] = ptr[3];
to[5] = ptr[2];
to[6] = ptr[1];
to[7] = ptr[0];
}
}
void Field_datetime::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("datetime"));
}
/****************************************************************************
** string type
** A string may be varchar or binary
****************************************************************************/
/*
Report "not well formed" or "cannot convert" error
after storing a character string info a field.
SYNOPSIS
check_string_copy_error()
field - Field
well_formed_error_pos - where not well formed data was first met
cannot_convert_error_pos - where a not-convertable character was first met
end - end of the string
cs - character set of the string
NOTES
As of version 5.0 both cases return the same error:
"Invalid string value: 'xxx' for column 't' at row 1"
Future versions will possibly introduce a new error message:
"Cannot convert character string: 'xxx' for column 't' at row 1"
RETURN
FALSE - If errors didn't happen
TRUE - If an error happened
*/
static bool
check_string_copy_error(Field_str *field,
const char *well_formed_error_pos,
const char *cannot_convert_error_pos,
const char *end,
CHARSET_INFO *cs)
{
const char *pos;
char tmp[32];
if (!(pos= well_formed_error_pos) &&
!(pos= cannot_convert_error_pos))
return FALSE;
convert_to_printable(tmp, sizeof(tmp), pos, (end - pos), cs, 6);
push_warning_printf(field->table->in_use,
field->table->in_use->abort_on_warning ?
MYSQL_ERROR::WARN_LEVEL_ERROR :
MYSQL_ERROR::WARN_LEVEL_WARN,
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
"string", tmp, field->field_name,
(ulong) field->table->in_use->row_count);
return TRUE;
}
/*
Check if we lost any important data and send a truncation error/warning
SYNOPSIS
Field_longstr::report_if_important_data()
pstr - Truncated rest of string
end - End of truncated string
count_spaces - Treat traling spaces as important data
RETURN VALUES
0 - None was truncated (or we don't count cut fields)
2 - Some bytes was truncated
NOTE
Check if we lost any important data (anything in a binary string,
or any non-space in others). If only trailing spaces was lost,
send a truncation note, otherwise send a truncation error.
Silently ignore traling spaces if the count_space parameter is FALSE.
*/
int
Field_longstr::report_if_important_data(const char *pstr, const char *end,
bool count_spaces)
{
if ((pstr < end) && table->in_use->count_cuted_fields)
{
if (test_if_important_data(field_charset, pstr, end))
{
if (table->in_use->abort_on_warning)
set_warning(MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DATA_TOO_LONG, 1);
else
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
return 2;
}
else if (count_spaces)
{ /* If we lost only spaces then produce a NOTE, not a WARNING */
set_warning(MYSQL_ERROR::WARN_LEVEL_NOTE, WARN_DATA_TRUNCATED, 1);
return 2;
}
}
return 0;
}
/* Copy a string and fill with space */
int Field_string::store(const char *from,uint length,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
uint copy_length;
const char *well_formed_error_pos;
const char *cannot_convert_error_pos;
const char *from_end_pos;
/* See the comment for Field_long::store(long long) */
DBUG_ASSERT(table->in_use == current_thd);
copy_length= well_formed_copy_nchars(field_charset,
(char*) ptr, field_length,
cs, from, length,
field_length / field_charset->mbmaxlen,
&well_formed_error_pos,
&cannot_convert_error_pos,
&from_end_pos);
/* Append spaces if the string was shorter than the field. */
if (copy_length < field_length)
field_charset->cset->fill(field_charset,(char*) ptr+copy_length,
field_length-copy_length,
field_charset->pad_char);
if (check_string_copy_error(this, well_formed_error_pos,
cannot_convert_error_pos, from + length, cs))
return 2;
return report_if_important_data(from_end_pos, from + length, FALSE);
}
/**
Store double value in Field_string or Field_varstring.
Pretty prints double number into field_length characters buffer.
@param nr number
*/
int Field_str::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
uint length;
uint local_char_length= field_length / charset()->mbmaxlen;
double anr= fabs(nr);
bool fractional= (anr != floor(anr));
int neg= (nr < 0.0) ? 1 : 0;
uint max_length;
int exp;
uint digits;
uint i;
/* Calculate the exponent from the 'e'-format conversion */
if (anr < 1.0 && anr > 0)
{
for (exp= 0; anr < 1e-100; exp-= 100, anr*= 1e100) ;
for (; anr < 1e-10; exp-= 10, anr*= 1e10) ;
for (i= 1; anr < 1 / log_10[i]; exp--, i++) ;
exp--;
}
else
{
for (exp= 0; anr > 1e100; exp+= 100, anr/= 1e100) ;
for (; anr > 1e10; exp+= 10, anr/= 1e10) ;
for (i= 1; anr > log_10[i]; exp++, i++) ;
}
max_length= local_char_length - neg;
/*
Since in sprintf("%g") precision means the number of significant digits,
calculate the maximum number of significant digits if the 'f'-format
would be used (+1 for decimal point if the number has a fractional part).
*/
digits= max(1, (int) max_length - fractional);
/*
If the exponent is negative, decrease digits by the number of leading zeros
after the decimal point that do not count as significant digits.
*/
if (exp < 0)
digits= max(1, (int) digits + exp);
/*
'e'-format is used only if the exponent is less than -4 or greater than or
equal to the precision. In this case we need to adjust the number of
significant digits to take "e+NN" + decimal point into account (hence -5).
We also have to reserve one additional character if abs(exp) >= 100.
*/
if (exp >= (int) digits || exp < -4)
digits= max(1, (int) (max_length - 5 - (exp >= 100 || exp <= -100)));
/* Limit precision to DBL_DIG to avoid garbage past significant digits */
set_if_smaller(digits, DBL_DIG);
length= (uint) sprintf(buff, "%-.*g", digits, nr);
#ifdef __WIN__
/*
Windows always zero-pads the exponent to 3 digits, we want to remove the
leading 0 to match the sprintf() output on other platforms.
*/
if ((exp >= (int) digits || exp < -4) && exp > -100 && exp < 100)
{
DBUG_ASSERT(length >= 6); /* 1e+NNN */
uint tmp= length - 3;
buff[tmp]= buff[tmp + 1];
tmp++;
buff[tmp]= buff[tmp + 1];
length--;
}
#endif
/*
+1 below is because "precision" in %g above means the
max. number of significant digits, not the output width.
Thus the width can be larger than number of significant digits by 1
(for decimal point)
the test for local_char_length < 5 is for extreme cases,
like inserting 500.0 in char(1)
*/
DBUG_ASSERT(local_char_length < 5 || length <= local_char_length+1);
return store(buff, length, charset());
}
uint Field::is_equal(Create_field *new_field)
{
return (new_field->sql_type == real_type());
}
uint Field_str::is_equal(Create_field *new_field)
{
if (field_flags_are_binary() != new_field->field_flags_are_binary())
return 0;
return ((new_field->sql_type == real_type()) &&
new_field->charset == field_charset &&
new_field->length == max_display_length());
}
int Field_string::store(longlong nr, bool unsigned_val)
{
char buff[64];
int l;
CHARSET_INFO *cs=charset();
l= (cs->cset->longlong10_to_str)(cs,buff,sizeof(buff),
unsigned_val ? 10 : -10, nr);
return Field_string::store(buff,(uint)l,cs);
}
int Field_longstr::store_decimal(const my_decimal *d)
{
char buff[DECIMAL_MAX_STR_LENGTH+1];
String str(buff, sizeof(buff), &my_charset_bin);
my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
return store(str.ptr(), str.length(), str.charset());
}
uint32 Field_longstr::max_data_length() const
{
return field_length + (field_length > 255 ? 2 : 1);
}
double Field_string::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int error;
char *end;
CHARSET_INFO *cs= charset();
double result;
result= my_strntod(cs,(char*) ptr,field_length,&end,&error);
if (!table->in_use->no_errors &&
(error || (field_length != (uint32)(end - (char*) ptr) &&
!check_if_only_end_space(cs, end,
(char*) ptr + field_length))))
{
char buf[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
String tmp(buf, sizeof(buf), cs);
tmp.copy((char*) ptr, field_length, cs);
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_TRUNCATED_WRONG_VALUE,
ER(ER_TRUNCATED_WRONG_VALUE),
"DOUBLE", tmp.c_ptr());
}
return result;
}
longlong Field_string::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int error;
char *end;
CHARSET_INFO *cs= charset();
longlong result;
result= my_strntoll(cs, (char*) ptr,field_length,10,&end,&error);
if (!table->in_use->no_errors &&
(error || (field_length != (uint32)(end - (char*) ptr) &&
!check_if_only_end_space(cs, end,
(char*) ptr + field_length))))
{
char buf[LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE];
String tmp(buf, sizeof(buf), cs);
tmp.copy((char*) ptr, field_length, cs);
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_TRUNCATED_WRONG_VALUE,
ER(ER_TRUNCATED_WRONG_VALUE),
"INTEGER", tmp.c_ptr());
}
return result;
}
String *Field_string::val_str(String *val_buffer __attribute__((unused)),
String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
/* See the comment for Field_long::store(long long) */
DBUG_ASSERT(table->in_use == current_thd);
uint length;
if (table->in_use->variables.sql_mode &
MODE_PAD_CHAR_TO_FULL_LENGTH)
length= my_charpos(field_charset, ptr, ptr + field_length,
field_length / field_charset->mbmaxlen);
else
length= field_charset->cset->lengthsp(field_charset, (const char*) ptr,
field_length);
val_ptr->set((const char*) ptr, length, field_charset);
return val_ptr;
}
my_decimal *Field_string::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int err= str2my_decimal(E_DEC_FATAL_ERROR, (char*) ptr, field_length,
charset(), decimal_value);
if (!table->in_use->no_errors && err)
{
char buf[DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE];
CHARSET_INFO *cs= charset();
String tmp(buf, sizeof(buf), cs);
tmp.copy((char*) ptr, field_length, cs);
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_TRUNCATED_WRONG_VALUE,
ER(ER_TRUNCATED_WRONG_VALUE),
"DECIMAL", tmp.c_ptr());
}
return decimal_value;
}
struct Check_field_param {
Field *field;
};
#ifdef HAVE_REPLICATION
static bool
check_field_for_37426(const void *param_arg)
{
Check_field_param *param= (Check_field_param*) param_arg;
DBUG_ASSERT(param->field->real_type() == MYSQL_TYPE_STRING);
DBUG_PRINT("debug", ("Field %s - type: %d, size: %d",
param->field->field_name,
param->field->real_type(),
param->field->row_pack_length()));
return param->field->row_pack_length() > 255;
}
#endif
int Field_string::compatible_field_size(uint field_metadata,
const Relay_log_info *rli_arg,
uint16 mflags __attribute__((unused)))
{
#ifdef HAVE_REPLICATION
const Check_field_param check_param = { this };
if (rpl_master_has_bug(rli_arg, 37426, TRUE,
check_field_for_37426, &check_param))
return FALSE; // Not compatible field sizes
#endif
return Field::compatible_field_size(field_metadata, rli_arg, mflags);
}
int Field_string::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
uint a_len, b_len;
if (field_charset->mbmaxlen != 1)
{
uint char_len= field_length/field_charset->mbmaxlen;
a_len= my_charpos(field_charset, a_ptr, a_ptr + field_length, char_len);
b_len= my_charpos(field_charset, b_ptr, b_ptr + field_length, char_len);
}
else
a_len= b_len= field_length;
/*
We have to remove end space to be able to compare multi-byte-characters
like in latin_de 'ae' and 0xe4
*/
return field_charset->coll->strnncollsp(field_charset,
a_ptr, a_len,
b_ptr, b_len,
0);
}
void Field_string::sort_string(uchar *to,uint length)
{
IF_DBUG(uint tmp=) my_strnxfrm(field_charset,
to, length,
ptr, field_length);
DBUG_ASSERT(tmp == length);
}
void Field_string::sql_type(String &res) const
{
THD *thd= table->in_use;
CHARSET_INFO *cs=res.charset();
ulong length;
length= cs->cset->snprintf(cs,(char*) res.ptr(),
res.alloced_length(), "%s(%d)",
((type() == MYSQL_TYPE_VAR_STRING &&
!thd->variables.new_mode) ?
(has_charset() ? "varchar" : "varbinary") :
(has_charset() ? "char" : "binary")),
(int) field_length / charset()->mbmaxlen);
res.length(length);
if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
has_charset() && (charset()->state & MY_CS_BINSORT))
res.append(STRING_WITH_LEN(" binary"));
}
uchar *Field_string::pack(uchar *to, const uchar *from,
uint max_length,
bool low_byte_first __attribute__((unused)))
{
uint length= min(field_length,max_length);
uint local_char_length= max_length/field_charset->mbmaxlen;
if (length > local_char_length)
local_char_length= my_charpos(field_charset, from, from+length,
local_char_length);
set_if_smaller(length, local_char_length);
while (length && from[length-1] == field_charset->pad_char)
length--;
// Length always stored little-endian
*to++= (uchar) length;
if (field_length > 255)
*to++= (uchar) (length >> 8);
// Store the actual bytes of the string
memcpy(to, from, length);
return to+length;
}
/**
Unpack a string field from row data.
This method is used to unpack a string field from a master whose size
of the field is less than that of the slave. Note that there can be a
variety of field types represented with this class. Certain types like
ENUM or SET are processed differently. Hence, the upper byte of the
@c param_data argument contains the result of field->real_type() from
the master.
@note For information about how the length is packed, see @c
Field_string::do_save_field_metadata
@param to Destination of the data
@param from Source of the data
@param param_data Real type (upper) and length (lower) values
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field_string::unpack(uchar *to,
const uchar *from,
uint param_data,
bool low_byte_first __attribute__((unused)))
{
uint from_length, length;
/*
Compute the declared length of the field on the master. This is
used to decide if one or two bytes should be read as length.
*/
if (param_data)
from_length= (((param_data >> 4) & 0x300) ^ 0x300) + (param_data & 0x00ff);
else
from_length= field_length;
DBUG_PRINT("debug",
("param_data: 0x%x, field_length: %u, from_length: %u",
param_data, field_length, from_length));
/*
Compute the actual length of the data by reading one or two bits
(depending on the declared field length on the master).
*/
if (from_length > 255)
{
length= uint2korr(from);
from+= 2;
}
else
length= (uint) *from++;
memcpy(to, from, length);
// Pad the string with the pad character of the fields charset
bfill(to + length, field_length - length, field_charset->pad_char);
return from+length;
}
/**
Save the field metadata for string fields.
Saves the real type in the first byte and the field length in the
second byte of the field metadata array at index of *metadata_ptr and
*(metadata_ptr + 1).
@note In order to be able to handle lengths exceeding 255 and be
backwards-compatible with pre-5.1.26 servers, an extra two bits of
the length has been added to the metadata in such a way that if
they are set, a new unrecognized type is generated. This will
cause pre-5.1-26 servers to stop due to a field type mismatch,
while new servers will be able to extract the extra bits. If the
length is <256, there will be no difference and both a new and an
old server will be able to handle it.
@note The extra two bits are added to bits 13 and 14 of the
parameter data (with 1 being the least siginficant bit and 16 the
most significant bit of the word) by xoring the extra length bits
with the real type. Since all allowable types have 0xF as most
significant bits of the metadata word, lengths <256 will not affect
the real type at all, while all other values will result in a
non-existant type in the range 17-244.
@see Field_string::unpack
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_string::do_save_field_metadata(uchar *metadata_ptr)
{
DBUG_ASSERT(field_length < 1024);
DBUG_ASSERT((real_type() & 0xF0) == 0xF0);
DBUG_PRINT("debug", ("field_length: %u, real_type: %u",
field_length, real_type()));
*metadata_ptr= (real_type() ^ ((field_length & 0x300) >> 4));
*(metadata_ptr + 1)= field_length & 0xFF;
return 2;
}
/*
Compare two packed keys
SYNOPSIS
pack_cmp()
a New key
b Original key
length Key length
insert_or_update 1 if this is an insert or update
RETURN
< 0 a < b
0 a = b
> 0 a > b
*/
int Field_string::pack_cmp(const uchar *a, const uchar *b, uint length,
my_bool insert_or_update)
{
uint a_length, b_length;
if (length > 255)
{
a_length= uint2korr(a);
b_length= uint2korr(b);
a+= 2;
b+= 2;
}
else
{
a_length= (uint) *a++;
b_length= (uint) *b++;
}
return field_charset->coll->strnncollsp(field_charset,
a, a_length,
b, b_length,
insert_or_update);
}
/**
Compare a packed key against row.
@param key Original key
@param length Key length. (May be less than field length)
@param insert_or_update 1 if this is an insert or update
@return
< 0 row < key
@return
0 row = key
@return
> 0 row > key
*/
int Field_string::pack_cmp(const uchar *key, uint length,
my_bool insert_or_update)
{
uint row_length, local_key_length;
uchar *end;
if (length > 255)
{
local_key_length= uint2korr(key);
key+= 2;
}
else
local_key_length= (uint) *key++;
/* Only use 'length' of key, not field_length */
end= ptr + length;
while (end > ptr && end[-1] == ' ')
end--;
row_length= (uint) (end - ptr);
return field_charset->coll->strnncollsp(field_charset,
ptr, row_length,
key, local_key_length,
insert_or_update);
}
uint Field_string::packed_col_length(const uchar *data_ptr, uint length)
{
if (length > 255)
return uint2korr(data_ptr)+2;
return (uint) *data_ptr + 1;
}
uint Field_string::max_packed_col_length(uint max_length)
{
return (max_length > 255 ? 2 : 1)+max_length;
}
uint Field_string::get_key_image(uchar *buff, uint length, imagetype type_arg)
{
uint bytes = my_charpos(field_charset, (char*) ptr,
(char*) ptr + field_length,
length / field_charset->mbmaxlen);
memcpy(buff, ptr, bytes);
if (bytes < length)
field_charset->cset->fill(field_charset, (char*) buff + bytes,
length - bytes, field_charset->pad_char);
return bytes;
}
Field *Field_string::new_field(MEM_ROOT *root, struct st_table *new_table,
bool keep_type)
{
Field *field;
if (type() != MYSQL_TYPE_VAR_STRING || keep_type)
field= Field::new_field(root, new_table, keep_type);
else if ((field= new Field_varstring(field_length, maybe_null(), field_name,
new_table->s, charset())))
{
/*
Old VARCHAR field which should be modified to a VARCHAR on copy
This is done to ensure that ALTER TABLE will convert old VARCHAR fields
to now VARCHAR fields.
*/
field->init(new_table);
/*
Normally orig_table is different from table only if field was created
via ::new_field. Here we alter the type of field, so ::new_field is
not applicable. But we still need to preserve the original field
metadata for the client-server protocol.
*/
field->orig_table= orig_table;
}
return field;
}
/****************************************************************************
VARCHAR type
Data in field->ptr is stored as:
1 or 2 bytes length-prefix-header (from Field_varstring::length_bytes)
data
NOTE:
When VARCHAR is stored in a key (for handler::index_read() etc) it's always
stored with a 2 byte prefix. (Just like blob keys).
Normally length_bytes is calculated as (field_length < 256 : 1 ? 2)
The exception is if there is a prefix key field that is part of a long
VARCHAR, in which case field_length for this may be 1 but the length_bytes
is 2.
****************************************************************************/
const uint Field_varstring::MAX_SIZE= UINT_MAX16;
/**
Save the field metadata for varstring fields.
Saves the field length in the first byte. Note: may consume
2 bytes. Caller must ensure second byte is contiguous with
first byte (e.g. array index 0,1).
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_varstring::do_save_field_metadata(uchar *metadata_ptr)
{
DBUG_ASSERT(field_length <= 65535);
int2store((char*)metadata_ptr, field_length);
return 2;
}
int Field_varstring::store(const char *from,uint length,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
uint copy_length;
const char *well_formed_error_pos;
const char *cannot_convert_error_pos;
const char *from_end_pos;
copy_length= well_formed_copy_nchars(field_charset,
(char*) ptr + length_bytes,
field_length,
cs, from, length,
field_length / field_charset->mbmaxlen,
&well_formed_error_pos,
&cannot_convert_error_pos,
&from_end_pos);
if (length_bytes == 1)
*ptr= (uchar) copy_length;
else
int2store(ptr, copy_length);
if (check_string_copy_error(this, well_formed_error_pos,
cannot_convert_error_pos, from + length, cs))
return 2;
return report_if_important_data(from_end_pos, from + length, TRUE);
}
int Field_varstring::store(longlong nr, bool unsigned_val)
{
char buff[64];
uint length;
length= (uint) (field_charset->cset->longlong10_to_str)(field_charset,
buff,
sizeof(buff),
(unsigned_val ? 10:
-10),
nr);
return Field_varstring::store(buff, length, field_charset);
}
double Field_varstring::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
char *end_not_used;
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
return my_strntod(field_charset, (char*) ptr+length_bytes, length,
&end_not_used, ¬_used);
}
longlong Field_varstring::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
char *end_not_used;
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
return my_strntoll(field_charset, (char*) ptr+length_bytes, length, 10,
&end_not_used, ¬_used);
}
String *Field_varstring::val_str(String *val_buffer __attribute__((unused)),
String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
val_ptr->set((const char*) ptr+length_bytes, length, field_charset);
return val_ptr;
}
my_decimal *Field_varstring::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
str2my_decimal(E_DEC_FATAL_ERROR, (char*) ptr+length_bytes, length,
charset(), decimal_value);
return decimal_value;
}
int Field_varstring::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
uint max_len)
{
uint a_length, b_length;
int diff;
if (length_bytes == 1)
{
a_length= (uint) *a_ptr;
b_length= (uint) *b_ptr;
}
else
{
a_length= uint2korr(a_ptr);
b_length= uint2korr(b_ptr);
}
set_if_smaller(a_length, max_len);
set_if_smaller(b_length, max_len);
diff= field_charset->coll->strnncollsp(field_charset,
a_ptr+
length_bytes,
a_length,
b_ptr+
length_bytes,
b_length,0);
return diff;
}
/**
@note
varstring and blob keys are ALWAYS stored with a 2 byte length prefix
*/
int Field_varstring::key_cmp(const uchar *key_ptr, uint max_key_length)
{
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
uint local_char_length= max_key_length / field_charset->mbmaxlen;
local_char_length= my_charpos(field_charset, ptr + length_bytes,
ptr + length_bytes + length, local_char_length);
set_if_smaller(length, local_char_length);
return field_charset->coll->strnncollsp(field_charset,
ptr + length_bytes,
length,
key_ptr+
HA_KEY_BLOB_LENGTH,
uint2korr(key_ptr), 0);
}
/**
Compare to key segments (always 2 byte length prefix).
@note
This is used only to compare key segments created for index_read().
(keys are created and compared in key.cc)
*/
int Field_varstring::key_cmp(const uchar *a,const uchar *b)
{
return field_charset->coll->strnncollsp(field_charset,
a + HA_KEY_BLOB_LENGTH,
uint2korr(a),
b + HA_KEY_BLOB_LENGTH,
uint2korr(b),
0);
}
void Field_varstring::sort_string(uchar *to,uint length)
{
uint tot_length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
if (field_charset == &my_charset_bin)
{
/* Store length last in high-byte order to sort longer strings first */
if (length_bytes == 1)
to[length-1]= tot_length;
else
mi_int2store(to+length-2, tot_length);
length-= length_bytes;
}
tot_length= my_strnxfrm(field_charset,
to, length, ptr + length_bytes,
tot_length);
DBUG_ASSERT(tot_length == length);
}
enum ha_base_keytype Field_varstring::key_type() const
{
enum ha_base_keytype res;
if (binary())
res= length_bytes == 1 ? HA_KEYTYPE_VARBINARY1 : HA_KEYTYPE_VARBINARY2;
else
res= length_bytes == 1 ? HA_KEYTYPE_VARTEXT1 : HA_KEYTYPE_VARTEXT2;
return res;
}
void Field_varstring::sql_type(String &res) const
{
THD *thd= table->in_use;
CHARSET_INFO *cs=res.charset();
ulong length;
length= cs->cset->snprintf(cs,(char*) res.ptr(),
res.alloced_length(), "%s(%d)",
(has_charset() ? "varchar" : "varbinary"),
(int) field_length / charset()->mbmaxlen);
res.length(length);
if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
has_charset() && (charset()->state & MY_CS_BINSORT))
res.append(STRING_WITH_LEN(" binary"));
}
uint32 Field_varstring::data_length()
{
return length_bytes == 1 ? (uint32) *ptr : uint2korr(ptr);
}
/*
Functions to create a packed row.
Here the number of length bytes are depending on the given max_length
*/
uchar *Field_varstring::pack(uchar *to, const uchar *from,
uint max_length,
bool low_byte_first __attribute__((unused)))
{
uint length= length_bytes == 1 ? (uint) *from : uint2korr(from);
set_if_smaller(max_length, field_length);
if (length > max_length)
length=max_length;
/* Length always stored little-endian */
*to++= length & 0xFF;
if (max_length > 255)
*to++= (length >> 8) & 0xFF;
/* Store bytes of string */
if (length > 0)
memcpy(to, from+length_bytes, length);
return to+length;
}
uchar *
Field_varstring::pack_key(uchar *to, const uchar *key, uint max_length,
bool low_byte_first __attribute__((unused)))
{
uint length= length_bytes == 1 ? (uint) *key : uint2korr(key);
uint local_char_length= ((field_charset->mbmaxlen > 1) ?
max_length/field_charset->mbmaxlen : max_length);
key+= length_bytes;
if (length > local_char_length)
{
local_char_length= my_charpos(field_charset, key, key+length,
local_char_length);
set_if_smaller(length, local_char_length);
}
*to++= (char) (length & 255);
if (max_length > 255)
*to++= (char) (length >> 8);
if (length)
memcpy(to, key, length);
return to+length;
}
/**
Unpack a key into a record buffer.
A VARCHAR key has a maximum size of 64K-1.
In its packed form, the length field is one or two bytes long,
depending on 'max_length'.
@param to Pointer into the record buffer.
@param key Pointer to the packed key.
@param max_length Key length limit from key description.
@return
Pointer to end of 'key' (To the next key part if multi-segment key)
*/
const uchar *
Field_varstring::unpack_key(uchar *to, const uchar *key, uint max_length,
bool low_byte_first __attribute__((unused)))
{
/* get length of the blob key */
uint32 length= *key++;
if (max_length > 255)
length+= (*key++) << 8;
/* put the length into the record buffer */
if (length_bytes == 1)
*ptr= (uchar) length;
else
int2store(ptr, length);
memcpy(ptr + length_bytes, key, length);
return key + length;
}
/**
Create a packed key that will be used for storage in the index tree.
@param to Store packed key segment here
@param from Key segment (as given to index_read())
@param max_length Max length of key
@return
end of key storage
*/
uchar *
Field_varstring::pack_key_from_key_image(uchar *to, const uchar *from, uint max_length,
bool low_byte_first __attribute__((unused)))
{
/* Key length is always stored as 2 bytes */
uint length= uint2korr(from);
if (length > max_length)
length= max_length;
*to++= (char) (length & 255);
if (max_length > 255)
*to++= (char) (length >> 8);
if (length)
memcpy(to, from+HA_KEY_BLOB_LENGTH, length);
return to+length;
}
/**
Unpack a varstring field from row data.
This method is used to unpack a varstring field from a master
whose size of the field is less than that of the slave.
@note
The string length is always packed little-endian.
@param to Destination of the data
@param from Source of the data
@param param_data Length bytes from the master's field data
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field_varstring::unpack(uchar *to, const uchar *from,
uint param_data,
bool low_byte_first __attribute__((unused)))
{
uint length;
uint l_bytes= (param_data && (param_data < field_length)) ?
(param_data <= 255) ? 1 : 2 : length_bytes;
if (l_bytes == 1)
{
to[0]= *from++;
length= to[0];
if (length_bytes == 2)
to[1]= 0;
}
else /* l_bytes == 2 */
{
length= uint2korr(from);
to[0]= *from++;
to[1]= *from++;
}
if (length)
memcpy(to+ length_bytes, from, length);
return from+length;
}
int Field_varstring::pack_cmp(const uchar *a, const uchar *b,
uint key_length_arg,
my_bool insert_or_update)
{
uint a_length, b_length;
if (key_length_arg > 255)
{
a_length=uint2korr(a); a+= 2;
b_length=uint2korr(b); b+= 2;
}
else
{
a_length= (uint) *a++;
b_length= (uint) *b++;
}
return field_charset->coll->strnncollsp(field_charset,
a, a_length,
b, b_length,
insert_or_update);
}
int Field_varstring::pack_cmp(const uchar *b, uint key_length_arg,
my_bool insert_or_update)
{
uchar *a= ptr+ length_bytes;
uint a_length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
uint b_length;
uint local_char_length= ((field_charset->mbmaxlen > 1) ?
key_length_arg / field_charset->mbmaxlen :
key_length_arg);
if (key_length_arg > 255)
{
b_length=uint2korr(b); b+= HA_KEY_BLOB_LENGTH;
}
else
b_length= (uint) *b++;
if (a_length > local_char_length)
{
local_char_length= my_charpos(field_charset, a, a+a_length,
local_char_length);
set_if_smaller(a_length, local_char_length);
}
return field_charset->coll->strnncollsp(field_charset,
a, a_length,
b, b_length,
insert_or_update);
}
uint Field_varstring::packed_col_length(const uchar *data_ptr, uint length)
{
if (length > 255)
return uint2korr(data_ptr)+2;
return (uint) *data_ptr + 1;
}
uint Field_varstring::max_packed_col_length(uint max_length)
{
return (max_length > 255 ? 2 : 1)+max_length;
}
uint Field_varstring::get_key_image(uchar *buff, uint length, imagetype type)
{
uint f_length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
uint local_char_length= length / field_charset->mbmaxlen;
uchar *pos= ptr+length_bytes;
local_char_length= my_charpos(field_charset, pos, pos + f_length,
local_char_length);
set_if_smaller(f_length, local_char_length);
/* Key is always stored with 2 bytes */
int2store(buff,f_length);
memcpy(buff+HA_KEY_BLOB_LENGTH, pos, f_length);
if (f_length < length)
{
/*
Must clear this as we do a memcmp in opt_range.cc to detect
identical keys
*/
bzero(buff+HA_KEY_BLOB_LENGTH+f_length, (length-f_length));
}
return HA_KEY_BLOB_LENGTH+f_length;
}
void Field_varstring::set_key_image(const uchar *buff,uint length)
{
length= uint2korr(buff); // Real length is here
(void) Field_varstring::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
field_charset);
}
int Field_varstring::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
uint32 max_length)
{
uint32 a_length,b_length;
if (length_bytes == 1)
{
a_length= (uint) *a_ptr;
b_length= (uint) *b_ptr;
}
else
{
a_length= uint2korr(a_ptr);
b_length= uint2korr(b_ptr);
}
set_if_smaller(a_length, max_length);
set_if_smaller(b_length, max_length);
if (a_length != b_length)
return 1;
return memcmp(a_ptr+length_bytes, b_ptr+length_bytes, a_length);
}
Field *Field_varstring::new_field(MEM_ROOT *root, struct st_table *new_table,
bool keep_type)
{
Field_varstring *res= (Field_varstring*) Field::new_field(root, new_table,
keep_type);
if (res)
res->length_bytes= length_bytes;
return res;
}
Field *Field_varstring::new_key_field(MEM_ROOT *root,
struct st_table *new_table,
uchar *new_ptr, uchar *new_null_ptr,
uint new_null_bit)
{
Field_varstring *res;
if ((res= (Field_varstring*) Field::new_key_field(root,
new_table,
new_ptr,
new_null_ptr,
new_null_bit)))
{
/* Keys length prefixes are always packed with 2 bytes */
res->length_bytes= 2;
}
return res;
}
uint Field_varstring::is_equal(Create_field *new_field)
{
if (new_field->sql_type == real_type() &&
new_field->charset == field_charset)
{
if (new_field->length == max_display_length())
return IS_EQUAL_YES;
if (new_field->length > max_display_length() &&
((new_field->length <= 255 && max_display_length() <= 255) ||
(new_field->length > 255 && max_display_length() > 255)))
return IS_EQUAL_PACK_LENGTH; // VARCHAR, longer variable length
}
return IS_EQUAL_NO;
}
void Field_varstring::hash(ulong *nr, ulong *nr2)
{
if (is_null())
{
*nr^= (*nr << 1) | 1;
}
else
{
uint len= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
CHARSET_INFO *cs= charset();
cs->coll->hash_sort(cs, ptr + length_bytes, len, nr, nr2);
}
}
/****************************************************************************
** blob type
** A blob is saved as a length and a pointer. The length is stored in the
** packlength slot and may be from 1-4.
****************************************************************************/
Field_blob::Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
enum utype unireg_check_arg, const char *field_name_arg,
TABLE_SHARE *share, uint blob_pack_length,
CHARSET_INFO *cs)
:Field_longstr(ptr_arg, BLOB_PACK_LENGTH_TO_MAX_LENGH(blob_pack_length),
null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg,
cs),
packlength(blob_pack_length)
{
flags|= BLOB_FLAG;
share->blob_fields++;
/* TODO: why do not fill table->s->blob_field array here? */
}
void Field_blob::store_length(uchar *i_ptr,
uint i_packlength,
uint32 i_number,
bool low_byte_first)
{
switch (i_packlength) {
case 1:
i_ptr[0]= (uchar) i_number;
break;
case 2:
#ifdef WORDS_BIGENDIAN
if (low_byte_first)
{
int2store(i_ptr,(unsigned short) i_number);
}
else
#endif
shortstore(i_ptr,(unsigned short) i_number);
break;
case 3:
int3store(i_ptr,i_number);
break;
case 4:
#ifdef WORDS_BIGENDIAN
if (low_byte_first)
{
int4store(i_ptr,i_number);
}
else
#endif
longstore(i_ptr,i_number);
}
}
uint32 Field_blob::get_length(const uchar *pos, uint packlength_arg, bool low_byte_first)
{
switch (packlength_arg) {
case 1:
return (uint32) pos[0];
case 2:
{
uint16 tmp;
#ifdef WORDS_BIGENDIAN
if (low_byte_first)
tmp=sint2korr(pos);
else
#endif
shortget(tmp,pos);
return (uint32) tmp;
}
case 3:
return (uint32) uint3korr(pos);
case 4:
{
uint32 tmp;
#ifdef WORDS_BIGENDIAN
if (low_byte_first)
tmp=uint4korr(pos);
else
#endif
longget(tmp,pos);
return (uint32) tmp;
}
}
/* When expanding this, see also MAX_FIELD_BLOBLENGTH. */
return 0; // Impossible
}
/**
Put a blob length field into a record buffer.
Depending on the maximum length of a blob, its length field is
put into 1 to 4 bytes. This is a property of the blob object,
described by 'packlength'.
@param pos Pointer into the record buffer.
@param length The length value to put.
*/
void Field_blob::put_length(uchar *pos, uint32 length)
{
switch (packlength) {
case 1:
*pos= (char) length;
break;
case 2:
int2store(pos, length);
break;
case 3:
int3store(pos, length);
break;
case 4:
int4store(pos, length);
break;
}
}
int Field_blob::store(const char *from,uint length,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
uint copy_length, new_length;
const char *well_formed_error_pos;
const char *cannot_convert_error_pos;
const char *from_end_pos, *tmp;
char buff[STRING_BUFFER_USUAL_SIZE];
String tmpstr(buff,sizeof(buff), &my_charset_bin);
if (!length)
{
bzero(ptr,Field_blob::pack_length());
return 0;
}
/*
If the 'from' address is in the range of the temporary 'value'-
object we need to copy the content to a different location or it will be
invalidated when the 'value'-object is reallocated to make room for
the new character set.
*/
if (from >= value.ptr() && from <= value.ptr()+value.length())
{
/*
If content of the 'from'-address is cached in the 'value'-object
it is possible that the content needs a character conversion.
*/
uint32 dummy_offset;
if (!String::needs_conversion(length, cs, field_charset, &dummy_offset))
{
Field_blob::store_length(length);
bmove(ptr+packlength,(char*) &from,sizeof(char*));
return 0;
}
if (tmpstr.copy(from, length, cs))
goto oom_error;
from= tmpstr.ptr();
}
new_length= min(max_data_length(), field_charset->mbmaxlen * length);
if (value.alloc(new_length))
goto oom_error;
if (f_is_hex_escape(flags))
{
copy_length= my_copy_with_hex_escaping(field_charset,
(char*) value.ptr(), new_length,
from, length);
Field_blob::store_length(copy_length);
tmp= value.ptr();
bmove(ptr + packlength, (uchar*) &tmp, sizeof(char*));
return 0;
}
/*
"length" is OK as "nchars" argument to well_formed_copy_nchars as this
is never used to limit the length of the data. The cut of long data
is done with the new_length value.
*/
copy_length= well_formed_copy_nchars(field_charset,
(char*) value.ptr(), new_length,
cs, from, length,
length,
&well_formed_error_pos,
&cannot_convert_error_pos,
&from_end_pos);
Field_blob::store_length(copy_length);
tmp= value.ptr();
bmove(ptr+packlength,(uchar*) &tmp,sizeof(char*));
if (check_string_copy_error(this, well_formed_error_pos,
cannot_convert_error_pos, from + length, cs))
return 2;
return report_if_important_data(from_end_pos, from + length, TRUE);
oom_error:
/* Fatal OOM error */
bzero(ptr,Field_blob::pack_length());
return -1;
}
int Field_blob::store(double nr)
{
CHARSET_INFO *cs=charset();
value.set_real(nr, 2, cs);
return Field_blob::store(value.ptr(),(uint) value.length(), cs);
}
int Field_blob::store(longlong nr, bool unsigned_val)
{
CHARSET_INFO *cs=charset();
value.set_int(nr, unsigned_val, cs);
return Field_blob::store(value.ptr(), (uint) value.length(), cs);
}
double Field_blob::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
char *end_not_used, *blob;
uint32 length;
CHARSET_INFO *cs;
memcpy_fixed(&blob,ptr+packlength,sizeof(char*));
if (!blob)
return 0.0;
length= get_length(ptr);
cs= charset();
return my_strntod(cs, blob, length, &end_not_used, ¬_used);
}
longlong Field_blob::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
char *blob;
memcpy_fixed(&blob,ptr+packlength,sizeof(char*));
if (!blob)
return 0;
uint32 length=get_length(ptr);
return my_strntoll(charset(),blob,length,10,NULL,¬_used);
}
String *Field_blob::val_str(String *val_buffer __attribute__((unused)),
String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
char *blob;
memcpy_fixed(&blob,ptr+packlength,sizeof(char*));
if (!blob)
val_ptr->set("",0,charset()); // A bit safer than ->length(0)
else
val_ptr->set((const char*) blob,get_length(ptr),charset());
return val_ptr;
}
my_decimal *Field_blob::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
const char *blob;
size_t length;
memcpy_fixed(&blob, ptr+packlength, sizeof(const uchar*));
if (!blob)
{
blob= "";
length= 0;
}
else
length= get_length(ptr);
str2my_decimal(E_DEC_FATAL_ERROR, blob, length, charset(),
decimal_value);
return decimal_value;
}
int Field_blob::cmp(const uchar *a,uint32 a_length, const uchar *b,
uint32 b_length)
{
return field_charset->coll->strnncollsp(field_charset,
a, a_length, b, b_length,
0);
}
int Field_blob::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
uint max_length)
{
uchar *blob1,*blob2;
memcpy_fixed(&blob1,a_ptr+packlength,sizeof(char*));
memcpy_fixed(&blob2,b_ptr+packlength,sizeof(char*));
uint a_len= get_length(a_ptr), b_len= get_length(b_ptr);
set_if_smaller(a_len, max_length);
set_if_smaller(b_len, max_length);
return Field_blob::cmp(blob1,a_len,blob2,b_len);
}
int Field_blob::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
uint32 max_length)
{
char *a,*b;
uint diff;
uint32 a_length,b_length;
memcpy_fixed(&a,a_ptr+packlength,sizeof(char*));
memcpy_fixed(&b,b_ptr+packlength,sizeof(char*));
a_length=get_length(a_ptr);
if (a_length > max_length)
a_length=max_length;
b_length=get_length(b_ptr);
if (b_length > max_length)
b_length=max_length;
diff=memcmp(a,b,min(a_length,b_length));
return diff ? diff : (int) (a_length - b_length);
}
/* The following is used only when comparing a key */
uint Field_blob::get_key_image(uchar *buff,uint length, imagetype type_arg)
{
uint32 blob_length= get_length(ptr);
uchar *blob;
#ifdef HAVE_SPATIAL
if (type_arg == itMBR)
{
const char *dummy;
MBR mbr;
Geometry_buffer buffer;
Geometry *gobj;
const uint image_length= SIZEOF_STORED_DOUBLE*4;
if (blob_length < SRID_SIZE)
{
bzero(buff, image_length);
return image_length;
}
get_ptr(&blob);
gobj= Geometry::construct(&buffer, (char*) blob, blob_length);
if (!gobj || gobj->get_mbr(&mbr, &dummy))
bzero(buff, image_length);
else
{
float8store(buff, mbr.xmin);
float8store(buff+8, mbr.xmax);
float8store(buff+16, mbr.ymin);
float8store(buff+24, mbr.ymax);
}
return image_length;
}
#endif /*HAVE_SPATIAL*/
get_ptr(&blob);
uint local_char_length= length / field_charset->mbmaxlen;
local_char_length= my_charpos(field_charset, blob, blob + blob_length,
local_char_length);
set_if_smaller(blob_length, local_char_length);
if ((uint32) length > blob_length)
{
/*
Must clear this as we do a memcmp in opt_range.cc to detect
identical keys
*/
bzero(buff+HA_KEY_BLOB_LENGTH+blob_length, (length-blob_length));
length=(uint) blob_length;
}
int2store(buff,length);
memcpy(buff+HA_KEY_BLOB_LENGTH, blob, length);
return HA_KEY_BLOB_LENGTH+length;
}
void Field_blob::set_key_image(const uchar *buff,uint length)
{
length= uint2korr(buff);
(void) Field_blob::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
field_charset);
}
int Field_blob::key_cmp(const uchar *key_ptr, uint max_key_length)
{
uchar *blob1;
uint blob_length=get_length(ptr);
memcpy_fixed(&blob1,ptr+packlength,sizeof(char*));
CHARSET_INFO *cs= charset();
uint local_char_length= max_key_length / cs->mbmaxlen;
local_char_length= my_charpos(cs, blob1, blob1+blob_length,
local_char_length);
set_if_smaller(blob_length, local_char_length);
return Field_blob::cmp(blob1, blob_length,
key_ptr+HA_KEY_BLOB_LENGTH,
uint2korr(key_ptr));
}
int Field_blob::key_cmp(const uchar *a,const uchar *b)
{
return Field_blob::cmp(a+HA_KEY_BLOB_LENGTH, uint2korr(a),
b+HA_KEY_BLOB_LENGTH, uint2korr(b));
}
/**
Save the field metadata for blob fields.
Saves the pack length in the first byte of the field metadata array
at index of *metadata_ptr.
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_blob::do_save_field_metadata(uchar *metadata_ptr)
{
*metadata_ptr= pack_length_no_ptr();
return 1;
}
uint32 Field_blob::sort_length() const
{
return (uint32) (current_thd->variables.max_sort_length +
(field_charset == &my_charset_bin ? 0 : packlength));
}
void Field_blob::sort_string(uchar *to,uint length)
{
uchar *blob;
uint blob_length=get_length();
if (!blob_length)
bzero(to,length);
else
{
if (field_charset == &my_charset_bin)
{
uchar *pos;
/*
Store length of blob last in blob to shorter blobs before longer blobs
*/
length-= packlength;
pos= to+length;
switch (packlength) {
case 1:
*pos= (char) blob_length;
break;
case 2:
mi_int2store(pos, blob_length);
break;
case 3:
mi_int3store(pos, blob_length);
break;
case 4:
mi_int4store(pos, blob_length);
break;
}
}
memcpy_fixed(&blob,ptr+packlength,sizeof(char*));
blob_length=my_strnxfrm(field_charset,
to, length, blob, blob_length);
DBUG_ASSERT(blob_length == length);
}
}
void Field_blob::sql_type(String &res) const
{
const char *str;
uint length;
switch (packlength) {
default: str="tiny"; length=4; break;
case 2: str=""; length=0; break;
case 3: str="medium"; length= 6; break;
case 4: str="long"; length=4; break;
}
res.set_ascii(str,length);
if (charset() == &my_charset_bin)
res.append(STRING_WITH_LEN("blob"));
else
{
res.append(STRING_WITH_LEN("text"));
}
}
uchar *Field_blob::pack(uchar *to, const uchar *from,
uint max_length, bool low_byte_first)
{
DBUG_ENTER("Field_blob::pack");
DBUG_PRINT("enter", ("to: 0x%lx; from: 0x%lx;"
" max_length: %u; low_byte_first: %d",
(ulong) to, (ulong) from,
max_length, low_byte_first));
DBUG_DUMP("record", from, table->s->reclength);
uchar *save= ptr;
ptr= (uchar*) from;
uint32 length=get_length(); // Length of from string
/*
Store max length, which will occupy packlength bytes. If the max
length given is smaller than the actual length of the blob, we
just store the initial bytes of the blob.
*/
store_length(to, packlength, min(length, max_length), low_byte_first);
/*
Store the actual blob data, which will occupy 'length' bytes.
*/
if (length > 0)
{
get_ptr((uchar**) &from);
memcpy(to+packlength, from,length);
}
ptr=save; // Restore org row pointer
DBUG_DUMP("packed", to, packlength + length);
DBUG_RETURN(to+packlength+length);
}
/**
Unpack a blob field from row data.
This method is used to unpack a blob field from a master whose size of
the field is less than that of the slave. Note: This method is included
to satisfy inheritance rules, but is not needed for blob fields. It
simply is used as a pass-through to the original unpack() method for
blob fields.
@param to Destination of the data
@param from Source of the data
@param param_data @c TRUE if base types should be stored in little-
endian format, @c FALSE if native format should
be used.
@return New pointer into memory based on from + length of the data
*/
const uchar *Field_blob::unpack(uchar *to,
const uchar *from,
uint param_data,
bool low_byte_first)
{
DBUG_ENTER("Field_blob::unpack");
DBUG_PRINT("enter", ("to: 0x%lx; from: 0x%lx;"
" param_data: %u; low_byte_first: %d",
(ulong) to, (ulong) from, param_data, low_byte_first));
uint const master_packlength=
param_data > 0 ? param_data & 0xFF : packlength;
uint32 const length= get_length(from, master_packlength, low_byte_first);
DBUG_DUMP("packed", from, length + master_packlength);
bitmap_set_bit(table->write_set, field_index);
store(reinterpret_cast<const char*>(from) + master_packlength,
length, field_charset);
DBUG_DUMP("record", to, table->s->reclength);
DBUG_RETURN(from + master_packlength + length);
}
/* Keys for blobs are like keys on varchars */
int Field_blob::pack_cmp(const uchar *a, const uchar *b, uint key_length_arg,
my_bool insert_or_update)
{
uint a_length, b_length;
if (key_length_arg > 255)
{
a_length=uint2korr(a); a+=2;
b_length=uint2korr(b); b+=2;
}
else
{
a_length= (uint) *a++;
b_length= (uint) *b++;
}
return field_charset->coll->strnncollsp(field_charset,
a, a_length,
b, b_length,
insert_or_update);
}
int Field_blob::pack_cmp(const uchar *b, uint key_length_arg,
my_bool insert_or_update)
{
uchar *a;
uint a_length, b_length;
memcpy_fixed(&a,ptr+packlength,sizeof(char*));
if (!a)
return key_length_arg > 0 ? -1 : 0;
a_length= get_length(ptr);
if (key_length_arg > 255)
{
b_length= uint2korr(b); b+=2;
}
else
b_length= (uint) *b++;
return field_charset->coll->strnncollsp(field_charset,
a, a_length,
b, b_length,
insert_or_update);
}
/** Create a packed key that will be used for storage from a MySQL row. */
uchar *
Field_blob::pack_key(uchar *to, const uchar *from, uint max_length,
bool low_byte_first __attribute__((unused)))
{
uchar *save= ptr;
ptr= (uchar*) from;
uint32 length=get_length(); // Length of from string
uint local_char_length= ((field_charset->mbmaxlen > 1) ?
max_length/field_charset->mbmaxlen : max_length);
if (length)
get_ptr((uchar**) &from);
if (length > local_char_length)
local_char_length= my_charpos(field_charset, from, from+length,
local_char_length);
set_if_smaller(length, local_char_length);
*to++= (uchar) length;
if (max_length > 255) // 2 byte length
*to++= (uchar) (length >> 8);
memcpy(to, from, length);
ptr=save; // Restore org row pointer
return to+length;
}
/**
Unpack a blob key into a record buffer.
A blob key has a maximum size of 64K-1.
In its packed form, the length field is one or two bytes long,
depending on 'max_length'.
Depending on the maximum length of a blob, its length field is
put into 1 to 4 bytes. This is a property of the blob object,
described by 'packlength'.
Blobs are internally stored apart from the record buffer, which
contains a pointer to the blob buffer.
@param to Pointer into the record buffer.
@param from Pointer to the packed key.
@param max_length Key length limit from key description.
@return
Pointer into 'from' past the last byte copied from packed key.
*/
const uchar *
Field_blob::unpack_key(uchar *to, const uchar *from, uint max_length,
bool low_byte_first __attribute__((unused)))
{
/* get length of the blob key */
uint32 length= *from++;
if (max_length > 255)
length+= *from++ << 8;
/* put the length into the record buffer */
put_length(to, length);
/* put the address of the blob buffer or NULL */
if (length)
memcpy_fixed(to + packlength, &from, sizeof(from));
else
bzero(to + packlength, sizeof(from));
/* point to first byte of next field in 'from' */
return from + length;
}
/** Create a packed key that will be used for storage from a MySQL key. */
uchar *
Field_blob::pack_key_from_key_image(uchar *to, const uchar *from, uint max_length,
bool low_byte_first __attribute__((unused)))
{
uint length=uint2korr(from);
if (length > max_length)
length=max_length;
*to++= (char) (length & 255);
if (max_length > 255)
*to++= (char) (length >> 8);
if (length)
memcpy(to, from+HA_KEY_BLOB_LENGTH, length);
return to+length;
}
uint Field_blob::packed_col_length(const uchar *data_ptr, uint length)
{
if (length > 255)
return uint2korr(data_ptr)+2;
return (uint) *data_ptr + 1;
}
uint Field_blob::max_packed_col_length(uint max_length)
{
return (max_length > 255 ? 2 : 1)+max_length;
}
uint Field_blob::is_equal(Create_field *new_field)
{
if (field_flags_are_binary() != new_field->field_flags_are_binary())
return 0;
return ((new_field->sql_type == get_blob_type_from_length(max_data_length()))
&& new_field->charset == field_charset &&
new_field->pack_length == pack_length());
}
#ifdef HAVE_SPATIAL
void Field_geom::sql_type(String &res) const
{
CHARSET_INFO *cs= &my_charset_latin1;
switch (geom_type)
{
case GEOM_POINT:
res.set(STRING_WITH_LEN("point"), cs);
break;
case GEOM_LINESTRING:
res.set(STRING_WITH_LEN("linestring"), cs);
break;
case GEOM_POLYGON:
res.set(STRING_WITH_LEN("polygon"), cs);
break;
case GEOM_MULTIPOINT:
res.set(STRING_WITH_LEN("multipoint"), cs);
break;
case GEOM_MULTILINESTRING:
res.set(STRING_WITH_LEN("multilinestring"), cs);
break;
case GEOM_MULTIPOLYGON:
res.set(STRING_WITH_LEN("multipolygon"), cs);
break;
case GEOM_GEOMETRYCOLLECTION:
res.set(STRING_WITH_LEN("geometrycollection"), cs);
break;
default:
res.set(STRING_WITH_LEN("geometry"), cs);
}
}
int Field_geom::store(double nr)
{
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
return -1;
}
int Field_geom::store(longlong nr, bool unsigned_val)
{
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
return -1;
}
int Field_geom::store_decimal(const my_decimal *)
{
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
return -1;
}
int Field_geom::store(const char *from, uint length, CHARSET_INFO *cs)
{
if (!length)
bzero(ptr, Field_blob::pack_length());
else
{
if (from == Geometry::bad_geometry_data.ptr())
goto err;
// Check given WKB
uint32 wkb_type;
if (length < SRID_SIZE + WKB_HEADER_SIZE + SIZEOF_STORED_DOUBLE*2)
goto err;
wkb_type= uint4korr(from + SRID_SIZE + 1);
if (wkb_type < (uint32) Geometry::wkb_point ||
wkb_type > (uint32) Geometry::wkb_last)
goto err;
Field_blob::store_length(length);
if (table->copy_blobs || length <= MAX_FIELD_WIDTH)
{ // Must make a copy
value.copy(from, length, cs);
from= value.ptr();
}
bmove(ptr + packlength, (char*) &from, sizeof(char*));
}
return 0;
err:
bzero(ptr, Field_blob::pack_length());
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
return -1;
}
#endif /*HAVE_SPATIAL*/
/****************************************************************************
** enum type.
** This is a string which only can have a selection of different values.
** If one uses this string in a number context one gets the type number.
****************************************************************************/
enum ha_base_keytype Field_enum::key_type() const
{
switch (packlength) {
default: return HA_KEYTYPE_BINARY;
case 2: return HA_KEYTYPE_USHORT_INT;
case 3: return HA_KEYTYPE_UINT24;
case 4: return HA_KEYTYPE_ULONG_INT;
case 8: return HA_KEYTYPE_ULONGLONG;
}
}
void Field_enum::store_type(ulonglong value)
{
switch (packlength) {
case 1: ptr[0]= (uchar) value; break;
case 2:
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int2store(ptr,(unsigned short) value);
}
else
#endif
shortstore(ptr,(unsigned short) value);
break;
case 3: int3store(ptr,(long) value); break;
case 4:
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int4store(ptr,value);
}
else
#endif
longstore(ptr,(long) value);
break;
case 8:
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int8store(ptr,value);
}
else
#endif
longlongstore(ptr,value); break;
}
}
/**
@note
Storing a empty string in a enum field gives a warning
(if there isn't a empty value in the enum)
*/
int Field_enum::store(const char *from,uint length,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int err= 0;
uint32 not_used;
char buff[STRING_BUFFER_USUAL_SIZE];
String tmpstr(buff,sizeof(buff), &my_charset_bin);
/* Convert character set if necessary */
if (String::needs_conversion(length, cs, field_charset, ¬_used))
{
uint dummy_errors;
tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
from= tmpstr.ptr();
length= tmpstr.length();
}
/* Remove end space */
length= field_charset->cset->lengthsp(field_charset, from, length);
uint tmp=find_type2(typelib, from, length, field_charset);
if (!tmp)
{
if (length < 6) // Can't be more than 99999 enums
{
/* This is for reading numbers with LOAD DATA INFILE */
char *end;
tmp=(uint) my_strntoul(cs,from,length,10,&end,&err);
if (err || end != from+length || tmp > typelib->count)
{
tmp=0;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
}
if (!table->in_use->count_cuted_fields)
err= 0;
}
else
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
}
store_type((ulonglong) tmp);
return err;
}
int Field_enum::store(double nr)
{
return Field_enum::store((longlong) nr, FALSE);
}
int Field_enum::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
if ((ulonglong) nr > typelib->count || nr == 0)
{
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
if (nr != 0 || table->in_use->count_cuted_fields)
{
nr= 0;
error= 1;
}
}
store_type((ulonglong) (uint) nr);
return error;
}
double Field_enum::val_real(void)
{
return (double) Field_enum::val_int();
}
longlong Field_enum::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
switch (packlength) {
case 1:
return (longlong) ptr[0];
case 2:
{
uint16 tmp;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
tmp=sint2korr(ptr);
else
#endif
shortget(tmp,ptr);
return (longlong) tmp;
}
case 3:
return (longlong) uint3korr(ptr);
case 4:
{
uint32 tmp;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
tmp=uint4korr(ptr);
else
#endif
longget(tmp,ptr);
return (longlong) tmp;
}
case 8:
{
longlong tmp;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
tmp=sint8korr(ptr);
else
#endif
longlongget(tmp,ptr);
return tmp;
}
}
return 0; // impossible
}
/**
Save the field metadata for enum fields.
Saves the real type in the first byte and the pack length in the
second byte of the field metadata array at index of *metadata_ptr and
*(metadata_ptr + 1).
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_enum::do_save_field_metadata(uchar *metadata_ptr)
{
*metadata_ptr= real_type();
*(metadata_ptr + 1)= pack_length();
return 2;
}
String *Field_enum::val_str(String *val_buffer __attribute__((unused)),
String *val_ptr)
{
uint tmp=(uint) Field_enum::val_int();
if (!tmp || tmp > typelib->count)
val_ptr->set("", 0, field_charset);
else
val_ptr->set((const char*) typelib->type_names[tmp-1],
typelib->type_lengths[tmp-1],
field_charset);
return val_ptr;
}
int Field_enum::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
uchar *old= ptr;
ptr= (uchar*) a_ptr;
ulonglong a=Field_enum::val_int();
ptr= (uchar*) b_ptr;
ulonglong b=Field_enum::val_int();
ptr= old;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_enum::sort_string(uchar *to,uint length __attribute__((unused)))
{
ulonglong value=Field_enum::val_int();
to+=packlength-1;
for (uint i=0 ; i < packlength ; i++)
{
*to-- = (uchar) (value & 255);
value>>=8;
}
}
void Field_enum::sql_type(String &res) const
{
char buffer[255];
String enum_item(buffer, sizeof(buffer), res.charset());
res.length(0);
res.append(STRING_WITH_LEN("enum("));
bool flag=0;
uint *len= typelib->type_lengths;
for (const char **pos= typelib->type_names; *pos; pos++, len++)
{
uint dummy_errors;
if (flag)
res.append(',');
/* convert to res.charset() == utf8, then quote */
enum_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
append_unescaped(&res, enum_item.ptr(), enum_item.length());
flag= 1;
}
res.append(')');
}
Field *Field_enum::new_field(MEM_ROOT *root, struct st_table *new_table,
bool keep_type)
{
Field_enum *res= (Field_enum*) Field::new_field(root, new_table, keep_type);
if (res)
res->typelib= copy_typelib(root, typelib);
return res;
}
/*
set type.
This is a string which can have a collection of different values.
Each string value is separated with a ','.
For example "One,two,five"
If one uses this string in a number context one gets the bits as a longlong
number.
*/
int Field_set::store(const char *from,uint length,CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
bool got_warning= 0;
int err= 0;
char *not_used;
uint not_used2;
uint32 not_used_offset;
char buff[STRING_BUFFER_USUAL_SIZE];
String tmpstr(buff,sizeof(buff), &my_charset_bin);
/* Convert character set if necessary */
if (String::needs_conversion(length, cs, field_charset, ¬_used_offset))
{
uint dummy_errors;
tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
from= tmpstr.ptr();
length= tmpstr.length();
}
ulonglong tmp= find_set(typelib, from, length, field_charset,
¬_used, ¬_used2, &got_warning);
if (!tmp && length && length < 22)
{
/* This is for reading numbers with LOAD DATA INFILE */
char *end;
tmp=my_strntoull(cs,from,length,10,&end,&err);
if (err || end != from+length ||
tmp > (ulonglong) (((longlong) 1 << typelib->count) - (longlong) 1))
{
tmp=0;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
}
}
else if (got_warning)
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
store_type(tmp);
return err;
}
int Field_set::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int error= 0;
ulonglong max_nr;
if (sizeof(ulonglong)*8 <= typelib->count)
max_nr= ULONGLONG_MAX;
else
max_nr= (ULL(1) << typelib->count) - 1;
if ((ulonglong) nr > max_nr)
{
nr&= max_nr;
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
error=1;
}
store_type((ulonglong) nr);
return error;
}
String *Field_set::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ulonglong tmp=(ulonglong) Field_enum::val_int();
uint bitnr=0;
val_buffer->length(0);
val_buffer->set_charset(field_charset);
while (tmp && bitnr < (uint) typelib->count)
{
if (tmp & 1)
{
if (val_buffer->length())
val_buffer->append(&field_separator, 1, &my_charset_latin1);
String str(typelib->type_names[bitnr],
typelib->type_lengths[bitnr],
field_charset);
val_buffer->append(str);
}
tmp>>=1;
bitnr++;
}
return val_buffer;
}
void Field_set::sql_type(String &res) const
{
char buffer[255];
String set_item(buffer, sizeof(buffer), res.charset());
res.length(0);
res.append(STRING_WITH_LEN("set("));
bool flag=0;
uint *len= typelib->type_lengths;
for (const char **pos= typelib->type_names; *pos; pos++, len++)
{
uint dummy_errors;
if (flag)
res.append(',');
/* convert to res.charset() == utf8, then quote */
set_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
append_unescaped(&res, set_item.ptr(), set_item.length());
flag= 1;
}
res.append(')');
}
/**
@retval
1 if the fields are equally defined
@retval
0 if the fields are unequally defined
*/
bool Field::eq_def(Field *field)
{
if (real_type() != field->real_type() || charset() != field->charset() ||
pack_length() != field->pack_length())
return 0;
return 1;
}
/**
Compare the first t1::count type names.
@return TRUE if the type names of t1 match those of t2. FALSE otherwise.
*/
static bool compare_type_names(CHARSET_INFO *charset, TYPELIB *t1, TYPELIB *t2)
{
for (uint i= 0; i < t1->count; i++)
if (my_strnncoll(charset,
(const uchar*) t1->type_names[i],
t1->type_lengths[i],
(const uchar*) t2->type_names[i],
t2->type_lengths[i]))
return FALSE;
return TRUE;
}
/**
@return
returns 1 if the fields are equally defined
*/
bool Field_enum::eq_def(Field *field)
{
TYPELIB *values;
if (!Field::eq_def(field))
return FALSE;
values= ((Field_enum*) field)->typelib;
/* Definition must be strictly equal. */
if (typelib->count != values->count)
return FALSE;
return compare_type_names(field_charset, typelib, values);
}
/**
Check whether two fields can be considered 'equal' for table
alteration purposes. Fields are equal if they retain the same
pack length and if new members are added to the end of the list.
@return IS_EQUAL_YES if fields are compatible.
IS_EQUAL_NO otherwise.
*/
uint Field_enum::is_equal(Create_field *new_field)
{
TYPELIB *values= new_field->interval;
/*
The fields are compatible if they have the same flags,
type, charset and have the same underlying length.
*/
if (new_field->field_flags_are_binary() != field_flags_are_binary() ||
new_field->sql_type != real_type() ||
new_field->charset != field_charset ||
new_field->pack_length != pack_length())
return IS_EQUAL_NO;
/*
Changing the definition of an ENUM or SET column by adding a new
enumeration or set members to the end of the list of valid member
values only alters table metadata and not table data.
*/
if (typelib->count > values->count)
return IS_EQUAL_NO;
/* Check whether there are modification before the end. */
if (! compare_type_names(field_charset, typelib, new_field->interval))
return IS_EQUAL_NO;
return IS_EQUAL_YES;
}
/**
@return
returns 1 if the fields are equally defined
*/
bool Field_num::eq_def(Field *field)
{
if (!Field::eq_def(field))
return 0;
Field_num *from_num= (Field_num*) field;
if (unsigned_flag != from_num->unsigned_flag ||
(zerofill && !from_num->zerofill && !zero_pack()) ||
dec != from_num->dec)
return 0;
return 1;
}
/**
Check whether two numeric fields can be considered 'equal' for table
alteration purposes. Fields are equal if they are of the same type
and retain the same pack length.
*/
uint Field_num::is_equal(Create_field *new_field)
{
return ((new_field->sql_type == real_type()) &&
((new_field->flags & UNSIGNED_FLAG) ==
(uint) (flags & UNSIGNED_FLAG)) &&
((new_field->flags & AUTO_INCREMENT_FLAG) ==
(uint) (flags & AUTO_INCREMENT_FLAG)) &&
(new_field->pack_length == pack_length()));
}
/*
Bit field.
We store the first 0 - 6 uneven bits among the null bits
at the start of the record. The rest bytes are stored in
the record itself.
For example:
CREATE TABLE t1 (a int, b bit(17), c bit(21) not null, d bit(8));
We would store data as follows in the record:
Byte Bit
1 7 - reserve for delete
6 - null bit for 'a'
5 - null bit for 'b'
4 - first (high) bit of 'b'
3 - first (high) bit of 'c'
2 - second bit of 'c'
1 - third bit of 'c'
0 - forth bit of 'c'
2 7 - firth bit of 'c'
6 - null bit for 'd'
3 - 6 four bytes for 'a'
7 - 8 two bytes for 'b'
9 - 10 two bytes for 'c'
11 one byte for 'd'
*/
Field_bit::Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg,
enum utype unireg_check_arg, const char *field_name_arg)
: Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg),
bit_ptr(bit_ptr_arg), bit_ofs(bit_ofs_arg), bit_len(len_arg & 7),
bytes_in_rec(len_arg / 8)
{
flags|= UNSIGNED_FLAG;
/*
Ensure that Field::eq() can distinguish between two different bit fields.
(two bit fields that are not null, may have same ptr and null_ptr)
*/
if (!null_ptr_arg)
null_bit= bit_ofs_arg;
}
void Field_bit::hash(ulong *nr, ulong *nr2)
{
if (is_null())
{
*nr^= (*nr << 1) | 1;
}
else
{
CHARSET_INFO *cs= &my_charset_bin;
longlong value= Field_bit::val_int();
uchar tmp[8];
mi_int8store(tmp,value);
cs->coll->hash_sort(cs, tmp, 8, nr, nr2);
}
}
size_t
Field_bit::do_last_null_byte() const
{
/*
Code elsewhere is assuming that bytes are 8 bits, so I'm using
that value instead of the correct one: CHAR_BIT.
REFACTOR SUGGESTION (Matz): Change to use the correct number of
bits. On systems with CHAR_BIT > 8 (not very common), the storage
will lose the extra bits.
*/
DBUG_PRINT("test", ("bit_ofs: %d, bit_len: %d bit_ptr: 0x%lx",
bit_ofs, bit_len, (long) bit_ptr));
uchar *result;
if (bit_len == 0)
result= null_ptr;
else if (bit_ofs + bit_len > 8)
result= bit_ptr + 1;
else
result= bit_ptr;
if (result)
return (size_t) (result - table->record[0]) + 1;
return LAST_NULL_BYTE_UNDEF;
}
Field *Field_bit::new_key_field(MEM_ROOT *root,
struct st_table *new_table,
uchar *new_ptr, uchar *new_null_ptr,
uint new_null_bit)
{
Field_bit *res;
if ((res= (Field_bit*) Field::new_key_field(root, new_table,
new_ptr, new_null_ptr,
new_null_bit)))
{
/* Move bits normally stored in null_pointer to new_ptr */
res->bit_ptr= new_ptr;
res->bit_ofs= 0;
if (bit_len)
res->ptr++; // Store rest of data here
}
return res;
}
uint Field_bit::is_equal(Create_field *new_field)
{
return (new_field->sql_type == real_type() &&
new_field->length == max_display_length());
}
int Field_bit::store(const char *from, uint length, CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int delta;
for (; length && !*from; from++, length--) ; // skip left 0's
delta= bytes_in_rec - length;
if (delta < -1 ||
(delta == -1 && (uchar) *from > ((1 << bit_len) - 1)) ||
(!bit_len && delta < 0))
{
set_rec_bits((1 << bit_len) - 1, bit_ptr, bit_ofs, bit_len);
memset(ptr, 0xff, bytes_in_rec);
if (table->in_use->really_abort_on_warning())
set_warning(MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DATA_TOO_LONG, 1);
else
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
return 1;
}
/* delta is >= -1 here */
if (delta > 0)
{
if (bit_len)
clr_rec_bits(bit_ptr, bit_ofs, bit_len);
bzero(ptr, delta);
memcpy(ptr + delta, from, length);
}
else if (delta == 0)
{
if (bit_len)
clr_rec_bits(bit_ptr, bit_ofs, bit_len);
memcpy(ptr, from, length);
}
else
{
if (bit_len)
{
set_rec_bits((uchar) *from, bit_ptr, bit_ofs, bit_len);
from++;
}
memcpy(ptr, from, bytes_in_rec);
}
return 0;
}
int Field_bit::store(double nr)
{
return Field_bit::store((longlong) nr, FALSE);
}
int Field_bit::store(longlong nr, bool unsigned_val)
{
char buf[8];
mi_int8store(buf, nr);
return store(buf, 8, NULL);
}
int Field_bit::store_decimal(const my_decimal *val)
{
int err= 0;
longlong i= convert_decimal2longlong(val, 1, &err);
return test(err | store(i, TRUE));
}
double Field_bit::val_real(void)
{
return (double) Field_bit::val_int();
}
longlong Field_bit::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
ulonglong bits= 0;
if (bit_len)
{
bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
bits<<= (bytes_in_rec * 8);
}
switch (bytes_in_rec) {
case 0: return bits;
case 1: return bits | (ulonglong) ptr[0];
case 2: return bits | mi_uint2korr(ptr);
case 3: return bits | mi_uint3korr(ptr);
case 4: return bits | mi_uint4korr(ptr);
case 5: return bits | mi_uint5korr(ptr);
case 6: return bits | mi_uint6korr(ptr);
case 7: return bits | mi_uint7korr(ptr);
default: return mi_uint8korr(ptr + bytes_in_rec - sizeof(longlong));
}
}
String *Field_bit::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
char buff[sizeof(longlong)];
uint length= min(pack_length(), sizeof(longlong));
ulonglong bits= val_int();
mi_int8store(buff,bits);
val_buffer->alloc(length);
memcpy_fixed((char*) val_buffer->ptr(), buff+8-length, length);
val_buffer->length(length);
val_buffer->set_charset(&my_charset_bin);
return val_buffer;
}
my_decimal *Field_bit::val_decimal(my_decimal *deciaml_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 1, deciaml_value);
return deciaml_value;
}
/*
Compare two bit fields using pointers within the record.
SYNOPSIS
cmp_max()
a Pointer to field->ptr in first record
b Pointer to field->ptr in second record
max_len Maximum length used in index
DESCRIPTION
This method is used from key_rec_cmp used by merge sorts used
by partitioned index read and later other similar places.
The a and b pointer must be pointers to the field in a record
(not the table->record[0] necessarily)
*/
int Field_bit::cmp_max(const uchar *a, const uchar *b, uint max_len)
{
my_ptrdiff_t a_diff= a - ptr;
my_ptrdiff_t b_diff= b - ptr;
if (bit_len)
{
int flag;
uchar bits_a= get_rec_bits(bit_ptr+a_diff, bit_ofs, bit_len);
uchar bits_b= get_rec_bits(bit_ptr+b_diff, bit_ofs, bit_len);
if ((flag= (int) (bits_a - bits_b)))
return flag;
}
return memcmp(a, b, field_length);
}
int Field_bit::key_cmp(const uchar *str, uint length)
{
if (bit_len)
{
int flag;
uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
if ((flag= (int) (bits - *str)))
return flag;
str++;
length--;
}
return memcmp(ptr, str, length);
}
int Field_bit::cmp_offset(uint row_offset)
{
if (bit_len)
{
int flag;
uchar bits_a= get_rec_bits(bit_ptr, bit_ofs, bit_len);
uchar bits_b= get_rec_bits(bit_ptr + row_offset, bit_ofs, bit_len);
if ((flag= (int) (bits_a - bits_b)))
return flag;
}
return memcmp(ptr, ptr + row_offset, bytes_in_rec);
}
uint Field_bit::get_key_image(uchar *buff, uint length, imagetype type_arg)
{
if (bit_len)
{
uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
*buff++= bits;
length--;
}
uint data_length = min(length, bytes_in_rec);
memcpy(buff, ptr, data_length);
return data_length + 1;
}
/**
Save the field metadata for bit fields.
Saves the bit length in the first byte and bytes in record in the
second byte of the field metadata array at index of *metadata_ptr and
*(metadata_ptr + 1).
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_bit::do_save_field_metadata(uchar *metadata_ptr)
{
/*
Since this class and Field_bit_as_char have different ideas of
what should be stored here, we compute the values of the metadata
explicitly using the field_length.
*/
metadata_ptr[0]= field_length % 8;
metadata_ptr[1]= field_length / 8;
return 2;
}
/**
Returns the number of bytes field uses in row-based replication
row packed size.
This method is used in row-based replication to determine the number
of bytes that the field consumes in the row record format. This is
used to skip fields in the master that do not exist on the slave.
@param field_metadata Encoded size in field metadata
@returns The size of the field based on the field metadata.
*/
uint Field_bit::pack_length_from_metadata(uint field_metadata)
{
uint const from_len= (field_metadata >> 8U) & 0x00ff;
uint const from_bit_len= field_metadata & 0x00ff;
uint const source_size= from_len + ((from_bit_len > 0) ? 1 : 0);
return (source_size);
}
/**
Check to see if field size is compatible with destination.
This method is used in row-based replication to verify that the slave's
field size is less than or equal to the master's field size. The
encoded field metadata (from the master or source) is decoded and compared
to the size of this field (the slave or destination).
@param field_metadata Encoded size in field metadata
@retval 0 if this field's size is < the source field's size
@retval 1 if this field's size is >= the source field's size
*/
int Field_bit::compatible_field_size(uint field_metadata,
const Relay_log_info * __attribute__((unused)),
uint16 mflags)
{
uint from_bit_len= 8 * (field_metadata >> 8) + (field_metadata & 0xff);
uint to_bit_len= max_display_length();
/*
If the bit length exact flag is clear, we are dealing with an old
master, so we allow some less strict behaviour if replicating by
moving both bit lengths to an even multiple of 8.
We do this by computing the number of bytes to store the field
instead, and then compare the result.
*/
if (!(mflags & Table_map_log_event::TM_BIT_LEN_EXACT_F)) {
from_bit_len= (from_bit_len + 7) / 8;
to_bit_len= (to_bit_len + 7) / 8;
}
return from_bit_len <= to_bit_len;
}
void Field_bit::sql_type(String &res) const
{
CHARSET_INFO *cs= res.charset();
ulong length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
"bit(%d)", (int) field_length);
res.length((uint) length);
}
uchar *
Field_bit::pack(uchar *to, const uchar *from, uint max_length,
bool low_byte_first __attribute__((unused)))
{
DBUG_ASSERT(max_length > 0);
uint length;
if (bit_len > 0)
{
/*
We have the following:
ptr Points into a field in record R1
from Points to a field in a record R2
bit_ptr Points to the byte (in the null bytes) that holds the
odd bits of R1
from_bitp Points to the byte that holds the odd bits of R2
We have the following:
ptr - bit_ptr = from - from_bitp
We want to isolate 'from_bitp', so this gives:
ptr - bit_ptr - from = - from_bitp
- ptr + bit_ptr + from = from_bitp
bit_ptr + from - ptr = from_bitp
*/
uchar bits= get_rec_bits(bit_ptr + (from - ptr), bit_ofs, bit_len);
*to++= bits;
}
length= min(bytes_in_rec, max_length - (bit_len > 0));
memcpy(to, from, length);
return to + length;
}
/**
Unpack a bit field from row data.
This method is used to unpack a bit field from a master whose size
of the field is less than that of the slave.
@param to Destination of the data
@param from Source of the data
@param param_data Bit length (upper) and length (lower) values
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field_bit::unpack(uchar *to, const uchar *from, uint param_data,
bool low_byte_first __attribute__((unused)))
{
uint const from_len= (param_data >> 8U) & 0x00ff;
uint const from_bit_len= param_data & 0x00ff;
/*
If the parameter data is zero (i.e., undefined), or if the master
and slave have the same sizes, then use the old unpack() method.
*/
if (param_data == 0 ||
((from_bit_len == bit_len) && (from_len == bytes_in_rec)))
{
if (bit_len > 0)
{
/*
set_rec_bits is a macro, don't put the post-increment in the
argument since that might cause strange side-effects.
For the choice of the second argument, see the explanation for
Field_bit::pack().
*/
set_rec_bits(*from, bit_ptr + (to - ptr), bit_ofs, bit_len);
from++;
}
memcpy(to, from, bytes_in_rec);
return from + bytes_in_rec;
}
/*
We are converting a smaller bit field to a larger one here.
To do that, we first need to construct a raw value for the original
bit value stored in the from buffer. Then that needs to be converted
to the larger field then sent to store() for writing to the field.
Lastly the odd bits need to be masked out if the bytes_in_rec > 0.
Otherwise stray bits can cause spurious values.
*/
uint new_len= (field_length + 7) / 8;
char *value= (char *)my_alloca(new_len);
bzero(value, new_len);
uint len= from_len + ((from_bit_len > 0) ? 1 : 0);
memcpy(value + (new_len - len), from, len);
/*
Mask out the unused bits in the partial byte.
TODO: Add code to the master to always mask these bits and remove
the following.
*/
if ((from_bit_len > 0) && (from_len > 0))
value[new_len - len]= value[new_len - len] & ((1U << from_bit_len) - 1);
bitmap_set_bit(table->write_set,field_index);
store(value, new_len, system_charset_info);
my_afree(value);
return from + len;
}
void Field_bit::set_default()
{
if (bit_len > 0)
{
my_ptrdiff_t const offset= table->s->default_values - table->record[0];
uchar bits= get_rec_bits(bit_ptr + offset, bit_ofs, bit_len);
set_rec_bits(bits, bit_ptr, bit_ofs, bit_len);
}
Field::set_default();
}
/*
Bit field support for non-MyISAM tables.
*/
Field_bit_as_char::Field_bit_as_char(uchar *ptr_arg, uint32 len_arg,
uchar *null_ptr_arg, uchar null_bit_arg,
enum utype unireg_check_arg,
const char *field_name_arg)
:Field_bit(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, 0, 0,
unireg_check_arg, field_name_arg)
{
flags|= UNSIGNED_FLAG;
bit_len= 0;
bytes_in_rec= (len_arg + 7) / 8;
}
int Field_bit_as_char::store(const char *from, uint length, CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int delta;
uchar bits= (uchar) (field_length & 7);
for (; length && !*from; from++, length--) ; // skip left 0's
delta= bytes_in_rec - length;
if (delta < 0 ||
(delta == 0 && bits && (uint) (uchar) *from >= (uint) (1 << bits)))
{
memset(ptr, 0xff, bytes_in_rec);
if (bits)
*ptr&= ((1 << bits) - 1); /* set first uchar */
if (table->in_use->really_abort_on_warning())
set_warning(MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DATA_TOO_LONG, 1);
else
set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
return 1;
}
bzero(ptr, delta);
memcpy(ptr + delta, from, length);
return 0;
}
void Field_bit_as_char::sql_type(String &res) const
{
CHARSET_INFO *cs= res.charset();
ulong length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
"bit(%d)", (int) field_length);
res.length((uint) length);
}
/*****************************************************************************
Handling of field and Create_field
*****************************************************************************/
/**
Convert create_field::length from number of characters to number of bytes.
*/
void Create_field::create_length_to_internal_length(void)
{
switch (sql_type) {
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_GEOMETRY:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VARCHAR:
length*= charset->mbmaxlen;
key_length= length;
pack_length= calc_pack_length(sql_type, length);
break;
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
/* Pack_length already calculated in sql_parse.cc */
length*= charset->mbmaxlen;
key_length= pack_length;
break;
case MYSQL_TYPE_BIT:
if (f_bit_as_char(pack_flag))
{
key_length= pack_length= ((length + 7) & ~7) / 8;
}
else
{
pack_length= length / 8;
/* We need one extra byte to store the bits we save among the null bits */
key_length= pack_length + test(length & 7);
}
break;
case MYSQL_TYPE_NEWDECIMAL:
key_length= pack_length=
my_decimal_get_binary_size(my_decimal_length_to_precision(length,
decimals,
flags &
UNSIGNED_FLAG),
decimals);
break;
default:
key_length= pack_length= calc_pack_length(sql_type, length);
break;
}
}
/**
Init for a tmp table field. To be extended if need be.
*/
void Create_field::init_for_tmp_table(enum_field_types sql_type_arg,
uint32 length_arg, uint32 decimals_arg,
bool maybe_null, bool is_unsigned)
{
field_name= "";
sql_type= sql_type_arg;
char_length= length= length_arg;;
unireg_check= Field::NONE;
interval= 0;
charset= &my_charset_bin;
geom_type= Field::GEOM_GEOMETRY;
pack_flag= (FIELDFLAG_NUMBER |
((decimals_arg & FIELDFLAG_MAX_DEC) << FIELDFLAG_DEC_SHIFT) |
(maybe_null ? FIELDFLAG_MAYBE_NULL : 0) |
(is_unsigned ? 0 : FIELDFLAG_DECIMAL));
}
/**
Initialize field definition for create.
@param thd Thread handle
@param fld_name Field name
@param fld_type Field type
@param fld_length Field length
@param fld_decimals Decimal (if any)
@param fld_type_modifier Additional type information
@param fld_default_value Field default value (if any)
@param fld_on_update_value The value of ON UPDATE clause
@param fld_comment Field comment
@param fld_change Field change
@param fld_interval_list Interval list (if any)
@param fld_charset Field charset
@param fld_geom_type Field geometry type (if any)
@retval
FALSE on success
@retval
TRUE on error
*/
bool Create_field::init(THD *thd, char *fld_name, enum_field_types fld_type,
char *fld_length, char *fld_decimals,
uint fld_type_modifier, Item *fld_default_value,
Item *fld_on_update_value, LEX_STRING *fld_comment,
char *fld_change, List<String> *fld_interval_list,
CHARSET_INFO *fld_charset, uint fld_geom_type)
{
uint sign_len, allowed_type_modifier= 0;
ulong max_field_charlength= MAX_FIELD_CHARLENGTH;
DBUG_ENTER("Create_field::init()");
field= 0;
field_name= fld_name;
def= fld_default_value;
flags= fld_type_modifier;
unireg_check= (fld_type_modifier & AUTO_INCREMENT_FLAG ?
Field::NEXT_NUMBER : Field::NONE);
decimals= fld_decimals ? (uint)atoi(fld_decimals) : 0;
if (decimals >= NOT_FIXED_DEC)
{
my_error(ER_TOO_BIG_SCALE, MYF(0), decimals, fld_name,
static_cast<ulong>(NOT_FIXED_DEC - 1));
DBUG_RETURN(TRUE);
}
sql_type= fld_type;
length= 0;
change= fld_change;
interval= 0;
pack_length= key_length= 0;
charset= fld_charset;
geom_type= (Field::geometry_type) fld_geom_type;
interval_list.empty();
comment= *fld_comment;
/*
Set NO_DEFAULT_VALUE_FLAG if this field doesn't have a default value and
it is NOT NULL, not an AUTO_INCREMENT field and not a TIMESTAMP.
*/
if (!fld_default_value && !(fld_type_modifier & AUTO_INCREMENT_FLAG) &&
(fld_type_modifier & NOT_NULL_FLAG) && fld_type != MYSQL_TYPE_TIMESTAMP)
flags|= NO_DEFAULT_VALUE_FLAG;
if (fld_length != NULL)
{
errno= 0;
length= strtoul(fld_length, NULL, 10);
if ((errno != 0) || (length > MAX_FIELD_BLOBLENGTH))
{
my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), fld_name, MAX_FIELD_BLOBLENGTH);
DBUG_RETURN(TRUE);
}
if (length == 0)
fld_length= NULL; /* purecov: inspected */
}
sign_len= fld_type_modifier & UNSIGNED_FLAG ? 0 : 1;
switch (fld_type) {
case MYSQL_TYPE_TINY:
if (!fld_length)
length= MAX_TINYINT_WIDTH+sign_len;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_SHORT:
if (!fld_length)
length= MAX_SMALLINT_WIDTH+sign_len;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_INT24:
if (!fld_length)
length= MAX_MEDIUMINT_WIDTH+sign_len;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_LONG:
if (!fld_length)
length= MAX_INT_WIDTH+sign_len;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_LONGLONG:
if (!fld_length)
length= MAX_BIGINT_WIDTH;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_NULL:
break;
case MYSQL_TYPE_NEWDECIMAL:
my_decimal_trim(&length, &decimals);
if (length > DECIMAL_MAX_PRECISION)
{
my_error(ER_TOO_BIG_PRECISION, MYF(0), static_cast<int>(length),
fld_name, static_cast<ulong>(DECIMAL_MAX_PRECISION));
DBUG_RETURN(TRUE);
}
if (length < decimals)
{
my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
length=
my_decimal_precision_to_length(length, decimals,
fld_type_modifier & UNSIGNED_FLAG);
pack_length=
my_decimal_get_binary_size(length, decimals);
break;
case MYSQL_TYPE_VARCHAR:
/*
Long VARCHAR's are automaticly converted to blobs in mysql_prepare_table
if they don't have a default value
*/
max_field_charlength= MAX_FIELD_VARCHARLENGTH;
break;
case MYSQL_TYPE_STRING:
break;
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_GEOMETRY:
if (fld_default_value)
{
/* Allow empty as default value. */
String str,*res;
res= fld_default_value->val_str(&str);
/*
A default other than '' is always an error, and any non-NULL
specified default is an error in strict mode.
*/
if (res->length() || (thd->variables.sql_mode &
(MODE_STRICT_TRANS_TABLES |
MODE_STRICT_ALL_TABLES)))
{
my_error(ER_BLOB_CANT_HAVE_DEFAULT, MYF(0),
fld_name); /* purecov: inspected */
DBUG_RETURN(TRUE);
}
else
{
/*
Otherwise a default of '' is just a warning.
*/
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_BLOB_CANT_HAVE_DEFAULT,
ER(ER_BLOB_CANT_HAVE_DEFAULT),
fld_name);
}
def= 0;
}
flags|= BLOB_FLAG;
break;
case MYSQL_TYPE_YEAR:
if (!fld_length || length != 2)
length= 4; /* Default length */
flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
break;
case MYSQL_TYPE_FLOAT:
/* change FLOAT(precision) to FLOAT or DOUBLE */
allowed_type_modifier= AUTO_INCREMENT_FLAG;
if (fld_length && !fld_decimals)
{
uint tmp_length= length;
if (tmp_length > PRECISION_FOR_DOUBLE)
{
my_error(ER_WRONG_FIELD_SPEC, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
else if (tmp_length > PRECISION_FOR_FLOAT)
{
sql_type= MYSQL_TYPE_DOUBLE;
length= MAX_DOUBLE_STR_LENGTH;
}
else
length= MAX_FLOAT_STR_LENGTH;
decimals= NOT_FIXED_DEC;
break;
}
if (!fld_length && !fld_decimals)
{
length= MAX_FLOAT_STR_LENGTH;
decimals= NOT_FIXED_DEC;
}
if (length < decimals &&
decimals != NOT_FIXED_DEC)
{
my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
break;
case MYSQL_TYPE_DOUBLE:
allowed_type_modifier= AUTO_INCREMENT_FLAG;
if (!fld_length && !fld_decimals)
{
length= DBL_DIG+7;
decimals= NOT_FIXED_DEC;
}
if (length < decimals &&
decimals != NOT_FIXED_DEC)
{
my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
break;
case MYSQL_TYPE_TIMESTAMP:
if (fld_length == NULL)
{
length= MAX_DATETIME_WIDTH;
}
else if (length != MAX_DATETIME_WIDTH)
{
/*
We support only even TIMESTAMP lengths less or equal than 14
and 19 as length of 4.1 compatible representation. Silently
shrink it to MAX_DATETIME_COMPRESSED_WIDTH.
*/
DBUG_ASSERT(MAX_DATETIME_COMPRESSED_WIDTH < UINT_MAX);
if (length != UINT_MAX) /* avoid overflow; is safe because of min() */
length= ((length+1)/2)*2;
length= min(length, MAX_DATETIME_COMPRESSED_WIDTH);
}
flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
/*
Since we silently rewrite down to MAX_DATETIME_COMPRESSED_WIDTH bytes,
the parser should not raise errors unless bizzarely large.
*/
max_field_charlength= UINT_MAX;
if (fld_default_value)
{
/* Grammar allows only NOW() value for ON UPDATE clause */
if (fld_default_value->type() == Item::FUNC_ITEM &&
((Item_func*)fld_default_value)->functype() == Item_func::NOW_FUNC)
{
unireg_check= (fld_on_update_value ? Field::TIMESTAMP_DNUN_FIELD:
Field::TIMESTAMP_DN_FIELD);
/*
We don't need default value any longer moreover it is dangerous.
Everything handled by unireg_check further.
*/
def= 0;
}
else
unireg_check= (fld_on_update_value ? Field::TIMESTAMP_UN_FIELD:
Field::NONE);
}
else
{
/*
If we have default TIMESTAMP NOT NULL column without explicit DEFAULT
or ON UPDATE values then for the sake of compatiblity we should treat
this column as having DEFAULT NOW() ON UPDATE NOW() (when we don't
have another TIMESTAMP column with auto-set option before this one)
or DEFAULT 0 (in other cases).
So here we are setting TIMESTAMP_OLD_FIELD only temporary, and will
replace this value by TIMESTAMP_DNUN_FIELD or NONE later when
information about all TIMESTAMP fields in table will be availiable.
If we have TIMESTAMP NULL column without explicit DEFAULT value
we treat it as having DEFAULT NULL attribute.
*/
unireg_check= (fld_on_update_value ? Field::TIMESTAMP_UN_FIELD :
(flags & NOT_NULL_FLAG ? Field::TIMESTAMP_OLD_FIELD :
Field::NONE));
}
break;
case MYSQL_TYPE_DATE:
/* Old date type. */
if (protocol_version != PROTOCOL_VERSION-1)
sql_type= MYSQL_TYPE_NEWDATE;
/* fall trough */
case MYSQL_TYPE_NEWDATE:
length= MAX_DATE_WIDTH;
break;
case MYSQL_TYPE_TIME:
length= 10;
break;
case MYSQL_TYPE_DATETIME:
length= MAX_DATETIME_WIDTH;
break;
case MYSQL_TYPE_SET:
{
pack_length= get_set_pack_length(fld_interval_list->elements);
List_iterator<String> it(*fld_interval_list);
String *tmp;
while ((tmp= it++))
interval_list.push_back(tmp);
/*
Set fake length to 1 to pass the below conditions.
Real length will be set in mysql_prepare_table()
when we know the character set of the column
*/
length= 1;
break;
}
case MYSQL_TYPE_ENUM:
{
/* Should be safe. */
pack_length= get_enum_pack_length(fld_interval_list->elements);
List_iterator<String> it(*fld_interval_list);
String *tmp;
while ((tmp= it++))
interval_list.push_back(tmp);
length= 1; /* See comment for MYSQL_TYPE_SET above. */
break;
}
case MYSQL_TYPE_VAR_STRING:
DBUG_ASSERT(0); /* Impossible. */
break;
case MYSQL_TYPE_BIT:
{
if (!fld_length)
length= 1;
if (length > MAX_BIT_FIELD_LENGTH)
{
my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), fld_name,
static_cast<ulong>(MAX_BIT_FIELD_LENGTH));
DBUG_RETURN(TRUE);
}
pack_length= (length + 7) / 8;
break;
}
case MYSQL_TYPE_DECIMAL:
DBUG_ASSERT(0); /* Was obsolete */
}
/* Remember the value of length */
char_length= length;
if (!(flags & BLOB_FLAG) &&
((length > max_field_charlength && fld_type != MYSQL_TYPE_SET &&
fld_type != MYSQL_TYPE_ENUM &&
(fld_type != MYSQL_TYPE_VARCHAR || fld_default_value)) ||
((length == 0) &&
fld_type != MYSQL_TYPE_STRING &&
fld_type != MYSQL_TYPE_VARCHAR && fld_type != MYSQL_TYPE_GEOMETRY)))
{
my_error((fld_type == MYSQL_TYPE_VAR_STRING ||
fld_type == MYSQL_TYPE_VARCHAR ||
fld_type == MYSQL_TYPE_STRING) ? ER_TOO_BIG_FIELDLENGTH :
ER_TOO_BIG_DISPLAYWIDTH,
MYF(0),
fld_name, max_field_charlength); /* purecov: inspected */
DBUG_RETURN(TRUE);
}
fld_type_modifier&= AUTO_INCREMENT_FLAG;
if ((~allowed_type_modifier) & fld_type_modifier)
{
my_error(ER_WRONG_FIELD_SPEC, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
switch (fld_type) {
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_NEWDATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIMESTAMP:
charset= &my_charset_bin;
flags|= BINCMP_FLAG;
default: break;
}
DBUG_RETURN(FALSE); /* success */
}
enum_field_types get_blob_type_from_length(ulong length)
{
enum_field_types type;
if (length < 256)
type= MYSQL_TYPE_TINY_BLOB;
else if (length < 65536)
type= MYSQL_TYPE_BLOB;
else if (length < 256L*256L*256L)
type= MYSQL_TYPE_MEDIUM_BLOB;
else
type= MYSQL_TYPE_LONG_BLOB;
return type;
}
/*
Make a field from the .frm file info
*/
uint32 calc_pack_length(enum_field_types type,uint32 length)
{
switch (type) {
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_DECIMAL: return (length);
case MYSQL_TYPE_VARCHAR: return (length + (length < 256 ? 1: 2));
case MYSQL_TYPE_YEAR:
case MYSQL_TYPE_TINY : return 1;
case MYSQL_TYPE_SHORT : return 2;
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_NEWDATE:
case MYSQL_TYPE_TIME: return 3;
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_LONG : return 4;
case MYSQL_TYPE_FLOAT : return sizeof(float);
case MYSQL_TYPE_DOUBLE: return sizeof(double);
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_LONGLONG: return 8; /* Don't crash if no longlong */
case MYSQL_TYPE_NULL : return 0;
case MYSQL_TYPE_TINY_BLOB: return 1+portable_sizeof_char_ptr;
case MYSQL_TYPE_BLOB: return 2+portable_sizeof_char_ptr;
case MYSQL_TYPE_MEDIUM_BLOB: return 3+portable_sizeof_char_ptr;
case MYSQL_TYPE_LONG_BLOB: return 4+portable_sizeof_char_ptr;
case MYSQL_TYPE_GEOMETRY: return 4+portable_sizeof_char_ptr;
case MYSQL_TYPE_SET:
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_NEWDECIMAL:
abort(); return 0; // This shouldn't happen
case MYSQL_TYPE_BIT: return length / 8;
default:
return 0;
}
}
uint pack_length_to_packflag(uint type)
{
switch (type) {
case 1: return f_settype((uint) MYSQL_TYPE_TINY);
case 2: return f_settype((uint) MYSQL_TYPE_SHORT);
case 3: return f_settype((uint) MYSQL_TYPE_INT24);
case 4: return f_settype((uint) MYSQL_TYPE_LONG);
case 8: return f_settype((uint) MYSQL_TYPE_LONGLONG);
}
return 0; // This shouldn't happen
}
Field *make_field(TABLE_SHARE *share, uchar *ptr, uint32 field_length,
uchar *null_pos, uchar null_bit,
uint pack_flag,
enum_field_types field_type,
CHARSET_INFO *field_charset,
Field::geometry_type geom_type,
Field::utype unireg_check,
TYPELIB *interval,
const char *field_name)
{
uchar *UNINIT_VAR(bit_ptr);
uchar UNINIT_VAR(bit_offset);
if (field_type == MYSQL_TYPE_BIT && !f_bit_as_char(pack_flag))
{
bit_ptr= null_pos;
bit_offset= null_bit;
if (f_maybe_null(pack_flag)) // if null field
{
bit_ptr+= (null_bit == 7); // shift bit_ptr and bit_offset
bit_offset= (bit_offset + 1) & 7;
}
}
if (!f_maybe_null(pack_flag))
{
null_pos=0;
null_bit=0;
}
else
{
null_bit= ((uchar) 1) << null_bit;
}
switch (field_type) {
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_NEWDATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIMESTAMP:
field_charset= &my_charset_bin;
default: break;
}
if (f_is_alpha(pack_flag))
{
if (!f_is_packed(pack_flag))
{
if (field_type == MYSQL_TYPE_STRING ||
field_type == MYSQL_TYPE_DECIMAL || // 3.23 or 4.0 string
field_type == MYSQL_TYPE_VAR_STRING)
return new Field_string(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
field_charset);
if (field_type == MYSQL_TYPE_VARCHAR)
return new Field_varstring(ptr,field_length,
HA_VARCHAR_PACKLENGTH(field_length),
null_pos,null_bit,
unireg_check, field_name,
share,
field_charset);
return 0; // Error
}
uint pack_length=calc_pack_length((enum_field_types)
f_packtype(pack_flag),
field_length);
#ifdef HAVE_SPATIAL
if (f_is_geom(pack_flag))
return new Field_geom(ptr,null_pos,null_bit,
unireg_check, field_name, share,
pack_length, geom_type);
#endif
if (f_is_blob(pack_flag))
return new Field_blob(ptr,null_pos,null_bit,
unireg_check, field_name, share,
pack_length, field_charset);
if (interval)
{
if (f_is_enum(pack_flag))
return new Field_enum(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
pack_length, interval, field_charset);
else
return new Field_set(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
pack_length, interval, field_charset);
}
}
switch (field_type) {
case MYSQL_TYPE_DECIMAL:
return new Field_decimal(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_decimals(pack_flag),
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_NEWDECIMAL:
return new Field_new_decimal(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_decimals(pack_flag),
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_FLOAT:
return new Field_float(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_decimals(pack_flag),
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag)== 0);
case MYSQL_TYPE_DOUBLE:
return new Field_double(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_decimals(pack_flag),
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag)== 0);
case MYSQL_TYPE_TINY:
return new Field_tiny(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_SHORT:
return new Field_short(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_INT24:
return new Field_medium(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_LONG:
return new Field_long(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_LONGLONG:
return new Field_longlong(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_TIMESTAMP:
return new Field_timestamp(ptr,field_length, null_pos, null_bit,
unireg_check, field_name, share,
field_charset);
case MYSQL_TYPE_YEAR:
return new Field_year(ptr,field_length,null_pos,null_bit,
unireg_check, field_name);
case MYSQL_TYPE_DATE:
return new Field_date(ptr,null_pos,null_bit,
unireg_check, field_name, field_charset);
case MYSQL_TYPE_NEWDATE:
return new Field_newdate(ptr,null_pos,null_bit,
unireg_check, field_name, field_charset);
case MYSQL_TYPE_TIME:
return new Field_time(ptr,null_pos,null_bit,
unireg_check, field_name, field_charset);
case MYSQL_TYPE_DATETIME:
return new Field_datetime(ptr,null_pos,null_bit,
unireg_check, field_name, field_charset);
case MYSQL_TYPE_NULL:
return new Field_null(ptr, field_length, unireg_check, field_name,
field_charset);
case MYSQL_TYPE_BIT:
return f_bit_as_char(pack_flag) ?
new Field_bit_as_char(ptr, field_length, null_pos, null_bit,
unireg_check, field_name) :
new Field_bit(ptr, field_length, null_pos, null_bit, bit_ptr,
bit_offset, unireg_check, field_name);
default: // Impossible (Wrong version)
break;
}
return 0;
}
/** Create a field suitable for create of table. */
Create_field::Create_field(Field *old_field,Field *orig_field)
{
field= old_field;
field_name=change=old_field->field_name;
length= old_field->field_length;
flags= old_field->flags;
unireg_check=old_field->unireg_check;
pack_length=old_field->pack_length();
key_length= old_field->key_length();
sql_type= old_field->real_type();
charset= old_field->charset(); // May be NULL ptr
comment= old_field->comment;
decimals= old_field->decimals();
/* Fix if the original table had 4 byte pointer blobs */
if (flags & BLOB_FLAG)
pack_length= (pack_length- old_field->table->s->blob_ptr_size +
portable_sizeof_char_ptr);
switch (sql_type) {
case MYSQL_TYPE_BLOB:
switch (pack_length - portable_sizeof_char_ptr) {
case 1: sql_type= MYSQL_TYPE_TINY_BLOB; break;
case 2: sql_type= MYSQL_TYPE_BLOB; break;
case 3: sql_type= MYSQL_TYPE_MEDIUM_BLOB; break;
default: sql_type= MYSQL_TYPE_LONG_BLOB; break;
}
length/= charset->mbmaxlen;
key_length/= charset->mbmaxlen;
break;
case MYSQL_TYPE_STRING:
/* Change CHAR -> VARCHAR if dynamic record length */
if (old_field->type() == MYSQL_TYPE_VAR_STRING)
sql_type= MYSQL_TYPE_VARCHAR;
/* fall through */
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_VAR_STRING:
/* This is corrected in create_length_to_internal_length */
length= (length+charset->mbmaxlen-1) / charset->mbmaxlen;
break;
#ifdef HAVE_SPATIAL
case MYSQL_TYPE_GEOMETRY:
geom_type= ((Field_geom*)old_field)->geom_type;
break;
#endif
case MYSQL_TYPE_YEAR:
if (length != 4)
{
char buff[sizeof("YEAR()") + MY_INT64_NUM_DECIMAL_DIGITS + 1];
my_snprintf(buff, sizeof(buff), "YEAR(%lu)", length);
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
ER_WARN_DEPRECATED_SYNTAX,
ER(ER_WARN_DEPRECATED_SYNTAX),
buff, "YEAR(4)");
}
break;
default:
break;
}
if (flags & (ENUM_FLAG | SET_FLAG))
interval= ((Field_enum*) old_field)->typelib;
else
interval=0;
def=0;
char_length= length;
if (!(flags & (NO_DEFAULT_VALUE_FLAG | BLOB_FLAG)) &&
old_field->ptr && orig_field &&
(sql_type != MYSQL_TYPE_TIMESTAMP || /* set def only if */
old_field->table->timestamp_field != old_field || /* timestamp field */
unireg_check == Field::TIMESTAMP_UN_FIELD)) /* has default val */
{
char buff[MAX_FIELD_WIDTH];
String tmp(buff,sizeof(buff), charset);
my_ptrdiff_t diff;
/* Get the value from default_values */
diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
orig_field->table->record[0]);
orig_field->move_field_offset(diff); // Points now at default_values
if (!orig_field->is_real_null())
{
char buff[MAX_FIELD_WIDTH], *pos;
String tmp(buff, sizeof(buff), charset), *res;
res= orig_field->val_str(&tmp);
pos= (char*) sql_strmake(res->ptr(), res->length());
def= new Item_string(pos, res->length(), charset);
}
orig_field->move_field_offset(-diff); // Back to record[0]
}
}
/**
maximum possible display length for blob.
@return
length
*/
uint32 Field_blob::max_display_length()
{
switch (packlength)
{
case 1:
return 255 * field_charset->mbmaxlen;
case 2:
return 65535 * field_charset->mbmaxlen;
case 3:
return 16777215 * field_charset->mbmaxlen;
case 4:
return (uint32) 4294967295U;
default:
DBUG_ASSERT(0); // we should never go here
return 0;
}
}
/*****************************************************************************
Warning handling
*****************************************************************************/
/**
Produce warning or note about data saved into field.
@param level - level of message (Note/Warning/Error)
@param code - error code of message to be produced
@param cuted_increment - whenever we should increase cut fields count or not
@note
This function won't produce warning and increase cut fields counter
if count_cuted_fields == CHECK_FIELD_IGNORE for current thread.
if count_cuted_fields == CHECK_FIELD_IGNORE then we ignore notes.
This allows us to avoid notes in optimisation, like convert_constant_item().
@retval
1 if count_cuted_fields == CHECK_FIELD_IGNORE and error level is not NOTE
@retval
0 otherwise
*/
bool
Field::set_warning(MYSQL_ERROR::enum_warning_level level, uint code,
int cuted_increment)
{
/*
If this field was created only for type conversion purposes it
will have table == NULL.
*/
THD *thd= table ? table->in_use : current_thd;
if (thd->count_cuted_fields)
{
thd->cuted_fields+= cuted_increment;
push_warning_printf(thd, level, code, ER(code), field_name,
thd->row_count);
return 0;
}
return level >= MYSQL_ERROR::WARN_LEVEL_WARN;
}
/**
Produce warning or note about datetime string data saved into field.
@param level level of message (Note/Warning/Error)
@param code error code of message to be produced
@param str string value which we tried to save
@param str_length length of string which we tried to save
@param ts_type type of datetime value (datetime/date/time)
@param cuted_increment whenever we should increase cut fields count or not
@note
This function will always produce some warning but won't increase cut
fields counter if count_cuted_fields ==FIELD_CHECK_IGNORE for current
thread.
*/
void
Field::set_datetime_warning(MYSQL_ERROR::enum_warning_level level, uint code,
const char *str, uint str_length,
timestamp_type ts_type, int cuted_increment)
{
THD *thd= table ? table->in_use : current_thd;
if ((thd->really_abort_on_warning() &&
level >= MYSQL_ERROR::WARN_LEVEL_WARN) ||
set_warning(level, code, cuted_increment))
make_truncated_value_warning(thd, level, str, str_length, ts_type,
field_name);
}
/**
Produce warning or note about integer datetime value saved into field.
@param level level of message (Note/Warning/Error)
@param code error code of message to be produced
@param nr numeric value which we tried to save
@param ts_type type of datetime value (datetime/date/time)
@param cuted_increment whenever we should increase cut fields count or not
@note
This function will always produce some warning but won't increase cut
fields counter if count_cuted_fields == FIELD_CHECK_IGNORE for current
thread.
*/
void
Field::set_datetime_warning(MYSQL_ERROR::enum_warning_level level, uint code,
longlong nr, timestamp_type ts_type,
int cuted_increment)
{
THD *thd= table ? table->in_use : current_thd;
if (thd->really_abort_on_warning() ||
set_warning(level, code, cuted_increment))
{
char str_nr[22];
char *str_end= longlong10_to_str(nr, str_nr, -10);
make_truncated_value_warning(thd, level, str_nr, (uint) (str_end - str_nr),
ts_type, field_name);
}
}
/**
Produce warning or note about double datetime data saved into field.
@param level level of message (Note/Warning/Error)
@param code error code of message to be produced
@param nr double value which we tried to save
@param ts_type type of datetime value (datetime/date/time)
@note
This function will always produce some warning but won't increase cut
fields counter if count_cuted_fields == FIELD_CHECK_IGNORE for current
thread.
*/
void
Field::set_datetime_warning(MYSQL_ERROR::enum_warning_level level, uint code,
double nr, timestamp_type ts_type)
{
THD *thd= table ? table->in_use : current_thd;
if (thd->really_abort_on_warning() ||
set_warning(level, code, 1))
{
/* DBL_DIG is enough to print '-[digits].E+###' */
char str_nr[DBL_DIG + 8];
uint str_len= sprintf(str_nr, "%g", nr);
make_truncated_value_warning(thd, level, str_nr, str_len, ts_type,
field_name);
}
}
|
// Copyright 2008-present Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/OpenImageIO/oiio
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <vector>
#include <OpenImageIO/dassert.h>
#include <OpenImageIO/deepdata.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/fmath.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/parallel.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/typedesc.h>
#include "imageio_pvt.h"
#include <boost/thread/tss.hpp>
using boost::thread_specific_ptr;
OIIO_NAMESPACE_BEGIN
using namespace pvt;
class ImageInput::Impl {
public:
// So we can lock this ImageInput for the thread-safe methods.
std::recursive_mutex m_mutex;
// Thread-specific error message for this ImageInput.
thread_specific_ptr<std::string> m_errormessage;
int m_threads = 0;
// The IOProxy object we will use for all I/O operations.
Filesystem::IOProxy* m_io = nullptr;
// The "local" proxy that we will create to use if the user didn't
// supply a proxy for us to use.
std::unique_ptr<Filesystem::IOProxy> m_io_local;
};
void
ImageInput::impl_deleter(Impl* impl)
{
delete impl;
}
void*
ImageInput::operator new(size_t size)
{
return ::operator new(size);
// Note: if we ever need to guarantee alignment, we can change to:
// return aligned_malloc (size, alignment);
}
void
ImageInput::operator delete(void* ptr)
{
ImageInput* in = (ImageInput*)ptr;
::operator delete(in);
// Note: if we ever need to guarantee alignment, we can change to:
// aligned_free (ptr);
}
ImageInput::ImageInput()
: m_impl(new Impl, impl_deleter)
{
}
ImageInput::~ImageInput() {}
// Default implementation of valid_file: try to do a full open. If it
// succeeds, it's the right kind of file. We assume that most plugins
// will override this with something smarter and much less expensive,
// like reading just the first few bytes of the file to check for magic
// numbers.
bool
ImageInput::valid_file(const std::string& filename) const
{
ImageSpec tmpspec;
bool ok = const_cast<ImageInput*>(this)->open(filename, tmpspec);
if (ok)
const_cast<ImageInput*>(this)->close();
return ok;
}
std::unique_ptr<ImageInput>
ImageInput::open(const std::string& filename, const ImageSpec* config,
Filesystem::IOProxy* ioproxy)
{
if (!config) {
// Without config, this is really just a call to create-with-open.
return ImageInput::create(filename, true, nullptr, ioproxy);
}
// With config, create without open, then try to open with config.
auto in = ImageInput::create(filename, false, config, ioproxy);
if (!in)
return in; // create() failed, return the empty ptr
ImageSpec newspec;
if (!in->open(filename, newspec, *config)) {
// The open failed. Transfer the error from 'in' to the global OIIO
// error, delete the ImageInput we allocated, and return NULL.
std::string err = in->geterror();
if (err.size())
OIIO::pvt::errorfmt("{}", err);
in.reset();
}
return in;
}
ImageSpec
ImageInput::spec(int subimage, int miplevel)
{
// This default base class implementation just locks, calls
// seek_subimage, then copies the spec. But ImageInput subclass
// implementations are free to do something more efficient, e.g. if they
// already internally cache all of the subimage specs and thus don't
// need a seek.
ImageSpec ret;
lock_guard lock(*this);
if (seek_subimage(subimage, miplevel))
ret = m_spec;
return ret;
// N.B. single return of named value should guaranteed copy elision.
}
ImageSpec
ImageInput::spec_dimensions(int subimage, int miplevel)
{
// This default base class implementation just locks, calls
// seek_subimage, then copies the spec. But ImageInput subclass
// implementations are free to do something more efficient, e.g. if they
// already internally cache all of the subimage specs and thus don't
// need a seek.
ImageSpec ret;
lock_guard lock(*this);
if (seek_subimage(subimage, miplevel))
ret.copy_dimensions(m_spec);
return ret;
// N.B. single return of named value should guaranteed copy elision.
}
bool
ImageInput::read_scanline(int y, int z, TypeDesc format, void* data,
stride_t xstride)
{
lock_guard lock(*this);
// native_pixel_bytes is the size of a pixel in the FILE, including
// the per-channel format.
stride_t native_pixel_bytes = (stride_t)m_spec.pixel_bytes(true);
// perchanfile is true if the file has different per-channel formats
bool perchanfile = m_spec.channelformats.size();
// native_data is true if the user asking for data in the native format
bool native_data = (format == TypeDesc::UNKNOWN
|| (format == m_spec.format && !perchanfile));
// buffer_pixel_bytes is the size in the buffer
stride_t buffer_pixel_bytes = native_data
? native_pixel_bytes
: format.size() * m_spec.nchannels;
if (native_data && xstride == AutoStride)
xstride = native_pixel_bytes;
else
m_spec.auto_stride(xstride, format, m_spec.nchannels);
// Do the strides indicate that the data area is contiguous?
bool contiguous = (xstride == buffer_pixel_bytes);
// If user's format and strides are set up to accept the native data
// layout, read the scanline directly into the user's buffer.
if (native_data && contiguous)
return read_native_scanline(current_subimage(), current_miplevel(), y,
z, data);
// Complex case -- either changing data type or stride
int scanline_values = m_spec.width * m_spec.nchannels;
unsigned char* buf;
OIIO_ALLOCATE_STACK_OR_HEAP(buf, unsigned char,
m_spec.scanline_bytes(true));
bool ok = read_native_scanline(current_subimage(), current_miplevel(), y, z,
buf);
if (!ok)
return false;
if (m_spec.channelformats.empty()) {
// No per-channel formats -- do the conversion in one shot
ok = contiguous ? convert_types(m_spec.format, buf, format, data,
scanline_values)
: convert_image(m_spec.nchannels, m_spec.width, 1, 1,
buf, m_spec.format, AutoStride,
AutoStride, AutoStride, data, format,
xstride, AutoStride, AutoStride);
} else {
// Per-channel formats -- have to convert/copy channels individually
OIIO_DASSERT(m_spec.channelformats.size() == (size_t)m_spec.nchannels);
size_t offset = 0;
for (int c = 0; ok && c < m_spec.nchannels; ++c) {
TypeDesc chanformat = m_spec.channelformats[c];
ok = convert_image(1 /* channels */, m_spec.width, 1, 1,
buf + offset, chanformat, native_pixel_bytes,
AutoStride, AutoStride,
(char*)data + c * format.size(), format, xstride,
AutoStride, AutoStride);
offset += chanformat.size();
}
}
if (!ok)
errorf("ImageInput::read_scanline : no support for format %s",
m_spec.format);
return ok;
}
bool
ImageInput::read_scanlines(int ybegin, int yend, int z, TypeDesc format,
void* data, stride_t xstride, stride_t ystride)
{
lock_guard lock(*this);
return read_scanlines(current_subimage(), current_miplevel(), ybegin, yend,
z, 0, m_spec.nchannels, format, data, xstride,
ystride);
}
bool
ImageInput::read_scanlines(int ybegin, int yend, int z, int chbegin, int chend,
TypeDesc format, void* data, stride_t xstride,
stride_t ystride)
{
lock_guard lock(*this);
return read_scanlines(current_subimage(), current_miplevel(), ybegin, yend,
z, chbegin, chend, format, data, xstride, ystride);
}
bool
ImageInput::read_scanlines(int subimage, int miplevel, int ybegin, int yend,
int z, int chbegin, int chend, TypeDesc format,
void* data, stride_t xstride, stride_t ystride)
{
ImageSpec spec;
int rps = 0;
{
// We need to lock briefly to retrieve rps from the spec
lock_guard lock(*this);
if (!seek_subimage(subimage, miplevel))
return false;
// Copying the dimensions of the designated subimage/miplevel to a
// local `spec` means that we can release the lock! (Calls to
// read_native_* will internally lock again if necessary.)
spec.copy_dimensions(m_spec);
// For scanline files, we also need one piece of metadata
if (!spec.tile_width)
rps = m_spec.get_int_attribute("tiff:RowsPerStrip", 64);
}
if (spec.image_bytes() < 1) {
errorfmt("Invalid image size {} x {} ({} chans)", m_spec.width,
m_spec.height, m_spec.nchannels);
return false;
}
chend = clamp(chend, chbegin + 1, spec.nchannels);
int nchans = chend - chbegin;
yend = std::min(yend, spec.y + spec.height);
size_t native_pixel_bytes = spec.pixel_bytes(chbegin, chend, true);
imagesize_t native_scanline_bytes
= clamped_mult64((imagesize_t)spec.width,
(imagesize_t)native_pixel_bytes);
bool native = (format == TypeDesc::UNKNOWN);
size_t pixel_bytes = native ? native_pixel_bytes : format.size() * nchans;
if (native && xstride == AutoStride)
xstride = pixel_bytes;
stride_t zstride = AutoStride;
spec.auto_stride(xstride, ystride, zstride, format, nchans, spec.width,
spec.height);
stride_t buffer_pixel_bytes = native ? native_pixel_bytes
: format.size() * nchans;
stride_t buffer_scanline_bytes = native ? native_scanline_bytes
: buffer_pixel_bytes * spec.width;
bool contiguous = (xstride == (stride_t)buffer_pixel_bytes
&& ystride == (stride_t)buffer_scanline_bytes);
if (native && contiguous) {
if (chbegin == 0 && chend == spec.nchannels)
return read_native_scanlines(subimage, miplevel, ybegin, yend, z,
data);
else
return read_native_scanlines(subimage, miplevel, ybegin, yend, z,
chbegin, chend, data);
}
// No such luck. Read scanlines in chunks.
// Split into reasonable chunks -- try to use around 64 MB, but
// round up to a multiple of the TIFF rows per strip (or 64).
int chunk = std::max(1, (1 << 26) / int(spec.scanline_bytes(true)));
chunk = std::max(chunk, int(oiio_read_chunk));
chunk = round_to_multiple(chunk, rps);
std::unique_ptr<char[]> buf(new char[chunk * native_scanline_bytes]);
bool ok = true;
int scanline_values = spec.width * nchans;
for (; ok && ybegin < yend; ybegin += chunk) {
int y1 = std::min(ybegin + chunk, yend);
ok &= read_native_scanlines(subimage, miplevel, ybegin, y1, z, chbegin,
chend, &buf[0]);
if (!ok)
break;
int nscanlines = y1 - ybegin;
int chunkvalues = scanline_values * nscanlines;
if (spec.channelformats.empty()) {
// No per-channel formats -- do the conversion in one shot
if (contiguous) {
ok = convert_types(spec.format, &buf[0], format, data,
chunkvalues);
} else {
ok = parallel_convert_image(nchans, spec.width, nscanlines, 1,
&buf[0], spec.format, AutoStride,
AutoStride, AutoStride, data,
format, xstride, ystride, zstride,
threads());
}
} else {
// Per-channel formats -- have to convert/copy channels individually
size_t offset = 0;
int n = 1;
for (int c = 0; ok && c < nchans; c += n) {
TypeDesc chanformat = spec.channelformats[c + chbegin];
// Try to do more than one channel at a time to improve
// memory coherence, if there are groups of adjacent
// channels needing the same data conversion.
for (n = 1; c + n < nchans; ++n)
if (spec.channelformats[c + chbegin + n] != chanformat)
break;
ok = parallel_convert_image(n /* channels */, spec.width,
nscanlines, 1, &buf[offset],
chanformat, native_pixel_bytes,
AutoStride, AutoStride,
(char*)data + c * format.size(),
format, xstride, ystride, zstride,
threads());
offset += n * chanformat.size();
}
}
if (!ok)
errorf("ImageInput::read_scanlines : no support for format %s",
spec.format);
data = (char*)data + ystride * nscanlines;
}
return ok;
}
bool
ImageInput::read_native_scanlines(int subimage, int miplevel, int ybegin,
int yend, int z, void* data)
{
// Base class implementation of read_native_scanlines just repeatedly
// calls read_native_scanline, which is supplied by every plugin.
// Only the hardcore ones will overload read_native_scanlines with
// their own implementation.
lock_guard lock(*this);
size_t ystride = m_spec.scanline_bytes(true);
yend = std::min(yend, spec().y + spec().height);
for (int y = ybegin; y < yend; ++y) {
bool ok = read_native_scanline(subimage, miplevel, y, z, data);
if (!ok)
return false;
data = (char*)data + ystride;
}
return true;
}
bool
ImageInput::read_native_scanlines(int subimage, int miplevel, int ybegin,
int yend, int z, int chbegin, int chend,
void* data)
{
ImageSpec spec = spec_dimensions(subimage, miplevel); // thread-safe
if (spec.undefined())
return false;
// All-channel case just reduces to the simpler read_native_scanlines.
if (chbegin == 0 && chend >= spec.nchannels)
return read_native_scanlines(subimage, miplevel, ybegin, yend, z, data);
// Base class implementation of read_native_scanlines (with channel
// subset) just calls read_native_scanlines (all channels), and
// copies the appropriate subset.
size_t prefix_bytes = spec.pixel_bytes(0, chbegin, true);
size_t subset_bytes = spec.pixel_bytes(chbegin, chend, true);
size_t subset_ystride = size_t(spec.width) * subset_bytes;
// Read all channels of the scanlines into a temp buffer.
size_t native_pixel_bytes = spec.pixel_bytes(true);
size_t native_ystride = size_t(spec.width) * native_pixel_bytes;
std::unique_ptr<char[]> buf(new char[native_ystride * (yend - ybegin)]);
yend = std::min(yend, spec.y + spec.height);
bool ok = read_native_scanlines(subimage, miplevel, ybegin, yend, z,
buf.get());
if (!ok)
return false;
// Now copy out the subset of channels we want. We can do this in
// parallel.
// clang-format off
parallel_for (0, yend-ybegin,
[&,subset_bytes,prefix_bytes,native_pixel_bytes](int64_t y){
char *b = buf.get() + native_ystride * y;
char *d = (char *)data + subset_ystride * y;
for (int x = 0; x < spec.width; ++x)
memcpy (d + subset_bytes*x,
&b[prefix_bytes+native_pixel_bytes*x], subset_bytes);
});
// clang-format on
return true;
}
bool
ImageInput::read_tile(int x, int y, int z, TypeDesc format, void* data,
stride_t xstride, stride_t ystride, stride_t zstride)
{
lock_guard lock(*this);
if (!m_spec.tile_width || ((x - m_spec.x) % m_spec.tile_width) != 0
|| ((y - m_spec.y) % m_spec.tile_height) != 0
|| ((z - m_spec.z) % m_spec.tile_depth) != 0)
return false; // coordinates are not a tile corner
// native_pixel_bytes is the size of a pixel in the FILE, including
// the per-channel format.
stride_t native_pixel_bytes = (stride_t)m_spec.pixel_bytes(true);
// perchanfile is true if the file has different per-channel formats
bool perchanfile = m_spec.channelformats.size();
// native_data is true if the user asking for data in the native format
bool native_data = (format == TypeDesc::UNKNOWN
|| (format == m_spec.format && !perchanfile));
if (format == TypeDesc::UNKNOWN && xstride == AutoStride)
xstride = native_pixel_bytes;
m_spec.auto_stride(xstride, ystride, zstride, format, m_spec.nchannels,
m_spec.tile_width, m_spec.tile_height);
stride_t buffer_pixel_bytes = native_data
? native_pixel_bytes
: format.size() * m_spec.nchannels;
// Do the strides indicate that the data area is contiguous?
bool contiguous
= xstride == buffer_pixel_bytes
&& (ystride == xstride * m_spec.tile_width
&& (zstride == ystride * m_spec.tile_height || zstride == 0));
// If user's format and strides are set up to accept the native data
// layout, read the tile directly into the user's buffer.
if (native_data && contiguous)
return read_native_tile(current_subimage(), current_miplevel(), x, y, z,
data); // Simple case
// Complex case -- either changing data type or stride
size_t tile_values = (size_t)m_spec.tile_pixels() * m_spec.nchannels;
std::unique_ptr<char[]> buf(new char[m_spec.tile_bytes(true)]);
bool ok = read_native_tile(current_subimage(), current_miplevel(), x, y, z,
&buf[0]);
if (!ok)
return false;
if (m_spec.channelformats.empty()) {
// No per-channel formats -- do the conversion in one shot
ok = contiguous ? convert_types(m_spec.format, &buf[0], format, data,
tile_values)
: convert_image(m_spec.nchannels, m_spec.tile_width,
m_spec.tile_height, m_spec.tile_depth,
&buf[0], m_spec.format, AutoStride,
AutoStride, AutoStride, data, format,
xstride, ystride, zstride);
} else {
// Per-channel formats -- have to convert/copy channels individually
OIIO_DASSERT(m_spec.channelformats.size() == (size_t)m_spec.nchannels);
size_t offset = 0;
for (int c = 0; c < m_spec.nchannels; ++c) {
TypeDesc chanformat = m_spec.channelformats[c];
ok = convert_image(1 /* channels */, m_spec.tile_width,
m_spec.tile_height, m_spec.tile_depth,
&buf[offset], chanformat, native_pixel_bytes,
AutoStride, AutoStride,
(char*)data + c * format.size(), format, xstride,
AutoStride, AutoStride);
offset += chanformat.size();
}
}
if (!ok)
errorf("ImageInput::read_tile : no support for format %s",
m_spec.format);
return ok;
}
bool
ImageInput::read_tiles(int xbegin, int xend, int ybegin, int yend, int zbegin,
int zend, TypeDesc format, void* data, stride_t xstride,
stride_t ystride, stride_t zstride)
{
int subimage, miplevel, chend;
{
lock_guard lock(*this);
subimage = current_subimage();
miplevel = current_miplevel();
chend = spec().nchannels;
}
return read_tiles(subimage, miplevel, xbegin, xend, ybegin, yend, zbegin,
zend, 0, chend, format, data, xstride, ystride, zstride);
}
bool
ImageInput::read_tiles(int xbegin, int xend, int ybegin, int yend, int zbegin,
int zend, int chbegin, int chend, TypeDesc format,
void* data, stride_t xstride, stride_t ystride,
stride_t zstride)
{
int subimage, miplevel;
{
lock_guard lock(*this);
subimage = current_subimage();
miplevel = current_miplevel();
}
return read_tiles(subimage, miplevel, xbegin, xend, ybegin, yend, zbegin,
zend, chbegin, chend, format, data, xstride, ystride,
zstride);
}
bool
ImageInput::read_tiles(int subimage, int miplevel, int xbegin, int xend,
int ybegin, int yend, int zbegin, int zend, int chbegin,
int chend, TypeDesc format, void* data, stride_t xstride,
stride_t ystride, stride_t zstride)
{
ImageSpec spec = spec_dimensions(subimage, miplevel); // thread-safe
if (spec.undefined())
return false;
chend = clamp(chend, chbegin + 1, spec.nchannels);
if (!spec.valid_tile_range(xbegin, xend, ybegin, yend, zbegin, zend))
return false;
int nchans = chend - chbegin;
// native_pixel_bytes is the size of a pixel in the FILE, including
// the per-channel format.
stride_t native_pixel_bytes = (stride_t)spec.pixel_bytes(chbegin, chend,
true);
// perchanfile is true if the file has different per-channel formats
bool perchanfile = spec.channelformats.size();
// native_data is true if the user asking for data in the native format
bool native_data = (format == TypeDesc::UNKNOWN
|| (format == spec.format && !perchanfile));
if (format == TypeDesc::UNKNOWN && xstride == AutoStride)
xstride = native_pixel_bytes;
spec.auto_stride(xstride, ystride, zstride, format, nchans, xend - xbegin,
yend - ybegin);
// Do the strides indicate that the data area is contiguous?
bool contiguous = (native_data && xstride == native_pixel_bytes)
|| (!native_data
&& xstride == (stride_t)spec.pixel_bytes(false));
contiguous
&= (ystride == xstride * (xend - xbegin)
&& (zstride == ystride * (yend - ybegin) || (zend - zbegin) <= 1));
int nxtiles = (xend - xbegin + spec.tile_width - 1) / spec.tile_width;
int nytiles = (yend - ybegin + spec.tile_height - 1) / spec.tile_height;
int nztiles = (zend - zbegin + spec.tile_depth - 1) / spec.tile_depth;
// If user's format and strides are set up to accept the native data
// layout, and we're asking for a whole number of tiles (no partial
// tiles at the edges), then read the tile directly into the user's
// buffer.
if (native_data && contiguous
&& (xend - xbegin) == nxtiles * spec.tile_width
&& (yend - ybegin) == nytiles * spec.tile_height
&& (zend - zbegin) == nztiles * spec.tile_depth) {
if (chbegin == 0 && chend == spec.nchannels)
return read_native_tiles(subimage, miplevel, xbegin, xend, ybegin,
yend, zbegin, zend,
data); // Simple case
else
return read_native_tiles(subimage, miplevel, xbegin, xend, ybegin,
yend, zbegin, zend, chbegin, chend, data);
}
// No such luck. Just punt and read tiles individually.
bool ok = true;
stride_t pixelsize = native_data ? native_pixel_bytes
: (format.size() * nchans);
stride_t native_pixelsize = spec.pixel_bytes(true);
stride_t full_pixelsize = native_data ? native_pixelsize
: (format.size() * spec.nchannels);
stride_t full_tilewidthbytes = full_pixelsize * spec.tile_width;
stride_t full_tilewhbytes = full_tilewidthbytes * spec.tile_height;
stride_t full_tilebytes = full_tilewhbytes * spec.tile_depth;
stride_t full_native_tilebytes = spec.tile_bytes(true);
size_t prefix_bytes = native_data ? spec.pixel_bytes(0, chbegin, true)
: format.size() * chbegin;
bool allchans = (chbegin == 0 && chend == spec.nchannels);
std::vector<char> buf;
for (int z = zbegin; z < zend; z += std::max(1, spec.tile_depth)) {
int zd = std::min(zend - z, spec.tile_depth);
bool full_z = (zd == spec.tile_depth);
for (int y = ybegin; ok && y < yend; y += spec.tile_height) {
char* tilestart = ((char*)data + (z - zbegin) * zstride
+ (y - ybegin) * ystride);
int yh = std::min(yend - y, spec.tile_height);
bool full_y = (yh == spec.tile_height);
int x = xbegin;
// If we're reading full y and z tiles and not doing any funny
// business with channels, try to read as many complete x tiles
// as we can in this row.
int x_full_tiles = (xend - xbegin) / spec.tile_width;
if (full_z && full_y && allchans && !perchanfile
&& x_full_tiles >= 1) {
int x_full_tile_end = xbegin + x_full_tiles * spec.tile_width;
if (buf.size() < size_t(full_native_tilebytes * x_full_tiles))
buf.resize(full_native_tilebytes * x_full_tiles);
ok &= read_native_tiles(subimage, miplevel, xbegin,
x_full_tile_end, y, y + yh, z, z + zd,
chbegin, chend, &buf[0]);
if (ok)
convert_image(nchans, x_full_tiles * spec.tile_width, yh,
zd, &buf[0], spec.format, native_pixelsize,
native_pixelsize * x_full_tiles
* spec.tile_width,
native_pixelsize * x_full_tiles
* spec.tile_width * spec.tile_height,
tilestart, format, xstride, ystride, zstride);
tilestart += x_full_tiles * spec.tile_width * xstride;
x += x_full_tiles * spec.tile_width;
}
// Now get the rest in the row, anything that is only a
// partial tile, which needs extra care.
// Since we are here relying on the non-thread-safe read_tile()
// call, we re-establish the lock and make sure we're on the
// right subimage/miplevel.
for (; ok && x < xend; x += spec.tile_width) {
int xw = std::min(xend - x, spec.tile_width);
bool full_x = (xw == spec.tile_width);
// Full tiles are read directly into the user buffer,
// but partial tiles (such as at the image edge) or
// partial channel subsets are read into a buffer and
// then copied.
if (full_x && full_y && full_z && allchans && !perchanfile) {
// Full tile, either native data or not needing
// per-tile data format conversion.
lock_guard lock(*this);
if (!seek_subimage(subimage, miplevel))
return false;
ok &= read_tile(x, y, z, format, tilestart, xstride,
ystride, zstride);
if (!ok)
return false;
} else {
if (buf.size() < size_t(full_tilebytes))
buf.resize(full_tilebytes);
{
lock_guard lock(*this);
if (!seek_subimage(subimage, miplevel))
return false;
ok &= read_tile(x, y, z, format, &buf[0],
full_pixelsize, full_tilewidthbytes,
full_tilewhbytes);
}
if (ok)
copy_image(nchans, xw, yh, zd, &buf[prefix_bytes],
pixelsize, full_pixelsize,
full_tilewidthbytes, full_tilewhbytes,
tilestart, xstride, ystride, zstride);
// N.B. It looks like read_tiles doesn't handle the
// per-channel data types case fully, but it does!
// The call to read_tile() above handles the case of
// per-channel data types, converting to to desired
// format, so all we have to do on our own is the
// copy_image.
}
tilestart += spec.tile_width * xstride;
}
if (!ok)
break;
}
}
return ok;
}
bool
ImageInput::read_native_tile(int /*subimage*/, int /*miplevel*/, int /*x*/,
int /*y*/, int /*z*/, void* /*data*/)
{
// The base class read_native_tile fails. A format reader that supports
// tiles MUST overload this virtual method that reads a single tile
// (all channels).
return false;
}
bool
ImageInput::read_native_tiles(int subimage, int miplevel, int xbegin, int xend,
int ybegin, int yend, int zbegin, int zend,
void* data)
{
// A format reader that supports reading multiple tiles at once (in
// a way that's more efficient than reading the tiles one at a time)
// is advised (but not required) to overload this virtual method.
// If an ImageInput subclass does not overload this, the default
// implementation here is simply to loop over the tiles, calling the
// single-tile read_native_tile() for each one.
ImageSpec spec = spec_dimensions(subimage, miplevel); // thread-safe
if (spec.undefined())
return false;
if (!spec.valid_tile_range(xbegin, xend, ybegin, yend, zbegin, zend))
return false;
// Base class implementation of read_native_tiles just repeatedly
// calls read_native_tile, which is supplied by every plugin that
// supports tiles. Only the hardcore ones will overload
// read_native_tiles with their own implementation.
stride_t pixel_bytes = (stride_t)spec.pixel_bytes(true);
stride_t tileystride = pixel_bytes * spec.tile_width;
stride_t tilezstride = tileystride * spec.tile_height;
stride_t ystride = (xend - xbegin) * pixel_bytes;
stride_t zstride = (yend - ybegin) * ystride;
std::unique_ptr<char[]> pels(new char[spec.tile_bytes(true)]);
for (int z = zbegin; z < zend; z += spec.tile_depth) {
for (int y = ybegin; y < yend; y += spec.tile_height) {
for (int x = xbegin; x < xend; x += spec.tile_width) {
bool ok = read_native_tile(subimage, miplevel, x, y, z,
&pels[0]);
if (!ok)
return false;
copy_image(spec.nchannels, spec.tile_width, spec.tile_height,
spec.tile_depth, &pels[0], size_t(pixel_bytes),
pixel_bytes, tileystride, tilezstride,
(char*)data + (z - zbegin) * zstride
+ (y - ybegin) * ystride
+ (x - xbegin) * pixel_bytes,
pixel_bytes, ystride, zstride);
}
}
}
return true;
}
bool
ImageInput::read_native_tiles(int subimage, int miplevel, int xbegin, int xend,
int ybegin, int yend, int zbegin, int zend,
int chbegin, int chend, void* data)
{
// A format reader that supports reading multiple tiles at once, and can
// handle a channel subset while doing so, is advised (but not required)
// to overload this virtual method. If an ImageInput subclass does not
// overload this, the default implementation here is simply to loop over
// the tiles, calling the single-tile read_native_tile() for each one
// (and copying carefully to handle the channel subset issues).
ImageSpec spec = spec_dimensions(subimage, miplevel); // thread-safe
if (spec.undefined())
return false;
chend = clamp(chend, chbegin + 1, spec.nchannels);
// All-channel case just reduces to the simpler version of
// read_native_tiles.
if (chbegin == 0 && chend >= spec.nchannels)
return read_native_tiles(subimage, miplevel, xbegin, xend, ybegin, yend,
zbegin, zend, data);
// More complicated cases follow.
if (!spec.valid_tile_range(xbegin, xend, ybegin, yend, zbegin, zend))
return false;
// Base class implementation of read_native_tiles just repeatedly
// calls read_native_tile, which is supplied by every plugin that
// supports tiles. Only the hardcore ones will overload
// read_native_tiles with their own implementation.
int nchans = chend - chbegin;
stride_t native_pixel_bytes = (stride_t)spec.pixel_bytes(true);
stride_t native_tileystride = native_pixel_bytes * spec.tile_width;
stride_t native_tilezstride = native_tileystride * spec.tile_height;
size_t prefix_bytes = spec.pixel_bytes(0, chbegin, true);
size_t subset_bytes = spec.pixel_bytes(chbegin, chend, true);
stride_t subset_ystride = (xend - xbegin) * subset_bytes;
stride_t subset_zstride = (yend - ybegin) * subset_ystride;
std::unique_ptr<char[]> pels(new char[spec.tile_bytes(true)]);
for (int z = zbegin; z < zend; z += spec.tile_depth) {
for (int y = ybegin; y < yend; y += spec.tile_height) {
for (int x = xbegin; x < xend; x += spec.tile_width) {
bool ok = read_native_tile(subimage, miplevel, x, y, z,
&pels[0]);
if (!ok)
return false;
copy_image(nchans, spec.tile_width, spec.tile_height,
spec.tile_depth, &pels[prefix_bytes], subset_bytes,
native_pixel_bytes, native_tileystride,
native_tilezstride,
(char*)data + (z - zbegin) * subset_zstride
+ (y - ybegin) * subset_ystride
+ (x - xbegin) * subset_bytes,
subset_bytes, subset_ystride, subset_zstride);
}
}
}
return true;
}
bool
ImageInput::read_image(TypeDesc format, void* data, stride_t xstride,
stride_t ystride, stride_t zstride,
ProgressCallback progress_callback,
void* progress_callback_data)
{
return read_image(current_subimage(), current_miplevel(), 0, -1, format,
data, xstride, ystride, zstride, progress_callback,
progress_callback_data);
}
bool
ImageInput::read_image(int chbegin, int chend, TypeDesc format, void* data,
stride_t xstride, stride_t ystride, stride_t zstride,
ProgressCallback progress_callback,
void* progress_callback_data)
{
int subimage, miplevel;
{
lock_guard lock(*this);
subimage = current_subimage();
miplevel = current_miplevel();
}
return read_image(subimage, miplevel, chbegin, chend, format, data, xstride,
ystride, zstride, progress_callback,
progress_callback_data);
}
bool
ImageInput::read_image(int subimage, int miplevel, int chbegin, int chend,
TypeDesc format, void* data, stride_t xstride,
stride_t ystride, stride_t zstride,
ProgressCallback progress_callback,
void* progress_callback_data)
{
ImageSpec spec;
int rps = 0;
{
// We need to lock briefly to retrieve rps from the spec
lock_guard lock(*this);
if (!seek_subimage(subimage, miplevel))
return false;
// Copying the dimensions of the designated subimage/miplevel to a
// local `spec` means that we can release the lock! (Calls to
// read_native_* will internally lock again if necessary.)
spec.copy_dimensions(m_spec);
// For scanline files, we also need one piece of metadata
if (!spec.tile_width)
rps = m_spec.get_int_attribute("tiff:RowsPerStrip", 64);
}
if (spec.image_bytes() < 1) {
errorfmt("Invalid image size {} x {} ({} chans)", m_spec.width,
m_spec.height, m_spec.nchannels);
return false;
}
if (chend < 0)
chend = spec.nchannels;
chend = clamp(chend, chbegin + 1, spec.nchannels);
int nchans = chend - chbegin;
bool native = (format == TypeDesc::UNKNOWN);
stride_t pixel_bytes = native ? (stride_t)spec.pixel_bytes(chbegin, chend,
native)
: (stride_t)(format.size() * nchans);
if (native && xstride == AutoStride)
xstride = pixel_bytes;
spec.auto_stride(xstride, ystride, zstride, format, nchans, spec.width,
spec.height);
bool ok = true;
if (progress_callback)
if (progress_callback(progress_callback_data, 0.0f))
return ok;
if (spec.tile_width) { // Tiled image -- rely on read_tiles
// Read in chunks of a whole row of tiles at once. If tiles are
// 64x64, a 2k image has 32 tiles across. That's fine for now (for
// parallelization purposes), but as typical core counts increase,
// we may someday want to revisit this to batch multiple rows.
for (int z = 0; z < spec.depth; z += spec.tile_depth) {
for (int y = 0; y < spec.height && ok; y += spec.tile_height) {
ok &= read_tiles(subimage, miplevel, spec.x,
spec.x + spec.width, y + spec.y,
std::min(y + spec.y + spec.tile_height,
spec.y + spec.height),
z + spec.z,
std::min(z + spec.z + spec.tile_depth,
spec.z + spec.depth),
chbegin, chend, format,
(char*)data + z * zstride + y * ystride,
xstride, ystride, zstride);
if (progress_callback
&& progress_callback(progress_callback_data,
(float)y / spec.height))
return ok;
}
}
} else { // Scanline image -- rely on read_scanlines.
// Split into reasonable chunks -- try to use around 64 MB or the
// oiio_read_chunk value, which ever is bigger, but also round up to
// a multiple of the TIFF rows per strip (or 64).
int chunk = std::max(1, (1 << 26) / int(spec.scanline_bytes(true)));
chunk = std::max(chunk, int(oiio_read_chunk));
chunk = round_to_multiple(chunk, rps);
for (int z = 0; z < spec.depth; ++z) {
for (int y = 0; y < spec.height && ok; y += chunk) {
int yend = std::min(y + spec.y + chunk, spec.y + spec.height);
ok &= read_scanlines(subimage, miplevel, y + spec.y, yend,
z + spec.z, chbegin, chend, format,
(char*)data + z * zstride + y * ystride,
xstride, ystride);
if (progress_callback)
if (progress_callback(progress_callback_data,
(float)y / spec.height))
return ok;
}
}
}
if (progress_callback)
progress_callback(progress_callback_data, 1.0f);
return ok;
}
bool
ImageInput::read_native_deep_scanlines(int /*subimage*/, int /*miplevel*/,
int /*ybegin*/, int /*yend*/, int /*z*/,
int /*chbegin*/, int /*chend*/,
DeepData& /*deepdata*/)
{
return false; // default: doesn't support deep images
}
bool
ImageInput::read_native_deep_tiles(int /*subimage*/, int /*miplevel*/,
int /*xbegin*/, int /*xend*/, int /*ybegin*/,
int /*yend*/, int /*zbegin*/, int /*zend*/,
int /*chbegin*/, int /*chend*/,
DeepData& /*deepdata*/)
{
return false; // default: doesn't support deep images
}
bool
ImageInput::read_native_deep_image(int subimage, int miplevel,
DeepData& deepdata)
{
ImageSpec spec = spec_dimensions(subimage, miplevel); // thread-safe
if (spec.undefined())
return false;
if (spec.depth > 1) {
errorf(
"read_native_deep_image is not supported for volume (3D) images.");
return false;
// FIXME? - not implementing 3D deep images for now. The only
// format that supports deep images at this time is OpenEXR, and
// it doesn't support volumes.
}
if (spec.tile_width) {
// Tiled image
return read_native_deep_tiles(subimage, miplevel, spec.x,
spec.x + spec.width, spec.y,
spec.y + spec.height, spec.z,
spec.z + spec.depth, 0, spec.nchannels,
deepdata);
} else {
// Scanline image
return read_native_deep_scanlines(subimage, miplevel, spec.y,
spec.y + spec.height, 0, 0,
spec.nchannels, deepdata);
}
}
int
ImageInput::send_to_input(const char* /*format*/, ...)
{
// FIXME -- I can't remember how this is supposed to work
return 0;
}
int
ImageInput::send_to_client(const char* /*format*/, ...)
{
// FIXME -- I can't remember how this is supposed to work
return 0;
}
void
ImageInput::append_error(string_view message) const
{
if (message.size() && message.back() == '\n')
message.remove_suffix(1);
std::string* errptr = m_impl->m_errormessage.get();
if (!errptr) {
errptr = new std::string;
m_impl->m_errormessage.reset(errptr);
}
OIIO_DASSERT(
errptr->size() < 1024 * 1024 * 16
&& "Accumulated error messages > 16MB. Try checking return codes!");
if (errptr->size() && errptr->back() != '\n')
*errptr += '\n';
*errptr += message;
}
bool
ImageInput::has_error() const
{
std::string* errptr = m_impl->m_errormessage.get();
return (errptr && errptr->size());
}
std::string
ImageInput::geterror(bool clear) const
{
std::string e;
std::string* errptr = m_impl->m_errormessage.get();
if (errptr) {
e = *errptr;
if (clear)
errptr->clear();
}
return e;
}
void
ImageInput::threads(int n)
{
m_impl->m_threads = n;
}
int
ImageInput::threads() const
{
return m_impl->m_threads;
}
void
ImageInput::lock() const
{
m_impl->m_mutex.lock();
}
bool
ImageInput::try_lock() const
{
return m_impl->m_mutex.try_lock();
}
void
ImageInput::unlock() const
{
m_impl->m_mutex.unlock();
}
Filesystem::IOProxy*
ImageInput::ioproxy()
{
return m_impl->m_io;
}
const Filesystem::IOProxy*
ImageInput::ioproxy() const
{
return m_impl->m_io;
}
bool
ImageInput::set_ioproxy(Filesystem::IOProxy* ioproxy)
{
m_impl->m_io = ioproxy;
return (ioproxy == nullptr || supports("ioproxy"));
}
bool
ImageInput::ioproxy_opened() const
{
Filesystem::IOProxy*& m_io(m_impl->m_io);
return m_io != nullptr && m_io->mode() == Filesystem::IOProxy::Read;
}
void
ImageInput::ioproxy_clear()
{
m_impl->m_io = nullptr;
m_impl->m_io_local.reset();
}
void
ImageInput::ioproxy_retrieve_from_config(const ImageSpec& config)
{
if (auto p = config.find_attribute("oiio:ioproxy", TypeDesc::PTR))
set_ioproxy(p->get<Filesystem::IOProxy*>());
}
bool
ImageInput::ioproxy_use_or_open(string_view name)
{
Filesystem::IOProxy*& m_io(m_impl->m_io);
if (!m_io) {
// If no proxy was supplied, create an IOFile
m_io = new Filesystem::IOFile(name, Filesystem::IOProxy::Mode::Read);
m_impl->m_io_local.reset(m_io);
}
if (!m_io || m_io->mode() != Filesystem::IOProxy::Mode::Read) {
errorfmt("Could not open file \"{}\"", name);
ioproxy_clear();
return false;
}
return true;
}
bool
ImageInput::ioread(void* buf, size_t itemsize, size_t nitems)
{
Filesystem::IOProxy*& m_io(m_impl->m_io);
size_t size = itemsize * nitems;
size_t n = m_io->read(buf, size);
if (n != size) {
if (size_t(m_io->tell()) >= m_io->size())
ImageInput::errorfmt("Read error on \"{}\": hit end of file",
m_io->filename());
else
ImageInput::errorfmt(
"Read error at position {}, could only read {}/{} bytes {}",
m_io->tell() - n, n, size, m_io->error());
}
return n == size;
}
bool
ImageInput::ioseek(int64_t pos, int origin)
{
Filesystem::IOProxy*& m_io(m_impl->m_io);
if (m_io && !m_io->seek(pos, origin)) {
errorfmt("Seek error, could not seek from {} to {} (total size {}) {}",
m_io->tell(),
origin == SEEK_SET ? pos
: (origin == SEEK_CUR ? pos + m_io->tell()
: pos + m_io->size()),
m_io->size(), m_io->error());
return false;
}
return true;
}
int64_t
ImageInput::iotell() const
{
return m_impl->m_io->tell();
}
OIIO_NAMESPACE_END
|
/******************************************************************************
* Copyright (c) 2020, Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
*
*****************************************************************************/
#include "sct_assert.h"
#include "systemc.h"
using namespace sc_core;
// Record with array member in CTHREAD
class A : public sc_module {
public:
sc_in_clk clk{"clk"};
sc_signal<bool> rst;
sc_signal<sc_uint<4>> sig;
SC_CTOR(A)
{
SC_CTHREAD(mult_array_decl, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(loc_array_decl1, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(loc_array_decl2, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(loc_array_decl3, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(loc_array_decl4, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(loc_array_decl5, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(loc_array_decl6, clk.pos());
async_reset_signal_is(rst, true);
SC_METHOD(loc_array_decl6_meth);
sensitive << sig;
SC_CTHREAD(loc_array_copy, clk.pos());
async_reset_signal_is(rst, true);
// // Incorrect code as inner record not supported yet, #127
// //SC_CTHREAD(loc_array_copy2, clk.pos());
// //async_reset_signal_is(rst, true);
//
SC_CTHREAD(loc_array_init, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(fcall_array_unknown, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(simple_access, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(array_access, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(loc_array_access, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(local_fcall_param, clk.pos());
async_reset_signal_is(rst, true);
SC_METHOD(local_fcall_param_noinit);
sensitive << sig;
SC_CTHREAD(fcall_param, clk.pos());
async_reset_signal_is(rst, true);
SC_CTHREAD(fcall_return, clk.pos());
async_reset_signal_is(rst, true);
}
struct Rec {
bool a;
sc_uint<4> b;
};
struct ArrRec {
bool a[3];
sc_uint<4> b[3];
void setA(bool par, int i) {
a[i] = par;
}
bool getA(int i ) {
return a[i];
}
};
struct ArrRecRec {
ArrRec rec;
};
struct MultArrRec {
sc_uint<4> b[3][2];
};
void mult_array_decl()
{
ArrRec qarr[5][4];
MultArrRec parr[4];
qarr[4][3].b[2] = 0;
parr[3].b[2][1] = 0;
wait();
while (true)
{
bool aa = qarr[3][2].a[1];
sc_uint<4> bb = parr[2].b[1][0];
wait();
}
}
// Declaration of local record array with array member
void loc_array_decl1()
{
ArrRec xarr1[2];
xarr1[1].b[2] = 0;
wait();
while (true)
{
wait();
}
}
void loc_array_decl2()
{
wait();
while (true)
{
ArrRec xarr2[2];
xarr2[1].b[2] = 0;
wait();
}
}
void loc_array_decl3()
{
wait();
while (true)
{
ArrRec xarr3[2]; // reg
xarr3[1].b[2] = 0;
wait();
auto l = xarr3[1].b[1];
}
}
void loc_array_decl4()
{
wait();
while (true)
{
ArrRec xarr4[2]; // reg
xarr4[1].b[2] = 0;
wait();
auto l = xarr4[1].b[2];
}
}
// Unknown index for member array
ArrRec xarr5[2]; // reg
void loc_array_decl5()
{
wait();
while (true)
{
int j = sig.read();
ArrRec xlarr5[2]; // reg
xarr5[1].b[j] = 0;
xlarr5[1].b[j] = 0;
wait();
auto l = xarr5[1].b[2] + xlarr5[1].b[2];
}
}
// Unknown index for record array
void loc_array_decl6()
{
wait();
while (true)
{
int j = sig.read();
ArrRec xarr6[2]; // reg
xarr6[j].b[2] = 0;
auto l = xarr6[1].b[2];
wait();
}
}
void loc_array_decl6_meth()
{
int j = sig.read();
ArrRec xarr6[2];
xarr6[j].b[2] = 0;
auto l = xarr6[1].b[2];
}
// Copy of record with array, check @par_b is register
template<class T>
void rec_param_copy(T par) { // reg
int j = sig.read();
par.b[j] = 1;
wait();
auto l = par.b[1];
}
void loc_array_copy()
{
wait();
while (true)
{
ArrRec xlarr;
rec_param_copy(xlarr);
wait();
}
}
// Copy of record with record with array, check @par_rec_b is register
template<class T>
void rec_param_copy2(T par) { // reg
int j = sig.read();
par.rec.b[j] = 1;
wait();
auto l = par.rec.b[1];
}
void loc_array_copy2()
{
wait();
while (true)
{
ArrRecRec xlarr;
rec_param_copy2(xlarr);
wait();
}
}
// Local array field initialization
void loc_array_init()
{
ArrRec x;
ArrRec xarr[2];
wait();
while (true)
{
wait();
}
}
void fcall_array_unknown()
{
ArrRec yarr[2];
int j = sig.read();
yarr[j].a[0] = 0;
wait();
while (true)
{
rec_param0(yarr[j]);
wait();
}
}
//----------------------------------------------------------------------------
// Record with array member read/write access
ArrRec s;
void simple_access()
{
for (int i = 0; i < 3; ++i) {
s.setA(false, i);
s.b[i] = 0;
}
wait();
while (true)
{
int j = sig.read();
s.b[j] = s.getA(j+1) ? j : 0;
wait();
}
}
//----------------------------------------------------------------------------
// Array of record with array member read/write access
ArrRec arr[2];
void array_access()
{
for (int j = 0; j < 2; ++j) {
for (int i = 0; i < 3; ++i) {
arr[j].setA(false, i);
arr[j].b[i] = 0;
}
}
wait();
while (true)
{
int j = sig.read();
auto l = arr[j].b[j+1];
arr[j].b[j+1] = arr[j].getA(j+1) ? j : 0;
wait();
}
}
//----------------------------------------------------------------------------
// Local array of record with array member read/write access
void loc_array_access()
{
ArrRec x;
ArrRec xarr[2];
for (int i = 0; i < 3; ++i) {
x.b[i] = i;
}
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 3; ++k) {
xarr[j].b[k] = 0;
}
}
wait();
while (true)
{
int j = sig.read();
auto l = x.b[j] + xarr[j+1].b[j+2];
x.b[j] = 1;
xarr[j+1].b[j+2] = 2;
xarr[j].setA(false, 1);
wait();
}
}
//----------------------------------------------------------------------------
// Record with array member as function parameter
// Local record array unknown element passing test
template<class T>
void rec_param0(T par) {
auto l = par.b[0];
}
// Record array passed as pointer
template<class T>
void rec_param1(T par, int i) {
par[i].b = par[i].a ? 1 : 2;
}
template<class T>
void rec_param2_val(T par, int j) {
par.b[j] = par.getA(j) ? 1 : 2;
}
template<class T>
void rec_param2_ref(T& par, int k) {
par.b[k] = par.getA(k) ? 1 : 2;
}
void local_fcall_param()
{
Rec vv[3];
ArrRec v;
ArrRec varr[2];
for (int d = 0; d < 2; ++d)
for (int e = 0; e < 3; ++e) varr[d].a[e] = 0;
int j = sig.read();
rec_param2_ref(varr[j], 0);
wait();
while (true)
{
rec_param1(vv, 1);
rec_param2_ref(v, 1);
rec_param0(varr[j]);
rec_param2_val(varr[j], 0);
rec_param2_ref(varr[j], 1);
wait();
}
}
// Check if non-initialized record leads to unknown condition in @rec_param2_ref
void local_fcall_param_noinit()
{
ArrRec varr[2];
int j = sig.read();
rec_param2_ref(varr[j], 0);
}
Rec rr[3];
ArrRec r;
ArrRec rarr[2];
void fcall_param()
{
for (int e = 0; e < 3; ++e) r.a[e] = 0;
rec_param2_val(r, 0); // par is reg as its reused after reset
wait();
while (true)
{
rec_param1(rr, 1);
rec_param2_ref(r, 1);
int j = sig.read();
rec_param0(rarr[j]);
rec_param2_val(rarr[j], 0);
rec_param2_ref(rarr[j], 1);
wait();
}
}
//----------------------------------------------------------------------------
// Record with array member return from function
template<class T>
T rec_return1(T par) {
return par;
}
template<class T>
T rec_return2(T par) {
T res = par;
wait();
return res;
}
ArrRec z;
ArrRec zarr[2];
void fcall_return()
{
for (int e = 0; e < 3; ++e) {
z.a[e] = 0; z.b[e] = 0;
}
auto lrec = rec_return1(z);
wait();
while (true)
{
auto llrec = rec_return2(z);
int j = sig.read();
auto lllrec = rec_return2(zarr[j]);
wait();
}
}
};
int sc_main(int argc, char *argv[]) {
sc_clock clk("clk", 1, SC_NS);
A a{"a"};
a.clk(clk);
sc_start();
return 0;
}
|
/***************************************************************************
# Copyright (c) 2015-21, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "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 COPYRIGHT OWNER OR
# CONTRIBUTORS 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.
**************************************************************************/
#include "stdafx.h"
#include "Core/FalcorConfig.h"
#if FALCOR_ENABLE_RTXDI
// If this include is not resolved this means that the RTXDI SDK is
// not installed properly. See README for installation details.
#include "rtxdi/rtxdi-sdk/src/RTXDI.cpp"
#endif
|
//
// basic_io_object.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2022 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_BASIC_IO_OBJECT_HPP
#define BOOST_ASIO_BASIC_IO_OBJECT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
#if defined(BOOST_ASIO_HAS_MOVE)
namespace detail
{
// Type trait used to determine whether a service supports move.
template <typename IoObjectService>
class service_has_move
{
private:
typedef IoObjectService service_type;
typedef typename service_type::implementation_type implementation_type;
template <typename T, typename U>
static auto asio_service_has_move_eval(T* t, U* u)
-> decltype(t->move_construct(*u, *u), char());
static char (&asio_service_has_move_eval(...))[2];
public:
static const bool value =
sizeof(asio_service_has_move_eval(
static_cast<service_type*>(0),
static_cast<implementation_type*>(0))) == 1;
};
}
#endif // defined(BOOST_ASIO_HAS_MOVE)
/// Base class for all I/O objects.
/**
* @note All I/O objects are non-copyable. However, when using C++0x, certain
* I/O objects do support move construction and move assignment.
*/
#if !defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
template <typename IoObjectService>
#else
template <typename IoObjectService,
bool Movable = detail::service_has_move<IoObjectService>::value>
#endif
class basic_io_object
{
public:
/// The type of the service that will be used to provide I/O operations.
typedef IoObjectService service_type;
/// The underlying implementation type of I/O object.
typedef typename service_type::implementation_type implementation_type;
#if !defined(BOOST_ASIO_NO_DEPRECATED)
/// (Deprecated: Use get_executor().) Get the io_context associated with the
/// object.
/**
* This function may be used to obtain the io_context object that the I/O
* object uses to dispatch handlers for asynchronous operations.
*
* @return A reference to the io_context object that the I/O object will use
* to dispatch handlers. Ownership is not transferred to the caller.
*/
boost::asio::io_context& get_io_context()
{
return service_.get_io_context();
}
/// (Deprecated: Use get_executor().) Get the io_context associated with the
/// object.
/**
* This function may be used to obtain the io_context object that the I/O
* object uses to dispatch handlers for asynchronous operations.
*
* @return A reference to the io_context object that the I/O object will use
* to dispatch handlers. Ownership is not transferred to the caller.
*/
boost::asio::io_context& get_io_service()
{
return service_.get_io_context();
}
#endif // !defined(BOOST_ASIO_NO_DEPRECATED)
/// The type of the executor associated with the object.
typedef boost::asio::io_context::executor_type executor_type;
/// Get the executor associated with the object.
executor_type get_executor() BOOST_ASIO_NOEXCEPT
{
return service_.get_io_context().get_executor();
}
protected:
/// Construct a basic_io_object.
/**
* Performs:
* @code get_service().construct(get_implementation()); @endcode
*/
explicit basic_io_object(boost::asio::io_context& io_context)
: service_(boost::asio::use_service<IoObjectService>(io_context))
{
service_.construct(implementation_);
}
#if defined(GENERATING_DOCUMENTATION)
/// Move-construct a basic_io_object.
/**
* Performs:
* @code get_service().move_construct(
* get_implementation(), other.get_implementation()); @endcode
*
* @note Available only for services that support movability,
*/
basic_io_object(basic_io_object&& other);
/// Move-assign a basic_io_object.
/**
* Performs:
* @code get_service().move_assign(get_implementation(),
* other.get_service(), other.get_implementation()); @endcode
*
* @note Available only for services that support movability,
*/
basic_io_object& operator=(basic_io_object&& other);
/// Perform a converting move-construction of a basic_io_object.
template <typename IoObjectService1>
basic_io_object(IoObjectService1& other_service,
typename IoObjectService1::implementation_type& other_implementation);
#endif // defined(GENERATING_DOCUMENTATION)
/// Protected destructor to prevent deletion through this type.
/**
* Performs:
* @code get_service().destroy(get_implementation()); @endcode
*/
~basic_io_object()
{
service_.destroy(implementation_);
}
/// Get the service associated with the I/O object.
service_type& get_service()
{
return service_;
}
/// Get the service associated with the I/O object.
const service_type& get_service() const
{
return service_;
}
/// Get the underlying implementation of the I/O object.
implementation_type& get_implementation()
{
return implementation_;
}
/// Get the underlying implementation of the I/O object.
const implementation_type& get_implementation() const
{
return implementation_;
}
private:
basic_io_object(const basic_io_object&);
basic_io_object& operator=(const basic_io_object&);
// The service associated with the I/O object.
service_type& service_;
/// The underlying implementation of the I/O object.
implementation_type implementation_;
};
#if defined(BOOST_ASIO_HAS_MOVE)
// Specialisation for movable objects.
template <typename IoObjectService>
class basic_io_object<IoObjectService, true>
{
public:
typedef IoObjectService service_type;
typedef typename service_type::implementation_type implementation_type;
#if !defined(BOOST_ASIO_NO_DEPRECATED)
boost::asio::io_context& get_io_context()
{
return service_->get_io_context();
}
boost::asio::io_context& get_io_service()
{
return service_->get_io_context();
}
#endif // !defined(BOOST_ASIO_NO_DEPRECATED)
typedef boost::asio::io_context::executor_type executor_type;
executor_type get_executor() BOOST_ASIO_NOEXCEPT
{
return service_->get_io_context().get_executor();
}
protected:
explicit basic_io_object(boost::asio::io_context& io_context)
: service_(&boost::asio::use_service<IoObjectService>(io_context))
{
service_->construct(implementation_);
}
basic_io_object(basic_io_object&& other)
: service_(&other.get_service())
{
service_->move_construct(implementation_, other.implementation_);
}
template <typename IoObjectService1>
basic_io_object(IoObjectService1& other_service,
typename IoObjectService1::implementation_type& other_implementation)
: service_(&boost::asio::use_service<IoObjectService>(
other_service.get_io_context()))
{
service_->converting_move_construct(implementation_,
other_service, other_implementation);
}
~basic_io_object()
{
service_->destroy(implementation_);
}
basic_io_object& operator=(basic_io_object&& other)
{
service_->move_assign(implementation_,
*other.service_, other.implementation_);
service_ = other.service_;
return *this;
}
service_type& get_service()
{
return *service_;
}
const service_type& get_service() const
{
return *service_;
}
implementation_type& get_implementation()
{
return implementation_;
}
const implementation_type& get_implementation() const
{
return implementation_;
}
private:
basic_io_object(const basic_io_object&);
void operator=(const basic_io_object&);
IoObjectService* service_;
implementation_type implementation_;
};
#endif // defined(BOOST_ASIO_HAS_MOVE)
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_BASIC_IO_OBJECT_HPP
|
// Test with PCH
// RUN: %clang_cc1 -std=c++11 -x c++-header -emit-pch -o %t %s
// RUN: %clang_cc1 -std=c++11 -include-pch %t -verify %s
// expected-no-diagnostics
// PR10847
#ifndef HEADER
#define HEADER
struct NSSize {
double width;
double height;
};
typedef struct NSSize NSSize;
static inline NSSize NSMakeSize(double w, double h) {
NSSize s = { w, h };
return s;
}
#else
float test(float v1, float v2) {
NSSize s = NSMakeSize(v1, v2);
return s.width;
}
#endif
|
#ifndef STAN_MATH_FWD_FUN_COLUMNS_DOT_SELF_HPP
#define STAN_MATH_FWD_FUN_COLUMNS_DOT_SELF_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/fun/dot_self.hpp>
namespace stan {
namespace math {
template <typename T, int R, int C>
inline Eigen::Matrix<fvar<T>, 1, C> columns_dot_self(
const Eigen::Matrix<fvar<T>, R, C>& x) {
Eigen::Matrix<fvar<T>, 1, C> ret(1, x.cols());
for (size_type i = 0; i < x.cols(); i++) {
Eigen::Matrix<fvar<T>, R, 1> ccol = x.col(i);
ret(0, i) = dot_self(ccol);
}
return ret;
}
} // namespace math
} // namespace stan
#endif
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkPointSetAlgorithm.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPointSetAlgorithm.h"
#include "vtkCommand.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkStructuredGrid.h"
#include "vtkUnstructuredGrid.h"
vtkStandardNewMacro(vtkPointSetAlgorithm);
//----------------------------------------------------------------------------
// Instantiate object so that cell data is not passed to output.
vtkPointSetAlgorithm::vtkPointSetAlgorithm()
{
this->SetNumberOfInputPorts(1);
this->SetNumberOfOutputPorts(1);
}
//----------------------------------------------------------------------------
vtkPointSet* vtkPointSetAlgorithm::GetOutput()
{
return this->GetOutput(0);
}
//----------------------------------------------------------------------------
vtkPointSet* vtkPointSetAlgorithm::GetOutput(int port)
{
return vtkPointSet::SafeDownCast(this->GetOutputDataObject(port));
}
//----------------------------------------------------------------------------
// Get the output as vtkPolyData.
vtkPolyData *vtkPointSetAlgorithm::GetPolyDataOutput()
{
return vtkPolyData::SafeDownCast(this->GetOutput());
}
//----------------------------------------------------------------------------
// Get the output as vtkStructuredGrid.
vtkStructuredGrid *vtkPointSetAlgorithm::GetStructuredGridOutput()
{
return vtkStructuredGrid::SafeDownCast(this->GetOutput());
}
//----------------------------------------------------------------------------
// Get the output as vtkUnstructuredGrid.
vtkUnstructuredGrid *vtkPointSetAlgorithm::GetUnstructuredGridOutput()
{
return vtkUnstructuredGrid::SafeDownCast(this->GetOutput());
}
//----------------------------------------------------------------------------
void vtkPointSetAlgorithm::SetInputData(vtkDataObject* input)
{
this->SetInputData(0, input);
}
//----------------------------------------------------------------------------
void vtkPointSetAlgorithm::SetInputData(int index, vtkDataObject* input)
{
this->SetInputDataInternal(index, input);
}
//----------------------------------------------------------------------------
void vtkPointSetAlgorithm::SetInputData(vtkPointSet* input)
{
this->SetInputData(0, static_cast<vtkDataObject*>(input));
}
//----------------------------------------------------------------------------
void vtkPointSetAlgorithm::SetInputData(int index, vtkPointSet* input)
{
this->SetInputData(index, static_cast<vtkDataObject*>(input));
}
//----------------------------------------------------------------------------
void vtkPointSetAlgorithm::AddInputData(vtkDataObject* input)
{
this->AddInputData(0, input);
}
//----------------------------------------------------------------------------
void vtkPointSetAlgorithm::AddInputData(int index, vtkDataObject* input)
{
this->AddInputDataInternal(index, input);
}
//----------------------------------------------------------------------------
void vtkPointSetAlgorithm::AddInputData(vtkPointSet* input)
{
this->AddInputData(0, static_cast<vtkDataObject*>(input));
}
//----------------------------------------------------------------------------
void vtkPointSetAlgorithm::AddInputData(int index, vtkPointSet* input)
{
this->AddInputData(index, static_cast<vtkDataObject*>(input));
}
//----------------------------------------------------------------------------
vtkDataObject* vtkPointSetAlgorithm::GetInput()
{
return this->GetExecutive()->GetInputData(0, 0);
}
//----------------------------------------------------------------------------
int vtkPointSetAlgorithm::ProcessRequest(
vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
// generate the data
if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()))
{
return this->RequestData(request, inputVector, outputVector);
}
// create the output
if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_OBJECT()))
{
return this->RequestDataObject(request, inputVector, outputVector);
}
// execute information
if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()))
{
return this->ExecuteInformation(request, inputVector, outputVector);
}
// set update extent
if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT()))
{
return this->ComputeInputUpdateExtent(request, inputVector, outputVector);
}
return this->Superclass::ProcessRequest(request, inputVector, outputVector);
}
//----------------------------------------------------------------------------
int vtkPointSetAlgorithm::RequestDataObject(
vtkInformation*,
vtkInformationVector** inputVector ,
vtkInformationVector* outputVector)
{
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
if (!inInfo)
{
return 0;
}
vtkPointSet *input = vtkPointSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
if (input)
{
// for each output
for(int i=0; i < this->GetNumberOfOutputPorts(); ++i)
{
vtkInformation* info = outputVector->GetInformationObject(i);
vtkPointSet *output = vtkPointSet::SafeDownCast(
info->Get(vtkDataObject::DATA_OBJECT()));
if (!output || !output->IsA(input->GetClassName()))
{
output = input->NewInstance();
info->Set(vtkDataObject::DATA_OBJECT(), output);
output->Delete();
}
}
return 1;
}
return 0;
}
//----------------------------------------------------------------------------
int vtkPointSetAlgorithm::FillOutputPortInformation(
int vtkNotUsed(port), vtkInformation* info)
{
// now add our info
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkPointSet");
return 1;
}
//----------------------------------------------------------------------------
int vtkPointSetAlgorithm::FillInputPortInformation(
int vtkNotUsed(port), vtkInformation* info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPointSet");
return 1;
}
//----------------------------------------------------------------------------
void vtkPointSetAlgorithm::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
|
#include "selfdrive/camerad/cameras/camera_webcam.h"
#include <unistd.h>
#include <cassert>
#include <cstring>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundefined-inline"
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#pragma clang diagnostic pop
#include "selfdrive/common/clutil.h"
#include "selfdrive/common/swaglog.h"
#include "selfdrive/common/timing.h"
#include "selfdrive/common/util.h"
// id of the video capturing device
const int ROAD_CAMERA_ID = util::getenv("ROADCAM_ID", 1);
const int DRIVER_CAMERA_ID = util::getenv("DRIVERCAM_ID", 2);
#define FRAME_WIDTH 1164
#define FRAME_HEIGHT 874
#define FRAME_WIDTH_FRONT 1152
#define FRAME_HEIGHT_FRONT 864
extern ExitHandler do_exit;
namespace {
CameraInfo cameras_supported[CAMERA_ID_MAX] = {
// road facing
[CAMERA_ID_LGC920] = {
.frame_width = FRAME_WIDTH,
.frame_height = FRAME_HEIGHT,
.frame_stride = FRAME_WIDTH*3,
.bayer = false,
.bayer_flip = false,
},
// driver facing
[CAMERA_ID_LGC615] = {
.frame_width = FRAME_WIDTH_FRONT,
.frame_height = FRAME_HEIGHT_FRONT,
.frame_stride = FRAME_WIDTH_FRONT*3,
.bayer = false,
.bayer_flip = false,
},
};
void camera_open(CameraState *s, bool rear) {
// empty
}
void camera_close(CameraState *s) {
// empty
}
void camera_init(VisionIpcServer * v, CameraState *s, int camera_id, unsigned int fps, cl_device_id device_id, cl_context ctx, VisionStreamType rgb_type, VisionStreamType yuv_type) {
assert(camera_id < std::size(cameras_supported));
s->ci = cameras_supported[camera_id];
assert(s->ci.frame_width != 0);
s->camera_num = camera_id;
s->fps = fps;
s->buf.init(device_id, ctx, s, v, FRAME_BUF_COUNT, rgb_type, yuv_type);
}
void run_camera(CameraState *s, cv::VideoCapture &video_cap, float *ts) {
assert(video_cap.isOpened());
cv::Size size(s->ci.frame_width, s->ci.frame_height);
const cv::Mat transform = cv::Mat(3, 3, CV_32F, ts);
uint32_t frame_id = 0;
size_t buf_idx = 0;
while (!do_exit) {
cv::Mat frame_mat, transformed_mat;
video_cap >> frame_mat;
if (frame_mat.empty()) continue;
cv::warpPerspective(frame_mat, transformed_mat, transform, size, cv::INTER_LINEAR, cv::BORDER_CONSTANT, 0);
s->buf.camera_bufs_metadata[buf_idx] = {.frame_id = frame_id};
auto &buf = s->buf.camera_bufs[buf_idx];
int transformed_size = transformed_mat.total() * transformed_mat.elemSize();
CL_CHECK(clEnqueueWriteBuffer(buf.copy_q, buf.buf_cl, CL_TRUE, 0, transformed_size, transformed_mat.data, 0, NULL, NULL));
s->buf.queue(buf_idx);
++frame_id;
buf_idx = (buf_idx + 1) % FRAME_BUF_COUNT;
}
}
static void road_camera_thread(CameraState *s) {
set_thread_name("webcam_road_camera_thread");
cv::VideoCapture cap_road(ROAD_CAMERA_ID, cv::CAP_V4L2); // road
cap_road.set(cv::CAP_PROP_FRAME_WIDTH, 853);
cap_road.set(cv::CAP_PROP_FRAME_HEIGHT, 480);
cap_road.set(cv::CAP_PROP_FPS, s->fps);
cap_road.set(cv::CAP_PROP_AUTOFOCUS, 0); // off
cap_road.set(cv::CAP_PROP_FOCUS, 0); // 0 - 255?
// cv::Rect roi_rear(160, 0, 960, 720);
// transforms calculation see tools/webcam/warp_vis.py
float ts[9] = {1.50330396, 0.0, -59.40969163,
0.0, 1.50330396, 76.20704846,
0.0, 0.0, 1.0};
// if camera upside down:
// float ts[9] = {-1.50330396, 0.0, 1223.4,
// 0.0, -1.50330396, 797.8,
// 0.0, 0.0, 1.0};
run_camera(s, cap_road, ts);
}
void driver_camera_thread(CameraState *s) {
cv::VideoCapture cap_driver(DRIVER_CAMERA_ID, cv::CAP_V4L2); // driver
cap_driver.set(cv::CAP_PROP_FRAME_WIDTH, 853);
cap_driver.set(cv::CAP_PROP_FRAME_HEIGHT, 480);
cap_driver.set(cv::CAP_PROP_FPS, s->fps);
// cv::Rect roi_front(320, 0, 960, 720);
// transforms calculation see tools/webcam/warp_vis.py
float ts[9] = {1.42070485, 0.0, -30.16740088,
0.0, 1.42070485, 91.030837,
0.0, 0.0, 1.0};
// if camera upside down:
// float ts[9] = {-1.42070485, 0.0, 1182.2,
// 0.0, -1.42070485, 773.0,
// 0.0, 0.0, 1.0};
run_camera(s, cap_driver, ts);
}
} // namespace
void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx) {
camera_init(v, &s->road_cam, CAMERA_ID_LGC920, 20, device_id, ctx,
VISION_STREAM_RGB_BACK, VISION_STREAM_YUV_BACK);
camera_init(v, &s->driver_cam, CAMERA_ID_LGC615, 10, device_id, ctx,
VISION_STREAM_RGB_FRONT, VISION_STREAM_YUV_FRONT);
s->pm = new PubMaster({"roadCameraState", "driverCameraState", "thumbnail"});
}
void camera_autoexposure(CameraState *s, float grey_frac) {}
void cameras_open(MultiCameraState *s) {
// LOG("*** open driver camera ***");
camera_open(&s->driver_cam, false);
// LOG("*** open road camera ***");
camera_open(&s->road_cam, true);
}
void cameras_close(MultiCameraState *s) {
camera_close(&s->road_cam);
camera_close(&s->driver_cam);
delete s->pm;
}
void process_driver_camera(MultiCameraState *s, CameraState *c, int cnt) {
MessageBuilder msg;
auto framed = msg.initEvent().initDriverCameraState();
framed.setFrameType(cereal::FrameData::FrameType::FRONT);
fill_frame_data(framed, c->buf.cur_frame_data);
s->pm->send("driverCameraState", msg);
}
void process_road_camera(MultiCameraState *s, CameraState *c, int cnt) {
const CameraBuf *b = &c->buf;
MessageBuilder msg;
auto framed = msg.initEvent().initRoadCameraState();
fill_frame_data(framed, b->cur_frame_data);
framed.setImage(kj::arrayPtr((const uint8_t *)b->cur_yuv_buf->addr, b->cur_yuv_buf->len));
framed.setTransform(b->yuv_transform.v);
s->pm->send("roadCameraState", msg);
}
void cameras_run(MultiCameraState *s) {
std::vector<std::thread> threads;
threads.push_back(start_process_thread(s, &s->road_cam, process_road_camera));
threads.push_back(start_process_thread(s, &s->driver_cam, process_driver_camera));
std::thread t_rear = std::thread(road_camera_thread, &s->road_cam);
set_thread_name("webcam_thread");
driver_camera_thread(&s->driver_cam);
t_rear.join();
for (auto &t : threads) t.join();
cameras_close(s);
}
|
/** @file
*****************************************************************************
Implementation of interfaces for wNAF ("weighted Non-Adjacent Form") exponentiation routines.
See wnaf.hpp .
*****************************************************************************
* @author This file is part of libff, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef WNAF_TCC_
#define WNAF_TCC_
#include <gmp.h>
namespace libff {
template<mp_size_t n>
std::vector<long> find_wnaf(const size_t window_size, const bigint<n> &scalar)
{
const size_t length = scalar.max_bits(); // upper bound
std::vector<long> res(length+1);
bigint<n> c = scalar;
long j = 0;
while (!c.is_zero())
{
long u;
if ((c.data[0] & 1) == 1)
{
u = c.data[0] % (1u << (window_size+1));
if (u > (1 << window_size))
{
u = u - (1 << (window_size+1));
}
if (u > 0)
{
mpn_sub_1(c.data, c.data, n, u);
}
else
{
mpn_add_1(c.data, c.data, n, -u);
}
}
else
{
u = 0;
}
res[j] = u;
++j;
mpn_rshift(c.data, c.data, n, 1); // c = c/2
}
return res;
}
template<typename T, mp_size_t n>
T fixed_window_wnaf_exp(const size_t window_size, const T &base, const bigint<n> &scalar)
{
std::vector<long> naf = find_wnaf(window_size, scalar);
std::vector<T> table(1ull<<(window_size-1));
T tmp = base;
T dbl = base.dbl();
for (size_t i = 0; i < 1ull<<(window_size-1); ++i)
{
table[i] = tmp;
tmp = tmp + dbl;
}
T res = T::zero();
bool found_nonzero = false;
for (long i = naf.size()-1; i >= 0; --i)
{
if (found_nonzero)
{
res = res.dbl();
}
if (naf[i] != 0)
{
found_nonzero = true;
if (naf[i] > 0)
{
res = res + table[naf[i]/2];
}
else
{
res = res - table[(-naf[i])/2];
}
}
}
return res;
}
template<typename T, mp_size_t n>
T opt_window_wnaf_exp(const T &base, const bigint<n> &scalar, const size_t scalar_bits)
{
size_t best = 0;
for (long i = T::wnaf_window_table.size() - 1; i >= 0; --i)
{
if (scalar_bits >= T::wnaf_window_table[i])
{
best = i+1;
break;
}
}
if (best > 0)
{
return fixed_window_wnaf_exp(best, base, scalar);
}
else
{
return scalar * base;
}
}
} // libff
#endif // WNAF_TCC_
|
#include "RotationAnimator.h"
#include "ITransformable.h"
RotationAnimator::RotationAnimator(core::vector3df speed)
{
this->speedRadians = speed * core::DEGTORAD;
}
void RotationAnimator::Animate(ITransformable *target, f32 dt)
{
core::quaternion rot( target->GetRotation() * core::DEGTORAD );
core::quaternion delta( speedRadians * dt );
rot = rot * delta;
target->SetRotation( maths::quaternion_to_euler(rot) );
}
|
#include "vrclient_private.h"
#include "vrclient_defs.h"
#include "openvr_v1.16.8/ivrclientcore.h"
using namespace vr;
extern "C" {
#include "struct_converters.h"
}
#include "cppIVRNotifications_IVRNotifications_002.h"
#ifdef __cplusplus
extern "C" {
#endif
vr::EVRNotificationError cppIVRNotifications_IVRNotifications_002_CreateNotification(void *linux_side, VROverlayHandle_t ulOverlayHandle, uint64_t ulUserValue, EVRNotificationType type, const char * pchText, EVRNotificationStyle style, NotificationBitmap_t * pImage, VRNotificationId * pNotificationId)
{
return ((IVRNotifications*)linux_side)->CreateNotification((vr::VROverlayHandle_t)ulOverlayHandle, (uint64_t)ulUserValue, (vr::EVRNotificationType)type, (const char *)pchText, (vr::EVRNotificationStyle)style, (const vr::NotificationBitmap_t *)pImage, (vr::VRNotificationId *)pNotificationId);
}
vr::EVRNotificationError cppIVRNotifications_IVRNotifications_002_RemoveNotification(void *linux_side, VRNotificationId notificationId)
{
return ((IVRNotifications*)linux_side)->RemoveNotification((vr::VRNotificationId)notificationId);
}
#ifdef __cplusplus
}
#endif
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the files COPYING and Copyright.html. COPYING can be found at the root *
* of the source code distribution tree; Copyright.html can be found at the *
* root level of an installed copy of the electronic HDF5 document set and *
* is linked from the top-level documents page. It can also be found at *
* http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have *
* access to either file, you may request a copy from help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <string>
#include "H5Include.h"
#include "H5Exception.h"
#include "H5IdComponent.h"
#include "H5PropList.h"
#include "H5Object.h"
#include "H5AbstractDs.h"
#include "H5DxferProp.h"
#include "H5DataSpace.h"
#include "H5DcreatProp.h"
#include "H5CommonFG.h"
#include "H5DataType.h"
#include "H5DataSet.h"
#include "H5AtomType.h"
#include "H5IntType.h"
#include "H5EnumType.h"
#ifndef H5_NO_NAMESPACE
namespace H5 {
#endif
//--------------------------------------------------------------------------
// Function: EnumType default constructor
///\brief Default constructor: Creates a stub datatype
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType() : DataType() {}
//--------------------------------------------------------------------------
// Function: EnumType overloaded constructor
///\brief Creates an EnumType object using the id of an existing datatype.
///\param existing_id - IN: Id of an existing datatype
///\exception H5::DataTypeIException
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( const hid_t existing_id ) : DataType( existing_id ) {}
//--------------------------------------------------------------------------
// Function: EnumType copy constructor
///\brief Copy constructor: makes a copy of the original EnumType object.
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( const EnumType& original ) : DataType( original ) {}
//--------------------------------------------------------------------------
// Function: EnumType overloaded constructor
///\brief Creates an empty enumeration datatype given a size, in bytes.
///\param size - IN: Number of bytes in the datatype to create
///\exception H5::DataTypeIException
// Description
// The DataType constructor calls the C API H5Tcreate to create
// the enum datatype.
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( size_t size ) : DataType( H5T_ENUM, size ) {}
//--------------------------------------------------------------------------
// Function: EnumType overloaded constructor
///\brief Gets the enum datatype of the specified dataset.
///\param dataset - IN: Dataset that this enum datatype associates with
///\exception H5::DataTypeIException
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( const DataSet& dataset ) : DataType()
{
// Calls C function H5Dget_type to get the id of the datatype
id = H5Dget_type( dataset.getId() );
// If the datatype id is not valid, throw an exception
if( id < 0 )
{
throw DataSetIException("EnumType constructor", "H5Dget_type failed");
}
}
//--------------------------------------------------------------------------
// Function: EnumType overloaded constructor
///\brief Creates a new enum datatype based on an integer datatype.
///\param data_type - IN: Base datatype
///\exception H5::DataTypeIException
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( const IntType& data_type ) : DataType()
{
// Calls C function H5Tenum_create to get the id of the datatype
id = H5Tenum_create( data_type.getId() );
// If the datatype id is not valid, throw an exception
if( id < 0 )
{
throw DataSetIException("EnumType constructor", "H5Tenum_create failed");
}
}
//--------------------------------------------------------------------------
// Function: EnumType::insert
///\brief Inserts a new member to this enumeration datatype.
///\param name - IN: Name of the new member
///\param value - IN: Pointer to the value of the new member
///\exception H5::DataTypeIException
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::insert( const char* name, void *value ) const
{
// Calls C routine H5Tenum_insert to insert the new enum datatype member.
herr_t ret_value = H5Tenum_insert( id, name, value );
if( ret_value < 0 )
{
throw DataTypeIException("EnumType::insert", "H5Tenum_insert failed");
}
}
//--------------------------------------------------------------------------
// Function: EnumType::insert
///\brief This is an overloaded member function, provided for convenience.
/// It differs from the above function only in the type of
/// argument \a name.
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::insert( const H5std_string& name, void *value ) const
{
insert( name.c_str(), value );
}
//--------------------------------------------------------------------------
// Function: EnumType::nameOf
///\brief Returns the symbol name corresponding to a specified member
/// of this enumeration datatype.
///\param value - IN: Pointer to the value of the enum datatype
///\param size - IN: Size for the name
///\exception H5::DataTypeIException
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
H5std_string EnumType::nameOf( void *value, size_t size ) const
{
char* name_C = new char[size+1]; // temporary C-string for C API
// Calls C routine H5Tenum_nameof to get the name of the specified enum type
herr_t ret_value = H5Tenum_nameof( id, value, name_C, size );
// If H5Tenum_nameof returns a negative value, raise an exception,
if( ret_value < 0 )
{
throw DataTypeIException("EnumType::nameOf", "H5Tenum_nameof failed");
}
// otherwise, create the string to hold the datatype name and return it
H5std_string name = H5std_string(name_C);
delete []name_C;
return( name );
}
//--------------------------------------------------------------------------
// Function: EnumType::valueOf
///\brief Retrieves the value corresponding to a member of this
/// enumeration datatype, given the member's name.
///\param name - IN: Name of the queried member
///\param value - OUT: Pointer to the retrieved value
///\exception H5::DataTypeIException
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::valueOf( const char* name, void *value ) const
{
// Calls C routine H5Tenum_valueof to get the enum datatype value
herr_t ret_value = H5Tenum_valueof( id, name, value );
if( ret_value < 0 )
{
throw DataTypeIException("EnumType::valueOf", "H5Tenum_valueof failed");
}
}
//--------------------------------------------------------------------------
// Function: EnumType::valueOf
///\brief This is an overloaded member function, provided for convenience.
/// It differs from the above function only in the type of
/// argument \a name.
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::valueOf( const H5std_string& name, void *value ) const
{
valueOf( name.c_str(), value );
}
//--------------------------------------------------------------------------
// Function: EnumType::getMemberIndex
///\brief Returns the index of a member in this enumeration datatype.
///\param name - IN: Name of the queried member
///\return Index of the member if it exists. Index will have the value
/// between 0 and \c N-1, where \c N is the value returned by the
/// member function \c EnumType::getNmembers.
///\exception H5::DataTypeIException
// Programmer Binh-Minh Ribler - May 16, 2002
//--------------------------------------------------------------------------
int EnumType::getMemberIndex(const char *name) const
{
int member_index = H5Tget_member_index(id, name);
if( member_index < 0 )
{
throw DataTypeIException("EnumType::getMemberIndex",
"H5Tget_member_index returns negative value");
}
return( member_index );
}
//--------------------------------------------------------------------------
// Function: EnumType::getMemberIndex
///\brief This is an overloaded member function, provided for convenience.
/// It differs from the above function only in the type of
/// argument \a name.
// Programmer Binh-Minh Ribler - May 16, 2002
//--------------------------------------------------------------------------
int EnumType::getMemberIndex(const H5std_string& name) const
{
return(EnumType::getMemberIndex(name.c_str()));
}
//--------------------------------------------------------------------------
// Function: EnumType::getNmembers
///\brief Returns the number of members in this enumeration datatype.
///\return Number of members
///\exception H5::DataTypeIException
// Programmer Binh-Minh Ribler - May, 2004
//--------------------------------------------------------------------------
int EnumType::getNmembers() const
{
int num_members = H5Tget_nmembers( id );
if( num_members < 0 )
{
throw DataTypeIException("EnumType::getNmembers",
"H5Tget_nmembers returns negative number of members");
}
return( num_members );
}
//--------------------------------------------------------------------------
// Function: EnumType::getMemberValue
///\brief Retrieves the value of a member in this enumeration datatype,
/// given the member's index.
///\param memb_no - IN: Index of the queried member
///\param value - OUT: Pointer to the retrieved value
///\exception H5::DataTypeIException
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::getMemberValue( unsigned memb_no, void *value ) const
{
// Call C routine H5Tget_member_value to get the datatype member's value
hid_t ret_value = H5Tget_member_value( id, memb_no, value );
if( ret_value < 0 )
{
throw DataTypeIException("EnumType::getMemberValue", "H5Tget_member_value failed");
}
}
//--------------------------------------------------------------------------
// Function: EnumType destructor
///\brief Properly terminates access to this enum datatype.
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::~EnumType() {}
#ifndef H5_NO_NAMESPACE
} // end namespace
#endif
|
#include "selfdrive/camerad/cameras/camera_replay.h"
#include <cassert>
#include <thread>
#include "selfdrive/common/clutil.h"
#include "selfdrive/common/util.h"
extern ExitHandler do_exit;
void camera_autoexposure(CameraState *s, float grey_frac) {}
namespace {
const char *BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/";
const std::string road_camera_route = "0c94aa1e1296d7c6|2021-05-05--19-48-37";
// const std::string driver_camera_route = "534ccd8a0950a00c|2021-06-08--12-15-37";
std::string get_url(std::string route_name, const std::string &camera, int segment_num) {
std::replace(route_name.begin(), route_name.end(), '|', '/');
return util::string_format("%s%s/%d/%s.hevc", BASE_URL, route_name.c_str(), segment_num, camera.c_str());
}
void camera_init(VisionIpcServer *v, CameraState *s, int camera_id, unsigned int fps, cl_device_id device_id, cl_context ctx, VisionStreamType rgb_type, VisionStreamType yuv_type, const std::string &url) {
// TODO: cache url file
s->frame = new FrameReader();
if (!s->frame->load(url)) {
printf("failed to load stream from %s", url.c_str());
assert(0);
}
CameraInfo ci = {
.frame_width = s->frame->width,
.frame_height = s->frame->height,
.frame_stride = s->frame->width * 3,
};
s->ci = ci;
s->camera_num = camera_id;
s->fps = fps;
s->buf.init(device_id, ctx, s, v, FRAME_BUF_COUNT, rgb_type, yuv_type);
}
void camera_close(CameraState *s) {
delete s->frame;
}
void run_camera(CameraState *s) {
uint32_t stream_frame_id = 0, frame_id = 0;
size_t buf_idx = 0;
while (!do_exit) {
if (stream_frame_id == s->frame->getFrameCount()) {
// loop stream
stream_frame_id = 0;
}
uint8_t *dat = s->frame->get(stream_frame_id++);
if (dat) {
s->buf.camera_bufs_metadata[buf_idx] = {.frame_id = frame_id};
auto &buf = s->buf.camera_bufs[buf_idx];
CL_CHECK(clEnqueueWriteBuffer(buf.copy_q, buf.buf_cl, CL_TRUE, 0, s->frame->getRGBSize(), dat, 0, NULL, NULL));
s->buf.queue(buf_idx);
++frame_id;
buf_idx = (buf_idx + 1) % FRAME_BUF_COUNT;
}
util::sleep_for(1000 / s->fps);
}
}
void road_camera_thread(CameraState *s) {
set_thread_name("replay_road_camera_thread");
run_camera(s);
}
// void driver_camera_thread(CameraState *s) {
// set_thread_name("replay_driver_camera_thread");
// run_camera(s);
// }
void process_road_camera(MultiCameraState *s, CameraState *c, int cnt) {
const CameraBuf *b = &c->buf;
MessageBuilder msg;
auto framed = msg.initEvent().initRoadCameraState();
fill_frame_data(framed, b->cur_frame_data);
framed.setImage(kj::arrayPtr((const uint8_t *)b->cur_yuv_buf->addr, b->cur_yuv_buf->len));
framed.setTransform(b->yuv_transform.v);
s->pm->send("roadCameraState", msg);
}
// void process_driver_camera(MultiCameraState *s, CameraState *c, int cnt) {
// MessageBuilder msg;
// auto framed = msg.initEvent().initDriverCameraState();
// framed.setFrameType(cereal::FrameData::FrameType::FRONT);
// fill_frame_data(framed, c->buf.cur_frame_data);
// s->pm->send("driverCameraState", msg);
// }
} // namespace
void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx) {
camera_init(v, &s->road_cam, CAMERA_ID_LGC920, 20, device_id, ctx,
VISION_STREAM_RGB_BACK, VISION_STREAM_YUV_BACK, get_url(road_camera_route, "fcamera", 0));
// camera_init(v, &s->driver_cam, CAMERA_ID_LGC615, 10, device_id, ctx,
// VISION_STREAM_RGB_FRONT, VISION_STREAM_YUV_FRONT, get_url(driver_camera_route, "dcamera", 0));
s->pm = new PubMaster({"roadCameraState", "driverCameraState", "thumbnail"});
}
void cameras_open(MultiCameraState *s) {}
void cameras_close(MultiCameraState *s) {
camera_close(&s->road_cam);
camera_close(&s->driver_cam);
delete s->pm;
}
void cameras_run(MultiCameraState *s) {
std::vector<std::thread> threads;
threads.push_back(start_process_thread(s, &s->road_cam, process_road_camera));
// threads.push_back(start_process_thread(s, &s->driver_cam, process_driver_camera));
// threads.push_back(std::thread(driver_camera_thread, &s->driver_cam));
road_camera_thread(&s->road_cam);
for (auto &t : threads) t.join();
cameras_close(s);
}
|
#include "opae_sim.h"
#include <verilated.h>
#include "Vvortex_afu_shim.h"
#include "Vvortex_afu_shim__Syms.h"
#ifdef VCD_OUTPUT
#include <verilated_vcd_c.h>
#endif
#include <iostream>
#include <fstream>
#include <iomanip>
#include <mem.h>
#define RAMULATOR
#include <ramulator/src/Gem5Wrapper.h>
#include <ramulator/src/Request.h>
#include <ramulator/src/Statistics.h>
#include <VX_config.h>
#include <vortex_afu.h>
#include <future>
#include <list>
#include <queue>
#include <unordered_map>
#ifndef MEMORY_BANKS
#ifdef PLATFORM_PARAM_LOCAL_MEMORY_BANKS
#define MEMORY_BANKS PLATFORM_PARAM_LOCAL_MEMORY_BANKS
#else
#define MEMORY_BANKS 2
#endif
#endif
#ifndef MEM_CYCLE_RATIO
#define MEM_CYCLE_RATIO -1
#endif
#undef MEM_BLOCK_SIZE
#define MEM_BLOCK_SIZE (PLATFORM_PARAM_LOCAL_MEMORY_DATA_WIDTH / 8)
#define CACHE_BLOCK_SIZE 64
#define CCI_LATENCY 8
#define CCI_RAND_MOD 8
#define CCI_RQ_SIZE 16
#define CCI_WQ_SIZE 16
#ifndef TRACE_START_TIME
#define TRACE_START_TIME 0ull
#endif
#ifndef TRACE_STOP_TIME
#define TRACE_STOP_TIME -1ull
#endif
#ifndef VERILATOR_RESET_VALUE
#define VERILATOR_RESET_VALUE 2
#endif
#define RAM_PAGE_SIZE 4096
using namespace vortex;
static uint64_t timestamp = 0;
double sc_time_stamp() {
return timestamp;
}
static void *__aligned_malloc(size_t alignment, size_t size) {
// reserve margin for alignment and storing of unaligned address
size_t margin = (alignment-1) + sizeof(void*);
void *unaligned_addr = malloc(size + margin);
void **aligned_addr = (void**)((uintptr_t)(((uint8_t*)unaligned_addr) + margin) & ~(alignment-1));
aligned_addr[-1] = unaligned_addr;
return aligned_addr;
}
static void __aligned_free(void *ptr) {
// retreive the stored unaligned address and use it to free the allocation
void* unaligned_addr = ((void**)ptr)[-1];
free(unaligned_addr);
}
///////////////////////////////////////////////////////////////////////////////
static bool trace_enabled = false;
static uint64_t trace_start_time = TRACE_START_TIME;
static uint64_t trace_stop_time = TRACE_STOP_TIME;
bool sim_trace_enabled() {
if (timestamp >= trace_start_time
&& timestamp < trace_stop_time)
return true;
return trace_enabled;
}
void sim_trace_enable(bool enable) {
trace_enabled = enable;
}
///////////////////////////////////////////////////////////////////////////////
class opae_sim::Impl {
public:
Impl()
: stop_(false)
, host_buffer_ids_(0) {
// force random values for unitialized signals
Verilated::randReset(VERILATOR_RESET_VALUE);
Verilated::randSeed(50);
// turn off assertion before reset
Verilated::assertOn(false);
// create RTL module instance
device_ = new Vvortex_afu_shim();
#ifdef VCD_OUTPUT
Verilated::traceEverOn(true);
trace_ = new VerilatedVcdC();
device_->trace(this->trace, 99);
trace_->open("trace.vcd");
#endif
ram_ = new RAM(RAM_PAGE_SIZE);
// initialize dram simulator
ramulator::Config ram_config;
ram_config.add("standard", "DDR4");
ram_config.add("channels", std::to_string(MEMORY_BANKS));
ram_config.add("ranks", "1");
ram_config.add("speed", "DDR4_2400R");
ram_config.add("org", "DDR4_4Gb_x8");
ram_config.add("mapping", "defaultmapping");
ram_config.set_core_num(1);
dram_ = new ramulator::Gem5Wrapper(ram_config, MEM_BLOCK_SIZE);
Stats::statlist.output("ramulator.ddr4.log");
// reset the device
this->reset();
// launch execution thread
future_ = std::async(std::launch::async, [&]{
while (!stop_) {
std::lock_guard<std::mutex> guard(mutex_);
this->tick();
}
});
}
~Impl() {
stop_ = true;
if (future_.valid()) {
future_.wait();
}
for (auto& buffer : host_buffers_) {
__aligned_free(buffer.second.data);
}
#ifdef VCD_OUTPUT
trace_->close();
delete trace_;
#endif
delete device_;
delete ram_;
if (dram_) {
dram_->finish();
Stats::statlist.printall();
delete dram_;
}
}
int prepare_buffer(uint64_t len, void **buf_addr, uint64_t *wsid, int flags) {
auto alloc = __aligned_malloc(CACHE_BLOCK_SIZE, len);
if (alloc == NULL)
return -1;
host_buffer_t buffer;
buffer.data = (uint64_t*)alloc;
buffer.size = len;
buffer.ioaddr = uintptr_t(alloc);
auto buffer_id = host_buffer_ids_++;
host_buffers_.emplace(buffer_id, buffer);
*buf_addr = alloc;
*wsid = buffer_id;
return 0;
}
void release_buffer(uint64_t wsid) {
auto it = host_buffers_.find(wsid);
if (it != host_buffers_.end()) {
__aligned_free(it->second.data);
host_buffers_.erase(it);
}
}
void get_io_address(uint64_t wsid, uint64_t *ioaddr) {
*ioaddr = host_buffers_[wsid].ioaddr;
}
void read_mmio64(uint32_t mmio_num, uint64_t offset, uint64_t *value) {
std::lock_guard<std::mutex> guard(mutex_);
device_->vcp2af_sRxPort_c0_mmioRdValid = 1;
device_->vcp2af_sRxPort_c0_ReqMmioHdr_address = offset / 4;
device_->vcp2af_sRxPort_c0_ReqMmioHdr_length = 1;
device_->vcp2af_sRxPort_c0_ReqMmioHdr_tid = 0;
this->tick();
device_->vcp2af_sRxPort_c0_mmioRdValid = 0;
assert(device_->af2cp_sTxPort_c2_mmioRdValid);
*value = device_->af2cp_sTxPort_c2_data;
}
void write_mmio64(uint32_t mmio_num, uint64_t offset, uint64_t value) {
std::lock_guard<std::mutex> guard(mutex_);
device_->vcp2af_sRxPort_c0_mmioWrValid = 1;
device_->vcp2af_sRxPort_c0_ReqMmioHdr_address = offset / 4;
device_->vcp2af_sRxPort_c0_ReqMmioHdr_length = 1;
device_->vcp2af_sRxPort_c0_ReqMmioHdr_tid = 0;
memcpy(device_->vcp2af_sRxPort_c0_data, &value, 8);
this->tick();
device_->vcp2af_sRxPort_c0_mmioWrValid = 0;
}
private:
void reset() {
cci_reads_.clear();
cci_writes_.clear();
device_->vcp2af_sRxPort_c0_mmioRdValid = 0;
device_->vcp2af_sRxPort_c0_mmioWrValid = 0;
device_->vcp2af_sRxPort_c0_rspValid = 0;
device_->vcp2af_sRxPort_c1_rspValid = 0;
device_->vcp2af_sRxPort_c0_TxAlmFull = 0;
device_->vcp2af_sRxPort_c1_TxAlmFull = 0;
for (int b = 0; b < MEMORY_BANKS; ++b) {
pending_mem_reqs_[b].clear();
device_->avs_readdatavalid[b] = 0;
device_->avs_waitrequest[b] = 0;
}
device_->reset = 1;
for (int i = 0; i < RESET_DELAY; ++i) {
device_->clk = 0;
this->eval();
device_->clk = 1;
this->eval();
}
device_->reset = 0;
// Turn on assertion after reset
Verilated::assertOn(true);
}
void tick() {
this->sRxPort_bus();
this->sTxPort_bus();
this->avs_bus();
if (!dram_queue_.empty()) {
if (dram_->send(dram_queue_.front()))
dram_queue_.pop();
}
device_->clk = 0;
this->eval();
device_->clk = 1;
this->eval();
if (MEM_CYCLE_RATIO > 0) {
auto cycle = timestamp / 2;
if ((cycle % MEM_CYCLE_RATIO) == 0)
dram_->tick();
} else {
for (int i = MEM_CYCLE_RATIO; i <= 0; ++i)
dram_->tick();
}
#ifndef NDEBUG
fflush(stdout);
#endif
}
void eval() {
device_->eval();
#ifdef VCD_OUTPUT
if (sim_trace_enabled()) {
trace_->dump(timestamp);
}
#endif
++timestamp;
}
void sRxPort_bus() {
// check mmio request
bool mmio_req_enabled = device_->vcp2af_sRxPort_c0_mmioRdValid
|| device_->vcp2af_sRxPort_c0_mmioWrValid;
// schedule CCI read responses
std::list<cci_rd_req_t>::iterator cci_rd_it(cci_reads_.end());
for (auto it = cci_reads_.begin(), ie = cci_reads_.end(); it != ie; ++it) {
if (it->cycles_left > 0)
it->cycles_left -= 1;
if ((cci_rd_it == ie) && (it->cycles_left == 0)) {
cci_rd_it = it;
}
}
// schedule CCI write responses
std::list<cci_wr_req_t>::iterator cci_wr_it(cci_writes_.end());
for (auto it = cci_writes_.begin(), ie = cci_writes_.end(); it != ie; ++it) {
if (it->cycles_left > 0)
it->cycles_left -= 1;
if ((cci_wr_it == ie) && (it->cycles_left == 0)) {
cci_wr_it = it;
}
}
// send CCI write response
device_->vcp2af_sRxPort_c1_rspValid = 0;
if (cci_wr_it != cci_writes_.end()) {
device_->vcp2af_sRxPort_c1_rspValid = 1;
device_->vcp2af_sRxPort_c1_hdr_resp_type = 0;
device_->vcp2af_sRxPort_c1_hdr_mdata = cci_wr_it->mdata;
cci_writes_.erase(cci_wr_it);
}
// send CCI read response (ensure mmio disabled)
device_->vcp2af_sRxPort_c0_rspValid = 0;
if (!mmio_req_enabled
&& (cci_rd_it != cci_reads_.end())) {
device_->vcp2af_sRxPort_c0_rspValid = 1;
device_->vcp2af_sRxPort_c0_hdr_resp_type = 0;
memcpy(device_->vcp2af_sRxPort_c0_data, cci_rd_it->data.data(), CACHE_BLOCK_SIZE);
device_->vcp2af_sRxPort_c0_hdr_mdata = cci_rd_it->mdata;
/*printf("%0ld: [sim] CCI Rd Rsp: addr=%ld, mdata=%d, data=", timestamp, cci_rd_it->addr, cci_rd_it->mdata);
for (int i = 0; i < CACHE_BLOCK_SIZE; ++i)
printf("%02x", cci_rd_it->data[CACHE_BLOCK_SIZE-1-i]);
printf("\n");*/
cci_reads_.erase(cci_rd_it);
}
}
void sTxPort_bus() {
// process read requests
if (device_->af2cp_sTxPort_c0_valid) {
assert(!device_->vcp2af_sRxPort_c0_TxAlmFull);
cci_rd_req_t cci_req;
cci_req.cycles_left = CCI_LATENCY + (timestamp % CCI_RAND_MOD);
cci_req.addr = device_->af2cp_sTxPort_c0_hdr_address;
cci_req.mdata = device_->af2cp_sTxPort_c0_hdr_mdata;
auto host_ptr = (uint64_t*)(device_->af2cp_sTxPort_c0_hdr_address * CACHE_BLOCK_SIZE);
memcpy(cci_req.data.data(), host_ptr, CACHE_BLOCK_SIZE);
//printf("%0ld: [sim] CCI Rd Req: addr=%ld, mdata=%d\n", timestamp, device_->af2cp_sTxPort_c0_hdr_address, cci_req.mdata);
cci_reads_.emplace_back(cci_req);
}
// process write requests
if (device_->af2cp_sTxPort_c1_valid) {
assert(!device_->vcp2af_sRxPort_c1_TxAlmFull);
cci_wr_req_t cci_req;
cci_req.cycles_left = CCI_LATENCY + (timestamp % CCI_RAND_MOD);
cci_req.mdata = device_->af2cp_sTxPort_c1_hdr_mdata;
auto host_ptr = (uint64_t*)(device_->af2cp_sTxPort_c1_hdr_address * CACHE_BLOCK_SIZE);
memcpy(host_ptr, device_->af2cp_sTxPort_c1_data, CACHE_BLOCK_SIZE);
cci_writes_.emplace_back(cci_req);
}
// check queues overflow
device_->vcp2af_sRxPort_c0_TxAlmFull = (cci_reads_.size() >= (CCI_RQ_SIZE-1));
device_->vcp2af_sRxPort_c1_TxAlmFull = (cci_writes_.size() >= (CCI_WQ_SIZE-1));
}
void avs_bus() {
for (int b = 0; b < MEMORY_BANKS; ++b) {
// process memory responses
device_->avs_readdatavalid[b] = 0;
if (!pending_mem_reqs_[b].empty()
&& (*pending_mem_reqs_[b].begin())->ready) {
auto mem_rd_it = pending_mem_reqs_[b].begin();
auto mem_req = *mem_rd_it;
device_->avs_readdatavalid[b] = 1;
memcpy(device_->avs_readdata[b], mem_req->data.data(), MEM_BLOCK_SIZE);
uint32_t addr = mem_req->addr;
pending_mem_reqs_[b].erase(mem_rd_it);
delete mem_req;
}
// process memory requests
assert(!device_->avs_read[b] || !device_->avs_write[b]);
unsigned byte_addr = device_->avs_address[b] * MEM_BLOCK_SIZE;
if (device_->avs_write[b]) {
uint64_t byteen = device_->avs_byteenable[b];
uint8_t* data = (uint8_t*)(device_->avs_writedata[b]);
for (int i = 0; i < MEM_BLOCK_SIZE; i++) {
if ((byteen >> i) & 0x1) {
(*ram_)[byte_addr + i] = data[i];
}
}
/*printf("%0ld: [sim] MEM Wr Req: bank=%d, addr=%x, data=", timestamp, b, byte_addr);
for (int i = 0; i < MEM_BLOCK_SIZE; i++) {
printf("%02x", data[(MEM_BLOCK_SIZE-1)-i]);
}
printf("\n");*/
// send dram request
ramulator::Request dram_req(
byte_addr,
ramulator::Request::Type::WRITE,
0
);
dram_queue_.push(dram_req);
}
if (device_->avs_read[b]) {
auto mem_req = new mem_rd_req_t();
mem_req->addr = device_->avs_address[b];
ram_->read(mem_req->data.data(), byte_addr, MEM_BLOCK_SIZE);
mem_req->ready = false;
pending_mem_reqs_[b].emplace_back(mem_req);
/*printf("%0ld: [sim] MEM Rd Req: bank=%d, addr=%x, pending={", timestamp, b, mem_req.addr * MEM_BLOCK_SIZE);
for (auto& req : pending_mem_reqs_[b]) {
if (req.cycles_left != 0)
printf(" !%0x", req.addr * MEM_BLOCK_SIZE);
else
printf(" %0x", req.addr * MEM_BLOCK_SIZE);
}
printf("}\n");*/
// send dram request
ramulator::Request dram_req(
byte_addr,
ramulator::Request::Type::READ,
std::bind([](ramulator::Request& dram_req, mem_rd_req_t* mem_req) {
mem_req->ready = true;
}, placeholders::_1, mem_req),
0
);
dram_queue_.push(dram_req);
}
device_->avs_waitrequest[b] = false;
}
}
typedef struct {
bool ready;
std::array<uint8_t, MEM_BLOCK_SIZE> data;
uint32_t addr;
} mem_rd_req_t;
typedef struct {
int cycles_left;
std::array<uint8_t, CACHE_BLOCK_SIZE> data;
uint64_t addr;
uint32_t mdata;
} cci_rd_req_t;
typedef struct {
int cycles_left;
uint32_t mdata;
} cci_wr_req_t;
typedef struct {
uint64_t* data;
size_t size;
uint64_t ioaddr;
} host_buffer_t;
std::future<void> future_;
bool stop_;
std::unordered_map<int64_t, host_buffer_t> host_buffers_;
int64_t host_buffer_ids_;
std::list<mem_rd_req_t*> pending_mem_reqs_[MEMORY_BANKS];
std::list<cci_rd_req_t> cci_reads_;
std::list<cci_wr_req_t> cci_writes_;
std::mutex mutex_;
RAM *ram_;
ramulator::Gem5Wrapper* dram_;
std::queue<ramulator::Request> dram_queue_;
Vvortex_afu_shim *device_;
#ifdef VCD_OUTPUT
VerilatedVcdC *trace_;
#endif
};
///////////////////////////////////////////////////////////////////////////////
opae_sim::opae_sim()
: impl_(new Impl())
{}
opae_sim::~opae_sim() {
delete impl_;
}
int opae_sim::prepare_buffer(uint64_t len, void **buf_addr, uint64_t *wsid, int flags) {
return impl_->prepare_buffer(len, buf_addr, wsid, flags);
}
void opae_sim::release_buffer(uint64_t wsid) {
impl_->release_buffer(wsid);
}
void opae_sim::get_io_address(uint64_t wsid, uint64_t *ioaddr) {
impl_->get_io_address(wsid, ioaddr);
}
void opae_sim::write_mmio64(uint32_t mmio_num, uint64_t offset, uint64_t value) {
impl_->write_mmio64(mmio_num, offset, value);
}
void opae_sim::read_mmio64(uint32_t mmio_num, uint64_t offset, uint64_t *value) {
impl_->read_mmio64(mmio_num, offset, value);
}
|
// The YukinoDB Unit Test Suite
//
// db_impl_test.cc
//
// Created by Niko Bellic.
//
//
#include "balance/db_impl.h"
#include "yukino/options.h"
#include "yukino/env.h"
#include "yukino/write_batch.h"
#include "gtest/gtest.h"
#include <stdio.h>
namespace yukino {
namespace balance {
class BalanceDBImplTest : public ::testing::Test {
public:
BalanceDBImplTest () {
}
virtual void SetUp() override {
options_.create_if_missing = true;
db_ = new DBImpl(options_, kDBName);
auto rs = db_->Open();
ASSERT_TRUE(rs.ok()) << rs.ToString();
}
virtual void TearDown() override {
delete db_;
db_ = nullptr;
Env::Default()->DeleteFile(kDBName, true);
}
DBImpl *db_ = nullptr;
Options options_;
static constexpr const char *kDBName = "test";
};
TEST_F(BalanceDBImplTest, Sanity) {
auto rs = db_->Put(WriteOptions(), "aaa", "1");
ASSERT_TRUE(rs.ok()) << rs.ToString();
rs = db_->Put(WriteOptions(), "aab", "2");
ASSERT_TRUE(rs.ok()) << rs.ToString();
rs = db_->Put(WriteOptions(), "aac", "3");
ASSERT_TRUE(rs.ok()) << rs.ToString();
std::string dummy;
rs = db_->Get(ReadOptions(), "aaa", &dummy);
ASSERT_TRUE(rs.ok()) << rs.ToString();
ASSERT_EQ("1", dummy);
rs = db_->Get(ReadOptions(), "aab", &dummy);
ASSERT_TRUE(rs.ok()) << rs.ToString();
ASSERT_EQ("2", dummy);
rs = db_->Get(ReadOptions(), "aac", &dummy);
ASSERT_TRUE(rs.ok()) << rs.ToString();
ASSERT_EQ("3", dummy);
}
TEST_F(BalanceDBImplTest, Checkpoint) {
static const char *keys[] = {
"a",
"aa",
"aaa",
"aaaa",
"aaaaa",
};
for (auto key : keys) {
auto rs = db_->Put(WriteOptions(), key, "1");
}
db_->ScheduleCheckpoint();
db_->TEST_WaitForCheckpoint();
}
TEST_F(BalanceDBImplTest, Recover) {
static const char *keys[] = {
"b",
"bb",
"bbb",
"bbbb",
"bbbbb",
};
for (auto key : keys) {
auto rs = db_->Put(WriteOptions(), key, "0");
}
delete db_;
options_.create_if_missing = false;
db_ = new DBImpl(options_, kDBName);
auto rs = db_->Open();
ASSERT_TRUE(rs.ok()) << rs.ToString();
}
} // namespace balance
} // namespace yukino
|
// MyTrace.cpp
#include "stdafx.h"
#include "MyTrace.h"
#ifdef _DEBUG
static LPCTSTR MyLevel[10] =
{
_T("|"),
_T("| |"),
_T("| | |"),
_T("| | |"),
_T("| | | |"),
_T("| | | | |"),
_T("| | | | | |"),
_T("| | | | | | |"),
_T("| | | | | | | |"),
_T("| | | | | | | |"),
};
static TCHAR MyTraceBuffer[512];
static int MyTraceLevel;
void MyTrace(int nLevel, LPCTSTR pFmt, ...)
{
va_list ap;
va_start( ap,pFmt );
_vsntprintf(MyTraceBuffer,512,pFmt,ap);
va_end(ap);
if( nLevel > 0 )
TRACE(_T("%s-> %s"),MyLevel[MyTraceLevel],MyTraceBuffer);
else if( nLevel < 0 && MyTraceLevel > 0 )
TRACE(_T("%s<- %s"),MyLevel[MyTraceLevel-1],MyTraceBuffer);
else
TRACE(_T("%s %s"),MyLevel[MyTraceLevel],MyTraceBuffer);
MyTraceLevel += nLevel;
if( MyTraceLevel < 0 )
MyTraceLevel = 0;
else if( MyTraceLevel >= 10 )
MyTraceLevel = 9;
}
MEMORY_BASIC_INFORMATION _mbi_;
void MyTraceSEH(PEXCEPTION_RECORD per)
{
MYTRACE(0,_T("ExceptionCode = 0x%p\n"),per->ExceptionCode);
MYTRACE(0,_T("ExceptionFlags = 0x%p\n"),per->ExceptionFlags);
MYTRACE(0,_T("ExceptionAddress = 0x%p\n"),per->ExceptionAddress);
MYTRACE(0,_T("NumberParameters = 0x%p\n"),per->NumberParameters);
for( DWORD i = 0; i < per->NumberParameters; ++i )
{
MYTRACE(0,_T("ExceptionInformation[%d] = 0x%p\n"),i,per->ExceptionInformation[i]);
}
if( per->NumberParameters > 1 )
{
MYTRACE(0,_T("Attempt to %s data at address %p\n"),
per->ExceptionInformation[0] ? _T("WRITE") : _T("READ"),
per->ExceptionInformation[1]);
DWORD dwRet = VirtualQuery(
(LPCVOID)(per->ExceptionInformation[1]),
&_mbi_, sizeof(_mbi_));
if( dwRet == sizeof(_mbi_) )
{
MYTRACE(0,_T("BaseAddress = %p\n"),_mbi_.BaseAddress);
MYTRACE(0,_T("AllocationBase = %p\n"),_mbi_.AllocationBase);
switch( _mbi_.AllocationProtect )
{
case PAGE_READONLY:
MYTRACE(0,_T("AllocationProtect = PAGE_READONLY\n"));
MYTRACE(0,_T("\"Attempts to write to or execut code in this page\n"));
MYTRACE(0,_T("raize an acess violation.\"\n"));
break;
case PAGE_READWRITE:
MYTRACE(0,_T("AllocationProtect = PAGE_READWRITE\n"));
MYTRACE(0,_T("\"Attemps to execute code in this page raise an acess\n"));
MYTRACE(0,_T("violation.\"\n"));
break;
case PAGE_WRITECOPY:
MYTRACE(0,_T("AllocationProtect = PAGE_WRITECOPY\n"));
MYTRACE(0,_T("Attemps to execute code in this page raise an access\n"));
MYTRACE(0,_T("violation. Attempts to write to memory in this page\n"));
MYTRACE(0,_T("cause the system to give the process its own private\n"));
MYTRACE(0,_T("copy of the page (backed byt the paging file).\"\n"));
break;
case PAGE_EXECUTE:
MYTRACE(0,_T("AllocationProtect = PAGE_EXECUTE\n"));
MYTRACE(0,_T("\"Attempts to read or write memory in this page raise\n"));
MYTRACE(0,_T("an access violation.\"\n"));
break;
case PAGE_EXECUTE_READ:
MYTRACE(0,_T("AllocationProtect = PAGE_EXECUTE_READ\n"));
MYTRACE(0,_T("\"Attemps to write to memory in this page raise an\n"));
MYTRACE(0,_T("access violation.\"\n"));
break;
case PAGE_EXECUTE_READWRITE:
MYTRACE(0,_T("AllocationProtect = PAGE_EXECUTE_READWRITE\n"));
MYTRACE(0,_T("\"There is nothin you can do to this page to raise an\n"));
MYTRACE(0,_T("access violation.\"\n"));
break;
case PAGE_EXECUTE_WRITECOPY:
MYTRACE(0,_T("AllocationProtect = PAGE_EXECUTE_WRITECOPY\n"));
MYTRACE(0,_T("\"There is nothing you can do to this region to raise an\n"));
MYTRACE(0,_T("access violation. Attempt to write to memory in this\n"));
MYTRACE(0,_T("page cause the system to give the process its own\n"));
MYTRACE(0,_T("private copy of the page (backed by the paging file).\"\n"));
break;
case PAGE_GUARD:
MYTRACE(0,_T("AllocationProtect = PAGE_GUARD\n"));
break;
case PAGE_NOACCESS:
MYTRACE(0,_T("AllocationProtect = PAGE_NOACCESS\n"));
MYTRACE(0,_T("\"Attempts to read from, writ to, or excute code in\n"));
MYTRACE(0,_T("this page raise an access violation.\"\n"));
break;
case PAGE_NOCACHE:
MYTRACE(0,_T("AllocationProtect = PAGE_NOCACHE\n"));
break;
}
MYTRACE(0,_T("RegionSize = %d\n"),_mbi_.RegionSize);
switch( _mbi_.State )
{
case MEM_COMMIT:
MYTRACE(0,_T("State = MEM_COMMIT\n"));
break;
case MEM_FREE:
MYTRACE(0,_T("State = MEM_FREE\n"));
break;
case MEM_RESERVE:
MYTRACE(0,_T("State = MEM_RESERVE\n"));
break;
}
MYTRACE(0,_T("Protect = %d\n"),_mbi_.Protect);
switch( _mbi_.Type )
{
case MEM_IMAGE:
MYTRACE(0,_T("Type = MEM_IMAGE\n"),_mbi_.Type);
break;
case MEM_MAPPED:
MYTRACE(0,_T("Type = MEM_MAPPED\n"),_mbi_.Type);
break;
case MEM_PRIVATE:
MYTRACE(0,_T("Type = MEM_PRIVATE\n"),_mbi_.Type);
break;
}
}
}
}
#else
void MyTrace(int /*nLevel*/, LPCTSTR /*pFmt*/, ...) {}
void MyTraceSEH(PEXCEPTION_RECORD /*per*/) {}
#endif
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include <memory>
#include <unordered_set>
#include <utility>
#include <vector>
#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/IdPair.hpp"
#include "DataStructures/VariablesTag.hpp"
#include "Domain/BlockLogicalCoordinates.hpp"
#include "Domain/Tags.hpp"
#include "Domain/TagsTimeDependent.hpp"
#include "Parallel/GlobalCache.hpp"
#include "Parallel/Invoke.hpp"
#include "Parallel/ParallelComponentHelpers.hpp"
#include "Utilities/Algorithm.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/Literals.hpp"
#include "Utilities/Requires.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TaggedTuple.hpp"
#include "Utilities/TypeTraits.hpp"
#include "Utilities/TypeTraits/CreateHasStaticMemberVariable.hpp"
/// \cond
// IWYU pragma: no_forward_declare db::DataBox
namespace intrp {
template <class Metavariables>
struct Interpolator;
template <typename Metavariables, typename InterpolationTargetTag>
class InterpolationTarget;
namespace Actions {
template <typename InterpolationTargetTag>
struct CleanUpInterpolator;
template <typename InterpolationTargetTag>
struct ReceivePoints;
} // namespace Actions
namespace Tags {
template <typename TemporalId>
struct IndicesOfFilledInterpPoints;
template <typename TemporalId>
struct IndicesOfInvalidInterpPoints;
template <typename InterpolationTargetTag, typename TemporalId>
struct InterpolatedVars;
template <typename TemporalId>
struct CompletedTemporalIds;
template <typename TemporalId>
struct PendingTemporalIds;
template <typename TemporalId>
struct TemporalIds;
} // namespace Tags
} // namespace intrp
template <typename TagsList>
struct Variables;
/// \endcond
namespace intrp {
namespace InterpolationTarget_detail {
double get_temporal_id_value(double time);
double get_temporal_id_value(const TimeStepId& time_id);
double evaluate_temporal_id_for_expiration(double time);
double evaluate_temporal_id_for_expiration(const TimeStepId& time_id);
// apply_callback accomplishes the overload for the
// two signatures of callback functions.
// Uses SFINAE on return type.
template <typename T, typename DbTags, typename Metavariables,
typename TemporalId>
auto apply_callback(
const gsl::not_null<db::DataBox<DbTags>*> box,
const gsl::not_null<Parallel::GlobalCache<Metavariables>*> cache,
const TemporalId& temporal_id)
-> decltype(T::post_interpolation_callback::apply(box, cache, temporal_id),
bool()) {
return T::post_interpolation_callback::apply(box, cache, temporal_id);
}
template <typename T, typename DbTags, typename Metavariables,
typename TemporalId>
auto apply_callback(
const gsl::not_null<db::DataBox<DbTags>*> box,
const gsl::not_null<Parallel::GlobalCache<Metavariables>*> cache,
const TemporalId& temporal_id)
-> decltype(T::post_interpolation_callback::apply(*box, *cache,
temporal_id),
bool()) {
T::post_interpolation_callback::apply(*box, *cache, temporal_id);
// For the simpler callback function, we will always clean up volume data, so
// we return true here.
return true;
}
CREATE_HAS_STATIC_MEMBER_VARIABLE(fill_invalid_points_with)
CREATE_HAS_STATIC_MEMBER_VARIABLE_V(fill_invalid_points_with)
// Fills invalid points with some constant value.
template <typename InterpolationTargetTag, typename TemporalId, typename DbTags,
Requires<not has_fill_invalid_points_with_v<
typename InterpolationTargetTag::post_interpolation_callback>> =
nullptr>
void fill_invalid_points(const gsl::not_null<db::DataBox<DbTags>*> /*box*/,
const TemporalId& /*temporal_id*/) {}
template <typename InterpolationTargetTag, typename TemporalId, typename DbTags,
Requires<has_fill_invalid_points_with_v<
typename InterpolationTargetTag::post_interpolation_callback>> =
nullptr>
void fill_invalid_points(const gsl::not_null<db::DataBox<DbTags>*> box,
const TemporalId& temporal_id) {
const auto& invalid_indices =
db::get<Tags::IndicesOfInvalidInterpPoints<TemporalId>>(*box);
if (invalid_indices.find(temporal_id) != invalid_indices.end() and
not invalid_indices.at(temporal_id).empty()) {
db::mutate<Tags::IndicesOfInvalidInterpPoints<TemporalId>,
Tags::InterpolatedVars<InterpolationTargetTag, TemporalId>>(
box,
[&temporal_id](
const gsl::not_null<
std::unordered_map<TemporalId, std::unordered_set<size_t>>*>
indices_of_invalid_points,
const gsl::not_null<std::unordered_map<
TemporalId, Variables<typename InterpolationTargetTag::
vars_to_interpolate_to_target>>*>
vars_dest_all_times) {
auto& vars_dest = vars_dest_all_times->at(temporal_id);
const size_t npts_dest = vars_dest.number_of_grid_points();
const size_t nvars = vars_dest.number_of_independent_components;
for (auto index : indices_of_invalid_points->at(temporal_id)) {
for (size_t v = 0; v < nvars; ++v) {
// clang-tidy: no pointer arithmetic
vars_dest.data()[index + v * npts_dest] = // NOLINT
InterpolationTargetTag::post_interpolation_callback::
fill_invalid_points_with;
}
}
// Further functions may test if there are invalid points.
// Clear the invalid points now, since we have filled them.
indices_of_invalid_points->erase(temporal_id);
});
}
}
/// Wraps calling the callback function on an InterpolationTarget.
///
/// First prepares for the callback, then calls the callback,
/// and returns true if the callback is done and
/// false if the callback is not done (e.g. if the callback is an
/// apparent horizon search and it needs another iteration).
///
/// call_callback is called by an Action of InterpolationTarget.
///
/// Currently two Actions call call_callback:
/// - InterpolationTargetReceiveVars (called by Interpolator ParallelComponent)
/// - InterpolationTargetVarsFromElement (called by DgElementArray)
template <typename InterpolationTargetTag, typename DbTags,
typename Metavariables, typename TemporalId>
bool call_callback(
const gsl::not_null<db::DataBox<DbTags>*> box,
const gsl::not_null<Parallel::GlobalCache<Metavariables>*> cache,
const TemporalId& temporal_id) {
// Before doing anything else, deal with the possibility that some
// of the points might be outside of the Domain.
fill_invalid_points<InterpolationTargetTag>(box, temporal_id);
// Fill ::Tags::Variables<typename
// InterpolationTargetTag::vars_to_interpolate_to_target>
// with variables from correct temporal_id.
db::mutate_apply<
tmpl::list<::Tags::Variables<
typename InterpolationTargetTag::vars_to_interpolate_to_target>>,
tmpl::list<Tags::InterpolatedVars<InterpolationTargetTag, TemporalId>>>(
[&temporal_id](
const gsl::not_null<Variables<
typename InterpolationTargetTag::vars_to_interpolate_to_target>*>
vars,
const std::unordered_map<
TemporalId, Variables<typename InterpolationTargetTag::
vars_to_interpolate_to_target>>&
vars_at_all_times) { *vars = vars_at_all_times.at(temporal_id); },
box);
// apply_callback should return true if we are done with this
// temporal_id. It should return false only if the callback
// calls another `intrp::Action` that needs the volume data at this
// same temporal_id.
return apply_callback<InterpolationTargetTag>(box, cache, temporal_id);
}
/// Frees InterpolationTarget's memory associated with the supplied
/// temporal_id.
///
/// clean_up_interpolation_target is called by an Action of InterpolationTarget.
///
/// Currently two Actions call clean_up_interpolation_target:
/// - InterpolationTargetReceiveVars (called by Interpolator ParallelComponent)
/// - InterpolationTargetVarsFromElement (called by DgElementArray)
template <typename InterpolationTargetTag, typename DbTags, typename TemporalId>
void clean_up_interpolation_target(
const gsl::not_null<db::DataBox<DbTags>*> box,
const TemporalId& temporal_id) {
// We are now done with this temporal_id, so we can pop it and
// clean up data associated with it.
db::mutate<Tags::TemporalIds<TemporalId>,
Tags::CompletedTemporalIds<TemporalId>,
Tags::IndicesOfFilledInterpPoints<TemporalId>,
Tags::IndicesOfInvalidInterpPoints<TemporalId>,
Tags::InterpolatedVars<InterpolationTargetTag, TemporalId>>(
box, [&temporal_id](
const gsl::not_null<std::deque<TemporalId>*> ids,
const gsl::not_null<std::deque<TemporalId>*> completed_ids,
const gsl::not_null<
std::unordered_map<TemporalId, std::unordered_set<size_t>>*>
indices_of_filled,
const gsl::not_null<
std::unordered_map<TemporalId, std::unordered_set<size_t>>*>
indices_of_invalid,
const gsl::not_null<std::unordered_map<
TemporalId, Variables<typename InterpolationTargetTag::
vars_to_interpolate_to_target>>*>
interpolated_vars) {
completed_ids->push_back(temporal_id);
ASSERT(std::find(ids->begin(), ids->end(), temporal_id) != ids->end(),
"Temporal id " << temporal_id << " does not exist in ids");
ids->erase(std::remove(ids->begin(), ids->end(), temporal_id),
ids->end());
// We want to keep track of all completed temporal_ids to deal with
// the possibility of late calls to
// AddTemporalIdsToInterpolationTarget. We could keep all
// completed_ids forever, but we probably don't want it to get too
// large, so we limit its size. We assume that
// asynchronous calls to AddTemporalIdsToInterpolationTarget do not span
// more than 1000 temporal_ids.
if (completed_ids->size() > 1000) {
completed_ids->pop_front();
}
indices_of_filled->erase(temporal_id);
indices_of_invalid->erase(temporal_id);
interpolated_vars->erase(temporal_id);
});
}
/// Returns true if this InterpolationTarget has received data
/// at all its points.
///
/// have_data_at_all_points is called by an Action of InterpolationTarget.
///
/// Currently two Actions call have_data_at_all_points:
/// - InterpolationTargetReceiveVars (called by Interpolator ParallelComponent)
/// - InterpolationTargetVarsFromElement (called by DgElementArray)
template <typename InterpolationTargetTag, typename DbTags, typename TemporalId>
bool have_data_at_all_points(const db::DataBox<DbTags>& box,
const TemporalId& temporal_id) {
const size_t filled_size =
db::get<Tags::IndicesOfFilledInterpPoints<TemporalId>>(box)
.at(temporal_id)
.size();
const size_t invalid_size = [&box, &temporal_id]() {
const auto& invalid_indices =
db::get<Tags::IndicesOfInvalidInterpPoints<TemporalId>>(box);
if (invalid_indices.count(temporal_id) > 0) {
return invalid_indices.at(temporal_id).size();
}
return 0_st;
}();
const size_t interp_size =
db::get<Tags::InterpolatedVars<InterpolationTargetTag, TemporalId>>(box)
.at(temporal_id)
.number_of_grid_points();
return (invalid_size + filled_size == interp_size);
}
/// Is domain::Tags::FunctionsOfTime in the mutable global cache?
/// Result is either std::true_type or std::false_type.
template <typename Metavariables>
using cache_contains_functions_of_time =
tmpl::found<Parallel::get_mutable_global_cache_tags<Metavariables>,
std::is_same<tmpl::_1, domain::Tags::FunctionsOfTime>>;
/// Returns true if at least one Block in the Domain has
/// time-dependent maps.
template <typename InterpolationTargetTag, typename DbTags,
typename Metavariables>
bool maps_are_time_dependent(const db::DataBox<DbTags>& box,
const tmpl::type_<Metavariables>& /*meta*/) {
const auto& domain =
db::get<domain::Tags::Domain<Metavariables::volume_dim>>(box);
return alg::any_of(domain.blocks(), [](const auto& block) {
return block.is_time_dependent();
});
}
/// Tells an InterpolationTarget that it should interpolate at
/// the supplied temporal_ids. Changes the InterpolationTarget's DataBox
/// accordingly.
///
/// Returns the temporal_ids that have actually been newly flagged
/// (since some of them may have been flagged already).
///
/// flag_temporal_ids_for_interpolation is called by an Action
/// of InterpolationTarget
///
/// Currently one Action calls flag_temporal_ids_for_interpolation:
/// - InterpolationTargetVarsFromElement (called by DgElementArray)
template <typename InterpolationTargetTag, typename DbTags, typename TemporalId>
std::vector<TemporalId> flag_temporal_ids_for_interpolation(
const gsl::not_null<db::DataBox<DbTags>*> box,
const std::vector<TemporalId>& temporal_ids) {
// We allow this function to be called multiple times with the same
// temporal_ids (e.g. from each element, or from each node of a
// NodeGroup ParallelComponent such as Interpolator). If multiple
// calls occur, we care only about the first one, and ignore the
// others. The first call will often begin interpolation. So if
// multiple calls occur, it is possible that some of them may arrive
// late, even after interpolation has been completed on one or more
// of the temporal_ids (and after that id has already been removed
// from `ids`). If this happens, we don't want to add the
// temporal_ids again. For that reason we keep track of the
// temporal_ids that we have already completed interpolation on. So
// here we do not add any temporal_ids that are already present in
// `ids` or `completed_ids`.
std::vector<TemporalId> new_temporal_ids{};
db::mutate_apply<tmpl::list<Tags::TemporalIds<TemporalId>>,
tmpl::list<Tags::CompletedTemporalIds<TemporalId>>>(
[&temporal_ids, &new_temporal_ids](
const gsl::not_null<std::deque<TemporalId>*> ids,
const std::deque<TemporalId>& completed_ids) {
for (auto& id : temporal_ids) {
if (std::find(completed_ids.begin(), completed_ids.end(), id) ==
completed_ids.end() and
std::find(ids->begin(), ids->end(), id) == ids->end()) {
ids->push_back(id);
new_temporal_ids.push_back(id);
}
}
},
box);
return new_temporal_ids;
}
/// Tells an InterpolationTarget that it should interpolate at
/// the supplied temporal_ids. Changes the InterpolationTarget's DataBox
/// accordingly.
///
/// Returns the temporal_ids that have actually been newly flagged
/// (since some of them may have been flagged already).
///
/// flag_temporal_ids_as_pending is called by an Action
/// of InterpolationTarget
///
/// Currently one Action calls flag_temporal_ids_as_pending:
/// - AddTemporalIdsToInterpolationTarget (called by Events::Interpolate)
template <typename InterpolationTargetTag, typename DbTags, typename TemporalId>
std::vector<TemporalId> flag_temporal_ids_as_pending(
const gsl::not_null<db::DataBox<DbTags>*> box,
const std::vector<TemporalId>& temporal_ids) {
// We allow this function to be called multiple times with the same
// temporal_ids (e.g. from each element, or from each node of a
// NodeGroup ParallelComponent such as Interpolator). If multiple
// calls occur, we care only about the first one, and ignore the
// others. The first call will often begin interpolation. So if
// multiple calls occur, it is possible that some of them may arrive
// late, even after interpolation has been completed on one or more
// of the temporal_ids (and after that id has already been removed
// from `ids`). If this happens, we don't want to add the
// temporal_ids again. For that reason we keep track of the
// temporal_ids that we have already completed interpolation on. So
// here we do not add any temporal_ids that are already present in
// `ids` or `completed_ids`.
std::vector<TemporalId> new_temporal_ids{};
db::mutate_apply<tmpl::list<Tags::PendingTemporalIds<TemporalId>>,
tmpl::list<Tags::TemporalIds<TemporalId>,
Tags::CompletedTemporalIds<TemporalId>>>(
[&temporal_ids, &new_temporal_ids](
const gsl::not_null<std::deque<TemporalId>*> pending_ids,
const std::deque<TemporalId>& ids,
const std::deque<TemporalId>& completed_ids) {
for (auto& id : temporal_ids) {
if (std::find(completed_ids.begin(), completed_ids.end(), id) ==
completed_ids.end() and
std::find(ids.begin(), ids.end(), id) == ids.end() and
std::find(pending_ids->begin(), pending_ids->end(), id) ==
pending_ids->end()) {
pending_ids->push_back(id);
new_temporal_ids.push_back(id);
}
}
},
box);
return new_temporal_ids;
}
/// Adds the supplied interpolated variables and offsets to the
/// InterpolationTarget's internal DataBox.
///
/// Note that the template argument to Variables in vars_src is called
/// InterpolationTargetTag::vars_to_interpolate_to_target. This is a list
/// of tags, and is used for both the interpolated variables (in
/// this function add_received_variables) and for the source variables
/// (in other functions). The source and interpolated quantities are
/// the same set of variables (but at different points).
///
/// add_received_variables is called by an Action of InterpolationTarget.
///
/// Currently two Actions call add_received_variables:
/// - InterpolationTargetReceiveVars (called by Interpolator ParallelComponent)
/// - InterpolationTargetVarsFromElement (called by DgElementArray)
template <typename InterpolationTargetTag, typename DbTags, typename TemporalId>
void add_received_variables(
const gsl::not_null<db::DataBox<DbTags>*> box,
const std::vector<Variables<
typename InterpolationTargetTag::vars_to_interpolate_to_target>>&
vars_src,
const std::vector<std::vector<size_t>>& global_offsets,
const TemporalId& temporal_id) {
db::mutate<Tags::IndicesOfFilledInterpPoints<TemporalId>,
Tags::InterpolatedVars<InterpolationTargetTag, TemporalId>>(
box, [&temporal_id, &vars_src, &global_offsets](
const gsl::not_null<
std::unordered_map<TemporalId, std::unordered_set<size_t>>*>
indices_of_filled,
const gsl::not_null<std::unordered_map<
TemporalId, Variables<typename InterpolationTargetTag::
vars_to_interpolate_to_target>>*>
vars_dest_all_times) {
auto& vars_dest = vars_dest_all_times->at(temporal_id);
// Here we assume that vars_dest has been allocated to the correct
// size (but could contain garbage, since below we are filling it).
const size_t npts_dest = vars_dest.number_of_grid_points();
const size_t nvars = vars_dest.number_of_independent_components;
for (size_t j = 0; j < global_offsets.size(); ++j) {
const size_t npts_src = global_offsets[j].size();
for (size_t i = 0; i < npts_src; ++i) {
// If a point is on the boundary of two (or more)
// elements, it is possible that we have received data
// for this point from more than one Interpolator.
// This will rarely occur, but it does occur, e.g. when
// a point is exactly on some symmetry
// boundary (such as the x-y plane) and this symmetry
// boundary is exactly the boundary between two
// elements. If this happens, we accept the first
// duplicated point, and we ignore subsequent
// duplicated points. The points are easy to keep track
// of because global_offsets uniquely identifies them.
if ((*indices_of_filled)[temporal_id]
.insert(global_offsets[j][i])
.second) {
for (size_t v = 0; v < nvars; ++v) {
// clang-tidy: no pointer arithmetic
vars_dest.data()[global_offsets[j][i] + // NOLINT
v * npts_dest] = // NOLINT
vars_src[j].data()[i + v * npts_src]; // NOLINT
}
}
}
}
});
}
/// Computes the block logical coordinates of an InterpolationTarget.
///
/// block_logical_coords is called by an Action of InterpolationTarget.
///
/// Currently two Actions call block_logical_coords:
/// - SendPointsToInterpolator (called by AddTemporalIdsToInterpolationTarget
/// and by FindApparentHorizon)
/// - InterpolationTargetVarsFromElement (called by DgElementArray)
/// - InterpolationTargetSendTimeIndepPointsToElements
/// (in InterpolationTarget ActionList)
template <typename InterpolationTargetTag, typename DbTags,
typename Metavariables, typename TemporalId>
auto block_logical_coords(const db::DataBox<DbTags>& box,
Parallel::GlobalCache<Metavariables>& cache,
const TemporalId& temporal_id) {
const auto& domain =
db::get<domain::Tags::Domain<Metavariables::volume_dim>>(box);
if constexpr (std::is_same_v<typename InterpolationTargetTag::
compute_target_points::frame,
::Frame::Grid>) {
// Frame is grid frame, so don't need any FunctionsOfTime,
// whether or not the maps are time_dependent.
return ::block_logical_coordinates(
domain, InterpolationTargetTag::compute_target_points::points(
box, tmpl::type_<Metavariables>{}, temporal_id));
}
if (maps_are_time_dependent<InterpolationTargetTag>(
box, tmpl::type_<Metavariables>{})) {
if constexpr (cache_contains_functions_of_time<Metavariables>::value) {
// Whoever calls block_logical_coords when the maps are
// time-dependent is responsible for ensuring
// that functions_of_time are up to date at temporal_id.
const auto& functions_of_time = get<domain::Tags::FunctionsOfTime>(cache);
return ::block_logical_coordinates(
domain,
InterpolationTargetTag::compute_target_points::points(
box, tmpl::type_<Metavariables>{}, temporal_id),
InterpolationTarget_detail::evaluate_temporal_id_for_expiration(
temporal_id),
functions_of_time);
} else {
// We error here because the maps are time-dependent, yet
// the cache does not contain FunctionsOfTime. It would be
// nice to make this a compile-time error; however, we want
// the code to compile for the completely time-independent
// case where there are no FunctionsOfTime in the cache at
// all. Unfortunately, checking whether the maps are
// time-dependent is currently not constexpr.
ERROR(
"There is a time-dependent CoordinateMap in at least one "
"of the Blocks, but FunctionsOfTime are not in the "
"GlobalCache. If you intend to use a time-dependent "
"CoordinateMap, please add FunctionsOfTime to the GlobalCache.");
}
}
// Time-independent case.
return ::block_logical_coordinates(
domain, InterpolationTargetTag::compute_target_points::points(
box, tmpl::type_<Metavariables>{}, temporal_id));
}
/// This is a version of block_logical_coords for when the coords
/// are time-independent.
template <typename InterpolationTargetTag, typename DbTags,
typename Metavariables>
auto block_logical_coords(const db::DataBox<DbTags>& box,
const tmpl::type_<Metavariables>& meta) {
const auto& domain =
db::get<domain::Tags::Domain<Metavariables::volume_dim>>(box);
return ::block_logical_coordinates(
domain, InterpolationTargetTag::compute_target_points::points(box, meta));
}
/// Initializes InterpolationTarget's variables storage and lists of indices
/// corresponding to the supplied block logical coordinates and `temporal_id`.
///
/// set_up_interpolation is called by an Action of InterpolationTarget.
///
/// Currently two Actions call set_up_interpolation:
/// - SendPointsToInterpolator (called by AddTemporalIdsToInterpolationTarget
/// and by FindApparentHorizon)
/// - InterpolationTargetVarsFromElement (called by DgElementArray)
template <typename InterpolationTargetTag, typename DbTags, size_t VolumeDim,
typename TemporalId>
void set_up_interpolation(
const gsl::not_null<db::DataBox<DbTags>*> box,
const TemporalId& temporal_id,
const std::vector<std::optional<
IdPair<domain::BlockId,
tnsr::I<double, VolumeDim, typename ::Frame::BlockLogical>>>>&
block_logical_coords) {
db::mutate<Tags::IndicesOfFilledInterpPoints<TemporalId>,
Tags::IndicesOfInvalidInterpPoints<TemporalId>,
Tags::InterpolatedVars<InterpolationTargetTag, TemporalId>>(
box, [&block_logical_coords, &temporal_id](
const gsl::not_null<
std::unordered_map<TemporalId, std::unordered_set<size_t>>*>
indices_of_filled,
const gsl::not_null<
std::unordered_map<TemporalId, std::unordered_set<size_t>>*>
indices_of_invalid_points,
const gsl::not_null<std::unordered_map<
TemporalId, Variables<typename InterpolationTargetTag::
vars_to_interpolate_to_target>>*>
vars_dest_all_times) {
// Because we are sending new points to the interpolator,
// we know that none of these points have been interpolated to,
// so clear the list.
indices_of_filled->erase(temporal_id);
// Set the indices of invalid points.
indices_of_invalid_points->erase(temporal_id);
for (size_t i = 0; i < block_logical_coords.size(); ++i) {
if (not block_logical_coords[i].has_value()) {
(*indices_of_invalid_points)[temporal_id].insert(i);
}
}
// At this point we don't know if vars_dest exists in the map;
// if it doesn't then we want to default construct it.
auto& vars_dest = (*vars_dest_all_times)[temporal_id];
// We will be filling vars_dest with interpolated data.
// Here we make sure it is allocated to the correct size.
if (vars_dest.number_of_grid_points() != block_logical_coords.size()) {
vars_dest = Variables<
typename InterpolationTargetTag::vars_to_interpolate_to_target>(
block_logical_coords.size());
}
});
}
} // namespace InterpolationTarget_detail
} // namespace intrp
|
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2021 Advanced Micro Devices, Inc.
*
* 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 <miopen/batchnorm/solvers.hpp>
#include <miopen/batchnorm/invoke_params.hpp>
#include <miopen/batchnorm/problem_description.hpp>
#include <miopen/batch_norm.hpp>
#include <miopen/visit_float.hpp>
#include <miopen/kernel_build_params.hpp>
namespace miopen {
namespace solver {
namespace batchnorm {
bool BnBwdTrainingSpatialMultiple::IsApplicable(
const ExecutionContext& context, const miopen::batchnorm::ProblemDescription& problem) const
{
if(problem.GetDirection() != miopen::batchnorm::Direction::Backward ||
problem.GetMode() != miopenBNSpatial)
return false;
return !BnBwdTrainingSpatialSingle{}.IsApplicable(context, problem);
}
ConvSolution BnBwdTrainingSpatialMultiple::GetSolution(
const ExecutionContext& context, const miopen::batchnorm::ProblemDescription& problem) const
{
const auto& handle = context.GetStream();
bool bfpmixparm = false;
bool bfp16parm = false;
bool bfp32parm = true;
if(problem.GetXDesc().GetType() == miopenHalf &&
problem.GetScaleBiasDiffDesc().GetType() == miopenHalf)
{
bfp16parm = true;
bfp32parm = false;
}
else if(problem.GetXDesc().GetType() == miopenHalf &&
problem.GetScaleBiasDiffDesc().GetType() == miopenFloat)
{
bfpmixparm = true;
bfp32parm = false;
}
int n, c, h, w;
std::tie(n, c, h, w) = tien<4>(problem.GetXDesc().GetLengths());
unsigned int in_cstride = h * w;
unsigned int in_nstride = c * in_cstride;
unsigned int in_nhw = n * in_cstride;
unsigned int in_nchw = n * in_nstride;
auto inhw = float(1.0 / in_nhw);
size_t xlocalsize = 1;
size_t ylocalsize = 1;
size_t xgridsize = 1;
size_t ygridsize = 1;
unsigned int ldsgcn = 0;
unsigned int ldsnogcn = 0;
int variant = 1;
if(problem.IsLayoutNHWC())
{
xlocalsize = 1024;
xgridsize = c * xlocalsize;
ldsgcn = xlocalsize / 64;
ldsnogcn = xlocalsize;
}
else
{
//*************************************************************************************************
// N*H*W < 32M and H*W > 1024, use batchnorm variant#1 implementation which parallelize
// work groups over channels and loop through NHW.
//*************************************************************************************************
if((in_nhw < (32 * 1024 * 1024) && in_cstride > 1024))
{
variant = 1;
xlocalsize = 1024;
xgridsize = c * xlocalsize;
ldsgcn = xlocalsize / 64;
ldsnogcn = xlocalsize;
}
//*************************************************************************************************
// N*H*W < 32M and H*W > 512 use batchnorm variant#1 or variant#3 implementation which
// parallelize
// work groups over channels and loop through N.
//*************************************************************************************************
else if(in_nhw < (32 * 1024 * 1024) && in_cstride > 512)
{
variant = (n >= 32) ? 1 : 3;
xlocalsize = std::min(64 * ((in_cstride + 63) / 64), static_cast<unsigned int>(1024));
xgridsize = c * xlocalsize;
ldsgcn = xlocalsize / 64;
ldsnogcn = xlocalsize;
}
//*************************************************************************************************
// H*W < 512 use batchnorm variant#0 or variant#3 implementation based on batch size and
// H*W
//*************************************************************************************************
else if(in_cstride <= 512)
{
if((n > 64) && (in_cstride > 160))
{
variant = 3;
xlocalsize =
std::min(64 * ((in_cstride + 63) / 64), static_cast<unsigned int>(1024));
xgridsize = c * xlocalsize;
ldsgcn = xlocalsize / 64;
ldsnogcn = xlocalsize;
}
else
{
variant = 0;
if(bfp32parm)
{
xlocalsize = 1024;
xgridsize = 1024 * c;
}
else
{
xlocalsize = 256;
xgridsize = 256 * c;
}
ldsgcn = xlocalsize / 64;
ldsnogcn = xlocalsize;
}
}
//*************************************************************************************************
// N*H*W > 32M, use batchnorm variant#2 implementation which parallelize
// work groups over channels and data segments.
//*************************************************************************************************
else
{
variant = 2;
ylocalsize = 1024;
auto segment = int(std::ceil(double(in_cstride) / double(ylocalsize)));
xgridsize = c;
ygridsize = segment * ylocalsize;
ldsgcn = ylocalsize / 64;
ldsnogcn = ylocalsize;
}
if((in_cstride < 200) && (in_cstride > 60) && bfpmixparm)
{
variant = 1;
xlocalsize = 1024;
xgridsize = c * xlocalsize;
ldsgcn = xlocalsize / 64;
ldsnogcn = xlocalsize;
}
}
auto result = ConvSolution{miopenStatusSuccess};
{
size_t zlocalsize = 1;
size_t zgridsize = 1;
auto kernel = KernelInfo{};
kernel.kernel_file = "MIOpenBatchNormBwdSpatial.cl";
kernel.kernel_name = "MIOpenBatchNormBwdSpatial";
auto build_params = KernelBuildParameters{
{"MIOPEN_USE_FP16", static_cast<int>(bfp16parm)},
{"MIOPEN_USE_FP32", static_cast<int>(bfp32parm)},
{"MIOPEN_USE_FPMIX", static_cast<int>(bfpmixparm)},
{"MIO_BN_USESAVED", static_cast<int>(problem.UseSaved())},
{"MIO_BN_N", static_cast<int>(n)},
{"MIO_BN_C", static_cast<int>(c)},
{"MIO_BN_HW", static_cast<int>(in_cstride)},
{"MIO_BN_NHW", static_cast<int>(in_nhw)},
{"MIO_BN_CHW", in_nstride},
{"MIO_BN_NCHW", in_nchw},
{"MIO_BN_NGRPS", int(std::ceil(float(ygridsize) / ylocalsize))},
{"MIO_BN_LDS_SIZE", ldsnogcn},
{"MIO_BN_LDSGCN_SIZE", ldsgcn},
{"MIO_BN_VARIANT", variant},
{"MIO_BN_GRP0", xlocalsize},
{"MIO_BN_GRP1", ylocalsize},
{"MIO_BN_GRP2", zlocalsize},
{"MIO_BN_GFX1030", ((handle.GetDeviceName() == "gfx1030") ? "1" : "0")},
{"MIO_LAYOUT_NHWC", static_cast<int>(problem.IsLayoutNHWC())},
};
kernel.comp_options = build_params.GenerateFor(kbp::OpenCL{});
kernel.l_wk.push_back(xlocalsize);
kernel.l_wk.push_back(ylocalsize);
kernel.l_wk.push_back(zlocalsize);
kernel.g_wk.push_back(xgridsize);
kernel.g_wk.push_back(ygridsize);
kernel.g_wk.push_back(zgridsize);
if(problem.UseSaved())
{
auto copy = kernel;
copy.kernel_name = kernel.kernel_name + "DScaleDBias";
result.construction_params.push_back(copy);
copy.kernel_name = kernel.kernel_name + "FinalDScaleDBias";
result.construction_params.push_back(copy);
copy.kernel_name = kernel.kernel_name + "DX";
result.construction_params.push_back(copy);
}
else
{
auto copy = kernel;
copy.kernel_name = kernel.kernel_name + "MeanVariance";
result.construction_params.push_back(copy);
copy.kernel_name = kernel.kernel_name + "FinalMeanVariance";
result.construction_params.push_back(copy);
copy.kernel_name = kernel.kernel_name + "DScaleDBias";
result.construction_params.push_back(copy);
copy.kernel_name = kernel.kernel_name + "FinalDScaleDBias";
result.construction_params.push_back(copy);
copy.kernel_name = kernel.kernel_name + "DX";
result.construction_params.push_back(copy);
}
}
const auto dtype = problem.GetScaleBiasDiffDesc().GetType();
const auto useSaved = problem.UseSaved();
result.invoker_factory = [=](const std::vector<Kernel>& kernels) {
return [=](const Handle& handle_, const AnyInvokeParams& raw_params) {
decltype(auto) params = raw_params.CastTo<miopen::batchnorm::BwdInvokeParams>();
float ctime = 0.;
visit_float(dtype, [&](auto as_float) {
if(useSaved)
{
handle_.Run(kernels[0])(
params.x, params.dy, params.dx, params.savedMean, params.savedInvVariance);
profileSequence(handle_, 0, &ctime);
handle_.Run(kernels[1])(
params.dx, params.resultBnScaleDiff, params.resultBnBiasDiff);
profileSequence(handle_, 1, &ctime);
handle_.Run(kernels[2])(params.x,
params.dy,
params.dx,
params.bnScale,
params.resultBnScaleDiff,
params.resultBnBiasDiff,
params.savedMean,
params.savedInvVariance,
as_float(inhw));
profileSequence(handle_, 2, &ctime);
}
else
{
handle_.Run(kernels[0])(params.x, params.dx); // mean variance
profileSequence(handle_, 0, &ctime);
handle_.Run(kernels[1])(
params.dx, as_float(inhw), params.epsilon); // final mean variance
profileSequence(handle_, 1, &ctime);
handle_.Run(kernels[2])(params.x, params.dy, params.dx); // dscale dbias
profileSequence(handle_, 1, &ctime);
handle_.Run(kernels[3])(params.dx,
params.resultBnScaleDiff,
params.resultBnBiasDiff); // final dscale dbias
profileSequence(handle_, 1, &ctime);
handle_.Run(kernels[4])(params.x,
params.dy,
params.dx,
params.bnScale,
params.resultBnScaleDiff,
params.resultBnBiasDiff,
as_float(inhw)); // dx
profileSequence(handle_, 2, &ctime);
}
});
};
};
return result;
}
} // namespace batchnorm
} // namespace solver
} // namespace miopen
|
// Copyright (c) 2012-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both bitcoind and bitcoin-core, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("ElsperoCore");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "f32743e194a3"
#define GIT_COMMIT_DATE "Wed, 28 Jun 2017 04:45:07 +0000"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
|
/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <fstream>
#include <sstream>
#include <float.h>
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <netdb.h>
#endif
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "parse_example.h"
#include "constant.h"
#include "gd.h"
#include "cache.h"
#include "accumulate.h"
#include "learner.h"
#include "vw.h"
#include <map>
#include "memory.h"
#include "vw_allreduce.h"
#include "rand48.h"
#include "floatbits.h"
#define SVM_KER_LIN 0
#define SVM_KER_RBF 1
#define SVM_KER_POLY 2
using namespace std;
using namespace LEARNER;
struct svm_params;
struct svm_example
{ v_array<float> krow;
flat_example ex;
~svm_example();
void init_svm_example(flat_example *fec);
int compute_kernels(svm_params& params);
int clear_kernels();
};
struct svm_model
{ size_t num_support;
v_array<svm_example*> support_vec;
v_array<float> alpha;
v_array<float> delta;
};
struct svm_params
{ size_t current_pass;
bool active;
bool active_pool_greedy;
bool para_active;
double active_c;
size_t pool_size;
size_t pool_pos;
size_t subsample; //NOTE: Eliminating subsample to only support 1/pool_size
size_t reprocess;
svm_model* model;
size_t maxcache;
//size_t curcache;
svm_example** pool;
float lambda;
void* kernel_params;
size_t kernel_type;
size_t local_begin, local_end;
size_t current_t;
float loss_sum;
vw* all;//flatten, parallel
};
static size_t num_kernel_evals = 0;
static size_t num_cache_evals = 0;
void svm_example::init_svm_example(flat_example *fec)
{ ex = *fec;
free(fec);
}
svm_example::~svm_example()
{ krow.delete_v();
// free flatten example contents
flat_example *fec = &calloc_or_throw<flat_example>();
*fec = ex;
free_flatten_example(fec); // free contents of flat example and frees fec.
}
float
kernel_function(const flat_example* fec1, const flat_example* fec2,
void* params, size_t kernel_type);
int
svm_example::compute_kernels(svm_params& params)
{ int alloc = 0;
svm_model *model = params.model;
size_t n = model->num_support;
if (krow.size() < n)
{ //computing new kernel values and caching them
//if(params->curcache + n > params->maxcache)
//trim_cache(params);
num_kernel_evals += krow.size();
//cerr<<"Kernels ";
for (size_t i=krow.size(); i<n; i++)
{ svm_example *sec = model->support_vec[i];
float kv = kernel_function(&ex, &(sec->ex), params.kernel_params, params.kernel_type);
krow.push_back(kv);
alloc += 1;
//cerr<<kv<<" ";
}
//cerr<<endl;
}
else
num_cache_evals += n;
return alloc;
}
int
svm_example::clear_kernels()
{ int rowsize = (int)krow.size();
krow.end() = krow.begin();
krow.resize(0);
return -rowsize;
}
static int
make_hot_sv(svm_params& params, size_t svi)
{ svm_model *model = params.model;
size_t n = model->num_support;
if (svi >= model->num_support)
cerr << "Internal error at " << __FILE__ << ":" << __LINE__ << endl;
// rotate params fields
svm_example *svi_e = model->support_vec[svi];
int alloc = svi_e->compute_kernels(params);
float svi_alpha = model->alpha[svi];
float svi_delta = model->delta[svi];
for (size_t i=svi; i>0; --i)
{ model->support_vec[i] = model->support_vec[i-1];
model->alpha[i] = model->alpha[i-1];
model->delta[i] = model->delta[i-1];
}
model->support_vec[0] = svi_e;
model->alpha[0] = svi_alpha;
model->delta[0] = svi_delta;
// rotate cache
for (size_t j=0; j<n; j++)
{ svm_example *e = model->support_vec[j];
size_t rowsize = e->krow.size();
if (svi < rowsize)
{ float kv = e->krow[svi];
for (size_t i=svi; i>0; --i)
e->krow[i] = e->krow[i-1];
e->krow[0] = kv;
}
else
{ float kv = svi_e->krow[j];
e->krow.push_back(0);
alloc += 1;
for (size_t i=e->krow.size()-1; i>0; --i)
e->krow[i] = e->krow[i-1];
e->krow[0] = kv;
}
}
return alloc;
}
static int
trim_cache(svm_params& params)
{ int sz = (int)params.maxcache;
svm_model *model = params.model;
size_t n = model->num_support;
int alloc = 0;
for (size_t i=0; i<n; i++)
{ svm_example *e = model->support_vec[i];
sz -= (int)e->krow.size();
if (sz < 0)
alloc += e->clear_kernels();
}
return alloc;
}
int save_load_flat_example(io_buf& model_file, bool read, flat_example*& fec)
{ size_t brw = 1;
if(read)
{ fec = &calloc_or_throw<flat_example>();
brw = bin_read_fixed(model_file, (char*) fec, sizeof(flat_example), "");
if(brw > 0)
{ if(fec->tag_len > 0)
{ fec->tag = calloc_or_throw<char>(fec->tag_len);
brw = bin_read_fixed(model_file, (char*) fec->tag, fec->tag_len*sizeof(char), "");
if(!brw) return 2;
}
if(fec->fs.size() > 0)
{ features& fs = fec->fs;
size_t len = fs.size();
fs.values = v_init<feature_value>();
fs.values.resize(len);
brw = bin_read_fixed(model_file, (char*) fs.values.begin(), len*sizeof(feature_value), ""); if(!brw) return 3;
fs.values.end() = fs.values.begin()+len;
len = fs.indicies.size();
fs.indicies = v_init<feature_index>();
fs.indicies.resize(len);
brw = bin_read_fixed(model_file, (char*) fs.indicies.begin(), len*sizeof(feature_index), ""); if(!brw) return 3;
fs.indicies.end() = fs.indicies.begin()+len;
}
}
else return 1;
}
else
{ brw = bin_write_fixed(model_file, (char*) fec, sizeof(flat_example));
if(brw > 0)
{ if(fec->tag_len > 0)
{ brw = bin_write_fixed(model_file, (char*) fec->tag, (uint32_t)fec->tag_len*sizeof(char));
if(!brw)
{ cerr<<fec->tag_len<<" "<<fec->tag<<endl;
return 2;
}
}
if(fec->fs.size() > 0)
{ brw = bin_write_fixed(model_file, (char*) fec->fs.values.begin(), (uint32_t)fec->fs.size()*sizeof(feature_value)); if(!brw) return 3;
brw = bin_write_fixed(model_file, (char*) fec->fs.indicies.begin(), (uint32_t)fec->fs.indicies.size()*sizeof(feature_index)); if(!brw) return 3;
}
}
else return 1;
}
return 0;
}
void save_load_svm_model(svm_params& params, io_buf& model_file, bool read, bool text)
{ svm_model* model = params.model;
//TODO: check about initialization
//cerr<<"Save load svm "<<read<<" "<<text<<endl;
if (model_file.files.size() == 0) return;
stringstream msg;
bin_text_read_write_fixed(model_file,(char*)&(model->num_support), sizeof(model->num_support),
"", read, msg, text);
//cerr<<"Read num support "<<model->num_support<<endl;
flat_example* fec = nullptr;
if(read)
model->support_vec.resize(model->num_support);
for(uint32_t i = 0; i < model->num_support; i++)
{ if(read)
{ save_load_flat_example(model_file, read, fec);
svm_example* tmp= &calloc_or_throw<svm_example>();
tmp->init_svm_example(fec);
model->support_vec.push_back(tmp);
}
else
{ fec = &(model->support_vec[i]->ex);
save_load_flat_example(model_file, read, fec);
}
}
if(read)
model->alpha.resize(model->num_support);
bin_text_read_write_fixed(model_file, (char*)model->alpha.begin(), (uint32_t)model->num_support*sizeof(float),
"", read, msg, text);
if(read)
model->delta.resize(model->num_support);
bin_text_read_write_fixed(model_file, (char*)model->delta.begin(), (uint32_t)model->num_support*sizeof(float),
"", read, msg, text);
}
void save_load(svm_params& params, io_buf& model_file, bool read, bool text)
{ if(text)
{ cerr<<"Not supporting readable model for kernel svm currently\n";
return;
}
save_load_svm_model(params, model_file, read, text);
}
float linear_kernel(const flat_example* fec1, const flat_example* fec2)
{
float dotprod = 0;
features& fs_1 = (features&)fec1->fs;
features& fs_2 = (features&)fec2->fs;
if (fs_2.indicies.size() == 0)
return 0.f;
int numint = 0;
for (size_t idx1 = 0, idx2 = 0; idx1 < fs_1.size() && idx2 < fs_2.size() ; idx1++)
{ uint64_t ec1pos = fs_1.indicies[idx1];
uint64_t ec2pos = fs_2.indicies[idx2];
//cerr<<ec1pos<<" "<<ec2pos<<" "<<idx1<<" "<<idx2<<" "<<f->x<<" "<<ec2f->x<<endl;
if(ec1pos < ec2pos) continue;
while(ec1pos > ec2pos && ++idx2 < fs_2.size())
ec2pos = fs_2.indicies[idx2];
if(ec1pos == ec2pos)
{ //cerr<<ec1pos<<" "<<ec2pos<<" "<<idx1<<" "<<idx2<<" "<<f->x<<" "<<ec2f->x<<endl;
numint++;
dotprod += fs_1.values[idx1] * fs_2.values[idx2];
++idx2;
}
}
//cerr<<endl;
//cerr<<"numint = "<<numint<<" dotprod = "<<dotprod<<endl;
return dotprod;
}
float poly_kernel(const flat_example* fec1, const flat_example* fec2, int power)
{ float dotprod = linear_kernel(fec1, fec2);
//cerr<<"Bandwidth = "<<bandwidth<<endl;
//cout<<pow(1 + dotprod, power)<<endl;
return pow(1 + dotprod, power);
}
float rbf_kernel(const flat_example* fec1, const flat_example* fec2, float bandwidth)
{ float dotprod = linear_kernel(fec1, fec2);
//cerr<<"Bandwidth = "<<bandwidth<<endl;
return expf(-(fec1->total_sum_feat_sq + fec2->total_sum_feat_sq - 2*dotprod)*bandwidth);
}
float kernel_function(const flat_example* fec1, const flat_example* fec2, void* params, size_t kernel_type)
{ switch(kernel_type)
{ case SVM_KER_RBF:
return rbf_kernel(fec1, fec2, *((float*)params));
case SVM_KER_POLY:
return poly_kernel(fec1, fec2, *((int*)params));
case SVM_KER_LIN:
return linear_kernel(fec1, fec2);
}
return 0;
}
float dense_dot(float* v1, v_array<float> v2, size_t n)
{ float dot_prod = 0.;
for(size_t i = 0; i < n; i++)
dot_prod += v1[i]*v2[i];
return dot_prod;
}
void predict (svm_params& params, svm_example** ec_arr, float* scores, size_t n)
{ svm_model* model = params.model;
for(size_t i = 0; i < n; i++)
{ ec_arr[i]->compute_kernels(params);
scores[i] = dense_dot(ec_arr[i]->krow.begin(), model->alpha, model->num_support)/params.lambda;
}
}
void predict(svm_params& params, base_learner &, example& ec)
{ flat_example* fec = flatten_sort_example(*(params.all),&ec);
if(fec)
{ svm_example* sec = &calloc_or_throw<svm_example>();
sec->init_svm_example(fec);
float score;
predict(params, &sec, &score, 1);
ec.pred.scalar = score;
sec->~svm_example();
free(sec);
}
}
size_t suboptimality(svm_model* model, double* subopt)
{
size_t max_pos = 0;
//cerr<<"Subopt ";
double max_val = 0;
for(size_t i = 0; i < model->num_support; i++)
{ double tmp = model->alpha[i]*model->support_vec[i]->ex.l.simple.label;
if((tmp < model->support_vec[i]->ex.l.simple.weight && model->delta[i] < 0) || (tmp > 0 && model->delta[i] > 0))
subopt[i] = fabs(model->delta[i]);
else
subopt[i] = 0;
if(subopt[i] > max_val)
{ max_val = subopt[i];
max_pos = i;
}
//cerr<<subopt[i]<<" ";
}
//cerr<<endl;
return max_pos;
}
int remove(svm_params& params, size_t svi)
{ svm_model* model = params.model;
if (svi >= model->num_support)
cerr << "Internal error at " << __FILE__ << ":" << __LINE__ << endl;
// shift params fields
svm_example* svi_e = model->support_vec[svi];
for (size_t i=svi; i<model->num_support-1; ++i)
{ model->support_vec[i] = model->support_vec[i+1];
model->alpha[i] = model->alpha[i+1];
model->delta[i] = model->delta[i+1];
}
svi_e->~svm_example();
free(svi_e);
model->support_vec.pop();
model->alpha.pop();
model->delta.pop();
model->num_support--;
// shift cache
int alloc = 0;
for (size_t j=0; j<model->num_support; j++)
{ svm_example *e = model->support_vec[j];
size_t rowsize = e->krow.size();
if (svi < rowsize)
{ for (size_t i=svi; i<rowsize-1; i++)
e->krow[i] = e->krow[i+1];
e->krow.pop();
alloc -= 1;
}
}
return alloc;
}
int add(svm_params& params, svm_example* fec)
{ svm_model* model = params.model;
model->num_support++;
model->support_vec.push_back(fec);
model->alpha.push_back(0.);
model->delta.push_back(0.);
//cout<<"After adding "<<model->num_support<<endl;
return (int)(model->support_vec.size()-1);
}
bool update(svm_params& params, size_t pos)
{
//cerr<<"Update\n";
svm_model* model = params.model;
bool overshoot = false;
//cerr<<"Updating model "<<pos<<" "<<model->num_support<<" ";
//cerr<<model->support_vec[pos]->example_counter<<endl;
svm_example* fec = model->support_vec[pos];
label_data& ld = fec->ex.l.simple;
fec->compute_kernels(params);
float *inprods = fec->krow.begin();
float alphaKi = dense_dot(inprods, model->alpha, model->num_support);
model->delta[pos] = alphaKi*ld.label/params.lambda - 1;
float alpha_old = model->alpha[pos];
alphaKi -= model->alpha[pos]*inprods[pos];
model->alpha[pos] = 0.;
float proj = alphaKi*ld.label;
float ai = (params.lambda - proj)/inprods[pos];
//cerr<<model->num_support<<" "<<pos<<" "<<proj<<" "<<alphaKi<<" "<<alpha_old<<" "<<ld->label<<" "<<model->delta[pos]<<" ";
if(ai > fec->ex.l.simple.weight)
ai = fec->ex.l.simple.weight;
else if(ai < 0)
ai = 0;
ai *= ld.label;
float diff = ai - alpha_old;
if(fabs(diff) > 1.0e-06)
overshoot = true;
if(fabs(diff) > 1.)
{ //cerr<<"Here\n";
diff = (float) (diff > 0) - (diff < 0);
ai = alpha_old + diff;
}
for(size_t i = 0; i < model->num_support; i++)
{ label_data& ldi = model->support_vec[i]->ex.l.simple;
model->delta[i] += diff*inprods[i]*ldi.label/params.lambda;
}
if(fabs(ai) <= 1.0e-10)
remove(params, pos);
else
model->alpha[pos] = ai;
return overshoot;
}
void copy_char(char& c1, const char& c2)
{ if (c2 != '\0')
c1 = c2;
}
void add_size_t(size_t& t1, const size_t& t2)
{ t1 += t2;
}
void add_double(double& t1, const double& t2)
{ t1 += t2;
}
void sync_queries(vw& all, svm_params& params, bool* train_pool)
{ io_buf* b = new io_buf();
char* queries;
flat_example* fec = nullptr;
for(size_t i = 0; i < params.pool_pos; i++)
{ if(!train_pool[i])
continue;
fec = &(params.pool[i]->ex);
save_load_flat_example(*b, false, fec);
delete params.pool[i];
}
size_t* sizes = calloc_or_throw<size_t>(all.all_reduce->total);
sizes[all.all_reduce->node] = b->head - b->space.begin();
//cerr<<"Sizes = "<<sizes[all.node]<<" ";
all_reduce<size_t, add_size_t>(all, sizes, all.all_reduce->total);
size_t prev_sum = 0, total_sum = 0;
for(size_t i = 0; i < all.all_reduce->total; i++)
{ if(i <= (all.all_reduce->node - 1))
prev_sum += sizes[i];
total_sum += sizes[i];
}
//cerr<<total_sum<<" "<<prev_sum<<endl;
if(total_sum > 0)
{ queries = calloc_or_throw<char>(total_sum);
memcpy(queries + prev_sum, b->space.begin(), b->head - b->space.begin());
b->space.delete_v();
all_reduce<char, copy_char>(all, queries, total_sum);
b->space.begin() = queries;
b->head = b->space.begin();
b->space.end() = &queries[total_sum*sizeof(char)];
size_t num_read = 0;
params.pool_pos = 0;
for(size_t i = 0; i < params.pool_size; i++)
{ if(!save_load_flat_example(*b, true, fec))
{ params.pool[i] = &calloc_or_throw<svm_example>();
params.pool[i]->init_svm_example(fec);
train_pool[i] = true;
params.pool_pos++;
// for(int j = 0;j < fec->feature_map_len;j++)
// cerr<<fec->feature_map[j].weight_index<<":"<<fec->feature_map[j].x<<" ";
// cerr<<endl;
// params.pool[i]->in_use = true;
// params.current_t += ((label_data*) params.pool[i]->ld)->weight;
// params.pool[i]->example_t = params.current_t;
}
else
break;
num_read += b->head - b->space.begin();
if(num_read == prev_sum)
params.local_begin = i+1;
if(num_read == prev_sum + sizes[all.all_reduce->node])
params.local_end = i;
}
}
if(fec)
free(fec);
free(sizes);
delete b;
}
void train(svm_params& params)
{
//cerr<<"In train "<<params.all->training<<endl;
bool* train_pool = calloc_or_throw<bool>(params.pool_size);
for(size_t i = 0; i < params.pool_size; i++)
train_pool[i] = false;
float* scores = calloc_or_throw<float>(params.pool_pos);
predict(params, params.pool, scores, params.pool_pos);
//cout<<scores[0]<<endl;
if(params.active)
{ if(params.active_pool_greedy)
{ multimap<double, size_t> scoremap;
for(size_t i = 0; i < params.pool_pos; i++)
scoremap.insert(pair<const double, const size_t>(fabs(scores[i]),i));
multimap<double, size_t>::iterator iter = scoremap.begin();
//cerr<<params.pool_size<<" "<<"Scoremap: ";
//for(;iter != scoremap.end();iter++)
//cerr<<iter->first<<" "<<iter->second<<" "<<((label_data*)params.pool[iter->second]->ld)->label<<"\t";
//cerr<<endl;
iter = scoremap.begin();
for(size_t train_size = 1; iter != scoremap.end() && train_size <= params.subsample; train_size++)
{ //cerr<<train_size<<" "<<iter->second<<" "<<iter->first<<endl;
train_pool[iter->second] = 1;
iter++;
}
}
else
{
for(size_t i = 0; i < params.pool_pos; i++)
{ float queryp = 2.0f/(1.0f + expf((float)(params.active_c*fabs(scores[i]))*(float)pow(params.pool[i]->ex.example_counter,0.5f)));
if(frand48() < queryp)
{ svm_example* fec = params.pool[i];
fec->ex.l.simple.weight *= 1/queryp;
train_pool[i] = 1;
}
}
}
//free(scores);
}
if(params.para_active)
{ for(size_t i = 0; i < params.pool_pos; i++)
if(!train_pool[i])
delete params.pool[i];
sync_queries(*(params.all), params, train_pool);
}
if(params.all->training)
{
svm_model* model = params.model;
for(size_t i = 0; i < params.pool_pos; i++)
{ //cerr<<"process: "<<i<<" "<<train_pool[i]<<endl;;
int model_pos = -1;
if(params.active)
{ if(train_pool[i])
{ //cerr<<"i = "<<i<<"train_pool[i] = "<<train_pool[i]<<" "<<params.pool[i]->example_counter<<endl;
model_pos = add(params, params.pool[i]);
}
}
else
model_pos = add(params, params.pool[i]);
//cerr<<"Added: "<<model_pos<<" "<<model->support_vec[model_pos]->example_counter<<endl;
//cout<<"After adding in train "<<model->num_support<<endl;
if(model_pos >= 0)
{ bool overshoot = update(params, model_pos);
//cerr<<model_pos<<":alpha = "<<model->alpha[model_pos]<<endl;
double* subopt = calloc_or_throw<double>(model->num_support);
for(size_t j = 0; j < params.reprocess; j++)
{ if(model->num_support == 0) break;
//cerr<<"reprocess: ";
int randi = 1;
if (frand48() < 0.5)
randi = 0;
if(randi)
{ size_t max_pos = suboptimality(model, subopt);
if(subopt[max_pos] > 0)
{ if(!overshoot && max_pos == (size_t)model_pos && max_pos > 0 && j == 0)
cerr<<"Shouldn't reprocess right after process!!!\n";
//cerr<<max_pos<<" "<<subopt[max_pos]<<endl;
// cerr<<params.model->support_vec[0]->example_counter<<endl;
if(max_pos*model->num_support <= params.maxcache)
make_hot_sv(params, max_pos);
update(params, max_pos);
}
}
else
{ size_t rand_pos = (size_t)floorf(frand48() * model->num_support);
update(params, rand_pos);
}
}
//cerr<<endl;
// cerr<<params.model->support_vec[0]->example_counter<<endl;
free(subopt);
}
}
}
else
for(size_t i = 0; i < params.pool_pos; i++)
delete params.pool[i];
// cerr<<params.model->support_vec[0]->example_counter<<endl;
// for(int i = 0;i < params.pool_size;i++)
// cerr<<scores[i]<<" ";
// cerr<<endl;
free(scores);
//cerr<<params.model->support_vec[0]->example_counter<<endl;
free(train_pool);
//cerr<<params.model->support_vec[0]->example_counter<<endl;
}
void learn(svm_params& params, base_learner&, example& ec)
{ flat_example* fec = flatten_sort_example(*(params.all),&ec);
// for(int i = 0;i < fec->feature_map_len;i++)
// cout<<i<<":"<<fec->feature_map[i].x<<" "<<fec->feature_map[i].weight_index<<" ";
// cout<<endl;
if(fec)
{ svm_example* sec = &calloc_or_throw<svm_example>();
sec->init_svm_example(fec);
float score = 0;
predict(params, &sec, &score, 1);
ec.pred.scalar = score;
ec.loss = max(0.f, 1.f - score*ec.l.simple.label);
params.loss_sum += ec.loss;
if(params.all->training && ec.example_counter % 100 == 0)
trim_cache(params);
if(params.all->training && ec.example_counter % 1000 == 0 && ec.example_counter >= 2)
{ cerr<<"Number of support vectors = "<<params.model->num_support<<endl;
cerr<<"Number of kernel evaluations = "<<num_kernel_evals<<" "<<"Number of cache queries = "<<num_cache_evals<<" loss sum = "<<params.loss_sum<<" "<<params.model->alpha[params.model->num_support-1]<<" "<<params.model->alpha[params.model->num_support-2]<<endl;
}
params.pool[params.pool_pos] = sec;
params.pool_pos++;
if(params.pool_pos == params.pool_size)
{ train(params);
params.pool_pos = 0;
}
}
}
void free_svm_model(svm_model* model)
{ for(size_t i = 0; i < model->num_support; i++)
{ model->support_vec[i]->~svm_example();
free(model->support_vec[i]);
model->support_vec[i] = 0;
}
model->support_vec.delete_v();
model->alpha.delete_v();
model->delta.delete_v();
free(model);
}
void finish(svm_params& params)
{ free(params.pool);
cerr<<"Num support = "<<params.model->num_support<<endl;
cerr<<"Number of kernel evaluations = "<<num_kernel_evals<<" "<<"Number of cache queries = "<<num_cache_evals<<endl;
cerr<<"Total loss = "<<params.loss_sum<<endl;
free_svm_model(params.model);
cerr<<"Done freeing model\n";
if(params.kernel_params) free(params.kernel_params);
cerr<<"Done freeing kernel params\n";
cerr<<"Done with finish \n";
}
LEARNER::base_learner* kernel_svm_setup(vw &all)
{ if (missing_option(all, true, "ksvm", "kernel svm")) return nullptr;
new_options(all, "KSVM options")
("reprocess", po::value<size_t>(), "number of reprocess steps for LASVM")
// ("active", "do active learning")
//("active_c", po::value<double>(), "parameter for query prob")
("pool_greedy", "use greedy selection on mini pools")
("para_active", "do parallel active learning")
("pool_size", po::value<size_t>(), "size of pools for active learning")
("subsample", po::value<size_t>(), "number of items to subsample from the pool")
("kernel", po::value<string>(), "type of kernel (rbf or linear (default))")
("bandwidth", po::value<float>(), "bandwidth of rbf kernel")
("degree", po::value<int>(), "degree of poly kernel")
("lambda", po::value<double>(), "saving regularization for test time");
add_options(all);
po::variables_map& vm = all.vm;
string loss_function = "hinge";
float loss_parameter = 0.0;
delete all.loss;
all.loss = getLossFunction(all, loss_function, (float)loss_parameter);
svm_params& params = calloc_or_throw<svm_params>();
params.model = &calloc_or_throw<svm_model>();
params.model->num_support = 0;
//params.curcache = 0;
params.maxcache = 1024*1024*1024;
params.loss_sum = 0.;
params.all = &all;
if(vm.count("reprocess"))
params.reprocess = vm["reprocess"].as<std::size_t>();
else
params.reprocess = 1;
if(vm.count("active"))
params.active = true;
if(params.active)
{ if(vm.count("active_c"))
params.active_c = vm["active_c"].as<double>();
else
params.active_c = 1.;
if(vm.count("pool_greedy"))
params.active_pool_greedy = 1;
/*if(vm.count("para_active"))
params.para_active = 1;*/
}
if(vm.count("pool_size"))
params.pool_size = vm["pool_size"].as<std::size_t>();
else
params.pool_size = 1;
params.pool = calloc_or_throw<svm_example*>(params.pool_size);
params.pool_pos = 0;
if(vm.count("subsample"))
params.subsample = vm["subsample"].as<std::size_t>();
else if(params.para_active)
params.subsample = (size_t)ceil(params.pool_size / all.all_reduce->total);
else
params.subsample = 1;
params.lambda = all.l2_lambda;
*all.file_options <<" --lambda "<< params.lambda;
cerr<<"Lambda = "<<params.lambda<<endl;
std::string kernel_type;
if(vm.count("kernel"))
kernel_type = vm["kernel"].as<std::string>();
else
kernel_type = string("linear");
*all.file_options <<" --kernel "<< kernel_type;
cerr<<"Kernel = "<<kernel_type<<endl;
if(kernel_type.compare("rbf") == 0)
{ params.kernel_type = SVM_KER_RBF;
float bandwidth = 1.;
if(vm.count("bandwidth"))
{ bandwidth = vm["bandwidth"].as<float>();
*all.file_options <<" --bandwidth "<<bandwidth;
}
cerr<<"bandwidth = "<<bandwidth<<endl;
params.kernel_params = &calloc_or_throw<double>();
*((float*)params.kernel_params) = bandwidth;
}
else if(kernel_type.compare("poly") == 0)
{ params.kernel_type = SVM_KER_POLY;
int degree = 2;
if(vm.count("degree"))
{ degree = vm["degree"].as<int>();
*all.file_options <<" --degree "<<degree;
}
cerr<<"degree = "<<degree<<endl;
params.kernel_params = &calloc_or_throw<int>();
*((int*)params.kernel_params) = degree;
}
else
params.kernel_type = SVM_KER_LIN;
params.all->reg.weight_mask = (uint64_t)LONG_MAX;
params.all->reg.stride_shift = 0;
learner<svm_params>& l = init_learner(¶ms, learn, 1);
l.set_predict(predict);
l.set_save_load(save_load);
l.set_finish(finish);
return make_base(l);
}
|
#include "catch.hpp"
#include "irods_linked_list_iterator.hpp"
#include "objInfo.h"
#include "dataObjOpr.hpp"
#include <memory>
#include <iterator>
#include <functional>
using deleter_t = std::function<void(dataObjInfo_t*)>;
auto make_c_linked_list(int _list_length) noexcept -> std::unique_ptr<dataObjInfo_t, deleter_t>;
TEST_CASE("irods_linked_list_iterator", "[iterator]")
{
const int list_length = 5;
auto list = make_c_linked_list(list_length);
irods::linked_list_iterator<dataObjInfo_t> pos{list.get()};
REQUIRE(list.get() != nullptr);
REQUIRE(list.get() == &*pos);
SECTION("copy_assignment")
{
const auto copy = pos;
REQUIRE(copy == pos);
}
SECTION("pre_fix_increment")
{
const auto copy = ++pos;
REQUIRE(copy == pos);
}
SECTION("post_fix_increment")
{
auto previous_pos = pos++;
REQUIRE(previous_pos != pos);
REQUIRE(previous_pos->next == &*pos);
REQUIRE(++previous_pos == pos);
}
SECTION("standard_algorithms")
{
REQUIRE(std::distance(begin(list.get()), end(list.get())) == list_length);
}
SECTION("range_based_for_loop")
{
int count = 0;
for (const auto& _ : list.get())
{
(void) _;
++count;
}
REQUIRE(count == list_length);
}
}
auto make_c_linked_list(int _list_length) noexcept -> std::unique_ptr<dataObjInfo_t, deleter_t>
{
auto deleter = [](auto* _list)
{
auto* head = _list;
auto* tail = _list->next;
while (head)
{
delete head;
if (!tail) break;
head = tail;
tail = tail->next;
}
};
std::unique_ptr<dataObjInfo_t, deleter_t> head{new dataObjInfo_t{}, deleter};
auto* list = head.get();
for (int i = 1; i < _list_length; ++i)
{
list->next = new dataObjInfo_t{};
list = list->next;
}
return head;
}
|
// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcnestedtests.h"
#include "chainparams.h"
#include "consensus/validation.h"
#include "fs.h"
#include "validation.h"
#include "rpc/register.h"
#include "rpc/server.h"
#include "rpcconsole.h"
#include "test/test_pigeon.h"
#include "univalue.h"
#include "util.h"
#include "evo/deterministicmns.h"
#include "llmq/quorums_init.h"
#include <QDir>
#include <QtGlobal>
static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
{
if (request.fHelp) {
return "help message";
}
return request.params.write(0, 0);
}
static const CRPCCommand vRPCCommands[] =
{
{ "test", "rpcNestedTest", &rpcNestedTest_rpc, true, {} },
};
void RPCNestedTests::rpcNestedTests()
{
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
//mempool.setSanityCheck(1.0);
TestingSetup test;
SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child contaning the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parametres is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "e0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signrawtransaction(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransaction(…)");
RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
#if QT_VERSION >= 0x050300
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
#endif
}
|
/**
* \file abstractDessin.cc
* \author {Clement Caumes Doudouh Yassin}
* \date 9 janvier 2018
* \brief contient la defintion des methodes de AbstractDessin
*/
#include "../head/abstractDessin.hh"
#include "../head/types.hh"
using namespace std;
/**
* \fn AbstractDessin::AbstractDessin()
* Constructeur AbstractDessin
*/
AbstractDessin::AbstractDessin() {}
/**
* \fn AbstractDessin::~AbstractDessin()
* Destructeur de AbstractDessin
*/
AbstractDessin::~AbstractDessin(){}
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Cpacoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"
#include "addressbookpage.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "walletmodel.h"
#include "base58.h"
#include "init.h"
#include "main.h" // For strMessageMagic
#include "wallet/wallet.h"
#include <string>
#include <vector>
#include <QClipboard>
SignVerifyMessageDialog::SignVerifyMessageDialog(const PlatformStyle *platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::SignVerifyMessageDialog),
model(0),
platformStyle(platformStyle)
{
ui->setupUi(this);
#if QT_VERSION >= 0x040700
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
#endif
QString theme = GUIUtil::getThemeName();
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->signMessageButton_SM->setIcon(QIcon());
ui->clearButton_SM->setIcon(QIcon());
ui->verifyMessageButton_VM->setIcon(QIcon());
ui->clearButton_VM->setIcon(QIcon());
#else
ui->signMessageButton_SM->setIcon(QIcon(":/icons/" + theme + "/edit"));
ui->clearButton_SM->setIcon(QIcon(":/icons/" + theme + "/remove"));
ui->verifyMessageButton_VM->setIcon(QIcon(":/icons/" + theme + "/transaction_0"));
ui->clearButton_VM->setIcon(QIcon(":/icons/" + theme + "/remove"));
#endif
// These icons are needed on Mac also
ui->addressBookButton_SM->setIcon(QIcon(":/icons/" + theme + "/address-book"));
ui->pasteButton_SM->setIcon(QIcon(":/icons/" + theme + "/editpaste"));
ui->copySignatureButton_SM->setIcon(QIcon(":/icons/" + theme + "/editcopy"));
ui->addressBookButton_VM->setIcon(QIcon(":/icons/" + theme + "/address-book"));
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->signatureOut_SM->setFont(GUIUtil::fixedPitchFont());
ui->signatureIn_VM->setFont(GUIUtil::fixedPitchFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel *model)
{
this->model = model;
}
void SignVerifyMessageDialog::setAddress_SM(const QString &address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(const QString &address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
if (!model)
return;
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
if (!addr.IsValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
return;
}
CKey key;
if (!pwalletMain->GetKey(keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
GUIUtil::setClipboard(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());
if (!addr.IsValid())
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid)
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CBitcoinAddress(pubkey.GetID()) == addr))
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
{
if (ui->tabWidget->currentIndex() == 0)
{
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM)
{
ui->signatureOut_SM->selectAll();
return true;
}
}
else if (ui->tabWidget->currentIndex() == 1)
{
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QDialog::eventFilter(object, event);
}
|
/****************************************************************************
**
** Copyright (p) 2009-2015 C.B. Barber. All rights reserved.
** $Id: //main/2015/qhull/src/qhulltest/QhullPointSet_test.cpp#3 $$Change: 2062 $
** $DateTime: 2016/01/17 13:13:18 $$Author: bbarber $
**
****************************************************************************/
//pre-compiled header
#include <iostream>
#include "RoadTest.h" // QT_VERSION
#include "libqhullcpp/QhullPointSet.h"
#include "libqhullcpp/RboxPoints.h"
#include "libqhullcpp/QhullPoint.h"
#include "libqhullcpp/QhullFacet.h"
#include "libqhullcpp/QhullFacetList.h"
#include "libqhullcpp/Qhull.h"
using std::cout;
using std::endl;
using std::ostringstream;
namespace orgQhull {
class QhullPointSet_test : public RoadTest
{
Q_OBJECT
#//!\name Test slots
private slots:
void cleanup();
void t_construct();
void t_convert();
void t_element();
void t_iterator();
void t_const_iterator();
void t_search();
void t_pointset_iterator();
void t_io();
};//QhullPointSet_test
void
add_QhullPointSet_test()
{
new QhullPointSet_test(); // RoadTest::s_testcases
}
//Executed after each testcase
void QhullPointSet_test::
cleanup()
{
RoadTest::cleanup();
}
void QhullPointSet_test::
t_construct()
{
// Default constructor is disallowed (i.e., private)
RboxPoints rcube("c W0 1000");
Qhull q(rcube,"Qc"); // cube with 1000 coplanar points
int coplanarCount= 0;
foreach(QhullFacet f, q.facetList()){
QhullPointSet ps(q, f.getFacetT()->outsideset);
QVERIFY(ps.isEmpty());
QCOMPARE(ps.count(), 0);
QCOMPARE(ps.size(), 0u);
QhullPointSet ps2(q.qh(), f.getFacetT()->coplanarset);
QVERIFY(!ps2.isEmpty());
coplanarCount += ps2.count();
QCOMPARE(ps2.count(), (int)ps2.size());
QhullPointSet ps3(ps2);
QVERIFY(!ps3.isEmpty());
QCOMPARE(ps3.count(), ps2.count());
QVERIFY(ps3==ps2);
QVERIFY(ps3!=ps);
QhullPointSet ps4= ps3;
QVERIFY(ps4==ps2);
}
QCOMPARE(coplanarCount, 1000);
}//t_construct
void QhullPointSet_test::
t_convert()
{
RboxPoints rcube("c W0 1000");
Qhull q(rcube,"Qc"); // cube with 1000 coplanar points
QhullFacet f= q.firstFacet();
QhullPointSet ps= f.coplanarPoints();
QVERIFY(ps.count()>=1); // Sometimes no coplanar points
std::vector<QhullPoint> vs= ps.toStdVector();
QCOMPARE(vs.size(), ps.size());
QhullPoint p= ps[0];
QhullPoint p2= vs[0];
QCOMPARE(p, p2);
QList<QhullPoint> qs= ps.toQList();
QCOMPARE(qs.size(), static_cast<int>(ps.size()));
QhullPoint p3= qs[0];
QCOMPARE(p3, p);
}//t_convert
// readonly tested in t_construct
// empty, isEmpty, ==, !=, size
void QhullPointSet_test::
t_element()
{
RboxPoints rcube("c W0 1000");
Qhull q(rcube,"Qc"); // cube with 1000 coplanar points
QhullFacet f= q.firstFacet();
QhullPointSet ps= f.coplanarPoints();
QVERIFY(ps.count()>=3); // Sometimes no coplanar points
QhullPoint p= ps[0];
QCOMPARE(p, ps[0]);
QhullPoint p2= ps[ps.count()-1];
QCOMPARE(ps.at(1), ps[1]);
QCOMPARE(ps.second(), ps[1]);
QCOMPARE(ps.first(), p);
QCOMPARE(ps.front(), ps.first());
QCOMPARE(ps.last(), p2);
QCOMPARE(ps.back(), ps.last());
QhullPoint p8(q);
QCOMPARE(ps.value(2), ps[2]);
QCOMPARE(ps.value(-1), p8);
QCOMPARE(ps.value(ps.count()), p8);
QCOMPARE(ps.value(ps.count(), p), p);
QVERIFY(ps.value(1, p)!=p);
QhullPointSet ps8= f.coplanarPoints();
QhullPointSet::Iterator i= ps8.begin();
foreach(QhullPoint p9, ps){ // Qt only
QCOMPARE(p9.dimension(), 3);
QCOMPARE(p9, *i++);
}
}//t_element
void QhullPointSet_test::
t_iterator()
{
RboxPoints rcube("c W0 1000");
Qhull q(rcube,"Qc"); // cube with 1000 coplanar points
QhullFacet f= q.firstFacet();
QhullPointSet ps= f.coplanarPoints();
QVERIFY(ps.count()>=3); // Sometimes no coplanar points
QhullPointSet::Iterator i= ps.begin();
QhullPointSet::iterator i2= ps.begin();
QVERIFY(i==i2);
QVERIFY(i>=i2);
QVERIFY(i<=i2);
i= ps.begin();
QVERIFY(i==i2);
i2= ps.end();
QVERIFY(i!=i2);
QhullPoint p= *i;
QCOMPARE(p.dimension(), q.dimension());
QCOMPARE(p, ps[0]);
i2--;
QhullPoint p2= *i2;
QCOMPARE(p2.dimension(), q.dimension());
QCOMPARE(p2, ps.last());
QhullPointSet::Iterator i5(i2);
QCOMPARE(*i2, *i5);
QhullPointSet::Iterator i3= i+1;
QVERIFY(i!=i3);
QCOMPARE(i[1], *i3);
(i3= i)++;
QCOMPARE((*i3)[0], ps[1][0]);
QCOMPARE((*i3).dimension(), 3);
QVERIFY(i==i);
QVERIFY(i!=i3);
QVERIFY(i<i3);
QVERIFY(i<=i3);
QVERIFY(i3>i);
QVERIFY(i3>=i);
QhullPointSet::ConstIterator i4= ps.begin();
QVERIFY(i==i4); // iterator COMP const_iterator
QVERIFY(i<=i4);
QVERIFY(i>=i4);
QVERIFY(i4==i); // const_iterator COMP iterator
QVERIFY(i4<=i);
QVERIFY(i4>=i);
QVERIFY(i>=i4);
QVERIFY(i4<=i);
QVERIFY(i2!=i4);
QVERIFY(i2>i4);
QVERIFY(i2>=i4);
QVERIFY(i4!=i2);
QVERIFY(i4<i2);
QVERIFY(i4<=i2);
++i4;
QVERIFY(i!=i4); // iterator COMP const_iterator
QVERIFY(i<i4);
QVERIFY(i<=i4);
QVERIFY(i4>i);
QVERIFY(i4>=i);
i4= ps.constBegin();
QVERIFY(i==i4); // iterator COMP const_iterator
QCOMPARE(i4+ps.count(), ps.constEnd());
i= ps.begin();
i2= ps.begin();
QCOMPARE(i, i2++);
QCOMPARE(*i2, ps[1]);
QCOMPARE(++i, i2);
QCOMPARE(i, i2--);
QCOMPARE(i2, ps.begin());
QCOMPARE(--i, i2);
QCOMPARE(i2+=ps.count(), ps.end());
QCOMPARE(i2-=ps.count(), ps.begin());
QCOMPARE(i2+0, ps.begin());
QCOMPARE(i2+ps.count(), ps.end());
i2 += ps.count();
i= i2-0;
QCOMPARE(i, i2);
i= i2-ps.count();
QCOMPARE(i, ps.begin());
QCOMPARE(i2-i, ps.count());
//ps.begin end tested above
// QhullPointSet is const-only
}//t_iterator
void QhullPointSet_test::
t_const_iterator()
{
RboxPoints rcube("c W0 1000");
Qhull q(rcube,"Qc"); // cube with 1000 coplanar points
QhullFacet f= q.firstFacet();
QhullPointSet ps= f.coplanarPoints();
QVERIFY(ps.count()>=3); // Sometimes no coplanar points
QhullPointSet::ConstIterator i= ps.begin();
QhullPointSet::const_iterator i2= ps.begin();
QVERIFY(i==i2);
QVERIFY(i>=i2);
QVERIFY(i<=i2);
// See t_iterator for const_iterator COMP iterator
i= ps.begin();
QVERIFY(i==i2);
i2= ps.end();
QVERIFY(i!=i2);
QhullPoint p= *i; // QhullPoint is the base class for QhullPointSet::iterator
QCOMPARE(p.dimension(), q.dimension());
QCOMPARE(p, ps[0]);
i2--;
QhullPoint p2= *i2;
QCOMPARE(p2.dimension(), q.dimension());
QCOMPARE(p2, ps.last());
QhullPointSet::ConstIterator i5(i2);
QCOMPARE(*i2, *i5);
QhullPointSet::ConstIterator i3= i+1;
QVERIFY(i!=i3);
QCOMPARE(i[1], *i3);
QVERIFY(i==i);
QVERIFY(i!=i3);
QVERIFY(i<i3);
QVERIFY(i<=i3);
QVERIFY(i3>i);
QVERIFY(i3>=i);
// QhullPointSet is const-only
}//t_const_iterator
void QhullPointSet_test::
t_search()
{
RboxPoints rcube("c W0 1000");
Qhull q(rcube,"Qc"); // cube with 1000 coplanar points
QhullFacet f= q.firstFacet();
QhullPointSet ps= f.coplanarPoints();
QVERIFY(ps.count()>=3); // Sometimes no coplanar points
QhullPoint p= ps.first();
QhullPoint p2= ps.last();
QVERIFY(ps.contains(p));
QVERIFY(ps.contains(p2));
QVERIFY(p!=p2);
QhullPoint p3= ps[2];
QVERIFY(ps.contains(p3));
QVERIFY(p!=p3);
QCOMPARE(ps.indexOf(p), 0);
QCOMPARE(ps.indexOf(p2), ps.count()-1);
QCOMPARE(ps.indexOf(p3), 2);
QhullPoint p4(q);
QCOMPARE(ps.indexOf(p4), -1);
QCOMPARE(ps.lastIndexOf(p), 0);
QCOMPARE(ps.lastIndexOf(p2), ps.count()-1);
QCOMPARE(ps.lastIndexOf(p3), 2);
QCOMPARE(ps.lastIndexOf(p4), -1);
}//t_search
void QhullPointSet_test::
t_pointset_iterator()
{
RboxPoints rcube("c W0 1000");
Qhull q(rcube,"Qc"); // cube with 1000 coplanar points
QhullFacet f= q.firstFacet();
QhullPointSet ps2= f.outsidePoints();
QVERIFY(ps2.count()==0); // No outside points after constructing the convex hull
QhullPointSetIterator i2= ps2;
QCOMPARE(i2.countRemaining(), 0);
QVERIFY(!i2.hasNext());
QVERIFY(!i2.hasPrevious());
i2.toBack();
QVERIFY(!i2.hasNext());
QVERIFY(!i2.hasPrevious());
QhullPointSet ps= f.coplanarPoints();
QVERIFY(ps.count()>=3); // Sometimes no coplanar points
QhullPointSetIterator i(ps);
i2= ps;
QCOMPARE(i2.countRemaining(), ps.count());
QVERIFY(i2.hasNext());
QVERIFY(!i2.hasPrevious());
QVERIFY(i.hasNext());
QVERIFY(!i.hasPrevious());
i2.toBack();
QCOMPARE(i2.countRemaining(), 0);
i.toFront();
QCOMPARE(i.countRemaining(), ps.count());
QCOMPARE(i2.countRemaining(), 0);
QVERIFY(!i2.hasNext());
QVERIFY(i2.hasPrevious());
QVERIFY(i.hasNext());
QVERIFY(!i.hasPrevious());
QhullPoint p= ps[0];
QhullPoint p2(ps[0]);
QCOMPARE(p, p2);
QVERIFY(p==p2);
QhullPoint p3(ps.last());
// p2[0]= 0.0;
QVERIFY(p==p2);
QCOMPARE(i2.peekPrevious(), p3);
QCOMPARE(i2.previous(), p3);
QCOMPARE(i2.previous(), ps[ps.count()-2]);
QVERIFY(i2.hasPrevious());
QCOMPARE(i.peekNext(), p);
// i.peekNext()= 1.0; // compiler error
QCOMPARE(i.next(), p);
QCOMPARE(i.countRemaining(), ps.count()-1);
QhullPoint p4= i.peekNext();
QVERIFY(p4!=p3);
QCOMPARE(i.next(), p4);
QVERIFY(i.hasNext());
i.toFront();
QCOMPARE(i.next(), p);
}//t_pointset_iterator
void QhullPointSet_test::
t_io()
{
ostringstream os;
RboxPoints rcube("c W0 120");
Qhull q(rcube,"Qc"); // cube with 100 coplanar points
QhullFacet f= q.firstFacet();
QhullPointSet ps= f.coplanarPoints();
QVERIFY(ps.count()>=3); // Sometimes no coplanar points
os << "QhullPointSet from coplanarPoints\n" << ps << endl;
os << ps.print("\nWith message\n");
os << ps.printIdentifiers("\nCoplanar points: ");
os << "\nAs a point set:\n";
os << ps;
cout << os.str();
QString s= QString::fromStdString(os.str());
QCOMPARE(s.count(" 0.5\n"), 3*ps.count());
QCOMPARE(s.count("p"), ps.count()+4);
}//t_io
}//orgQhull
#include "moc/QhullPointSet_test.moc"
|
//
// Created by 王耀 on 2017/10/7.
//
#include <new>
#include "funcnode.h"
FuncNode::FuncNode(int entryPoint, unsigned int paramCount, unsigned int localDataSize) {
new (this)FuncNode(-1, entryPoint, paramCount, localDataSize);
}
FuncNode::FuncNode(int index, int entryPoint, unsigned int paramCount, unsigned int localDataSize) {
iIndex = index;
iEntryPoint = entryPoint;
uiParamCount = paramCount;
uiLocalDataSize = localDataSize;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "validation.h"
#include "arith_uint256.h"
#include "chain.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "checkqueue.h"
#include "consensus/consensus.h"
#include "consensus/merkle.h"
#include "consensus/tx_verify.h"
#include "consensus/validation.h"
#include "cuckoocache.h"
#include "fs.h"
#include "hash.h"
#include "init.h"
#include "policy/fees.h"
#include "policy/policy.h"
#include "policy/rbf.h"
#include "pow.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "random.h"
#include "reverse_iterator.h"
#include "script/script.h"
#include "script/sigcache.h"
#include "script/standard.h"
#include "timedata.h"
#include "tinyformat.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "undo.h"
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include "validationinterface.h"
#include "versionbits.h"
#include "warnings.h"
#include <atomic>
#include <sstream>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/thread.hpp>
#if defined(NDEBUG)
# error "Ragecoin cannot be compiled without assertions."
#endif
/**
* Global state
*/
CCriticalSection cs_main;
BlockMap mapBlockIndex;
CChain chainActive;
CBlockIndex *pindexBestHeader = nullptr;
CWaitableCriticalSection csBestBlock;
CConditionVariable cvBlockChange;
int nScriptCheckThreads = 0;
std::atomic_bool fImporting(false);
bool fReindex = false;
bool fTxIndex = false;
bool fHavePruned = false;
bool fPruneMode = false;
bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
bool fRequireStandard = true;
bool fCheckBlockIndex = false;
bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
size_t nCoinCacheUsage = 5000 * 300;
uint64_t nPruneTarget = 0;
int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
uint256 hashAssumeValid;
arith_uint256 nMinimumChainWork;
CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
CBlockPolicyEstimator feeEstimator;
CTxMemPool mempool(&feeEstimator);
static void CheckBlockIndex(const Consensus::Params& consensusParams);
/** Constant stuff for coinbase transactions we create: */
CScript COINBASE_FLAGS;
const std::string strMessageMagic = "Ragecoin Signed Message:\n";
// Internal stuff
namespace {
struct CBlockIndexWorkComparator
{
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
// First sort by most total work, ...
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
// ... then by earliest time received, ...
if (pa->nSequenceId < pb->nSequenceId) return false;
if (pa->nSequenceId > pb->nSequenceId) return true;
// Use pointer address as tie breaker (should only happen with blocks
// loaded from disk, as those all have id 0).
if (pa < pb) return false;
if (pa > pb) return true;
// Identical blocks.
return false;
}
};
CBlockIndex *pindexBestInvalid;
/**
* The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
* as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
* missing the data for the block.
*/
std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
/** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
* Pruned nodes may have entries where B is missing data.
*/
std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
CCriticalSection cs_LastBlockFile;
std::vector<CBlockFileInfo> vinfoBlockFile;
int nLastBlockFile = 0;
/** Global flag to indicate we should check to see if there are
* block/undo files that should be deleted. Set on startup
* or if we allocate more file space when we're in prune mode
*/
bool fCheckForPruning = false;
/**
* Every received block is assigned a unique and increasing identifier, so we
* know which one to give priority in case of a fork.
*/
CCriticalSection cs_nBlockSequenceId;
/** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
int32_t nBlockSequenceId = 1;
/** Decreasing counter (used by subsequent preciousblock calls). */
int32_t nBlockReverseSequenceId = -1;
/** chainwork for the last block that preciousblock has been applied to. */
arith_uint256 nLastPreciousChainwork = 0;
/** In order to efficiently track invalidity of headers, we keep the set of
* blocks which we tried to connect and found to be invalid here (ie which
* were set to BLOCK_FAILED_VALID since the last restart). We can then
* walk this set and check if a new header is a descendant of something in
* this set, preventing us from having to walk mapBlockIndex when we try
* to connect a bad block and fail.
*
* While this is more complicated than marking everything which descends
* from an invalid block as invalid at the time we discover it to be
* invalid, doing so would require walking all of mapBlockIndex to find all
* descendants. Since this case should be very rare, keeping track of all
* BLOCK_FAILED_VALID blocks in a set should be just fine and work just as
* well.
*
* Because we alreardy walk mapBlockIndex in height-order at startup, we go
* ahead and mark descendants of invalid blocks as FAILED_CHILD at that time,
* instead of putting things in this set.
*/
std::set<CBlockIndex*> g_failed_blocks;
/** Dirty block index entries. */
std::set<CBlockIndex*> setDirtyBlockIndex;
/** Dirty block file entries. */
std::set<int> setDirtyFileInfo;
} // anon namespace
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
{
// Find the first block the caller has in the main chain
for (const uint256& hash : locator.vHave) {
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (chain.Contains(pindex))
return pindex;
if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
return chain.Tip();
}
}
}
return chain.Genesis();
}
CCoinsViewDB *pcoinsdbview = nullptr;
CCoinsViewCache *pcoinsTip = nullptr;
CBlockTreeDB *pblocktree = nullptr;
enum FlushStateMode {
FLUSH_STATE_NONE,
FLUSH_STATE_IF_NEEDED,
FLUSH_STATE_PERIODIC,
FLUSH_STATE_ALWAYS
};
// See definition for documentation
static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr);
static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
bool CheckFinalTx(const CTransaction &tx, int flags)
{
AssertLockHeld(cs_main);
// By convention a negative value for flags indicates that the
// current network-enforced consensus rules should be used. In
// a future soft-fork scenario that would mean checking which
// rules would be enforced for the next block and setting the
// appropriate flags. At the present time no soft-forks are
// scheduled, so no flags are set.
flags = std::max(flags, 0);
// CheckFinalTx() uses chainActive.Height()+1 to evaluate
// nLockTime because when IsFinalTx() is called within
// CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a
// transaction can be part of the *next* block, we need to call
// IsFinalTx() with one more than chainActive.Height().
const int nBlockHeight = chainActive.Height() + 1;
// BIP113 will require that time-locked transactions have nLockTime set to
// less than the median time of the previous block they're contained in.
// When the next block is created its previous block will be the current
// chain tip, so we use that to calculate the median time passed to
// IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
? chainActive.Tip()->GetMedianTimePast()
: GetAdjustedTime();
return IsFinalTx(tx, nBlockHeight, nBlockTime);
}
bool TestLockPointValidity(const LockPoints* lp)
{
AssertLockHeld(cs_main);
assert(lp);
// If there are relative lock times then the maxInputBlock will be set
// If there are no relative lock times, the LockPoints don't depend on the chain
if (lp->maxInputBlock) {
// Check whether chainActive is an extension of the block at which the LockPoints
// calculation was valid. If not LockPoints are no longer valid
if (!chainActive.Contains(lp->maxInputBlock)) {
return false;
}
}
// LockPoints still valid
return true;
}
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
{
AssertLockHeld(cs_main);
AssertLockHeld(mempool.cs);
CBlockIndex* tip = chainActive.Tip();
CBlockIndex index;
index.pprev = tip;
// CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
// height based locks because when SequenceLocks() is called within
// ConnectBlock(), the height of the block *being*
// evaluated is what is used.
// Thus if we want to know if a transaction can be part of the
// *next* block, we need to use one more than chainActive.Height()
index.nHeight = tip->nHeight + 1;
std::pair<int, int64_t> lockPair;
if (useExistingLockPoints) {
assert(lp);
lockPair.first = lp->height;
lockPair.second = lp->time;
}
else {
// pcoinsTip contains the UTXO set for chainActive.Tip()
CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
std::vector<int> prevheights;
prevheights.resize(tx.vin.size());
for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
const CTxIn& txin = tx.vin[txinIndex];
Coin coin;
if (!viewMemPool.GetCoin(txin.prevout, coin)) {
return error("%s: Missing input", __func__);
}
if (coin.nHeight == MEMPOOL_HEIGHT) {
// Assume all mempool transaction confirm in the next block
prevheights[txinIndex] = tip->nHeight + 1;
} else {
prevheights[txinIndex] = coin.nHeight;
}
}
lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
if (lp) {
lp->height = lockPair.first;
lp->time = lockPair.second;
// Also store the hash of the block with the highest height of
// all the blocks which have sequence locked prevouts.
// This hash needs to still be on the chain
// for these LockPoint calculations to be valid
// Note: It is impossible to correctly calculate a maxInputBlock
// if any of the sequence locked inputs depend on unconfirmed txs,
// except in the special case where the relative lock time/height
// is 0, which is equivalent to no sequence lock. Since we assume
// input height of tip+1 for mempool txs and test the resulting
// lockPair from CalculateSequenceLocks against tip+1. We know
// EvaluateSequenceLocks will fail if there was a non-zero sequence
// lock on a mempool input, so we can use the return value of
// CheckSequenceLocks to indicate the LockPoints validity
int maxInputHeight = 0;
for (int height : prevheights) {
// Can ignore mempool inputs since we'll fail if they had non-zero locks
if (height != tip->nHeight+1) {
maxInputHeight = std::max(maxInputHeight, height);
}
}
lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
}
}
return EvaluateSequenceLocks(index, lockPair);
}
// Returns the script flags which should be checked for a given block
static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
int expired = pool.Expire(GetTime() - age);
if (expired != 0) {
LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
}
std::vector<COutPoint> vNoSpendsRemaining;
pool.TrimToSize(limit, &vNoSpendsRemaining);
for (const COutPoint& removed : vNoSpendsRemaining)
pcoinsTip->Uncache(removed);
}
/** Convert CValidationState to a human-readable message for logging */
std::string FormatStateMessage(const CValidationState &state)
{
return strprintf("%s%s (code %i)",
state.GetRejectReason(),
state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
state.GetRejectCode());
}
static bool IsCurrentForFeeEstimation()
{
AssertLockHeld(cs_main);
if (IsInitialBlockDownload())
return false;
if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
return false;
if (chainActive.Height() < pindexBestHeader->nHeight - 1)
return false;
return true;
}
/* Make mempool consistent after a reorg, by re-adding or recursively erasing
* disconnected block transactions from the mempool, and also removing any
* other transactions from the mempool that are no longer valid given the new
* tip/height.
*
* Note: we assume that disconnectpool only contains transactions that are NOT
* confirmed in the current chain nor already in the mempool (otherwise,
* in-mempool descendants of such transactions would be removed).
*
* Passing fAddToMempool=false will skip trying to add the transactions back,
* and instead just erase from the mempool as needed.
*/
void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
{
AssertLockHeld(cs_main);
std::vector<uint256> vHashUpdate;
// disconnectpool's insertion_order index sorts the entries from
// oldest to newest, but the oldest entry will be the last tx from the
// latest mined block that was disconnected.
// Iterate disconnectpool in reverse, so that we add transactions
// back to the mempool starting with the earliest transaction that had
// been previously seen in a block.
auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
// ignore validation errors in resurrected transactions
CValidationState stateDummy;
if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, false, nullptr, nullptr, true)) {
// If the transaction doesn't make it in to the mempool, remove any
// transactions that depend on it (which would now be orphans).
mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
} else if (mempool.exists((*it)->GetHash())) {
vHashUpdate.push_back((*it)->GetHash());
}
++it;
}
disconnectpool.queuedTx.clear();
// AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
// no in-mempool children, which is generally not true when adding
// previously-confirmed transactions back to the mempool.
// UpdateTransactionsFromBlock finds descendants of any transactions in
// the disconnectpool that were added back and cleans up the mempool state.
mempool.UpdateTransactionsFromBlock(vHashUpdate);
// We also need to remove any now-immature transactions
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
// Re-limit mempool size, in case we added any transactions
LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
}
// Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
// were somehow broken and returning the wrong scriptPubKeys
static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
AssertLockHeld(cs_main);
// pool.cs should be locked already, but go ahead and re-take the lock here
// to enforce that mempool doesn't change between when we check the view
// and when we actually call through to CheckInputs
LOCK(pool.cs);
assert(!tx.IsCoinBase());
for (const CTxIn& txin : tx.vin) {
const Coin& coin = view.AccessCoin(txin.prevout);
// At this point we haven't actually checked if the coins are all
// available (or shouldn't assume we have, since CheckInputs does).
// So we just return failure if the inputs are not available here,
// and then only have to check equivalence for available inputs.
if (coin.IsSpent()) return false;
const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
if (txFrom) {
assert(txFrom->GetHash() == txin.prevout.hash);
assert(txFrom->vout.size() > txin.prevout.n);
assert(txFrom->vout[txin.prevout.n] == coin.out);
} else {
const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
assert(!coinFromDisk.IsSpent());
assert(coinFromDisk.out == coin.out);
}
}
return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
}
static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
{
const CTransaction& tx = *ptx;
const uint256 hash = tx.GetHash();
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
if (!CheckTransaction(tx, state))
return false; // state filled in by CheckTransaction
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return state.DoS(100, false, REJECT_INVALID, "coinbase");
// Reject transactions with witness before segregated witness activates (override with -prematurewitness)
bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
}
// Rather not work on nonstandard transactions (unless -testnet/-regtest)
std::string reason;
if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
return state.DoS(0, false, REJECT_NONSTANDARD, reason);
// Only accept nLockTime-using transactions that can be mined in the next
// block; we don't want our mempool filled up with transactions that can't
// be mined yet.
if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
// is it already in the memory pool?
if (pool.exists(hash)) {
return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
}
// Check for conflicts with in-memory transactions
std::set<uint256> setConflicts;
{
LOCK(pool.cs); // protect pool.mapNextTx
for (const CTxIn &txin : tx.vin)
{
auto itConflicting = pool.mapNextTx.find(txin.prevout);
if (itConflicting != pool.mapNextTx.end())
{
const CTransaction *ptxConflicting = itConflicting->second;
if (!setConflicts.count(ptxConflicting->GetHash()))
{
// Allow opt-out of transaction replacement by setting
// nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
//
// SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
// non-replaceable transactions. All inputs rather than just one
// is for the sake of multi-party protocols, where we don't
// want a single party to be able to disable replacement.
//
// The opt-out ignores descendants as anyone relying on
// first-seen mempool behavior should be checking all
// unconfirmed ancestors anyway; doing otherwise is hopelessly
// insecure.
bool fReplacementOptOut = true;
if (fEnableReplacement)
{
for (const CTxIn &_txin : ptxConflicting->vin)
{
if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
{
fReplacementOptOut = false;
break;
}
}
}
if (fReplacementOptOut) {
return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
}
setConflicts.insert(ptxConflicting->GetHash());
}
}
}
}
{
CCoinsView dummy;
CCoinsViewCache view(&dummy);
CAmount nValueIn = 0;
LockPoints lp;
{
LOCK(pool.cs);
CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
view.SetBackend(viewMemPool);
// do all inputs exist?
for (const CTxIn txin : tx.vin) {
if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
coins_to_uncache.push_back(txin.prevout);
}
if (!view.HaveCoin(txin.prevout)) {
// Are inputs missing because we already have the tx?
for (size_t out = 0; out < tx.vout.size(); out++) {
// Optimistically just do efficient check of cache for outputs
if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
}
}
// Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
if (pfMissingInputs) {
*pfMissingInputs = true;
}
return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
}
}
// Bring the best block into scope
view.GetBestBlock();
nValueIn = view.GetValueIn(tx);
// we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
view.SetBackend(dummy);
// Only accept BIP68 sequence locked transactions that can be mined in the next
// block; we don't want our mempool filled up with transactions that can't
// be mined yet.
// Must keep pool.cs for this unless we change CheckSequenceLocks to take a
// CoinsViewCache instead of create its own
if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
}
// Check for non-standard pay-to-script-hash in inputs
if (fRequireStandard && !AreInputsStandard(tx, view))
return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
// Check for non-standard witness in P2WSH
if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
CAmount nValueOut = tx.GetValueOut();
CAmount nFees = nValueIn-nValueOut;
// nModifiedFees includes any fee deltas from PrioritiseTransaction
CAmount nModifiedFees = nFees;
pool.ApplyDelta(hash, nModifiedFees);
// Keep track of transactions that spend a coinbase, which we re-scan
// during reorgs to ensure COINBASE_MATURITY is still met.
bool fSpendsCoinbase = false;
for (const CTxIn &txin : tx.vin) {
const Coin &coin = view.AccessCoin(txin.prevout);
if (coin.IsCoinBase()) {
fSpendsCoinbase = true;
break;
}
}
CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
fSpendsCoinbase, nSigOpsCost, lp);
unsigned int nSize = entry.GetTxSize();
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
strprintf("%d", nSigOpsCost));
CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
}
// No transactions are allowed below minRelayTxFee except from disconnected blocks
if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
}
if (nAbsurdFee && nFees > nAbsurdFee)
return state.Invalid(false,
REJECT_HIGHFEE, "absurdly-high-fee",
strprintf("%d > %d", nFees, nAbsurdFee));
// Calculate in-mempool ancestors, up to a limit.
CTxMemPool::setEntries setAncestors;
size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
std::string errString;
if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
}
// A transaction that spends outputs that would be replaced by it is invalid. Now
// that we have the set of all ancestors we can detect this
// pathological case by making sure setConflicts and setAncestors don't
// intersect.
for (CTxMemPool::txiter ancestorIt : setAncestors)
{
const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
if (setConflicts.count(hashAncestor))
{
return state.DoS(10, false,
REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
strprintf("%s spends conflicting transaction %s",
hash.ToString(),
hashAncestor.ToString()));
}
}
// Check if it's economically rational to mine this transaction rather
// than the ones it replaces.
CAmount nConflictingFees = 0;
size_t nConflictingSize = 0;
uint64_t nConflictingCount = 0;
CTxMemPool::setEntries allConflicting;
// If we don't hold the lock allConflicting might be incomplete; the
// subsequent RemoveStaged() and addUnchecked() calls don't guarantee
// mempool consistency for us.
LOCK(pool.cs);
const bool fReplacementTransaction = setConflicts.size();
if (fReplacementTransaction)
{
CFeeRate newFeeRate(nModifiedFees, nSize);
std::set<uint256> setConflictsParents;
const int maxDescendantsToVisit = 100;
CTxMemPool::setEntries setIterConflicting;
for (const uint256 &hashConflicting : setConflicts)
{
CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
if (mi == pool.mapTx.end())
continue;
// Save these to avoid repeated lookups
setIterConflicting.insert(mi);
// Don't allow the replacement to reduce the feerate of the
// mempool.
//
// We usually don't want to accept replacements with lower
// feerates than what they replaced as that would lower the
// feerate of the next block. Requiring that the feerate always
// be increased is also an easy-to-reason about way to prevent
// DoS attacks via replacements.
//
// The mining code doesn't (currently) take children into
// account (CPFP) so we only consider the feerates of
// transactions being directly replaced, not their indirect
// descendants. While that does mean high feerate children are
// ignored when deciding whether or not to replace, we do
// require the replacement to pay more overall fees too,
// mitigating most cases.
CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
if (newFeeRate <= oldFeeRate)
{
return state.DoS(0, false,
REJECT_INSUFFICIENTFEE, "insufficient fee", false,
strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
hash.ToString(),
newFeeRate.ToString(),
oldFeeRate.ToString()));
}
for (const CTxIn &txin : mi->GetTx().vin)
{
setConflictsParents.insert(txin.prevout.hash);
}
nConflictingCount += mi->GetCountWithDescendants();
}
// This potentially overestimates the number of actual descendants
// but we just want to be conservative to avoid doing too much
// work.
if (nConflictingCount <= maxDescendantsToVisit) {
// If not too many to replace, then calculate the set of
// transactions that would have to be evicted
for (CTxMemPool::txiter it : setIterConflicting) {
pool.CalculateDescendants(it, allConflicting);
}
for (CTxMemPool::txiter it : allConflicting) {
nConflictingFees += it->GetModifiedFee();
nConflictingSize += it->GetTxSize();
}
} else {
return state.DoS(0, false,
REJECT_NONSTANDARD, "too many potential replacements", false,
strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
hash.ToString(),
nConflictingCount,
maxDescendantsToVisit));
}
for (unsigned int j = 0; j < tx.vin.size(); j++)
{
// We don't want to accept replacements that require low
// feerate junk to be mined first. Ideally we'd keep track of
// the ancestor feerates and make the decision based on that,
// but for now requiring all new inputs to be confirmed works.
if (!setConflictsParents.count(tx.vin[j].prevout.hash))
{
// Rather than check the UTXO set - potentially expensive -
// it's cheaper to just check if the new input refers to a
// tx that's in the mempool.
if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
return state.DoS(0, false,
REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
strprintf("replacement %s adds unconfirmed input, idx %d",
hash.ToString(), j));
}
}
// The replacement must pay greater fees than the transactions it
// replaces - if we did the bandwidth used by those conflicting
// transactions would not be paid for.
if (nModifiedFees < nConflictingFees)
{
return state.DoS(0, false,
REJECT_INSUFFICIENTFEE, "insufficient fee", false,
strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
}
// Finally in addition to paying more fees than the conflicts the
// new transaction must pay for its own bandwidth.
CAmount nDeltaFees = nModifiedFees - nConflictingFees;
if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
{
return state.DoS(0, false,
REJECT_INSUFFICIENTFEE, "insufficient fee", false,
strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
hash.ToString(),
FormatMoney(nDeltaFees),
FormatMoney(::incrementalRelayFee.GetFee(nSize))));
}
}
unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
if (!chainparams.RequireStandard()) {
scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
PrecomputedTransactionData txdata(tx);
if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
// SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
// need to turn both off, and compare against just turning off CLEANSTACK
// to see if the failure is specifically due to witness validation.
CValidationState stateDummy; // Want reported failures to be from first CheckInputs
if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
!CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
// Only the witness is missing, so the transaction itself may be fine.
state.SetCorruptionPossible();
}
return false; // state filled in by CheckInputs
}
// Check again against the current block tip's script verification
// flags to cache our script execution flags. This is, of course,
// useless if the next block has different script flags from the
// previous one, but because the cache tracks script flags for us it
// will auto-invalidate and we'll just have a few blocks of extra
// misses on soft-fork activation.
//
// This is also useful in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks (using TestBlockValidity), however allowing such
// transactions into the mempool can be exploited as a DoS attack.
unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
{
// If we're using promiscuousmempoolflags, we may hit this normally
// Check if current block has some flags that scriptVerifyFlags
// does not before printing an ominous warning
if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
__func__, hash.ToString(), FormatStateMessage(state));
} else {
if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
__func__, hash.ToString(), FormatStateMessage(state));
} else {
LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
}
}
}
// Remove conflicting transactions from the mempool
for (const CTxMemPool::txiter it : allConflicting)
{
LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s RAGE additional fees, %d delta bytes\n",
it->GetTx().GetHash().ToString(),
hash.ToString(),
FormatMoney(nModifiedFees - nConflictingFees),
(int)nSize - (int)nConflictingSize);
if (plTxnReplaced)
plTxnReplaced->push_back(it->GetSharedTx());
}
pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
// This transaction should only count for fee estimation if it isn't a
// BIP 125 replacement transaction (may not be widely supported), the
// node is not behind, and the transaction is not dependent on any other
// transactions in the mempool.
bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
// Store transaction in memory
pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
// trim mempool and check if tx was trimmed
if (!fOverrideMempoolLimit) {
LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
if (!pool.exists(hash))
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
}
}
GetMainSignals().TransactionAddedToMempool(ptx);
return true;
}
/** (try to) add transaction to memory pool with a specified acceptance time **/
static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
{
std::vector<COutPoint> coins_to_uncache;
bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, coins_to_uncache);
if (!res) {
for (const COutPoint& hashTx : coins_to_uncache)
pcoinsTip->Uncache(hashTx);
}
// After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
CValidationState stateDummy;
FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
return res;
}
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
{
const CChainParams& chainparams = Params();
return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
}
/** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
{
CBlockIndex *pindexSlow = nullptr;
LOCK(cs_main);
CTransactionRef ptx = mempool.get(hash);
if (ptx)
{
txOut = ptx;
return true;
}
if (fTxIndex) {
CDiskTxPos postx;
if (pblocktree->ReadTxIndex(hash, postx)) {
CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
if (file.IsNull())
return error("%s: OpenBlockFile failed", __func__);
CBlockHeader header;
try {
file >> header;
fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
file >> txOut;
} catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
hashBlock = header.GetHash();
if (txOut->GetHash() != hash)
return error("%s: txid mismatch", __func__);
return true;
}
}
if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
const Coin& coin = AccessByTxid(*pcoinsTip, hash);
if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
}
if (pindexSlow) {
CBlock block;
if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
for (const auto& tx : block.vtx) {
if (tx->GetHash() == hash) {
txOut = tx;
hashBlock = pindexSlow->GetBlockHash();
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
{
// Open history file to append
CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("WriteBlockToDisk: OpenBlockFile failed");
// Write index header
unsigned int nSize = GetSerializeSize(fileout, block);
fileout << FLATDATA(messageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("WriteBlockToDisk: ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << block;
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
{
block.SetNull();
// Open history file to read
CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
// Read block
try {
filein >> block;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
}
// Check the header
if (!CheckProofOfWork(block.GetPoWHash(), block.nBits, consensusParams))
return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
return false;
if (block.GetHash() != pindex->GetBlockHash())
return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
pindex->ToString(), pindex->GetBlockPos().ToString());
return true;
}
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
{
int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
// Force block reward to zero when right shift is undefined.
if (halvings >= 64)
return 0;
CAmount nSubsidy = 50 * COIN;
// Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
nSubsidy >>= halvings;
return nSubsidy;
}
bool IsInitialBlockDownload()
{
// Once this function has returned false, it must remain false.
static std::atomic<bool> latchToFalse{false};
// Optimization: pre-test latch before taking the lock.
if (latchToFalse.load(std::memory_order_relaxed))
return false;
LOCK(cs_main);
if (latchToFalse.load(std::memory_order_relaxed))
return false;
if (fImporting || fReindex)
return true;
if (chainActive.Tip() == nullptr)
return true;
if (chainActive.Tip()->nChainWork < nMinimumChainWork)
return true;
if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
return true;
LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
latchToFalse.store(true, std::memory_order_relaxed);
return false;
}
CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
static void AlertNotify(const std::string& strMessage)
{
uiInterface.NotifyAlertChanged();
std::string strCmd = gArgs.GetArg("-alertnotify", "");
if (strCmd.empty()) return;
// Alert text should be plain ascii coming from a trusted source, but to
// be safe we first strip anything not in safeChars, then add single quotes around
// the whole string before passing it to the shell:
std::string singleQuote("'");
std::string safeStatus = SanitizeString(strMessage);
safeStatus = singleQuote+safeStatus+singleQuote;
boost::replace_all(strCmd, "%s", safeStatus);
boost::thread t(runCommand, strCmd); // thread runs free
}
static void CheckForkWarningConditions()
{
AssertLockHeld(cs_main);
// Before we get past initial download, we cannot reliably alert about forks
// (we assume we don't get stuck on a fork before finishing our initial sync)
if (IsInitialBlockDownload())
return;
// If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
// of our head, drop it
if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
pindexBestForkTip = nullptr;
if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
{
if (!GetfLargeWorkForkFound() && pindexBestForkBase)
{
std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
pindexBestForkBase->phashBlock->ToString() + std::string("'");
AlertNotify(warning);
}
if (pindexBestForkTip && pindexBestForkBase)
{
LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__,
pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
SetfLargeWorkForkFound(true);
}
else
{
LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
SetfLargeWorkInvalidChainFound(true);
}
}
else
{
SetfLargeWorkForkFound(false);
SetfLargeWorkInvalidChainFound(false);
}
}
static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
{
AssertLockHeld(cs_main);
// If we are on a fork that is sufficiently large, set a warning flag
CBlockIndex* pfork = pindexNewForkTip;
CBlockIndex* plonger = chainActive.Tip();
while (pfork && pfork != plonger)
{
while (plonger && plonger->nHeight > pfork->nHeight)
plonger = plonger->pprev;
if (pfork == plonger)
break;
pfork = pfork->pprev;
}
// We define a condition where we should warn the user about as a fork of at least 7 blocks
// with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
// We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
// hash rate operating on the fork.
// or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
// We define it this way because it allows us to only store the highest fork tip (+ base) which meets
// the 7-block condition and from this always have the most-likely-to-cause-warning fork
if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
chainActive.Height() - pindexNewForkTip->nHeight < 72)
{
pindexBestForkTip = pindexNewForkTip;
pindexBestForkBase = pfork;
}
CheckForkWarningConditions();
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
pindexBestInvalid = pindexNew;
LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
pindexNew->GetBlockTime()));
CBlockIndex *tip = chainActive.Tip();
assert (tip);
LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
CheckForkWarningConditions();
}
void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
if (!state.CorruptionPossible()) {
pindex->nStatus |= BLOCK_FAILED_VALID;
g_failed_blocks.insert(pindex);
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
InvalidChainFound(pindex);
}
}
void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
{
// mark inputs spent
if (!tx.IsCoinBase()) {
txundo.vprevout.reserve(tx.vin.size());
for (const CTxIn &txin : tx.vin) {
txundo.vprevout.emplace_back();
bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
assert(is_spent);
}
}
// add outputs
AddCoins(inputs, tx, nHeight);
}
void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
{
CTxUndo txundo;
UpdateCoins(tx, inputs, txundo, nHeight);
}
bool CScriptCheck::operator()() {
const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
return VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error);
}
int GetSpendHeight(const CCoinsViewCache& inputs)
{
LOCK(cs_main);
CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
return pindexPrev->nHeight + 1;
}
static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
static uint256 scriptExecutionCacheNonce(GetRandHash());
void InitScriptExecutionCache() {
// nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
// setup_bytes creates the minimum possible cache (2 elements).
size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
(nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
}
/**
* Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
* This does not modify the UTXO set.
*
* If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
* script checks which are not necessary (eg due to script execution cache hits) are, obviously,
* not pushed onto pvChecks/run.
*
* Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
* which are matched. This is useful for checking blocks where we will likely never need the cache
* entry again.
*
* Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
*/
bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
{
if (!tx.IsCoinBase())
{
if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
return false;
if (pvChecks)
pvChecks->reserve(tx.vin.size());
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
// Skip script verification when connecting blocks under the
// assumevalid block. Assuming the assumevalid block is valid this
// is safe because block merkle hashes are still computed and checked,
// Of course, if an assumed valid block is invalid due to false scriptSigs
// this optimization would allow an invalid chain to be accepted.
if (fScriptChecks) {
// First check if script executions have been cached with the same
// flags. Note that this assumes that the inputs provided are
// correct (ie that the transaction hash which is in tx's prevouts
// properly commits to the scriptPubKey in the inputs view of that
// transaction).
uint256 hashCacheEntry;
// We only use the first 19 bytes of nonce to avoid a second SHA
// round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
return true;
}
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const Coin& coin = inputs.AccessCoin(prevout);
assert(!coin.IsSpent());
// We very carefully only pass in things to CScriptCheck which
// are clearly committed to by tx' witness hash. This provides
// a sanity check that our caching is not introducing consensus
// failures through additional data in, eg, the coins being
// spent being checked as a part of CScriptCheck.
const CScript& scriptPubKey = coin.out.scriptPubKey;
const CAmount amount = coin.out.nValue;
// Verify signature
CScriptCheck check(scriptPubKey, amount, tx, i, flags, cacheSigStore, &txdata);
if (pvChecks) {
pvChecks->push_back(CScriptCheck());
check.swap(pvChecks->back());
} else if (!check()) {
if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
// Check whether the failure was caused by a
// non-mandatory script verification check, such as
// non-standard DER encodings or non-null dummy
// arguments; if so, don't trigger DoS protection to
// avoid splitting the network between upgraded and
// non-upgraded nodes.
CScriptCheck check2(scriptPubKey, amount, tx, i,
flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
if (check2())
return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
}
// Failures of other flags indicate a transaction that is
// invalid in new blocks, e.g. an invalid P2SH. We DoS ban
// such nodes as they are not following the protocol. That
// said during an upgrade careful thought should be taken
// as to the correct behavior - we may want to continue
// peering with non-upgraded nodes even after soft-fork
// super-majority signaling has occurred.
return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
}
}
if (cacheFullScriptStore && !pvChecks) {
// We executed all of the provided scripts, and were told to
// cache the result. Do so now.
scriptExecutionCache.insert(hashCacheEntry);
}
}
}
return true;
}
namespace {
bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
{
// Open history file to append
CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s: OpenUndoFile failed", __func__);
// Write index header
unsigned int nSize = GetSerializeSize(fileout, blockundo);
fileout << FLATDATA(messageStart) << nSize;
// Write undo data
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("%s: ftell failed", __func__);
pos.nPos = (unsigned int)fileOutPos;
fileout << blockundo;
// calculate & write checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << blockundo;
fileout << hasher.GetHash();
return true;
}
bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
{
// Open history file to read
CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s: OpenUndoFile failed", __func__);
// Read block
uint256 hashChecksum;
CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
try {
verifier << hashBlock;
verifier >> blockundo;
filein >> hashChecksum;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
// Verify checksum
if (hashChecksum != verifier.GetHash())
return error("%s: Checksum mismatch", __func__);
return true;
}
/** Abort with a message */
bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
{
SetMiscWarning(strMessage);
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(
userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
}
bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
{
AbortNode(strMessage, userMessage);
return state.Error(strMessage);
}
} // namespace
enum DisconnectResult
{
DISCONNECT_OK, // All good.
DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
DISCONNECT_FAILED // Something else went wrong.
};
/**
* Restore the UTXO in a Coin at a given COutPoint
* @param undo The Coin to be restored.
* @param view The coins view to which to apply the changes.
* @param out The out point that corresponds to the tx input.
* @return A DisconnectResult as an int
*/
int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
{
bool fClean = true;
if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
if (undo.nHeight == 0) {
// Missing undo metadata (height and coinbase). Older versions included this
// information only in undo records for the last spend of a transactions'
// outputs. This implies that it must be present for some other output of the same tx.
const Coin& alternate = AccessByTxid(view, out.hash);
if (!alternate.IsSpent()) {
undo.nHeight = alternate.nHeight;
undo.fCoinBase = alternate.fCoinBase;
} else {
return DISCONNECT_FAILED; // adding output for transaction without known metadata
}
}
// The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
// sure that the coin did not already exist in the cache. As we have queried for that above
// using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
// it is an overwrite.
view.AddCoin(out, std::move(undo), !fClean);
return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
}
/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
* When FAILED is returned, view is left in an indeterminate state. */
static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
{
bool fClean = true;
CBlockUndo blockUndo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (pos.IsNull()) {
error("DisconnectBlock(): no undo data available");
return DISCONNECT_FAILED;
}
if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
error("DisconnectBlock(): failure reading undo data");
return DISCONNECT_FAILED;
}
if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
error("DisconnectBlock(): block and undo data inconsistent");
return DISCONNECT_FAILED;
}
// undo transactions in reverse order
for (int i = block.vtx.size() - 1; i >= 0; i--) {
const CTransaction &tx = *(block.vtx[i]);
uint256 hash = tx.GetHash();
bool is_coinbase = tx.IsCoinBase();
// Check that all outputs are available and match the outputs in the block itself
// exactly.
for (size_t o = 0; o < tx.vout.size(); o++) {
if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
COutPoint out(hash, o);
Coin coin;
bool is_spent = view.SpendCoin(out, &coin);
if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
fClean = false; // transaction output mismatch
}
}
}
// restore inputs
if (i > 0) { // not coinbases
CTxUndo &txundo = blockUndo.vtxundo[i-1];
if (txundo.vprevout.size() != tx.vin.size()) {
error("DisconnectBlock(): transaction and undo data inconsistent");
return DISCONNECT_FAILED;
}
for (unsigned int j = tx.vin.size(); j-- > 0;) {
const COutPoint &out = tx.vin[j].prevout;
int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
fClean = fClean && res != DISCONNECT_UNCLEAN;
}
// At this point, all of txundo.vprevout should have been moved out.
}
}
// move best block pointer to prevout block
view.SetBestBlock(pindex->pprev->GetBlockHash());
return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
}
void static FlushBlockFile(bool fFinalize = false)
{
LOCK(cs_LastBlockFile);
CDiskBlockPos posOld(nLastBlockFile, 0);
FILE *fileOld = OpenBlockFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
FileCommit(fileOld);
fclose(fileOld);
}
fileOld = OpenUndoFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
FileCommit(fileOld);
fclose(fileOld);
}
}
static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
void ThreadScriptCheck() {
RenameThread("bitcoin-scriptch");
scriptcheckqueue.Thread();
}
// Protected by cs_main
VersionBitsCache versionbitscache;
int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
{
LOCK(cs_main);
int32_t nVersion = VERSIONBITS_TOP_BITS;
for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
}
}
return nVersion;
}
/**
* Threshold condition checker that triggers when unknown versionbits are seen on the network.
*/
class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
{
private:
int bit;
public:
WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
{
return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
((pindex->nVersion >> bit) & 1) != 0 &&
((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
}
};
// Protected by cs_main
static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
AssertLockHeld(cs_main);
// BIP16 didn't become active until Oct 1 2012
int64_t nBIP16SwitchTime = 1349049600;
bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
// Start enforcing the DERSIG (BIP66) rule
if (pindex->nHeight >= consensusparams.BIP66Height) {
flags |= SCRIPT_VERIFY_DERSIG;
}
// Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
if (pindex->nHeight >= consensusparams.BIP65Height) {
flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
}
// Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
}
// Start enforcing WITNESS rules using versionbits logic.
if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
flags |= SCRIPT_VERIFY_WITNESS;
flags |= SCRIPT_VERIFY_NULLDUMMY;
}
return flags;
}
static int64_t nTimeCheck = 0;
static int64_t nTimeForks = 0;
static int64_t nTimeVerify = 0;
static int64_t nTimeConnect = 0;
static int64_t nTimeIndex = 0;
static int64_t nTimeCallbacks = 0;
static int64_t nTimeTotal = 0;
/** Apply the effects of this block (with given index) on the UTXO set represented by coins.
* Validity checks that depend on the UTXO set are also done; ConnectBlock()
* can fail if those validity checks fail (among other reasons). */
static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
{
AssertLockHeld(cs_main);
assert(pindex);
// pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
assert((pindex->phashBlock == nullptr) ||
(*pindex->phashBlock == block.GetHash()));
int64_t nTimeStart = GetTimeMicros();
// Check it again in case a previous version let a bad block in
if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
// verify that the view's current state corresponds to the previous block
uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
assert(hashPrevBlock == view.GetBestBlock());
// Special case for the genesis block, skipping connection of its transactions
// (its coinbase is unspendable)
if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
if (!fJustCheck)
view.SetBestBlock(pindex->GetBlockHash());
return true;
}
bool fScriptChecks = true;
if (!hashAssumeValid.IsNull()) {
// We've been configured with the hash of a block which has been externally verified to have a valid history.
// A suitable default value is included with the software and updated from time to time. Because validity
// relative to a piece of software is an objective fact these defaults can be easily reviewed.
// This setting doesn't force the selection of any particular chain but makes validating some faster by
// effectively caching the result of part of the verification.
BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
if (it != mapBlockIndex.end()) {
if (it->second->GetAncestor(pindex->nHeight) == pindex &&
pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
pindexBestHeader->nChainWork >= nMinimumChainWork) {
// This block is a member of the assumed verified chain and an ancestor of the best header.
// The equivalent time check discourages hash power from extorting the network via DOS attack
// into accepting an invalid block through telling users they must manually set assumevalid.
// Requiring a software change or burying the invalid block, regardless of the setting, makes
// it hard to hide the implication of the demand. This also avoids having release candidates
// that are hardly doing any signature verification at all in testing without having to
// artificially set the default assumed verified block further back.
// The test against nMinimumChainWork prevents the skipping when denied access to any chain at
// least as good as the expected chain.
fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
}
}
}
int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes during their
// initial block download.
bool fEnforceBIP30 = true;
//(!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
// !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
// (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
// Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
// with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
// time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
// before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
// duplicate transactions descending from the known pairs either.
// If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
//Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
if (fEnforceBIP30) {
for (const auto& tx : block.vtx) {
for (size_t o = 0; o < tx->vout.size(); o++) {
if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
REJECT_INVALID, "bad-txns-BIP30");
}
}
}
}
// Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
int nLockTimeFlags = 0;
if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
}
// Get the script flags for this block
unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
CBlockUndo blockundo;
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
std::vector<int> prevheights;
CAmount nFees = 0;
int nInputs = 0;
int64_t nSigOpsCost = 0;
CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
std::vector<std::pair<uint256, CDiskTxPos> > vPos;
vPos.reserve(block.vtx.size());
blockundo.vtxundo.reserve(block.vtx.size() - 1);
std::vector<PrecomputedTransactionData> txdata;
txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
for (unsigned int i = 0; i < block.vtx.size(); i++)
{
const CTransaction &tx = *(block.vtx[i]);
nInputs += tx.vin.size();
if (!tx.IsCoinBase())
{
if (!view.HaveInputs(tx))
return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
REJECT_INVALID, "bad-txns-inputs-missingorspent");
// Check that transaction is BIP68 final
// BIP68 lock checks (as opposed to nLockTime checks) must
// be in ConnectBlock because they require the UTXO set
prevheights.resize(tx.vin.size());
for (size_t j = 0; j < tx.vin.size(); j++) {
prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
}
if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
REJECT_INVALID, "bad-txns-nonfinal");
}
}
// GetTransactionSigOpCost counts 3 types of sigops:
// * legacy (always)
// * p2sh (when P2SH enabled in flags and excludes coinbase)
// * witness (when witness enabled in flags and excludes coinbase)
nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
return state.DoS(100, error("ConnectBlock(): too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
txdata.emplace_back(tx);
if (!tx.IsCoinBase())
{
nFees += view.GetValueIn(tx)-tx.GetValueOut();
std::vector<CScriptCheck> vChecks;
bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
return error("ConnectBlock(): CheckInputs on %s failed with %s",
tx.GetHash().ToString(), FormatStateMessage(state));
control.Add(vChecks);
}
CTxUndo undoDummy;
if (i > 0) {
blockundo.vtxundo.push_back(CTxUndo());
}
UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
vPos.push_back(std::make_pair(tx.GetHash(), pos));
pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
}
int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
if (block.vtx[0]->GetValueOut() > blockReward)
return state.DoS(100,
error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
block.vtx[0]->GetValueOut(), blockReward),
REJECT_INVALID, "bad-cb-amount");
if (!control.Wait())
return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
if (fJustCheck)
return true;
// Write undo information to disk
if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
{
if (pindex->GetUndoPos().IsNull()) {
CDiskBlockPos _pos;
if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
return error("ConnectBlock(): FindUndoPos failed");
if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
return AbortNode(state, "Failed to write undo data");
// update nUndoPos in block index
pindex->nUndoPos = _pos.nPos;
pindex->nStatus |= BLOCK_HAVE_UNDO;
}
pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
setDirtyBlockIndex.insert(pindex);
}
if (fTxIndex)
if (!pblocktree->WriteTxIndex(vPos))
return AbortNode(state, "Failed to write transaction index");
// add this block to the view's block chain
view.SetBestBlock(pindex->GetBlockHash());
int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
return true;
}
/**
* Update the on-disk chain state.
* The caches and indexes are flushed depending on the mode we're called with
* if they're too large, if it's been a while since the last write,
* or always and in all cases if we're in prune mode and are deleting files.
*/
bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
LOCK(cs_main);
static int64_t nLastWrite = 0;
static int64_t nLastFlush = 0;
static int64_t nLastSetChain = 0;
std::set<int> setFilesToPrune;
bool fFlushForPrune = false;
bool fDoFullFlush = false;
int64_t nNow = 0;
try {
{
LOCK(cs_LastBlockFile);
if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
if (nManualPruneHeight > 0) {
FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
} else {
FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
fCheckForPruning = false;
}
if (!setFilesToPrune.empty()) {
fFlushForPrune = true;
if (!fHavePruned) {
pblocktree->WriteFlag("prunedblockfiles", true);
fHavePruned = true;
}
}
}
nNow = GetTimeMicros();
// Avoid writing/flushing immediately after startup.
if (nLastWrite == 0) {
nLastWrite = nNow;
}
if (nLastFlush == 0) {
nLastFlush = nNow;
}
if (nLastSetChain == 0) {
nLastSetChain = nNow;
}
int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
// The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
// The cache is over the limit, we have to write now.
bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
// It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
// It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
// Combine all conditions that result in a full cache flush.
fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
// Write blocks and block index to disk.
if (fDoFullFlush || fPeriodicWrite) {
// Depend on nMinDiskSpace to ensure we can write block index
if (!CheckDiskSpace(0))
return state.Error("out of disk space");
// First make sure all block and undo data is flushed to disk.
FlushBlockFile();
// Then update all block file information (which may refer to block and undo files).
{
std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
vFiles.reserve(setDirtyFileInfo.size());
for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
setDirtyFileInfo.erase(it++);
}
std::vector<const CBlockIndex*> vBlocks;
vBlocks.reserve(setDirtyBlockIndex.size());
for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
vBlocks.push_back(*it);
setDirtyBlockIndex.erase(it++);
}
if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
return AbortNode(state, "Failed to write to block index database");
}
}
// Finally remove any pruned files
if (fFlushForPrune)
UnlinkPrunedFiles(setFilesToPrune);
nLastWrite = nNow;
}
// Flush best chain related state. This can only be done if the blocks / block index write was also done.
if (fDoFullFlush) {
// Typical Coin structures on disk are around 48 bytes in size.
// Pushing a new one to the database can cause it to be written
// twice (once in the log, and once in the tables). This is already
// an overestimation, as most will delete an existing entry or
// overwrite one. Still, use a conservative safety factor of 2.
if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
return state.Error("out of disk space");
// Flush the chainstate (which may refer to block index entries).
if (!pcoinsTip->Flush())
return AbortNode(state, "Failed to write to coin database");
nLastFlush = nNow;
}
}
if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
// Update best block in wallet (so we can detect restored wallets).
GetMainSignals().SetBestChain(chainActive.GetLocator());
nLastSetChain = nNow;
}
} catch (const std::runtime_error& e) {
return AbortNode(state, std::string("System error while flushing: ") + e.what());
}
return true;
}
void FlushStateToDisk() {
CValidationState state;
const CChainParams& chainparams = Params();
FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
}
void PruneAndFlush() {
CValidationState state;
fCheckForPruning = true;
const CChainParams& chainparams = Params();
FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
}
static void DoWarning(const std::string& strWarning)
{
static bool fWarned = false;
SetMiscWarning(strWarning);
if (!fWarned) {
AlertNotify(strWarning);
fWarned = true;
}
}
/** Update chainActive and related internal data structures. */
void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
chainActive.SetTip(pindexNew);
// New best block
mempool.AddTransactionsUpdated(1);
cvBlockChange.notify_all();
std::vector<std::string> warningMessages;
if (!IsInitialBlockDownload())
{
int nUpgraded = 0;
const CBlockIndex* pindex = chainActive.Tip();
for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
WarningBitsConditionChecker checker(bit);
ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
if (state == THRESHOLD_ACTIVE) {
DoWarning(strWarning);
} else {
warningMessages.push_back(strWarning);
}
}
}
// Check the version of the last 100 blocks to see if we need to upgrade:
for (int i = 0; i < 100 && pindex != nullptr; i++)
{
int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
if (nUpgraded > 100/2)
{
std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
// notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
DoWarning(strWarning);
}
}
LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
if (!warningMessages.empty())
LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
LogPrintf("\n");
}
/** Disconnect chainActive's tip.
* After calling, the mempool will be in an inconsistent state, with
* transactions from disconnected blocks being added to disconnectpool. You
* should make the mempool consistent again by calling UpdateMempoolForReorg.
* with cs_main held.
*
* If disconnectpool is nullptr, then no disconnected transactions are added to
* disconnectpool (note that the caller is responsible for mempool consistency
* in any case).
*/
bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
{
CBlockIndex *pindexDelete = chainActive.Tip();
assert(pindexDelete);
// Read block from disk.
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
CBlock& block = *pblock;
if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
return AbortNode(state, "Failed to read block");
// Apply the block atomically to the chain state.
int64_t nStart = GetTimeMicros();
{
CCoinsViewCache view(pcoinsTip);
assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
bool flushed = view.Flush();
assert(flushed);
}
LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
return false;
if (disconnectpool) {
// Save transactions to re-add to mempool at end of reorg
for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
disconnectpool->addTransaction(*it);
}
while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
// Drop the earliest entry, and remove its children from the mempool.
auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
disconnectpool->removeEntry(it);
}
}
// Update chainActive and related variables.
UpdateTip(pindexDelete->pprev, chainparams);
// Let wallets know transactions went from 1-confirmed to
// 0-confirmed or conflicted:
GetMainSignals().BlockDisconnected(pblock);
return true;
}
static int64_t nTimeReadFromDisk = 0;
static int64_t nTimeConnectTotal = 0;
static int64_t nTimeFlush = 0;
static int64_t nTimeChainState = 0;
static int64_t nTimePostConnect = 0;
struct PerBlockConnectTrace {
CBlockIndex* pindex = nullptr;
std::shared_ptr<const CBlock> pblock;
std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
};
/**
* Used to track blocks whose transactions were applied to the UTXO state as a
* part of a single ActivateBestChainStep call.
*
* This class also tracks transactions that are removed from the mempool as
* conflicts (per block) and can be used to pass all those transactions
* through SyncTransaction.
*
* This class assumes (and asserts) that the conflicted transactions for a given
* block are added via mempool callbacks prior to the BlockConnected() associated
* with those transactions. If any transactions are marked conflicted, it is
* assumed that an associated block will always be added.
*
* This class is single-use, once you call GetBlocksConnected() you have to throw
* it away and make a new one.
*/
class ConnectTrace {
private:
std::vector<PerBlockConnectTrace> blocksConnected;
CTxMemPool &pool;
public:
ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
}
~ConnectTrace() {
pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
}
void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
assert(!blocksConnected.back().pindex);
assert(pindex);
assert(pblock);
blocksConnected.back().pindex = pindex;
blocksConnected.back().pblock = std::move(pblock);
blocksConnected.emplace_back();
}
std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
// We always keep one extra block at the end of our list because
// blocks are added after all the conflicted transactions have
// been filled in. Thus, the last entry should always be an empty
// one waiting for the transactions from the next block. We pop
// the last entry here to make sure the list we return is sane.
assert(!blocksConnected.back().pindex);
assert(blocksConnected.back().conflictedTxs->empty());
blocksConnected.pop_back();
return blocksConnected;
}
void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
assert(!blocksConnected.back().pindex);
if (reason == MemPoolRemovalReason::CONFLICT) {
blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
}
}
};
/**
* Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
* corresponding to pindexNew, to bypass loading it again from disk.
*
* The block is added to connectTrace if connection succeeds.
*/
bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
{
assert(pindexNew->pprev == chainActive.Tip());
// Read block from disk.
int64_t nTime1 = GetTimeMicros();
std::shared_ptr<const CBlock> pthisBlock;
if (!pblock) {
std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
return AbortNode(state, "Failed to read block");
pthisBlock = pblockNew;
} else {
pthisBlock = pblock;
}
const CBlock& blockConnecting = *pthisBlock;
// Apply the block atomically to the chain state.
int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
int64_t nTime3;
LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
{
CCoinsViewCache view(pcoinsTip);
bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
GetMainSignals().BlockChecked(blockConnecting, state);
if (!rv) {
if (state.IsInvalid())
InvalidBlockFound(pindexNew, state);
return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
}
nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
bool flushed = view.Flush();
assert(flushed);
}
int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
return false;
int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
// Remove conflicting transactions from the mempool.;
mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
disconnectpool.removeForBlock(blockConnecting.vtx);
// Update chainActive & related variables.
UpdateTip(pindexNew, chainparams);
int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
return true;
}
/**
* Return the tip of the chain with the most work in it, that isn't
* known to be invalid (it's however far from certain to be valid).
*/
static CBlockIndex* FindMostWorkChain() {
do {
CBlockIndex *pindexNew = nullptr;
// Find the best candidate header.
{
std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
if (it == setBlockIndexCandidates.rend())
return nullptr;
pindexNew = *it;
}
// Check whether all blocks on the path between the currently active chain and the candidate are valid.
// Just going until the active chain is an optimization, as we know all blocks in it are valid already.
CBlockIndex *pindexTest = pindexNew;
bool fInvalidAncestor = false;
while (pindexTest && !chainActive.Contains(pindexTest)) {
assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
// Pruned nodes may have entries in setBlockIndexCandidates for
// which block files have been deleted. Remove those as candidates
// for the most work chain if we come across them; we can't switch
// to a chain unless we have all the non-active-chain parent blocks.
bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
if (fFailedChain || fMissingData) {
// Candidate chain is not usable (either invalid or missing data)
if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindexNew;
CBlockIndex *pindexFailed = pindexNew;
// Remove the entire chain from the set.
while (pindexTest != pindexFailed) {
if (fFailedChain) {
pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
} else if (fMissingData) {
// If we're missing data, then add back to mapBlocksUnlinked,
// so that if the block arrives in the future we can try adding
// to setBlockIndexCandidates again.
mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
}
setBlockIndexCandidates.erase(pindexFailed);
pindexFailed = pindexFailed->pprev;
}
setBlockIndexCandidates.erase(pindexTest);
fInvalidAncestor = true;
break;
}
pindexTest = pindexTest->pprev;
}
if (!fInvalidAncestor)
return pindexNew;
} while(true);
}
/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
static void PruneBlockIndexCandidates() {
// Note that we can't delete the current block itself, as we may need to return to it later in case a
// reorganization to a better block fails.
std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
setBlockIndexCandidates.erase(it++);
}
// Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
assert(!setBlockIndexCandidates.empty());
}
/**
* Try to make some progress towards making pindexMostWork the active block.
* pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
*/
static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
{
AssertLockHeld(cs_main);
const CBlockIndex *pindexOldTip = chainActive.Tip();
const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
// Disconnect active blocks which are no longer in the best chain.
bool fBlocksDisconnected = false;
DisconnectedBlockTransactions disconnectpool;
while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
if (!DisconnectTip(state, chainparams, &disconnectpool)) {
// This is likely a fatal error, but keep the mempool consistent,
// just in case. Only remove from the mempool in this case.
UpdateMempoolForReorg(disconnectpool, false);
return false;
}
fBlocksDisconnected = true;
}
// Build list of new blocks to connect.
std::vector<CBlockIndex*> vpindexToConnect;
bool fContinue = true;
int nHeight = pindexFork ? pindexFork->nHeight : -1;
while (fContinue && nHeight != pindexMostWork->nHeight) {
// Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
// a few blocks along the way.
int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
vpindexToConnect.clear();
vpindexToConnect.reserve(nTargetHeight - nHeight);
CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
while (pindexIter && pindexIter->nHeight != nHeight) {
vpindexToConnect.push_back(pindexIter);
pindexIter = pindexIter->pprev;
}
nHeight = nTargetHeight;
// Connect new blocks.
for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
if (state.IsInvalid()) {
// The block violates a consensus rule.
if (!state.CorruptionPossible())
InvalidChainFound(vpindexToConnect.back());
state = CValidationState();
fInvalidFound = true;
fContinue = false;
break;
} else {
// A system error occurred (disk space, database error, ...).
// Make the mempool consistent with the current tip, just in case
// any observers try to use it before shutdown.
UpdateMempoolForReorg(disconnectpool, false);
return false;
}
} else {
PruneBlockIndexCandidates();
if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
// We're in a better position than we were. Return temporarily to release the lock.
fContinue = false;
break;
}
}
}
}
if (fBlocksDisconnected) {
// If any blocks were disconnected, disconnectpool may be non empty. Add
// any disconnected transactions back to the mempool.
UpdateMempoolForReorg(disconnectpool, true);
}
mempool.check(pcoinsTip);
// Callbacks/notifications for a new best chain.
if (fInvalidFound)
CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
else
CheckForkWarningConditions();
return true;
}
static void NotifyHeaderTip() {
bool fNotify = false;
bool fInitialBlockDownload = false;
static CBlockIndex* pindexHeaderOld = nullptr;
CBlockIndex* pindexHeader = nullptr;
{
LOCK(cs_main);
pindexHeader = pindexBestHeader;
if (pindexHeader != pindexHeaderOld) {
fNotify = true;
fInitialBlockDownload = IsInitialBlockDownload();
pindexHeaderOld = pindexHeader;
}
}
// Send block tip changed notifications without cs_main
if (fNotify) {
uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
}
}
/**
* Make the best chain active, in multiple steps. The result is either failure
* or an activated best chain. pblock is either nullptr or a pointer to a block
* that is already loaded (to avoid loading it again from disk).
*/
bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
// Note that while we're often called here from ProcessNewBlock, this is
// far from a guarantee. Things in the P2P/RPC will often end up calling
// us in the middle of ProcessNewBlock - do not assume pblock is set
// sanely for performance or correctness!
CBlockIndex *pindexMostWork = nullptr;
CBlockIndex *pindexNewTip = nullptr;
int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
do {
boost::this_thread::interruption_point();
if (ShutdownRequested())
break;
const CBlockIndex *pindexFork;
bool fInitialDownload;
{
LOCK(cs_main);
ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
CBlockIndex *pindexOldTip = chainActive.Tip();
if (pindexMostWork == nullptr) {
pindexMostWork = FindMostWorkChain();
}
// Whether we have anything to do at all.
if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
return true;
bool fInvalidFound = false;
std::shared_ptr<const CBlock> nullBlockPtr;
if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
return false;
if (fInvalidFound) {
// Wipe cache, we may need another branch now.
pindexMostWork = nullptr;
}
pindexNewTip = chainActive.Tip();
pindexFork = chainActive.FindFork(pindexOldTip);
fInitialDownload = IsInitialBlockDownload();
for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
assert(trace.pblock && trace.pindex);
GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
}
}
// When we reach this point, we switched to a new tip (stored in pindexNewTip).
// Notifications/callbacks that can run without cs_main
// Notify external listeners about the new tip.
GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
// Always notify the UI if a new block tip was connected
if (pindexFork != pindexNewTip) {
uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
}
if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
} while (pindexNewTip != pindexMostWork);
CheckBlockIndex(chainparams.GetConsensus());
// Write changes periodically to disk, after relay.
if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
return false;
}
return true;
}
bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
{
{
LOCK(cs_main);
if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
// Nothing to do, this block is not at the tip.
return true;
}
if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
// The chain has been extended since the last call, reset the counter.
nBlockReverseSequenceId = -1;
}
nLastPreciousChainwork = chainActive.Tip()->nChainWork;
setBlockIndexCandidates.erase(pindex);
pindex->nSequenceId = nBlockReverseSequenceId;
if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
// We can't keep reducing the counter if somebody really wants to
// call preciousblock 2**31-1 times on the same set of tips...
nBlockReverseSequenceId--;
}
if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
setBlockIndexCandidates.insert(pindex);
PruneBlockIndexCandidates();
}
}
return ActivateBestChain(state, params);
}
bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
{
AssertLockHeld(cs_main);
// We first disconnect backwards and then mark the blocks as invalid.
// This prevents a case where pruned nodes may fail to invalidateblock
// and be left unable to start as they have no tip candidates (as there
// are no blocks that meet the "have data and are not invalid per
// nStatus" criteria for inclusion in setBlockIndexCandidates).
bool pindex_was_in_chain = false;
CBlockIndex *invalid_walk_tip = chainActive.Tip();
DisconnectedBlockTransactions disconnectpool;
while (chainActive.Contains(pindex)) {
pindex_was_in_chain = true;
// ActivateBestChain considers blocks already in chainActive
// unconditionally valid already, so force disconnect away from it.
if (!DisconnectTip(state, chainparams, &disconnectpool)) {
// It's probably hopeless to try to make the mempool consistent
// here if DisconnectTip failed, but we can try.
UpdateMempoolForReorg(disconnectpool, false);
return false;
}
}
// Now mark the blocks we just disconnected as descendants invalid
// (note this may not be all descendants).
while (pindex_was_in_chain && invalid_walk_tip != pindex) {
invalid_walk_tip->nStatus |= BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(invalid_walk_tip);
setBlockIndexCandidates.erase(invalid_walk_tip);
invalid_walk_tip = invalid_walk_tip->pprev;
}
// Mark the block itself as invalid.
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
g_failed_blocks.insert(pindex);
// DisconnectTip will add transactions to disconnectpool; try to add these
// back to the mempool.
UpdateMempoolForReorg(disconnectpool, true);
// The resulting new best tip may not be in setBlockIndexCandidates anymore, so
// add it again.
BlockMap::iterator it = mapBlockIndex.begin();
while (it != mapBlockIndex.end()) {
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
setBlockIndexCandidates.insert(it->second);
}
it++;
}
InvalidChainFound(pindex);
uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
return true;
}
bool ResetBlockFailureFlags(CBlockIndex *pindex) {
AssertLockHeld(cs_main);
int nHeight = pindex->nHeight;
// Remove the invalidity flag from this block and all its descendants.
BlockMap::iterator it = mapBlockIndex.begin();
while (it != mapBlockIndex.end()) {
if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
it->second->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(it->second);
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
setBlockIndexCandidates.insert(it->second);
}
if (it->second == pindexBestInvalid) {
// Reset invalid block marker if it was pointing to one of those.
pindexBestInvalid = nullptr;
}
g_failed_blocks.erase(it->second);
}
it++;
}
// Remove the invalidity flag from all ancestors too.
while (pindex != nullptr) {
if (pindex->nStatus & BLOCK_FAILED_MASK) {
pindex->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(pindex);
}
pindex = pindex->pprev;
}
return true;
}
static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
{
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator it = mapBlockIndex.find(hash);
if (it != mapBlockIndex.end())
return it->second;
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(block);
assert(pindexNew);
// We assign the sequence id to blocks only when the full data is available,
// to avoid miners withholding blocks but broadcasting headers, to get a
// competitive advantage.
pindexNew->nSequenceId = 0;
BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
pindexNew->BuildSkip();
}
pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
pindexNew->RaiseValidity(BLOCK_VALID_TREE);
if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
pindexBestHeader = pindexNew;
setDirtyBlockIndex.insert(pindexNew);
return pindexNew;
}
/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
{
pindexNew->nTx = block.vtx.size();
pindexNew->nChainTx = 0;
pindexNew->nFile = pos.nFile;
pindexNew->nDataPos = pos.nPos;
pindexNew->nUndoPos = 0;
pindexNew->nStatus |= BLOCK_HAVE_DATA;
if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
pindexNew->nStatus |= BLOCK_OPT_WITNESS;
}
pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
setDirtyBlockIndex.insert(pindexNew);
if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
// If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
std::deque<CBlockIndex*> queue;
queue.push_back(pindexNew);
// Recursively process any descendant blocks that now may be eligible to be connected.
while (!queue.empty()) {
CBlockIndex *pindex = queue.front();
queue.pop_front();
pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
{
LOCK(cs_nBlockSequenceId);
pindex->nSequenceId = nBlockSequenceId++;
}
if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
setBlockIndexCandidates.insert(pindex);
}
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
while (range.first != range.second) {
std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
queue.push_back(it->second);
range.first++;
mapBlocksUnlinked.erase(it);
}
}
} else {
if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
}
}
return true;
}
static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
{
LOCK(cs_LastBlockFile);
unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
if (!fKnown) {
while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
nFile++;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
}
pos.nFile = nFile;
pos.nPos = vinfoBlockFile[nFile].nSize;
}
if ((int)nFile != nLastBlockFile) {
if (!fKnown) {
LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
}
FlushBlockFile(!fKnown);
nLastBlockFile = nFile;
}
vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
if (fKnown)
vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
else
vinfoBlockFile[nFile].nSize += nAddSize;
if (!fKnown) {
unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (fPruneMode)
fCheckForPruning = true;
if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenBlockFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
}
else
return state.Error("out of disk space");
}
}
setDirtyFileInfo.insert(nFile);
return true;
}
static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
{
pos.nFile = nFile;
LOCK(cs_LastBlockFile);
unsigned int nNewSize;
pos.nPos = vinfoBlockFile[nFile].nUndoSize;
nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
setDirtyFileInfo.insert(nFile);
unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (fPruneMode)
fCheckForPruning = true;
if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenUndoFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
}
else
return state.Error("out of disk space");
}
return true;
}
static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
{
// Check proof of work matches claimed amount
if (fCheckPOW && !CheckProofOfWork(block.GetPoWHash(), block.nBits, consensusParams))
return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
return true;
}
bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
{
// These are checks that are independent of context.
if (block.fChecked)
return true;
// Check that the header is valid (particularly PoW). This is mostly
// redundant with the call in AcceptBlockHeader.
if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
return false;
// Check the merkle root.
if (fCheckMerkleRoot) {
bool mutated;
uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
if (block.hashMerkleRoot != hashMerkleRoot2)
return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
// Check for merkle tree malleability (CVE-2012-2459): repeating sequences
// of transactions in a block without affecting the merkle root of a block,
// while still invalidating it.
if (mutated)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
}
// All potential-corruption validation must be done before we do any
// transaction validation, as otherwise we may mark the header as invalid
// because we receive the wrong transactions for it.
// Note that witness malleability is checked in ContextualCheckBlock, so no
// checks that use witness data may be performed here.
// Size limits
if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
// First transaction must be coinbase, the rest must not be
if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
for (unsigned int i = 1; i < block.vtx.size(); i++)
if (block.vtx[i]->IsCoinBase())
return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
// Check transactions
for (const auto& tx : block.vtx)
if (!CheckTransaction(*tx, state, false))
return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
unsigned int nSigOps = 0;
for (const auto& tx : block.vtx)
{
nSigOps += GetLegacySigOpCount(*tx);
}
if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
if (fCheckPOW && fCheckMerkleRoot)
block.fChecked = true;
return true;
}
bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
{
LOCK(cs_main);
return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
}
// Compute at which vout of the block's coinbase transaction the witness
// commitment occurs, or -1 if not found.
static int GetWitnessCommitmentIndex(const CBlock& block)
{
int commitpos = -1;
if (!block.vtx.empty()) {
for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
if (block.vtx[0]->vout[o].scriptPubKey.size() >= 38 && block.vtx[0]->vout[o].scriptPubKey[0] == OP_RETURN && block.vtx[0]->vout[o].scriptPubKey[1] == 0x24 && block.vtx[0]->vout[o].scriptPubKey[2] == 0xaa && block.vtx[0]->vout[o].scriptPubKey[3] == 0x21 && block.vtx[0]->vout[o].scriptPubKey[4] == 0xa9 && block.vtx[0]->vout[o].scriptPubKey[5] == 0xed) {
commitpos = o;
}
}
}
return commitpos;
}
void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
{
int commitpos = GetWitnessCommitmentIndex(block);
static const std::vector<unsigned char> nonce(32, 0x00);
if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
CMutableTransaction tx(*block.vtx[0]);
tx.vin[0].scriptWitness.stack.resize(1);
tx.vin[0].scriptWitness.stack[0] = nonce;
block.vtx[0] = MakeTransactionRef(std::move(tx));
}
}
std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
{
std::vector<unsigned char> commitment;
int commitpos = GetWitnessCommitmentIndex(block);
std::vector<unsigned char> ret(32, 0x00);
if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
if (commitpos == -1) {
uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
CTxOut out;
out.nValue = 0;
out.scriptPubKey.resize(38);
out.scriptPubKey[0] = OP_RETURN;
out.scriptPubKey[1] = 0x24;
out.scriptPubKey[2] = 0xaa;
out.scriptPubKey[3] = 0x21;
out.scriptPubKey[4] = 0xa9;
out.scriptPubKey[5] = 0xed;
memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
CMutableTransaction tx(*block.vtx[0]);
tx.vout.push_back(out);
block.vtx[0] = MakeTransactionRef(std::move(tx));
}
}
UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
return commitment;
}
/** Context-dependent validity checks.
* By "context", we mean only the previous block headers, but not the UTXO
* set; UTXO-related validity checks are done in ConnectBlock(). */
static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
{
assert(pindexPrev != nullptr);
const int nHeight = pindexPrev->nHeight + 1;
// Check proof of work
const Consensus::Params& consensusParams = params.GetConsensus();
if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
// Check against checkpoints
if (fCheckpointsEnabled) {
// Don't accept any forks from the main chain prior to last checkpoint.
// GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
// MapBlockIndex.
CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
if (pcheckpoint && nHeight < pcheckpoint->nHeight)
return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
}
// Check timestamp against prev
if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
// Check timestamp
if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
// Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
// check for version 2, 3 and 4 upgrades
if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
(block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
(block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
strprintf("rejected nVersion=0x%08x block", block.nVersion));
if (block.nVersion < VERSIONBITS_TOP_BITS && IsWitnessEnabled(pindexPrev, consensusParams))
return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
strprintf("rejected nVersion=0x%08x block", block.nVersion));
return true;
}
static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
// Start enforcing BIP113 (Median Time Past) using versionbits logic.
int nLockTimeFlags = 0;
if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
}
int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
? pindexPrev->GetMedianTimePast()
: block.GetBlockTime();
// Check that all transactions are finalized
for (const auto& tx : block.vtx) {
if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
}
}
// Enforce rule that the coinbase starts with serialized block height
if (nHeight >= consensusParams.BIP34Height)
{
CScript expect = CScript() << nHeight;
if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
!std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
}
}
// Validation for witness commitments.
// * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
// coinbase (where 0x0000....0000 is used instead).
// * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
// * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
// * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
// {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
// multiple, the last one is used.
bool fHaveWitness = false;
if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
int commitpos = GetWitnessCommitmentIndex(block);
if (commitpos != -1) {
bool malleated = false;
uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
// The malleation check is ignored; as the transaction tree itself
// already does not permit it, it is impossible to trigger in the
// witness tree.
if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
}
CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
}
fHaveWitness = true;
}
}
// No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
if (!fHaveWitness) {
for (const auto& tx : block.vtx) {
if (tx->HasWitness()) {
return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
}
}
}
// After the coinbase witness nonce and commitment are verified,
// we can check if the block weight passes (before we've checked the
// coinbase witness, it would be possible for the weight to be too
// large by filling up the coinbase witness, which doesn't change
// the block hash, so we couldn't mark the block as permanently
// failed).
if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
}
return true;
}
static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator miSelf = mapBlockIndex.find(hash);
CBlockIndex *pindex = nullptr;
if (hash != chainparams.GetConsensus().hashGenesisBlock) {
if (miSelf != mapBlockIndex.end()) {
// Block header is already known.
pindex = miSelf->second;
if (ppindex)
*ppindex = pindex;
if (pindex->nStatus & BLOCK_FAILED_MASK)
return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
return true;
}
if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
// Get prev block index
CBlockIndex* pindexPrev = nullptr;
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi == mapBlockIndex.end())
return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
pindexPrev = (*mi).second;
if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
for (const CBlockIndex* failedit : g_failed_blocks) {
if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
assert(failedit->nStatus & BLOCK_FAILED_VALID);
CBlockIndex* invalid_walk = pindexPrev;
while (invalid_walk != failedit) {
invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(invalid_walk);
invalid_walk = invalid_walk->pprev;
}
return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
}
}
}
}
if (pindex == nullptr)
pindex = AddToBlockIndex(block);
if (ppindex)
*ppindex = pindex;
CheckBlockIndex(chainparams.GetConsensus());
return true;
}
// Exposed wrapper for AcceptBlockHeader
bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
{
if (first_invalid != nullptr) first_invalid->SetNull();
{
LOCK(cs_main);
for (const CBlockHeader& header : headers) {
CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
if (first_invalid) *first_invalid = header;
return false;
}
if (ppindex) {
*ppindex = pindex;
}
}
}
NotifyHeaderTip();
return true;
}
/** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
{
const CBlock& block = *pblock;
if (fNewBlock) *fNewBlock = false;
AssertLockHeld(cs_main);
CBlockIndex *pindexDummy = nullptr;
CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
if (!AcceptBlockHeader(block, state, chainparams, &pindex))
return false;
// Try to process all requested blocks that we don't have, but only
// process an unrequested block if it's new and has enough work to
// advance our tip, and isn't too many blocks ahead.
bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
bool fHasMoreOrSameWork = (chainActive.Tip() ? pindex->nChainWork >= chainActive.Tip()->nChainWork : true);
// Blocks that are too out-of-order needlessly limit the effectiveness of
// pruning, because pruning will not delete block files that contain any
// blocks which are too close in height to the tip. Apply this test
// regardless of whether pruning is enabled; it should generally be safe to
// not process unrequested blocks.
bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
// TODO: Decouple this function from the block download logic by removing fRequested
// This requires some new chain data structure to efficiently look up if a
// block is in a chain leading to a candidate for best tip, despite not
// being such a candidate itself.
// TODO: deal better with return value and error conditions for duplicate
// and unrequested blocks.
if (fAlreadyHave) return true;
if (!fRequested) { // If we didn't ask for it:
if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
if (fTooFarAhead) return true; // Block height is too high
// Protect against DoS attacks from low-work chains.
// If our tip is behind, a peer could try to send us
// low-work blocks on a fake chain that we would never
// request; don't process these.
if (pindex->nChainWork < nMinimumChainWork) return true;
}
if (fNewBlock) *fNewBlock = true;
if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
if (state.IsInvalid() && !state.CorruptionPossible()) {
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
}
return error("%s: %s", __func__, FormatStateMessage(state));
}
// Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
// (but if it does not build on our best tip, let the SendMessages loop relay it)
if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
GetMainSignals().NewPoWValidBlock(pindex, pblock);
int nHeight = pindex->nHeight;
// Write block to history file
try {
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
if (dbp != nullptr)
blockPos = *dbp;
if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
return error("AcceptBlock(): FindBlockPos failed");
if (dbp == nullptr)
if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
AbortNode(state, "Failed to write block");
if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
return error("AcceptBlock(): ReceivedBlockTransactions failed");
} catch (const std::runtime_error& e) {
return AbortNode(state, std::string("System error: ") + e.what());
}
if (fCheckForPruning)
FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
return true;
}
bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
{
{
CBlockIndex *pindex = nullptr;
if (fNewBlock) *fNewBlock = false;
CValidationState state;
// Ensure that CheckBlock() passes before calling AcceptBlock, as
// belt-and-suspenders.
bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
LOCK(cs_main);
if (ret) {
// Store to disk
ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
}
CheckBlockIndex(chainparams.GetConsensus());
if (!ret) {
GetMainSignals().BlockChecked(*pblock, state);
return error("%s: AcceptBlock FAILED", __func__);
}
}
NotifyHeaderTip();
CValidationState state; // Only used to report errors, not invalidity - ignore it
if (!ActivateBestChain(state, chainparams, pblock))
return error("%s: ActivateBestChain failed", __func__);
return true;
}
bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
{
AssertLockHeld(cs_main);
assert(pindexPrev && pindexPrev == chainActive.Tip());
CCoinsViewCache viewNew(pcoinsTip);
CBlockIndex indexDummy(block);
indexDummy.pprev = pindexPrev;
indexDummy.nHeight = pindexPrev->nHeight + 1;
// NOTE: CheckBlockHeader is called by CheckBlock
if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
return false;
assert(state.IsValid());
return true;
}
/**
* BLOCK PRUNING CODE
*/
/* Calculate the amount of disk space the block & undo files currently use */
static uint64_t CalculateCurrentUsage()
{
uint64_t retval = 0;
for (const CBlockFileInfo &file : vinfoBlockFile) {
retval += file.nSize + file.nUndoSize;
}
return retval;
}
/* Prune a block file (modify associated database entries)*/
void PruneOneBlockFile(const int fileNumber)
{
for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
CBlockIndex* pindex = it->second;
if (pindex->nFile == fileNumber) {
pindex->nStatus &= ~BLOCK_HAVE_DATA;
pindex->nStatus &= ~BLOCK_HAVE_UNDO;
pindex->nFile = 0;
pindex->nDataPos = 0;
pindex->nUndoPos = 0;
setDirtyBlockIndex.insert(pindex);
// Prune from mapBlocksUnlinked -- any block we prune would have
// to be downloaded again in order to consider its chain, at which
// point it would be considered as a candidate for
// mapBlocksUnlinked or setBlockIndexCandidates.
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
while (range.first != range.second) {
std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
range.first++;
if (_it->second == pindex) {
mapBlocksUnlinked.erase(_it);
}
}
}
}
vinfoBlockFile[fileNumber].SetNull();
setDirtyFileInfo.insert(fileNumber);
}
void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
{
for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
CDiskBlockPos pos(*it, 0);
fs::remove(GetBlockPosFilename(pos, "blk"));
fs::remove(GetBlockPosFilename(pos, "rev"));
LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
}
}
/* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
{
assert(fPruneMode && nManualPruneHeight > 0);
LOCK2(cs_main, cs_LastBlockFile);
if (chainActive.Tip() == nullptr)
return;
// last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
int count=0;
for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
continue;
PruneOneBlockFile(fileNumber);
setFilesToPrune.insert(fileNumber);
count++;
}
LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
}
/* This function is called from the RPC code for pruneblockchain */
void PruneBlockFilesManual(int nManualPruneHeight)
{
CValidationState state;
const CChainParams& chainparams = Params();
FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
}
/**
* Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
* The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
* space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
* (which in this case means the blockchain must be re-downloaded.)
*
* Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
* Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
* Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
* Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
* The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
* A db flag records the fact that at least some block files have been pruned.
*
* @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
*/
static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
{
LOCK2(cs_main, cs_LastBlockFile);
if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
return;
}
if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
return;
}
unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
uint64_t nCurrentUsage = CalculateCurrentUsage();
// We don't check to prune until after we've allocated new space for files
// So we should leave a buffer under our target to account for another allocation
// before the next pruning.
uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
uint64_t nBytesToPrune;
int count=0;
if (nCurrentUsage + nBuffer >= nPruneTarget) {
for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
if (vinfoBlockFile[fileNumber].nSize == 0)
continue;
if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
break;
// don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
continue;
PruneOneBlockFile(fileNumber);
// Queue up the files for removal
setFilesToPrune.insert(fileNumber);
nCurrentUsage -= nBytesToPrune;
count++;
}
}
LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
nLastBlockWeCanPrune, count);
}
bool CheckDiskSpace(uint64_t nAdditionalBytes)
{
uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
return true;
}
static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
{
if (pos.IsNull())
return nullptr;
fs::path path = GetBlockPosFilename(pos, prefix);
fs::create_directories(path.parent_path());
FILE* file = fsbridge::fopen(path, "rb+");
if (!file && !fReadOnly)
file = fsbridge::fopen(path, "wb+");
if (!file) {
LogPrintf("Unable to open file %s\n", path.string());
return nullptr;
}
if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) {
LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
fclose(file);
return nullptr;
}
}
return file;
}
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "blk", fReadOnly);
}
/** Open an undo file (rev?????.dat) */
static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "rev", fReadOnly);
}
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
{
return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
}
CBlockIndex * InsertBlockIndex(uint256 hash)
{
if (hash.IsNull())
return nullptr;
// Return existing
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew)
throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool static LoadBlockIndexDB(const CChainParams& chainparams)
{
if (!pblocktree->LoadBlockIndexGuts(chainparams.GetConsensus(), InsertBlockIndex))
return false;
boost::this_thread::interruption_point();
// Calculate nChainWork
std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
{
CBlockIndex* pindex = item.second;
pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
// We can link the chain of blocks for which we've received transactions at some point.
// Pruned nodes may have deleted the block.
if (pindex->nTx > 0) {
if (pindex->pprev) {
if (pindex->pprev->nChainTx) {
pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
} else {
pindex->nChainTx = 0;
mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
}
} else {
pindex->nChainTx = pindex->nTx;
}
}
if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
pindex->nStatus |= BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(pindex);
}
if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
setBlockIndexCandidates.insert(pindex);
if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindex;
if (pindex->pprev)
pindex->BuildSkip();
if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
pindexBestHeader = pindex;
}
// Load block file info
pblocktree->ReadLastBlockFile(nLastBlockFile);
vinfoBlockFile.resize(nLastBlockFile + 1);
LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
}
LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
for (int nFile = nLastBlockFile + 1; true; nFile++) {
CBlockFileInfo info;
if (pblocktree->ReadBlockFileInfo(nFile, info)) {
vinfoBlockFile.push_back(info);
} else {
break;
}
}
// Check presence of blk files
LogPrintf("Checking all blk files are present...\n");
std::set<int> setBlkDataFiles;
for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
{
CBlockIndex* pindex = item.second;
if (pindex->nStatus & BLOCK_HAVE_DATA) {
setBlkDataFiles.insert(pindex->nFile);
}
}
for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
{
CDiskBlockPos pos(*it, 0);
if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
return false;
}
}
// Check whether we have ever pruned block & undo files
pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
if (fHavePruned)
LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
// Check whether we need to continue reindexing
bool fReindexing = false;
pblocktree->ReadReindexing(fReindexing);
fReindex |= fReindexing;
// Check whether we have a transaction index
pblocktree->ReadFlag("txindex", fTxIndex);
LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
return true;
}
bool LoadChainTip(const CChainParams& chainparams)
{
if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
// In case we just added the genesis block, connect it now, so
// that we always have a chainActive.Tip() when we return.
LogPrintf("%s: Connecting genesis block...\n", __func__);
CValidationState state;
if (!ActivateBestChain(state, chainparams)) {
return false;
}
}
// Load pointer to end of best chain
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
if (it == mapBlockIndex.end())
return false;
chainActive.SetTip(it->second);
PruneBlockIndexCandidates();
LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
return true;
}
CVerifyDB::CVerifyDB()
{
uiInterface.ShowProgress(_("Verifying blocks..."), 0);
}
CVerifyDB::~CVerifyDB()
{
uiInterface.ShowProgress("", 100);
}
bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
{
LOCK(cs_main);
if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
return true;
// Verify blocks in the best chain
if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
nCheckDepth = chainActive.Height();
nCheckLevel = std::max(0, std::min(4, nCheckLevel));
LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CCoinsViewCache coins(coinsview);
CBlockIndex* pindexState = chainActive.Tip();
CBlockIndex* pindexFailure = nullptr;
int nGoodTransactions = 0;
CValidationState state;
int reportDone = 0;
LogPrintf("[0%%]...");
for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
{
boost::this_thread::interruption_point();
int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
if (reportDone < percentageDone/10) {
// report every 10% step
LogPrintf("[%d%%]...", percentageDone);
reportDone = percentageDone/10;
}
uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
if (pindex->nHeight < chainActive.Height()-nCheckDepth)
break;
if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
// If pruning, only go back as far as we have data.
LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
break;
}
CBlock block;
// check level 0: read from disk
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 1: verify block validity
if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
// check level 2: verify undo validity
if (nCheckLevel >= 2 && pindex) {
CBlockUndo undo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (!pos.IsNull()) {
if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
// check level 3: check for inconsistencies during memory-only disconnect of tip blocks
if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
assert(coins.GetBestBlock() == pindex->GetBlockHash());
DisconnectResult res = DisconnectBlock(block, pindex, coins);
if (res == DISCONNECT_FAILED) {
return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
pindexState = pindex->pprev;
if (res == DISCONNECT_UNCLEAN) {
nGoodTransactions = 0;
pindexFailure = pindex;
} else {
nGoodTransactions += block.vtx.size();
}
}
if (ShutdownRequested())
return true;
}
if (pindexFailure)
return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
// check level 4: try reconnecting blocks
if (nCheckLevel >= 4) {
CBlockIndex *pindex = pindexState;
while (pindex != chainActive.Tip()) {
boost::this_thread::interruption_point();
uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
pindex = chainActive.Next(pindex);
CBlock block;
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
if (!ConnectBlock(block, state, pindex, coins, chainparams))
return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
LogPrintf("[DONE].\n");
LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
return true;
}
/** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
{
// TODO: merge with ConnectBlock
CBlock block;
if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
for (const CTransactionRef& tx : block.vtx) {
if (!tx->IsCoinBase()) {
for (const CTxIn &txin : tx->vin) {
inputs.SpendCoin(txin.prevout);
}
}
// Pass check = true as every addition may be an overwrite.
AddCoins(inputs, *tx, pindex->nHeight, true);
}
return true;
}
bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
{
LOCK(cs_main);
CCoinsViewCache cache(view);
std::vector<uint256> hashHeads = view->GetHeadBlocks();
if (hashHeads.empty()) return true; // We're already in a consistent state.
if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
uiInterface.ShowProgress(_("Replaying blocks..."), 0);
LogPrintf("Replaying blocks\n");
const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
const CBlockIndex* pindexNew; // New tip during the interrupted flush.
const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
if (mapBlockIndex.count(hashHeads[0]) == 0) {
return error("ReplayBlocks(): reorganization to unknown block requested");
}
pindexNew = mapBlockIndex[hashHeads[0]];
if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
if (mapBlockIndex.count(hashHeads[1]) == 0) {
return error("ReplayBlocks(): reorganization from unknown block requested");
}
pindexOld = mapBlockIndex[hashHeads[1]];
pindexFork = LastCommonAncestor(pindexOld, pindexNew);
assert(pindexFork != nullptr);
}
// Rollback along the old branch.
while (pindexOld != pindexFork) {
if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
CBlock block;
if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
}
LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
if (res == DISCONNECT_FAILED) {
return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
}
// If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
// overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
// applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
// the result is still a version of the UTXO set with the effects of that block undone.
}
pindexOld = pindexOld->pprev;
}
// Roll forward from the forking point to the new tip.
int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
if (!RollforwardBlock(pindex, cache, params)) return false;
}
cache.SetBestBlock(pindexNew->GetBlockHash());
cache.Flush();
uiInterface.ShowProgress("", 100);
return true;
}
bool RewindBlockIndex(const CChainParams& params)
{
LOCK(cs_main);
// Note that during -reindex-chainstate we are called with an empty chainActive!
int nHeight = 1;
while (nHeight <= chainActive.Height()) {
if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
break;
}
nHeight++;
}
// nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
CValidationState state;
CBlockIndex* pindex = chainActive.Tip();
while (chainActive.Height() >= nHeight) {
if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
// If pruning, don't try rewinding past the HAVE_DATA point;
// since older blocks can't be served anyway, there's
// no need to walk further, and trying to DisconnectTip()
// will fail (and require a needless reindex/redownload
// of the blockchain).
break;
}
if (!DisconnectTip(state, params, nullptr)) {
return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
}
// Occasionally flush state to disk.
if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
return false;
}
// Reduce validity flag and have-data flags.
// We do this after actual disconnecting, otherwise we'll end up writing the lack of data
// to disk before writing the chainstate, resulting in a failure to continue if interrupted.
for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
CBlockIndex* pindexIter = it->second;
// Note: If we encounter an insufficiently validated block that
// is on chainActive, it must be because we are a pruning node, and
// this block or some successor doesn't HAVE_DATA, so we were unable to
// rewind all the way. Blocks remaining on chainActive at this point
// must not have their validity reduced.
if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
// Reduce validity
pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
// Remove have-data flags.
pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
// Remove storage location.
pindexIter->nFile = 0;
pindexIter->nDataPos = 0;
pindexIter->nUndoPos = 0;
// Remove various other things
pindexIter->nTx = 0;
pindexIter->nChainTx = 0;
pindexIter->nSequenceId = 0;
// Make sure it gets written.
setDirtyBlockIndex.insert(pindexIter);
// Update indexes
setBlockIndexCandidates.erase(pindexIter);
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
while (ret.first != ret.second) {
if (ret.first->second == pindexIter) {
mapBlocksUnlinked.erase(ret.first++);
} else {
++ret.first;
}
}
} else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
setBlockIndexCandidates.insert(pindexIter);
}
}
if (chainActive.Tip() != nullptr) {
// We can't prune block index candidates based on our tip if we have
// no tip due to chainActive being empty!
PruneBlockIndexCandidates();
CheckBlockIndex(params.GetConsensus());
// FlushStateToDisk can possibly read chainActive. Be conservative
// and skip it here, we're about to -reindex-chainstate anyway, so
// it'll get called a bunch real soon.
if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
return false;
}
}
return true;
}
// May NOT be used after any connections are up as much
// of the peer-processing logic assumes a consistent
// block index state
void UnloadBlockIndex()
{
LOCK(cs_main);
setBlockIndexCandidates.clear();
chainActive.SetTip(nullptr);
pindexBestInvalid = nullptr;
pindexBestHeader = nullptr;
mempool.clear();
mapBlocksUnlinked.clear();
vinfoBlockFile.clear();
nLastBlockFile = 0;
nBlockSequenceId = 1;
setDirtyBlockIndex.clear();
g_failed_blocks.clear();
setDirtyFileInfo.clear();
versionbitscache.Clear();
for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
warningcache[b].clear();
}
for (BlockMap::value_type& entry : mapBlockIndex) {
delete entry.second;
}
mapBlockIndex.clear();
fHavePruned = false;
}
bool LoadBlockIndex(const CChainParams& chainparams)
{
// Load block index from databases
bool needs_init = fReindex;
if (!fReindex) {
bool ret = LoadBlockIndexDB(chainparams);
if (!ret) return false;
needs_init = mapBlockIndex.empty();
}
if (needs_init) {
// Everything here is for *new* reindex/DBs. Thus, though
// LoadBlockIndexDB may have set fReindex if we shut down
// mid-reindex previously, we don't check fReindex and
// instead only check it prior to LoadBlockIndexDB to set
// needs_init.
LogPrintf("Initializing databases...\n");
// Use the provided setting for -txindex in the new database
fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
pblocktree->WriteFlag("txindex", fTxIndex);
}
return true;
}
bool LoadGenesisBlock(const CChainParams& chainparams)
{
LOCK(cs_main);
// Check whether we're already initialized by checking for genesis in
// mapBlockIndex. Note that we can't use chainActive here, since it is
// set based on the coins db, not the block index db, which is the only
// thing loaded at this point.
if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
return true;
try {
CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
// Start new block file
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
CValidationState state;
if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
return error("%s: FindBlockPos failed", __func__);
if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
return error("%s: writing genesis block to disk failed", __func__);
CBlockIndex *pindex = AddToBlockIndex(block);
if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
return error("%s: genesis block not accepted", __func__);
} catch (const std::runtime_error& e) {
return error("%s: failed to write genesis block: %s", __func__, e.what());
}
return true;
}
bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
{
// Map of disk positions for blocks with unknown parent (only used for reindex)
static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
int64_t nStart = GetTimeMillis();
int nLoaded = 0;
try {
// This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
uint64_t nRewind = blkdat.GetPos();
while (!blkdat.eof()) {
boost::this_thread::interruption_point();
blkdat.SetPos(nRewind);
nRewind++; // start one byte further next time, in case of failure
blkdat.SetLimit(); // remove former limit
unsigned int nSize = 0;
try {
// locate a header
unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
blkdat.FindByte(chainparams.MessageStart()[0]);
nRewind = blkdat.GetPos()+1;
blkdat >> FLATDATA(buf);
if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
continue;
// read size
blkdat >> nSize;
if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
continue;
} catch (const std::exception&) {
// no valid block header found; don't complain
break;
}
try {
// read block
uint64_t nBlockPos = blkdat.GetPos();
if (dbp)
dbp->nPos = nBlockPos;
blkdat.SetLimit(nBlockPos + nSize);
blkdat.SetPos(nBlockPos);
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
CBlock& block = *pblock;
blkdat >> block;
nRewind = blkdat.GetPos();
// detect out of order blocks, and store them for later
uint256 hash = block.GetHash();
if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
block.hashPrevBlock.ToString());
if (dbp)
mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
continue;
}
// process in case the block isn't known yet
if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
LOCK(cs_main);
CValidationState state;
if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
nLoaded++;
if (state.IsError())
break;
} else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
}
// Activate the genesis block so normal node progress can continue
if (hash == chainparams.GetConsensus().hashGenesisBlock) {
CValidationState state;
if (!ActivateBestChain(state, chainparams)) {
break;
}
}
NotifyHeaderTip();
// Recursively process earlier encountered successors of this block
std::deque<uint256> queue;
queue.push_back(hash);
while (!queue.empty()) {
uint256 head = queue.front();
queue.pop_front();
std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
while (range.first != range.second) {
std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
{
LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
head.ToString());
LOCK(cs_main);
CValidationState dummy;
if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
{
nLoaded++;
queue.push_back(pblockrecursive->GetHash());
}
}
range.first++;
mapBlocksUnknownParent.erase(it);
NotifyHeaderTip();
}
}
} catch (const std::exception& e) {
LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
}
}
} catch (const std::runtime_error& e) {
AbortNode(std::string("System error: ") + e.what());
}
if (nLoaded > 0)
LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
void static CheckBlockIndex(const Consensus::Params& consensusParams)
{
if (!fCheckBlockIndex) {
return;
}
LOCK(cs_main);
// During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
// so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
// iterating the block tree require that chainActive has been initialized.)
if (chainActive.Height() < 0) {
assert(mapBlockIndex.size() <= 1);
return;
}
// Build forward-pointing map of the entire block tree.
std::multimap<CBlockIndex*,CBlockIndex*> forward;
for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
forward.insert(std::make_pair(it->second->pprev, it->second));
}
assert(forward.size() == mapBlockIndex.size());
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
CBlockIndex *pindex = rangeGenesis.first->second;
rangeGenesis.first++;
assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
// Iterate over the entire block tree, using depth-first search.
// Along the way, remember whether there are blocks on the path from genesis
// block being explored which are the first to have certain properties.
size_t nNodes = 0;
int nHeight = 0;
CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
while (pindex != nullptr) {
nNodes++;
if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
// Begin: actual consistency checks.
if (pindex->pprev == nullptr) {
// Genesis block checks.
assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
}
if (pindex->nChainTx == 0) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
// VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
// HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
if (!fHavePruned) {
// If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
assert(pindexFirstMissing == pindexFirstNeverProcessed);
} else {
// If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
}
if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
// All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
assert(pindex->nHeight == nHeight); // nHeight must be consistent.
assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
if (pindexFirstInvalid == nullptr) {
// Checks for not-invalid blocks.
assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
}
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
if (pindexFirstInvalid == nullptr) {
// If this block sorts at least as good as the current tip and
// is valid and we have all data for its parents, it must be in
// setBlockIndexCandidates. chainActive.Tip() must also be there
// even if some data has been pruned.
if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
assert(setBlockIndexCandidates.count(pindex));
}
// If some parent is missing, then it could be that this block was in
// setBlockIndexCandidates but had to be removed because of the missing data.
// In this case it must be in mapBlocksUnlinked -- see test below.
}
} else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
assert(setBlockIndexCandidates.count(pindex) == 0);
}
// Check whether this block is in mapBlocksUnlinked.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
bool foundInUnlinked = false;
while (rangeUnlinked.first != rangeUnlinked.second) {
assert(rangeUnlinked.first->first == pindex->pprev);
if (rangeUnlinked.first->second == pindex) {
foundInUnlinked = true;
break;
}
rangeUnlinked.first++;
}
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
// If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
assert(foundInUnlinked);
}
if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
// We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
assert(fHavePruned); // We must have pruned.
// This block may have entered mapBlocksUnlinked if:
// - it has a descendant that at some point had more work than the
// tip, and
// - we tried switching to that descendant but were missing
// data for some intermediate block between chainActive and the
// tip.
// So if this block is itself better than chainActive.Tip() and it wasn't in
// setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
if (pindexFirstInvalid == nullptr) {
assert(foundInUnlinked);
}
}
}
// assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
// End: actual consistency checks.
// Try descending into the first subnode.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
if (range.first != range.second) {
// A subnode was found.
pindex = range.first->second;
nHeight++;
continue;
}
// This is a leaf node.
// Move upwards until we reach a node of which we have not yet visited the last child.
while (pindex) {
// We are going to either move to a parent or a sibling of pindex.
// If pindex was the first with a certain property, unset the corresponding variable.
if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
// Find our parent.
CBlockIndex* pindexPar = pindex->pprev;
// Find which child we just visited.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
while (rangePar.first->second != pindex) {
assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
rangePar.first++;
}
// Proceed to the next one.
rangePar.first++;
if (rangePar.first != rangePar.second) {
// Move to the sibling.
pindex = rangePar.first->second;
break;
} else {
// Move up further.
pindex = pindexPar;
nHeight--;
continue;
}
}
}
// Check that we actually traversed the entire map.
assert(nNodes == forward.size());
}
std::string CBlockFileInfo::ToString() const
{
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
}
CBlockFileInfo* GetBlockFileInfo(size_t n)
{
return &vinfoBlockFile.at(n);
}
ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
{
LOCK(cs_main);
return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
}
BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
{
LOCK(cs_main);
return VersionBitsStatistics(chainActive.Tip(), params, pos);
}
int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
{
LOCK(cs_main);
return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
}
static const uint64_t MEMPOOL_DUMP_VERSION = 1;
bool LoadMempool(void)
{
const CChainParams& chainparams = Params();
int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
if (file.IsNull()) {
LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
return false;
}
int64_t count = 0;
int64_t skipped = 0;
int64_t failed = 0;
int64_t nNow = GetTime();
try {
uint64_t version;
file >> version;
if (version != MEMPOOL_DUMP_VERSION) {
return false;
}
uint64_t num;
file >> num;
while (num--) {
CTransactionRef tx;
int64_t nTime;
int64_t nFeeDelta;
file >> tx;
file >> nTime;
file >> nFeeDelta;
CAmount amountdelta = nFeeDelta;
if (amountdelta) {
mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
}
CValidationState state;
if (nTime + nExpiryTimeout > nNow) {
LOCK(cs_main);
AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, true, nullptr, nTime, nullptr, false, 0);
if (state.IsValid()) {
++count;
} else {
++failed;
}
} else {
++skipped;
}
if (ShutdownRequested())
return false;
}
std::map<uint256, CAmount> mapDeltas;
file >> mapDeltas;
for (const auto& i : mapDeltas) {
mempool.PrioritiseTransaction(i.first, i.second);
}
} catch (const std::exception& e) {
LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
return false;
}
LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
return true;
}
void DumpMempool(void)
{
int64_t start = GetTimeMicros();
std::map<uint256, CAmount> mapDeltas;
std::vector<TxMempoolInfo> vinfo;
{
LOCK(mempool.cs);
for (const auto &i : mempool.mapDeltas) {
mapDeltas[i.first] = i.second;
}
vinfo = mempool.infoAll();
}
int64_t mid = GetTimeMicros();
try {
FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
if (!filestr) {
return;
}
CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
uint64_t version = MEMPOOL_DUMP_VERSION;
file << version;
file << (uint64_t)vinfo.size();
for (const auto& i : vinfo) {
file << *(i.tx);
file << (int64_t)i.nTime;
file << (int64_t)i.nFeeDelta;
mapDeltas.erase(i.tx->GetHash());
}
file << mapDeltas;
FileCommit(file.Get());
file.fclose();
RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
int64_t last = GetTimeMicros();
LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
} catch (const std::exception& e) {
LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
}
}
//! Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
if (pindex == nullptr)
return 0.0;
int64_t nNow = time(nullptr);
double fTxTotal;
if (pindex->nChainTx <= data.nTxCount) {
fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
} else {
fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
}
return pindex->nChainTx / fTxTotal;
}
class CMainCleanup
{
public:
CMainCleanup() {}
~CMainCleanup() {
// block headers
BlockMap::iterator it1 = mapBlockIndex.begin();
for (; it1 != mapBlockIndex.end(); it1++)
delete (*it1).second;
mapBlockIndex.clear();
}
} instance_of_cmaincleanup;
|
/* file: linear_regression_train_dense_normeq_helper_fpt_cpu.cpp */
/*******************************************************************************
* Copyright 2014-2020 Intel Corporation
*
* 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.
*******************************************************************************/
/*
//++
// Implementation of linear regression training functions for the method
// of normal equations.
//--
*/
#include "src/algorithms/linear_regression/linear_regression_train_dense_normeq_helper_impl.i"
namespace daal
{
namespace algorithms
{
namespace linear_regression
{
namespace training
{
namespace internal
{
template class KernelHelper<DAAL_FPTYPE, DAAL_CPU>;
}
} // namespace training
} // namespace linear_regression
} // namespace algorithms
} // namespace daal
|
// Copyright 2016 The Draco Authors.
//
// 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.
//
#include "draco/mesh/mesh_are_equivalent.h"
#include <sstream>
#include "draco/core/draco_test_base.h"
#include "draco/core/draco_test_utils.h"
#include "draco/io/mesh_io.h"
#include "draco/io/obj_decoder.h"
#include "draco/mesh/mesh.h"
namespace draco {
class MeshAreEquivalentTest : public ::testing::Test {};
TEST_F(MeshAreEquivalentTest, TestOnIndenticalMesh) {
const std::string file_name = "test_nm.obj";
const std::unique_ptr<Mesh> mesh(ReadMeshFromTestFile(file_name));
ASSERT_NE(mesh, nullptr) << "Failed to load test model." << file_name;
MeshAreEquivalent equiv;
ASSERT_TRUE(equiv(*mesh, *mesh));
}
TEST_F(MeshAreEquivalentTest, TestPermutedOneFace) {
const std::string file_name_0 = "one_face_123.obj";
const std::string file_name_1 = "one_face_312.obj";
const std::string file_name_2 = "one_face_321.obj";
const std::unique_ptr<Mesh> mesh_0(ReadMeshFromTestFile(file_name_0));
const std::unique_ptr<Mesh> mesh_1(ReadMeshFromTestFile(file_name_1));
const std::unique_ptr<Mesh> mesh_2(ReadMeshFromTestFile(file_name_2));
ASSERT_NE(mesh_0, nullptr) << "Failed to load test model." << file_name_0;
ASSERT_NE(mesh_1, nullptr) << "Failed to load test model." << file_name_1;
ASSERT_NE(mesh_2, nullptr) << "Failed to load test model." << file_name_2;
MeshAreEquivalent equiv;
ASSERT_TRUE(equiv(*mesh_0, *mesh_0));
ASSERT_TRUE(equiv(*mesh_0, *mesh_1)); // Face rotated.
ASSERT_FALSE(equiv(*mesh_0, *mesh_2)); // Face inverted.
}
TEST_F(MeshAreEquivalentTest, TestPermutedTwoFaces) {
const std::string file_name_0 = "two_faces_123.obj";
const std::string file_name_1 = "two_faces_312.obj";
const std::unique_ptr<Mesh> mesh_0(ReadMeshFromTestFile(file_name_0));
const std::unique_ptr<Mesh> mesh_1(ReadMeshFromTestFile(file_name_1));
ASSERT_NE(mesh_0, nullptr) << "Failed to load test model." << file_name_0;
ASSERT_NE(mesh_1, nullptr) << "Failed to load test model." << file_name_1;
MeshAreEquivalent equiv;
ASSERT_TRUE(equiv(*mesh_0, *mesh_0));
ASSERT_TRUE(equiv(*mesh_1, *mesh_1));
ASSERT_TRUE(equiv(*mesh_0, *mesh_1));
}
//
TEST_F(MeshAreEquivalentTest, TestPermutedThreeFaces) {
const std::string file_name_0 = "three_faces_123.obj";
const std::string file_name_1 = "three_faces_312.obj";
const std::unique_ptr<Mesh> mesh_0(ReadMeshFromTestFile(file_name_0));
const std::unique_ptr<Mesh> mesh_1(ReadMeshFromTestFile(file_name_1));
ASSERT_NE(mesh_0, nullptr) << "Failed to load test model." << file_name_0;
ASSERT_NE(mesh_1, nullptr) << "Failed to load test model." << file_name_1;
MeshAreEquivalent equiv;
ASSERT_TRUE(equiv(*mesh_0, *mesh_0));
ASSERT_TRUE(equiv(*mesh_1, *mesh_1));
ASSERT_TRUE(equiv(*mesh_0, *mesh_1));
}
// This test checks that the edgebreaker algorithm does not change the mesh up
// to the order of faces and vertices.
TEST_F(MeshAreEquivalentTest, TestOnBigMesh) {
const std::string file_name = "test_nm.obj";
const std::unique_ptr<Mesh> mesh0(ReadMeshFromTestFile(file_name));
ASSERT_NE(mesh0, nullptr) << "Failed to load test model." << file_name;
std::unique_ptr<Mesh> mesh1;
std::stringstream ss;
WriteMeshIntoStream(mesh0.get(), ss, MESH_EDGEBREAKER_ENCODING);
ReadMeshFromStream(&mesh1, ss);
ASSERT_TRUE(ss.good()) << "Mesh IO failed.";
MeshAreEquivalent equiv;
ASSERT_TRUE(equiv(*mesh0, *mesh0));
ASSERT_TRUE(equiv(*mesh1, *mesh1));
ASSERT_TRUE(equiv(*mesh0, *mesh1));
}
} // namespace draco
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/document/bucket/fixed_bucket_spaces.h>
#include "cluster_state_bundle.h"
#include "clusterstate.h"
#include <iostream>
#include <sstream>
namespace storage::lib {
ClusterStateBundle::ClusterStateBundle(const ClusterState &baselineClusterState)
: _baselineClusterState(std::make_shared<const ClusterState>(baselineClusterState)),
_deferredActivation(false)
{
}
ClusterStateBundle::ClusterStateBundle(const ClusterState& baselineClusterState,
BucketSpaceStateMapping derivedBucketSpaceStates)
: _baselineClusterState(std::make_shared<const ClusterState>(baselineClusterState)),
_derivedBucketSpaceStates(std::move(derivedBucketSpaceStates)),
_deferredActivation(false)
{
}
ClusterStateBundle::ClusterStateBundle(const ClusterState& baselineClusterState,
BucketSpaceStateMapping derivedBucketSpaceStates,
bool deferredActivation)
: _baselineClusterState(std::make_shared<const ClusterState>(baselineClusterState)),
_derivedBucketSpaceStates(std::move(derivedBucketSpaceStates)),
_deferredActivation(deferredActivation)
{
}
ClusterStateBundle::~ClusterStateBundle() = default;
const std::shared_ptr<const lib::ClusterState> &
ClusterStateBundle::getBaselineClusterState() const
{
return _baselineClusterState;
}
const std::shared_ptr<const lib::ClusterState> &
ClusterStateBundle::getDerivedClusterState(document::BucketSpace bucketSpace) const
{
auto itr = _derivedBucketSpaceStates.find(bucketSpace);
if (itr != _derivedBucketSpaceStates.end()) {
return itr->second;
}
return _baselineClusterState;
}
uint32_t
ClusterStateBundle::getVersion() const
{
return _baselineClusterState->getVersion();
}
bool
ClusterStateBundle::operator==(const ClusterStateBundle &rhs) const
{
if (!(*_baselineClusterState == *rhs._baselineClusterState)) {
return false;
}
if (_derivedBucketSpaceStates.size() != rhs._derivedBucketSpaceStates.size()) {
return false;
}
if (_deferredActivation != rhs._deferredActivation) {
return false;
}
// Can't do a regular operator== comparison since we must check equality
// of cluster state _values_, not their _pointers_.
for (auto& lhs_ds : _derivedBucketSpaceStates) {
auto rhs_iter = rhs._derivedBucketSpaceStates.find(lhs_ds.first);
if ((rhs_iter == rhs._derivedBucketSpaceStates.end())
|| !(*lhs_ds.second == *rhs_iter->second)) {
return false;
}
}
return true;
}
std::string
ClusterStateBundle::toString() const
{
std::ostringstream os;
os << *this;
return os.str();
}
std::ostream& operator<<(std::ostream& os, const ClusterStateBundle& bundle) {
os << "ClusterStateBundle('" << *bundle.getBaselineClusterState();
if (!bundle.getDerivedClusterStates().empty()) {
// Output ordering is undefined for of per-space states.
for (auto& ds : bundle.getDerivedClusterStates()) {
os << "', ";
os << document::FixedBucketSpaces::to_string(ds.first);
os << " '" << *ds.second;
}
}
os << '\'';
if (bundle.deferredActivation()) {
os << " (deferred activation)";
}
os << ")";
return os;
}
}
|
/*
* Copyright 2017 Sony Corporation
*/
#include "gtest/gtest.h"
#include "Poco/ThreadPool.h"
#include "easyhttpcpp/common/CommonMacros.h"
#include "easyhttpcpp/common/FileUtil.h"
namespace easyhttpcpp {
namespace common {
namespace test {
namespace {
const Poco::Path TestRootPath(EASYHTTPCPP_STRINGIFY_MACRO(RUNTIME_DATA_ROOT), "FileUtilMultiThreadUnitTest");
const Poco::Path TestTargetDir(TestRootPath, "a/b/c/d/e/f");
class DirsCreateRunner : public Poco::Runnable {
public:
bool m_success;
DirsCreateRunner() : m_success(false)
{
}
virtual void run()
{
m_success = FileUtil::createDirsIfAbsent(TestTargetDir);
}
};
} /* namespace */
class FileUtilMultiThreadUnitTest : public testing::Test {
public:
virtual void TearDown()
{
FileUtil::removeDirsIfPresent(TestRootPath);
}
};
// test for bug in Poco::File::createDirectories()
// see, https://github.com/pocoproject/poco/issues/1573
TEST_F(FileUtilMultiThreadUnitTest, createDirsIfAbsent_Succeeds_WhenCalledOnMultipleThreadsWithSameDir)
{
// Given: set up thread pool
Poco::ThreadPool threadPool;
const int threadTotal = 5;
// When: call createDirsIfAbsent() on multiple threads
DirsCreateRunner runners[threadTotal];
for (int runnerCount = 0; runnerCount < threadTotal; ++runnerCount) {
threadPool.start(runners[runnerCount]);
}
threadPool.joinAll();
// Then: directory is created successfully
for (int runnerCount = 0; runnerCount < threadTotal; ++runnerCount) {
EXPECT_TRUE(runners[runnerCount].m_success) << "runner index: " << runnerCount;
}
EXPECT_TRUE(Poco::File(TestTargetDir).exists());
}
} /* namespace test */
} /* namespace common */
} /* namespace easyhttpcpp */
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* 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.
*****************************************************************************/
#include "modules/planning/scenarios/learning_model/stage_run.h"
#include "gtest/gtest.h"
#include "cyber/common/file.h"
#include "cyber/common/log.h"
namespace apollo {
namespace planning {
namespace scenario {
class StageRunTest : public ::testing::Test {
public:
virtual void SetUp() {
config_.set_stage_type(
ScenarioConfig::LEARNING_MODEL_RUN);
}
protected:
ScenarioConfig::StageConfig config_;
};
TEST_F(StageRunTest, Init) {
LearningModelSampleStageRun learning_model_stage_run(config_);
EXPECT_EQ(learning_model_stage_run.Name(),
ScenarioConfig::StageType_Name(ScenarioConfig::LEARNING_MODEL_RUN));
}
} // namespace scenario
} // namespace planning
} // namespace apollo
|
// SQL Notebook
// Copyright (C) 2016 Brian Luft
//
// 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 <Windows.h>
#include "SqlNotebookCore.h"
using namespace System::Runtime::InteropServices;
using namespace SqlNotebookCore;
// .NET string -> UTF-16 C++ string
std::wstring Util::WStr(String^ mstr) {
auto utf16 = Marshal::StringToHGlobalUni(mstr);
std::wstring wstr((const wchar_t*)utf16.ToPointer());
Marshal::FreeHGlobal(utf16);
return wstr;
}
// .NET string -> UTF-8 C++ string
std::string Util::CStr(String^ mstr) {
auto utf16 = Marshal::StringToHGlobalUni(mstr);
auto utf16Str = (const wchar_t*)utf16.ToPointer();
int bufferSizeBytes = WideCharToMultiByte(CP_UTF8, 0, utf16Str, -1, nullptr, 0, nullptr, nullptr);
if (bufferSizeBytes <= 0) {
Marshal::FreeHGlobal(utf16);
throw gcnew InvalidOperationException("Unable to convert string from UTF-16 to UTF-8.");
}
char* buffer = new char[bufferSizeBytes];
if (WideCharToMultiByte(CP_UTF8, 0, utf16Str, -1, buffer, bufferSizeBytes, nullptr, nullptr) <= 0) {
Marshal::FreeHGlobal(utf16);
delete buffer;
throw gcnew InvalidOperationException("Unable to convert string from UTF-16 to UTF-8.");
}
Marshal::FreeHGlobal(utf16);
std::string cstr(buffer);
delete buffer;
return cstr;
}
// UTF-16 C string -> .NET string
String^ Util::Str(const wchar_t* utf16Str) {
return Marshal::PtrToStringUni(IntPtr((void*)utf16Str));
}
// UTF-8 C string -> .NET string
String^ Util::Str(const char* utf8Str) {
int nDataLen = (int)strlen(utf8Str) + 1;
int bufferSizeChars = MultiByteToWideChar(CP_UTF8, 0, utf8Str, nDataLen, nullptr, 0);
if (bufferSizeChars <= 0) {
throw gcnew InvalidOperationException("Unable to convert string from UTF-8 to UTF-16.");
}
wchar_t* buffer = new wchar_t[bufferSizeChars];
if (MultiByteToWideChar(CP_UTF8, 0, utf8Str, nDataLen, buffer, bufferSizeChars) <= 0) {
delete buffer;
throw gcnew InvalidOperationException("Unable to convert string from UTF-8 to UTF-16.");
}
auto mstr = Marshal::PtrToStringUni(IntPtr(buffer));
delete buffer;
return mstr;
}
|
#include <AMReX_Vector.H>
#include <AMReX_AmrCore.H>
#include <AMReX_ParallelDescriptor.H>
#include <AMReX_ParmParse.H>
#include <AMReX_MultiFabUtil.H>
#include <AMReX_FillPatchUtil.H>
#include <AMReX_PlotFileUtil.H>
#include <AMReX_VisMF.H>
#include <AMReX_PhysBCFunct.H>
#include <AMReX_EB_utils.H>
#include <AMReX_EBAmrUtil.H>
#include <AMReX_EB_F.H>
#ifdef BL_USE_SENSEI_INSITU
#include <AMReX_AmrMeshInSituBridge.H>
#endif
#ifdef BL_MEM_PROFILING
#include <AMReX_MemProfiler.H>
#endif
#include <AMReX_EB_LSCoreBase.H>
//using namespace amrex;
namespace amrex {
// constructor - reads in parameters from inputs file
// - sizes multilevel arrays and data structures
// - initializes BCRec boundary condition object
LSCoreBase::LSCoreBase () {
BL_PROFILE("LSCoreBase::LSCoreBase()");
//NOTE: Geometry on all levels has been defined already.
ReadParameters();
InitLSCoreBase();
}
LSCoreBase::LSCoreBase(const RealBox * rb, int max_level_in, const Vector<int> & n_cell_in, int coord)
: AmrCore(rb, max_level_in, n_cell_in, coord)
{
BL_PROFILE("LSCoreBase::LSCoreBase(RealBox)");
//NOTE: Geometry on all levels has been defined already.
ReadParameters();
InitLSCoreBase();
}
LSCoreBase::~LSCoreBase () {
BL_PROFILE("LSCoreBase::~LSCoreBase()");
}
void LSCoreBase::InitLSCoreBase() {
// No valid BoxArray and DistributionMapping have been defined.
// But the arrays for them have been resized.
BL_PROFILE("LSCoreBase::InitLSCoreBase()");
int nlevs_max = max_level + 1;
level_set.resize(nlevs_max);
level_set_valid.resize(nlevs_max);
ls_factory.resize(nlevs_max);
eb_levels.resize(nlevs_max);
rebuild_eb.resize(nlevs_max, 1); // At first rebuild eb on each level
bcs.resize(1);
// // periodic boundaries
// int bc_lo[] = {BCType::int_dir, BCType::int_dir, BCType::int_dir};
// int bc_hi[] = {BCType::int_dir, BCType::int_dir, BCType::int_dir};
// walls (Neumann)
int bc_lo[] = {FOEXTRAP, FOEXTRAP, FOEXTRAP};
int bc_hi[] = {FOEXTRAP, FOEXTRAP, FOEXTRAP};
for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) {
// lo-side BCs
if (bc_lo[idim] == BCType::int_dir || // periodic uses "internal Dirichlet"
bc_lo[idim] == BCType::foextrap || // first-order extrapolation
bc_lo[idim] == BCType::ext_dir ) { // external Dirichlet
bcs[0].setLo(idim, bc_lo[idim]);
}
else {
amrex::Abort("Invalid bc_lo");
}
// hi-side BCSs
if (bc_hi[idim] == BCType::int_dir || // periodic uses "internal Dirichlet"
bc_hi[idim] == BCType::foextrap || // first-order extrapolation
bc_hi[idim] == BCType::ext_dir ) { // external Dirichlet
bcs[0].setHi(idim, bc_hi[idim]);
}
else {
amrex::Abort("Invalid bc_hi");
}
}
}
void LSCoreBase::LoadTagLevels () {
BL_PROFILE("LSCoreBase::LoadTagLevels()");
// read in an array of "phierr", which is the tagging threshold in this
// example, we tag values of "phi" which are greater than phierr for that
// particular level in subroutine state_error, you could use more elaborate
// tagging, such as more advanced logical expressions, or gradients, etc.
ParmParse pp("amr");
int n = pp.countval("phierr");
if (n > 0) {
pp.getarr("phierr", phierr, 0, n);
}
}
void LSCoreBase::SetTagLevels (const Vector<Real> & m_phierr) {
BL_PROFILE("LSCoreBase::SetTagLevels()");
phierr = m_phierr;
}
// Initializes multilevel data
void LSCoreBase::Init () {
BL_PROFILE("LSCoreBase::Init()");
if (restart_chkfile == "") {
// start simulation from the beginning
const Real time = 0.0;
// This tells the AmrMesh class not to iterate when creating the
// initial grid hierarchy
SetIterateToFalse();
// This tells the Cluster routine to use the new chopping
// routine which rejects cuts if they don't improve the efficiency
SetUseNewChop();
InitFromScratch(time);
AverageDown();
if (chk_int > 0)
WriteCheckpointFile();
} else {
// restart from a checkpoint
ReadCheckpointFile();
}
if (plot_int > 0)
WritePlotFile();
}
void LSCoreBase::InitData (bool a_use_phierr) {
BL_PROFILE("LSCoreBase::InitData()");
use_phierr = a_use_phierr;
if (use_phierr)
LoadTagLevels();
Init();
}
void LSCoreBase::InitData (const Vector<Real> & m_phierr) {
BL_PROFILE("LSCoreBase::InitData(phierr)");
SetTagLevels(m_phierr);
Init();
}
// Make a new level using provided BoxArray and DistributionMapping and fill
// with interpolated coarse level data. Overrides the pure virtual function in
// AmrCore
void LSCoreBase::MakeNewLevelFromCoarse ( int lev, Real time, const BoxArray & ba,
const DistributionMapping & dm) {
BL_PROFILE("LSCoreBase::MakeNewLevelFromCoarse()");
BL_ASSERT(lev > 0);
LSCoreBase::MakeNewLevelFromCoarse(level_set[lev], level_set[lev - 1], ba, dm,
geom[lev], geom[lev - 1], bcs, refRatio(lev - 1 ));
// At this point, we consider _everywhere_ as valid. This is maintained for
// legacy reasons. TODO: There might be a better way of doing things.
const int ncomp = level_set[lev].nComp();
const int nghost = level_set[lev].nGrow();
BoxArray ba_nd = amrex::convert(ba, IntVect::TheNodeVector());
level_set_valid[lev].define(ba_nd, dm, ncomp, nghost);
level_set_valid[lev].setVal(1);
}
// Remake an existing level using provided BoxArray and DistributionMapping and
// fill with existing fine and coarse data. Overrides the pure virtual function
// in AmrCore
void LSCoreBase::RemakeLevel ( int lev, Real time, const BoxArray & ba,
const DistributionMapping & dm) {
BL_PROFILE("LSCoreBase::RemakeLevel()");
const int ncomp = level_set[lev].nComp();
const int nghost = level_set[lev].nGrow();
BoxArray ba_nd = amrex::convert(ba, IntVect::TheUnitVector());
MultiFab new_state(ba_nd, dm, ncomp, nghost);
FillPatch(lev, time, new_state, 0, ncomp);
std::swap(new_state, level_set[lev]);
// At this point, we consider _everywhere_ as valid. This is maintained for
// legacy reasons. TODO: There might be a better way of doing things.
level_set_valid[lev].define(ba_nd, dm, ncomp, nghost);
level_set_valid[lev].setVal(1);
}
void LSCoreBase::UpdateGrids (int lev, const BoxArray & ba, const DistributionMapping & dm){
BL_PROFILE("LSCoreBase::UpdateGrids()");
bool ba_changed = ( ba != grids[lev] );
bool dm_changed = ( dm != dmap[lev] );
if (! (ba_changed || dm_changed))
return;
SetBoxArray(lev, ba);
SetDistributionMap(lev, dm);
BoxArray ba_nd = amrex::convert(ba, IntVect::TheUnitVector());
MultiFab ls_regrid = MFUtil::duplicate<MultiFab, MFUtil::SymmetricGhost>
(ba_nd, dm, level_set[lev]);
iMultiFab valid_regrid = MFUtil::duplicate<iMultiFab, MFUtil::SymmetricGhost>
(ba_nd, dm, level_set_valid[lev]);
std::swap(ls_regrid, level_set[lev]);
std::swap(valid_regrid, level_set_valid[lev]);
}
void LSCoreBase::FillLevelSetTags(int lev, TagBoxArray & tags, const Vector<Real> & phierr,
const MultiFab & levelset_data, const Vector<Geometry> & geom ) {
BL_PROFILE("LSCoreBase::FillLevelSetTags()");
if (lev >= phierr.size()) return;
const int clearval = TagBox::CLEAR;
const int tagval = TagBox::SET;
const Real * dx = geom[lev].CellSize();
const Real * prob_lo = geom[lev].ProbLo();
#ifdef _OPENMP
#pragma omp parallel
#endif
{
Vector<int> itags;
for (MFIter mfi(levelset_data, true); mfi.isValid(); ++mfi) {
const Box & tilebox = mfi.tilebox();
TagBox & tagfab = tags[mfi];
// We cannot pass tagfab to Fortran because it is BaseFab<char>. So
// we are going to get a temporary integer array. set itags
// initially to 'untagged' everywhere we define itags over the
// tilebox region
tagfab.get_itags(itags, tilebox);
// data pointer and index space
int * tptr = itags.dataPtr();
const int * tlo = tilebox.loVect();
const int * thi = tilebox.hiVect();
//-------------------------------------------------------------------
// Tag cells for refinement
Real time = 0; // Temporary storing "time" => not needed for level-set tagging
amrex_eb_levelset_error ( tptr, AMREX_ARLIM_3D(tlo), AMREX_ARLIM_3D(thi),
BL_TO_FORTRAN_3D(levelset_data[mfi]),
& tagval, & clearval,
BL_TO_FORTRAN_BOX(tilebox),
AMREX_ZFILL(dx), AMREX_ZFILL(prob_lo),
& time, & phierr[lev]);
//___________________________________________________________________
// Update the tags in the TagBox in the tilebox region to be equal
// to itags
tagfab.tags_and_untags(itags, tilebox);
}
}
}
void LSCoreBase::FillVolfracTags(int lev, TagBoxArray & tags,
const Vector<BoxArray> & grids,
const Vector<DistributionMapping> & dmap,
const EB2::Level & eb_lev, const Vector<Geometry> & geom) {
BL_PROFILE("LSCoreBase::FillVolfracTags()");
//___________________________________________________________________________
// Tag all cells with volfrac \in (0, 1)
MultiFab volfrac(grids[lev], dmap[lev], 1, 1);
eb_lev.fillVolFrac(volfrac, geom[lev]);
amrex::TagVolfrac(tags, volfrac);
}
// Fill an entire multifab by interpolating from the coarser level.
void LSCoreBase::FillCoarsePatch (MultiFab & mf_fne, const MultiFab & mf_crse,
const Geometry & geom_fne, const Geometry & geom_crse,
const Vector<BCRec> & bcs, const IntVect & ref, int icomp, int ncomp) {
BL_PROFILE("static LSCoreBase::FillCoarsePatch()");
BndryFuncArray bfunc(amrex_eb_phifill);
PhysBCFunct<BndryFuncArray> cphysbc(geom_crse, bcs, bfunc);
PhysBCFunct<BndryFuncArray> fphysbc(geom_fne, bcs, bfunc);
Interpolater * mapper = & node_bilinear_interp;
amrex::InterpFromCoarseLevel(mf_fne, 0, mf_crse, 0, icomp, ncomp, geom_crse, geom_fne,
cphysbc, 0, fphysbc, 0, ref, mapper, bcs, 0);
}
// Make a new level using provided BoxArray and DistributionMapping and fill
// with interpolated coarse level data.
void LSCoreBase::MakeNewLevelFromCoarse (MultiFab & ls_fine, const MultiFab & ls_crse,
const BoxArray & ba, const DistributionMapping & dm,
const Geometry & geom_fine, const Geometry & geom_crse,
const Vector<BCRec> & bcs, const IntVect & ref){
BL_PROFILE("static LSCoreBase::MakeNewLevelFromCoarse()");
const int ncomp = ls_crse.nComp();
const int nghost = ls_crse.nGrow();
BoxArray ba_nd = amrex::convert(ba, IntVect::TheNodeVector());
ls_fine.define(ba_nd, dm, ncomp, nghost);
LSCoreBase::FillCoarsePatch(ls_fine, ls_crse, geom_fine, geom_crse, bcs, ref, 0, ncomp);
}
// Constructs a box over which to look for EB facets. The Box size grows based
// on the coarse-level level-set value. But it never grows larger than
// max_eb_pad.
Box LSCoreBase::EBSearchBox( const Box & tilebox, const FArrayBox & ls_crse,
const Geometry & geom_fine, const IntVect & max_grow, bool & bail) {
BL_PROFILE("LSCoreBase::EBSearchBox()");
// Infinities don't work well with std::max, so just bail and construct the
// maximum box.
if (ls_crse.contains_inf()){
Box bx = amrex::convert(ls_crse.box(), IntVect::TheZeroVector());
bx.grow(max_grow);
bail = true;
return bx;
}
// Something's gone wrong :( ... so just bail and construct the maximum box.
if (ls_crse.contains_nan()){
Box bx = amrex::convert(ls_crse.box(), IntVect::TheZeroVector());
bx.grow(max_grow);
bail = true;
return bx;
}
Real max_ls = std::max(std::abs(ls_crse.max()), std::abs(ls_crse.min()));
IntVect n_grow_ls(AMREX_D_DECL(geom_fine.InvCellSize(0)*max_ls,
geom_fine.InvCellSize(1)*max_ls,
geom_fine.InvCellSize(2)*max_ls));
for (int i = 0; i < AMREX_SPACEDIM; i++)
if (n_grow_ls[i] > max_grow[i]) {
n_grow_ls[i] = max_grow[i];
bail = true;
}
Box bx = amrex::convert(tilebox, IntVect::TheZeroVector());
bx.grow(n_grow_ls);
return bx;
}
// tag all cells for refinement
// overrides the pure virtual function in AmrCore
void LSCoreBase::ErrorEst (int lev, TagBoxArray & tags, Real time, int ngrow) {
if (use_phierr) {
LSCoreBase::FillLevelSetTags(lev, tags, phierr, level_set[lev], geom);
} else {
LSCoreBase::FillVolfracTags(lev, tags, grids, dmap, * eb_levels[lev], geom);
}
}
// Read some parameters from inputs file
void LSCoreBase::ReadParameters () {
BL_PROFILE("LSCoreBase::ReadParameters()");
/************************************************************************
* Parse inputs *
***********************************************************************/
ParmParse pp("eb_amr");
pp.query("eb_pad", eb_pad);
pp.query("max_eb_pad", max_eb_pad);
}
// Set covered coarse cells to be the average of overlying fine cells
void LSCoreBase::AverageDown () {
BL_PROFILE("LSCoreBase::AverageDown()");
for (int lev = finest_level-1; lev >= 0; lev--) {
amrex::average_down(level_set[lev + 1], level_set[lev],
0, level_set[lev].nComp(), refRatio(lev));
}
}
// More flexible version of AverageDown() that lets you average down across
// multiple levels
void LSCoreBase::AverageDownTo (int crse_lev) {
BL_PROFILE("LSCoreBase::AverageDownTo()");
amrex::average_down(level_set[crse_lev+1], level_set[crse_lev],
0, level_set[crse_lev].nComp(), refRatio(crse_lev));
}
// Compute a new multifab by coping in phi from valid region and filling ghost
// cells works for single level and 2-level cases (fill fine grid ghost by
// interpolating from coarse)
void LSCoreBase::FillPatch (int lev, Real time, MultiFab& mf, int icomp, int ncomp) {
BL_PROFILE("LSCoreBase::FillPatch()");
if (lev == 0) {
BndryFuncArray bfunc(amrex_eb_phifill);
PhysBCFunct<BndryFuncArray> physbc(geom[lev], bcs, bfunc);
// NOTE: if source MultiFab vector as size = 1 => no interpolation
amrex::FillPatchSingleLevel(mf, time, {& level_set[0]}, {0.}, 0, icomp, ncomp,
geom[lev], physbc, 0);
} else {
BndryFuncArray bfunc(amrex_eb_phifill);
PhysBCFunct<BndryFuncArray> cphysbc(geom[lev-1], bcs, bfunc);
PhysBCFunct<BndryFuncArray> fphysbc(geom[lev ], bcs, bfunc);
Interpolater * mapper = & node_bilinear_interp;
amrex::FillPatchTwoLevels(mf, time, {& level_set[lev - 1]}, {0.}, {& level_set[lev]}, {0.},
0, icomp, ncomp, geom[lev-1], geom[lev],
cphysbc, 0, fphysbc, 0,
refRatio(lev-1), mapper, bcs, 0);
}
}
// Fill an entire multifab by interpolating from the coarser level. This comes
// into play when a new level of refinement appears
void LSCoreBase::FillCoarsePatch (int lev, Real time, MultiFab & mf, int icomp, int ncomp) {
BL_PROFILE("LSCoreBase::FillCoarsePatch()");
BL_ASSERT(lev > 0);
LSCoreBase::FillCoarsePatch(mf, level_set[lev - 1], geom[lev], geom[lev - 1],
bcs, refRatio(lev - 1), icomp, ncomp);
}
// Constructs a box over which to look for EB facets. The Box size grows based
// on the coarse-level level-set value. But it never grows larger than
// max_eb_pad.
Box LSCoreBase::EBSearchBox(const Box & tilebox, const FArrayBox & ls_crse,
const Geometry & geom_fine, bool & bail) {
IntVect n_grow(AMREX_D_DECL(max_eb_pad, max_eb_pad, max_eb_pad));
Box bx = LSCoreBase::EBSearchBox(tilebox, ls_crse, geom_fine, n_grow, bail);
return bx;
}
void LSCoreBase::FillLevelSet( MultiFab & level_set, const MultiFab & ls_crse,
const EBFArrayBoxFactory & eb_factory, const MultiFab & mf_impfunc,
const IntVect & ebt_size, int eb_pad, const Geometry & geom ) {
BL_PROFILE("LSCoreBase::FillLevelSet()");
// EB boundary-centre data
const MultiCutFab & bndrycent = eb_factory.getBndryCent();
const auto & flags = eb_factory.getMultiEBCellFlagFab();
const BoxArray & ba_ls = level_set.boxArray();
const BoxArray & ba_cc = amrex::convert(ba_ls, IntVect::TheZeroVector());
const BoxArray & ba_nd = amrex::convert(ba_ls, IntVect::TheUnitVector());
const DistributionMapping & dm = level_set.DistributionMap();
// EB normal data
MultiFab normal(ba_cc, dm, 3, eb_pad + 1);
FillEBNormals(normal, eb_factory, geom);
iMultiFab eb_valid(ba_cc, dm, 1, eb_pad + 1);
eb_valid.setVal(0);
// Level_set threshold
Real min_dx = LSUtility::min_dx(geom);
Real ls_threshold = min_dx * (eb_pad + 1);
const IntVect max_grow{eb_pad, eb_pad, eb_pad};
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(level_set, ebt_size); mfi.isValid(); ++mfi) {
const auto & ls_tile = ls_crse[mfi];
bool bail = false;
Box tile_box = mfi.tilebox();
Box eb_search = LSCoreBase::EBSearchBox(tile_box, ls_tile, geom, max_grow, bail);
if (bail) continue;
int n_facets = 0;
const auto & flag = flags[mfi];
// Need to count number of eb-facets (in order to allocate facet_list)
amrex_eb_count_facets(BL_TO_FORTRAN_BOX(eb_search),
BL_TO_FORTRAN_3D(flag),
& n_facets);
int facet_list_size = 6 * n_facets;
Vector<Real> facet_list(facet_list_size);
auto & ls_tile_w = level_set[mfi];
auto & v_tile = eb_valid[mfi];
const auto & if_tile = mf_impfunc[mfi];
if (n_facets > 0) {
const auto & norm_tile = normal[mfi];
const auto & bcent_tile = bndrycent[mfi];
int c_facets = 0;
amrex_eb_as_list(BL_TO_FORTRAN_BOX(eb_search), & c_facets,
BL_TO_FORTRAN_3D(flag),
BL_TO_FORTRAN_3D(norm_tile),
BL_TO_FORTRAN_3D(bcent_tile),
facet_list.dataPtr(), & facet_list_size,
geom.CellSize() );
amrex_eb_fill_levelset_loc(BL_TO_FORTRAN_BOX(tile_box),
facet_list.dataPtr(), & facet_list_size,
BL_TO_FORTRAN_3D(v_tile),
BL_TO_FORTRAN_3D(ls_tile_w),
BL_TO_FORTRAN_3D(ls_tile), & ls_threshold,
geom.CellSize(), geom.CellSize() );
}
//_______________________________________________________________________
// Enforce threshold of local level-set
amrex_eb_threshold_levelset(BL_TO_FORTRAN_BOX(tile_box), & ls_threshold,
BL_TO_FORTRAN_3D(ls_tile_w));
//_______________________________________________________________________
// Validate level-set
const int ls_grid_ref = 1;
amrex_eb_validate_levelset(BL_TO_FORTRAN_BOX(tile_box), & ls_grid_ref,
BL_TO_FORTRAN_3D(if_tile),
BL_TO_FORTRAN_3D(v_tile),
BL_TO_FORTRAN_3D(ls_tile_w) );
}
level_set.FillBoundary(geom.periodicity());
}
// Get plotfile name
std::string LSCoreBase::PlotFileName (int lev) const {
// return amrex::Concatenate(plot_file, lev, 5);
return plot_file;
}
// Put together an array of multifabs for writing
Vector<MultiFab> LSCoreBase::PlotFileMF () const {
BL_PROFILE("LSCoreBase::PlotFileMF()");
Vector<MultiFab> r(max_level + 1);
for (int i = 0; i < max_level + 1; i++) {
const int ncomp = level_set[i].nComp();
const int nghost = level_set[i].nGrow();
r[i].define(grids[i], dmap[i], ncomp, nghost);
amrex::average_node_to_cellcenter(r[i], 0, level_set[i], 0, 1);
}
return std::move(r);
}
// Set plotfile variable names
Vector<std::string> LSCoreBase::PlotFileVarNames () const {
return {"level-set"};
}
// Write plotfile to disk
void LSCoreBase::WritePlotFile () const {
BL_PROFILE("LSCoreBase::WritePlotFile()");
// Get plotfile name
const std::string & plotfilename = PlotFileName(0);
// Generate cell-centered data to put into plotfile
const Vector<MultiFab> mf_plt = PlotFileMF();
Vector<const MultiFab*> mf_ptr;
for (const MultiFab & mf : mf_plt)
mf_ptr.push_back(& mf);
// Get variable names
const auto & varnames = PlotFileVarNames();
// Keep user informed
amrex::Print() << "Writing ";
for (const std::string & str_name : varnames)
amrex::Print() << str_name << " ";
amrex::Print() << "plotfile: " << plotfilename << "\n";
// Save plot file
Vector<int> istep(max_level + 1, 0);
amrex::WriteMultiLevelPlotfile(plotfilename, finest_level + 1, mf_ptr, varnames,
Geom(), 0., istep, refRatio());
}
void LSCoreBase::WriteCheckpointFile () const {
BL_PROFILE("LSCoreBase::WriteCheckpointFile()");
// chk00010 write a checkpoint file with this root directory
// chk00010/Header this contains information you need to save (e.g.,
// finest_level, t_new, etc.) and also the BoxArrays at
// each level
// chk00010/Level_0/
// chk00010/Level_1/
// etc. these subdirectories will hold the MultiFab data at
// each level of refinement
// checkpoint file name, e.g., chk00010
// const std::string & checkpointname = amrex::Concatenate(chk_file,istep[0]);
const std::string & checkpointname = chk_file;
amrex::Print() << "Writing checkpoint " << checkpointname << "\n";
const int nlevels = finest_level + 1;
// ---- prebuild a hierarchy of directories
// ---- dirName is built first. if dirName exists, it is renamed. then build
// ---- dirName/subDirPrefix_0 .. dirName/subDirPrefix_nlevels-1
// ---- if callBarrier is true, call ParallelDescriptor::Barrier()
// ---- after all directories are built
// ---- ParallelDescriptor::IOProcessor() creates the directories
amrex::PreBuildDirectorHierarchy(checkpointname, "Level_", nlevels, true);
// write Header file
if (ParallelDescriptor::IOProcessor()) {
std::string HeaderFileName(checkpointname + "/Header");
VisMF::IO_Buffer io_buffer(VisMF::IO_Buffer_Size);
std::ofstream HeaderFile;
HeaderFile.rdbuf()->pubsetbuf(io_buffer.dataPtr(), io_buffer.size());
HeaderFile.open(HeaderFileName.c_str(), std::ofstream::out |
std::ofstream::trunc |
std::ofstream::binary);
if( ! HeaderFile.good()) {
amrex::FileOpenFailed(HeaderFileName);
}
HeaderFile.precision(17);
// write out title line
HeaderFile << "Checkpoint file for AmrCoreAdv\n";
// write out finest_level
HeaderFile << finest_level << "\n";
// write out array of istep
Vector<int> istep(max_level + 1, 0);
for (int i = 0; i < istep.size(); ++i) {
HeaderFile << istep[i] << " ";
}
HeaderFile << "\n";
// write the BoxArray at each level
for (int lev = 0; lev <= finest_level; ++lev) {
boxArray(lev).writeOn(HeaderFile);
HeaderFile << '\n';
}
}
// write the MultiFab data to, e.g., chk00010/Level_0/
for (int lev = 0; lev <= finest_level; ++lev) {
VisMF::Write(level_set[lev],
amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "phi"));
}
}
void LSCoreBase::ReadCheckpointFile () {
BL_PROFILE("LSCoreBase::ReadCheckpointFile()");
amrex::Print() << "Restart from checkpoint " << restart_chkfile << "\n";
// Header
std::string File(restart_chkfile + "/Header");
VisMF::IO_Buffer io_buffer(VisMF::GetIOBufferSize());
Vector<char> fileCharPtr;
ParallelDescriptor::ReadAndBcastFile(File, fileCharPtr);
std::string fileCharPtrString(fileCharPtr.dataPtr());
std::istringstream is(fileCharPtrString, std::istringstream::in);
std::string line, word;
// read in title line
std::getline(is, line);
// read in finest_level
is >> finest_level;
GotoNextLine(is);
for (int lev = 0; lev <= finest_level; ++lev) {
// read in level 'lev' BoxArray from Header
BoxArray ba;
ba.readFrom(is);
GotoNextLine(is);
// create a distribution mapping
DistributionMapping dm { ba, ParallelDescriptor::NProcs() };
// set BoxArray grids and DistributionMapping dmap in AMReX_AmrMesh.H class
SetBoxArray(lev, ba);
SetDistributionMap(lev, dm);
// build MultiFab and FluxRegister data
int ncomp = 1;
int nghost = 0;
level_set[lev].define(grids[lev], dmap[lev], ncomp, nghost);
}
// read in the MultiFab data
for (int lev = 0; lev <= finest_level; ++lev) {
VisMF::Read(level_set[lev],
amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "phi"));
}
}
// utility to skip to next line in Header
void LSCoreBase::GotoNextLine (std::istream & is) {
constexpr std::streamsize bl_ignore_max { 100000 };
is.ignore(bl_ignore_max, '\n');
}
}
|
// Copyright 2016 The Native Client 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 <pthread.h>
#include "native_client/src/include/nacl_assert.h"
#include "native_client/src/untrusted/pll_loader/pll_loader.h"
namespace {
template <typename VarType>
void CheckTlsVar(ModuleSet *modset, const char *name_of_getter,
int alignment, VarType expected_value) {
auto getter = (VarType *(*)()) (uintptr_t) modset->GetSym(name_of_getter);
ASSERT_NE(getter, NULL);
VarType *var_ptr = getter();
ASSERT_NE(var_ptr, NULL);
ASSERT_EQ((uintptr_t) var_ptr & (alignment - 1), 0);
ASSERT_EQ(*var_ptr, expected_value);
}
struct ThreadArgs {
int *(*tls_var_getter)();
void *tls_var_on_main_thread;
};
void *ThreadFunc(void *thread_arg) {
ThreadArgs *args = (ThreadArgs *) thread_arg;
int *var_ptr = args->tls_var_getter();
ASSERT_NE(var_ptr, NULL);
ASSERT_EQ(*var_ptr, 123);
ASSERT_NE(var_ptr, args->tls_var_on_main_thread);
return NULL;
}
} // namespace
int main(int argc, char **argv) {
if (argc != 5) {
fprintf(stderr, "Usage: pll_loader_test <Directory path> <3 ELF files>\n");
return 1;
}
const char *module_directory = argv[1];
const char *module_a_soname = argv[2];
const char *module_b_soname = argv[3];
const char *module_tls_soname = argv[4];
ModuleSet modset;
std::vector<std::string> search_path;
search_path.push_back(module_directory);
modset.SetSonameSearchPath(search_path);
// "module_a_var" should only be resolvable after we load module A.
int *module_a_var = (int *) modset.GetSym("module_a_var");
ASSERT_EQ(module_a_var, NULL);
ASSERT_NE(modset.AddBySoname(module_a_soname), NULL);
module_a_var = (int *) modset.GetSym("module_a_var");
ASSERT_NE(module_a_var, NULL);
ASSERT_EQ(*module_a_var, 2345);
// Demonstrate that the same soname cannot be loaded multiple times.
ASSERT_EQ(modset.AddBySoname(module_a_soname), NULL);
ASSERT_NE(modset.AddBySoname(module_b_soname), NULL);
int *module_b_var = (int *) modset.GetSym("module_b_var");
ASSERT_NE(module_b_var, NULL);
ASSERT_EQ(*module_b_var, 1234);
ASSERT_NE(modset.AddBySoname(module_tls_soname), NULL);
modset.ResolveRefs();
// Check that "addr_of_module_a_var" has been correctly relocated to
// point to the other module.
int **addr_of_module_a_var = (int **) modset.GetSym("addr_of_module_a_var");
ASSERT_NE(addr_of_module_a_var, NULL);
ASSERT_EQ(*addr_of_module_a_var, module_a_var);
// Test that TLS variables are instantiated and aligned properly.
CheckTlsVar<int>(&modset, "get_tls_var1", sizeof(int), 123);
CheckTlsVar<int *>(&modset, "get_tls_var2", sizeof(int), module_a_var);
CheckTlsVar<int>(&modset, "get_tls_var_aligned", 256, 345);
CheckTlsVar<int>(&modset, "get_tls_bss_var1", sizeof(int), 0);
CheckTlsVar<int>(&modset, "get_tls_bss_var_aligned", 256, 0);
CheckTlsVar<int>(&modset, "get_tls_var_exported1", sizeof(int), 1234);
CheckTlsVar<int>(&modset, "get_tls_var_exported2", sizeof(int), 5678);
// Test that TLS variables are instantiated separately for each thread.
ThreadArgs thread_args;
thread_args.tls_var_getter =
(int *(*)()) (uintptr_t) modset.GetSym("get_tls_var1");
thread_args.tls_var_on_main_thread = thread_args.tls_var_getter();
pthread_t tid;
int err = pthread_create(&tid, NULL, ThreadFunc, &thread_args);
ASSERT_EQ(err, 0);
err = pthread_join(tid, NULL);
ASSERT_EQ(err, 0);
// Check that the TLS var is still given the same address. This
// should not have been affected by launching a child thread.
ASSERT_EQ(thread_args.tls_var_getter(), thread_args.tls_var_on_main_thread);
return 0;
}
|
/* $Id: Simple_replace.hpp 549711 2017-10-26 18:03:18Z gotvyans $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
*/
/// @file Simple_replace.hpp
/// User-defined methods of the data storage class.
///
/// This file was originally generated by application DATATOOL
/// using the following specifications:
/// 'macro.asn'.
///
/// New methods or data members can be added to it if needed.
/// See also: Simple_replace_.hpp
#ifndef OBJECTS_MACRO_SIMPLE_REPLACE_HPP
#define OBJECTS_MACRO_SIMPLE_REPLACE_HPP
// generated includes
#include <objects/macro/Simple_replace_.hpp>
// generated classes
#include <objects/macro/String_constraint.hpp>
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
/////////////////////////////////////////////////////////////////////////////
class CSimple_replace : public CSimple_replace_Base
{
typedef CSimple_replace_Base Tparent;
public:
// constructor
CSimple_replace(void);
// destructor
~CSimple_replace(void);
bool ApplyToString(string& result, const CMatchString& str, CConstRef<CString_constraint> find) const;
private:
// Prohibit copy constructor and assignment operator
CSimple_replace(const CSimple_replace& value);
CSimple_replace& operator=(const CSimple_replace& value);
};
/////////////////// CSimple_replace inline methods
// constructor
inline
CSimple_replace::CSimple_replace(void)
{
}
/////////////////// end of CSimple_replace inline methods
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
#endif // OBJECTS_MACRO_SIMPLE_REPLACE_HPP
/* Original file checksum: lines: 86, chars: 2481, CRC32: c06c7da7 */
|
#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QColorDialog>
#ifdef Q_OS_LINUX
#include <QUuid>
#include <QDir>
#include <QFile>
#include <QStandardPaths>
#endif
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget),
taskbar(new QTaskbarControl(this))
{
ui->setupUi(this);
connect(ui->progressCheckBox, &QCheckBox::clicked,
taskbar, &QTaskbarControl::setProgressVisible);
connect(ui->counterCheckBox, &QCheckBox::clicked,
taskbar, &QTaskbarControl::setCounterVisible);
connect(ui->counterSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
taskbar, &QTaskbarControl::setCounter);
#ifdef Q_OS_LINUX
auto name = QUuid::createUuid().toString() + QStringLiteral(".desktop");
QGuiApplication::setDesktopFileName(name);
QDir appDir = QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation);
QFile desktopFile(appDir.absoluteFilePath(name));
if(!desktopFile.exists()) {
desktopFile.open(QIODevice::WriteOnly);
desktopFile.write("[Desktop Entry]\n");
desktopFile.write("Type=Application\n");
desktopFile.write("Version=1.1\n");
desktopFile.write("Name=" + QApplication::applicationDisplayName().toUtf8() + "\n");
desktopFile.write("Exec=" + QApplication::applicationFilePath().toUtf8() + "\n");
desktopFile.close();
}
ui->desktopFileLineEdit->setText(name);
#else
ui->desktopFileLabel->setVisible(false);
ui->desktopFileLineEdit->setVisible(false);
#endif
#ifdef Q_OS_WIN
taskbar->setWidget(this);
#else
ui->progressStateLabel->setVisible(false);
ui->progressStateComboBox->setVisible(false);
ui->badgeIconLabel->setVisible(false);
ui->badgeIconPushButton->setVisible(false);
ui->badgeTextColorLabel->setVisible(false);
ui->badgeTextColorPushButton->setVisible(false);
ui->indeterminateLabel->setVisible(false);
ui->indeterminatePushButton->setVisible(false);
#endif
}
Widget::~Widget()
{
#ifdef Q_OS_LINUX
auto name = QGuiApplication::desktopFileName();
QDir appDir = QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation);
QFile::remove(appDir.absoluteFilePath(name));
#endif
delete ui;
}
void Widget::on_progressSlider_valueChanged(int value)
{
taskbar->setProgress(static_cast<double>(value) / ui->progressSlider->maximum());
}
void Widget::on_progressStateComboBox_currentIndexChanged(int index)
{
taskbar->setWindowsProgressState(static_cast<QTaskbarControl::WinProgressState>(index));
}
void Widget::on_badgeIconPushButton_clicked()
{
auto file = QFileDialog::getOpenFileName(this,
tr("Select an icon"),
QString(),
tr("Icons (*.ico *.png *.bmp);;All Files (*)"));
if(!file.isNull())
taskbar->setWindowsBadgeIcon(QIcon(file));
}
void Widget::on_badgeTextColorPushButton_clicked()
{
auto color = QColorDialog::getColor(taskbar->windowsBadgeTextColor(),
this,
tr("Select a color"));
if(color.isValid())
taskbar->setWindowsBadgeTextColor(color);
}
void Widget::on_indeterminatePushButton_clicked()
{
taskbar->setProgress(-1);
}
|
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
/*
This file implements the function
template <class VertexAndEdgeListGraph, class DistanceMatrix,
class P, class T, class R>
bool
johnson_all_pairs_shortest_paths
(VertexAndEdgeListGraph& g,
DistanceMatrix& D,
const bgl_named_params<P, T, R>& params)
*/
#ifndef BOOST_GRAPH_JOHNSON_HPP
#define BOOST_GRAPH_JOHNSON_HPP
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map.hpp>
#include <boost/graph/bellman_ford_shortest_paths.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/pending/ct_if.hpp>
#include <boost/type_traits/same_traits.hpp>
namespace boost {
template <class VertexAndEdgeListGraph, class DistanceMatrix,
class VertexID, class Weight, class DistanceZero>
bool
johnson_all_pairs_shortest_paths(VertexAndEdgeListGraph& g1,
DistanceMatrix& D,
VertexID id1, Weight w1, DistanceZero zero)
{
typedef graph_traits<VertexAndEdgeListGraph> Traits1;
typedef typename property_traits<Weight>::value_type DT;
function_requires< BasicMatrixConcept<DistanceMatrix,
typename Traits1::vertices_size_type, DT> >();
typedef typename Traits1::directed_category DirCat;
bool is_undirected = is_same<DirCat, undirected_tag>::value;
typedef adjacency_list<vecS, vecS, directedS,
property< vertex_distance_t, DT>,
property< edge_weight_t, DT,
property< edge_weight2_t, DT > > > Graph2;
typedef graph_traits<Graph2> Traits2;
Graph2 g2(num_vertices(g1) + 1);
typename property_map<Graph2, edge_weight_t>::type
w = get(edge_weight, g2);
typename property_map<Graph2, edge_weight2_t>::type
w_hat = get(edge_weight2, g2);
typename property_map<Graph2, vertex_distance_t>::type
d = get(vertex_distance, g2);
typedef typename property_map<Graph2, vertex_index_t>::type VertexID2;
VertexID2 id2 = get(vertex_index, g2);
// Construct g2 where V[g2] = V[g1] U {s}
// and E[g2] = E[g1] U {(s,v)| v in V[g1]}
std::vector<typename Traits1::vertex_descriptor>
verts1(num_vertices(g1) + 1);
typename Traits2::vertex_descriptor s = *vertices(g2).first;
{
typename Traits1::vertex_iterator v, v_end;
int i = 1;
for (tie(v, v_end) = vertices(g1); v != v_end; ++v, ++i) {
typename Traits2::edge_descriptor e; bool z;
tie(e, z) = add_edge(s, get(id1, *v) + 1, g2);
put(w, e, zero);
verts1[i] = *v;
}
typename Traits1::edge_iterator e, e_end;
for (tie(e, e_end) = edges(g1); e != e_end; ++e) {
typename Traits2::edge_descriptor e2; bool z;
tie(e2, z) = add_edge(get(id1, source(*e, g1)) + 1,
get(id1, target(*e, g1)) + 1, g2);
put(w, e2, get(w1, *e));
if (is_undirected) {
tie(e2, z) = add_edge(get(id1, target(*e, g1)) + 1,
get(id1, source(*e, g1)) + 1, g2);
put(w, e2, get(w1, *e));
}
}
}
typename Traits2::vertex_iterator v, v_end, u, u_end;
typename Traits2::edge_iterator e, e_end;
std::vector<DT> h_vec(num_vertices(g2));
typedef typename std::vector<DT>::iterator iter_t;
iterator_property_map<iter_t,VertexID2,DT,DT&> h(h_vec.begin(), id2);
DT inf = (std::numeric_limits<DT>::max)();
for (tie(v, v_end) = vertices(g2); v != v_end; ++v)
d[*v] = inf;
put(d, s, zero);
// Using the non-named parameter versions of bellman_ford and
// dijkstra for portability reasons.
dummy_property_map pred; closed_plus<DT> combine;
std::less<DT> compare; bellman_visitor<> bvis;
if (bellman_ford_shortest_paths
(g2, num_vertices(g2), w, pred, d, combine, compare, bvis)) {
for (tie(v, v_end) = vertices(g2); v != v_end; ++v)
put(h, *v, get(d, *v));
// Reweight the edges to remove negatives
for (tie(e, e_end) = edges(g2); e != e_end; ++e) {
typename Traits2::vertex_descriptor a = source(*e, g2),
b = target(*e, g2);
put(w_hat, *e, get(w, *e) + get(h, a) - get(h, b));
}
for (tie(u, u_end) = vertices(g2); u != u_end; ++u) {
dijkstra_visitor<> dvis;
dijkstra_shortest_paths
(g2, *u, pred, d, w_hat, id2, compare, combine, inf, zero,dvis);
for (tie(v, v_end) = vertices(g2); v != v_end; ++v) {
if (*u != s && *v != s) {
typename Traits1::vertex_descriptor u1, v1;
u1 = verts1[id2[*u]]; v1 = verts1[id2[*v]];
D[id2[*u]-1][id2[*v]-1] = get(d, *v) + get(h, *v) - get(h, *u);
}
}
}
return true;
} else
return false;
}
namespace detail {
template <class VertexAndEdgeListGraph, class DistanceMatrix,
class P, class T, class R, class Weight,
class VertexID>
bool
johnson_dispatch(VertexAndEdgeListGraph& g,
DistanceMatrix& D,
const bgl_named_params<P, T, R>& params,
Weight w, VertexID id)
{
typedef typename property_traits<Weight>::value_type WT;
return johnson_all_pairs_shortest_paths
(g, D, id, w,
choose_param(get_param(params, distance_zero_t()), WT()) );
}
} // namespace detail
template <class VertexAndEdgeListGraph, class DistanceMatrix,
class P, class T, class R>
bool
johnson_all_pairs_shortest_paths
(VertexAndEdgeListGraph& g,
DistanceMatrix& D,
const bgl_named_params<P, T, R>& params)
{
return detail::johnson_dispatch
(g, D, params,
choose_const_pmap(get_param(params, edge_weight), g, edge_weight),
choose_const_pmap(get_param(params, vertex_index), g, vertex_index)
);
}
template <class VertexAndEdgeListGraph, class DistanceMatrix>
bool
johnson_all_pairs_shortest_paths
(VertexAndEdgeListGraph& g, DistanceMatrix& D)
{
bgl_named_params<int,int> params(1);
return detail::johnson_dispatch
(g, D, params, get(edge_weight, g), get(vertex_index, g));
}
} // namespace boost
#endif // BOOST_GRAPH_JOHNSON_HPP
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzCore/UnitTest/TestTypes.h>
#include <AzCore/PlatformIncl.h>
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/Memory/MallocSchema.h>
using namespace AZ;
using namespace AZ::Debug;
namespace UnitTest
{
class MallocSchemaTest : public ::testing::Test
{
public:
void RunTests()
{
TestAllocationDeallocation();
TestReallocation();
}
private:
void TestAllocationDeallocation()
{
static const AZStd::pair<size_t, size_t> sizeAndAlignments[] =
{
{ 16, 8 },
{ 15, 1 },
{ 17, 1 },
{ 1024, 16 },
{ 1023, 1 },
{ 1025, 1 },
{ 65536, 16 },
{ 65535, 1 },
{ 65537, 1 }
};
AZStd::fixed_vector<void*, AZ_ARRAY_SIZE(sizeAndAlignments)> records;
size_t totalAllocated = 0;
// Allocate memory
for (const auto& sizeAndAlignment : sizeAndAlignments)
{
void* p = m_mallocSchema.Allocate(sizeAndAlignment.first, sizeAndAlignment.second, 0);
EXPECT_NE(p, nullptr);
EXPECT_EQ(m_mallocSchema.AllocationSize(p), sizeAndAlignment.first);
records.push_back(p);
totalAllocated += sizeAndAlignment.first;
EXPECT_EQ(m_mallocSchema.NumAllocatedBytes(), totalAllocated);
}
// Deallocate memory
for (auto record : records)
{
totalAllocated -= m_mallocSchema.AllocationSize(record);
m_mallocSchema.DeAllocate(record);
EXPECT_EQ(m_mallocSchema.NumAllocatedBytes(), totalAllocated);
}
EXPECT_EQ(totalAllocated, 0);
}
void TestReallocation()
{
static const AZStd::pair<size_t, size_t> sizeAndAlignments[] =
{
{ 16, 8 },
{ 1024, 16 },
{ 32, 8 },
{ 0, 0 }
};
void* p = nullptr;
// Keep reallocating the same pointer
for (const auto& sizeAndAlignment : sizeAndAlignments)
{
p = m_mallocSchema.ReAllocate(p, sizeAndAlignment.first, sizeAndAlignment.second);
if (sizeAndAlignment.first)
{
EXPECT_NE(p, nullptr);
EXPECT_EQ(m_mallocSchema.AllocationSize(p), sizeAndAlignment.first);
EXPECT_EQ(m_mallocSchema.NumAllocatedBytes(), sizeAndAlignment.first);
}
else
{
EXPECT_EQ(p, nullptr);
EXPECT_EQ(m_mallocSchema.NumAllocatedBytes(), 0);
}
}
}
MallocSchema m_mallocSchema;
};
TEST_F(MallocSchemaTest, Test)
{
RunTests();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.