本文整理汇总了C++中result函数的典型用法代码示例。如果您正苦于以下问题:C++ result函数的具体用法?C++ result怎么用?C++ result使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了result函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: result
transform_iterator operator++(int)
{
transform_iterator result (*this);
increment();
return result;
}
示例2: result
tree_iterator operator--(int)
{
tree_iterator result (*this);
members_.nodeptr_ = node_algorithms::prev_node(members_.nodeptr_);
return result;
}
示例3: switch
void CUser::ZoneChange(uint16 sNewZone, float x, float z)
{
C3DMap * pMap = g_pMain->GetZoneByID(sNewZone);
if (pMap == nullptr)
return;
ZoneChangeError errorReason;
if (!CanChangeZone(pMap, errorReason))
{
Packet result;
switch (errorReason)
{
case ZoneChangeErrorWrongLevel:
/* this will depend on the zone */
break;
case ZoneChangeErrorWarActive:
result.Initialize(WIZ_WARP_LIST);
result << uint8(2) << uint8(4);
Send(&result);
break;
case ZoneChangeErrorNeedLoyalty:
/* does this have an error? */
break;
}
return;
}
m_bWarp = true;
m_bZoneChangeFlag = true;
UserInOut(INOUT_OUT);
if (sNewZone == ZONE_SNOW_BATTLE)
SetMaxHp(1);
if (GetZoneID() != sNewZone)
{
SetZoneAbilityChange();
// Reset the user's anger gauge when leaving the zone
// Unknown if this is official behaviour, but it's logical.
if (GetAngerGauge() > 0)
UpdateAngerGauge(0);
/*
Here we also send a clan packet with subopcode 0x16 (with a byte flag of 2) if war zone/Moradon
or subopcode 0x17 (with nWarEnemyID) for all else
*/
#if 0
if (isInClan())
{
CKnights * pKnights = g_pMain->GetClanPtr(GetClanID());
if (pKnights != nullptr
&& pKnights->bKnightsWarStarted)
{
Packet clanPacket(WIZ_KNIGHTS_PROCESS);
if (pMap->isWarZone() || byNewZone == ZONE_MORADON)
clanPacket << uint8(0x17) << uint8(2);
else
clanPacket << uint16(0x16) << uint16(0 /*nWarEnemyID*/);
Send(&clanPacket);
}
}
#endif
if (sNewZone == ZONE_SNOW_BATTLE)
SetMaxHp();
if (isInParty())
PartyRemove(GetSocketID());
ResetWindows();
}
m_bZone = (uint8) sNewZone; // this is 2 bytes to support the warp data loaded from SMDs. It should not go above a byte, however.
SetPosition(x, 0.0f, z);
m_pMap = pMap;
if (g_pMain->m_nServerNo != pMap->m_nServerNo)
{
_ZONE_SERVERINFO *pInfo = g_pMain->m_ServerArray.GetData(pMap->m_nServerNo);
if (pInfo == nullptr)
return;
UserDataSaveToAgent();
m_bLogout = 2; // server change flag
SendServerChange(pInfo->strServerIP, 2);
return;
}
SetRegion(GetNewRegionX(), GetNewRegionZ());
Packet result(WIZ_ZONE_CHANGE, uint8(ZoneChangeTeleport));
//.........这里部分代码省略.........
示例4: result
constant_iterator operator++(int)
{
constant_iterator result (*this);
increment();
return result;
}
示例5: main
//.........这里部分代码省略.........
llvm::BasicBlock* mainBB = llvm::BasicBlock::Create(context, "mainBB", mainFunction);
builder.SetInsertPoint(mainBB);
/* function Teste */
llvm::Type* boolType = llvm::Type::getInt1Ty(context);
std::vector<llvm::Type*> testeParams(3, boolType);
llvm::FunctionType* typeOfTeste = llvm::FunctionType::get(boolType, testeParams, false);
llvm::Function* testeFunction = llvm::Function::Create(typeOfTeste, llvm::Function::ExternalLinkage, "teste", module);
llvm::Function::arg_iterator params = testeFunction->arg_begin();
params->setName("x");
params++;
params->setName("y");
params++;
params->setName("z");
llvm::BasicBlock* testeBB = llvm::BasicBlock::Create(context, "testeBB", testeFunction);
builder.SetInsertPoint(testeBB);
llvm::Function::arg_iterator declParams = testeFunction->arg_begin();
auto x = declParams;
auto y = ++declParams;
auto z = ++declParams;
auto xy = builder.CreateAnd(x, y, "andxy");
auto xz = builder.CreateAnd(x, z, "andxz");
auto nz = builder.CreateNot(z, "nz");
auto ny = builder.CreateNot(y, "ny");
auto nzny = builder.CreateAnd(nz, ny, "nzny");
auto res = builder.CreateOr(xy, xz, "res");
res = builder.CreateOr(res, nzny, "res");
builder.CreateRet(res);
llvm::verifyFunction(*testeFunction);
/* function Exemplo */
llvm::Type* realType = llvm::Type::getDoubleTy(context);
std::vector<llvm::Type*> exemploParams(2, realType);
llvm::FunctionType* typeOfExemplo = llvm::FunctionType::get(realType, exemploParams, false);
llvm::Function* exemploFunction = llvm::Function::Create(typeOfExemplo, llvm::Function::ExternalLinkage, "exemplo", module);
params = exemploFunction->arg_begin();
params->setName("a");
params++;
params->setName("b");
llvm::BasicBlock* exemploBB = llvm::BasicBlock::Create(context, "exemploBB", exemploFunction);
builder.SetInsertPoint(exemploBB);
auto a = exemploFunction->arg_begin();
auto b = ++(exemploFunction->arg_begin());
auto multab = builder.CreateFMul(a, b, "multab");
auto const20 = llvm::ConstantFP::get(context, llvm::APFloat(2.0));
auto modab = builder.CreateFRem(a, b, "modab");//???
auto ret = builder.CreateFMul(const20, modab, "ret");
ret = builder.CreateFSub(multab, ret, "ret");
builder.CreateRet(ret);
llvm::verifyFunction(*exemploFunction);
/* Chamando as funções */
builder.SetInsertPoint(mainBB);
std::vector<llvm::Value*> args;
args.push_back(llvm::ConstantInt::get(context, llvm::APInt(1, 0)));
args.push_back(llvm::ConstantInt::get(context, llvm::APInt(1, 0)));
args.push_back(llvm::ConstantInt::get(context, llvm::APInt(1, 1)));
auto testeRet = builder.CreateCall(testeFunction, args, "callteste");
std::vector<llvm::Value*> args2;
args2.push_back(llvm::ConstantFP::get(context, llvm::APFloat(10.0)));
args2.push_back(llvm::ConstantFP::get(context, llvm::APFloat(5.0)));
auto exemploRet = builder.CreateCall(exemploFunction, args2, "callexemplo");
builder.CreateRet(testeRet);
module->dump();
llvm::ExecutionEngine* execEngine;
std::string err;
LLVMInitializeNativeTarget();
execEngine = llvm::EngineBuilder(module).setErrorStr(&err).create();
if(!execEngine) {
fprintf(stderr, "Could not create execEngine: %s\n", err.c_str());
exit(1);
}
void* mainPtr = execEngine->getPointerToFunction(mainFunction);
int(*result)() = (int (*)())(intptr_t)mainPtr;
std::cout << "Result of main: " << result() << std::endl;
}
示例6: result
String operator+(const String &s1, const String &s2)
{
String result(s1);
result.append(s2);
return result;
}
示例7: sizePixels
const QImage ImageLoaderFreeImage::imageAsRGB(const QSize &size) const
{
const QSize resultSize = size.isValid() ? size : sizePixels();
const bool isRGB24 = colorDataType() == Types::ColorTypeRGB && bitsPerPixel() == 24;
const bool isARGB32 = colorDataType() == Types::ColorTypeRGBA && bitsPerPixel() == 32;
QImage result(resultSize, isARGB32 ? QImage::Format_ARGB32 : QImage::Format_RGB32);
const int width = resultSize.width();
const int height = resultSize.height();
const QSize sizePixels = this->sizePixels();
FIBITMAP* originalImage = m_bitmap;
FIBITMAP* temp24BPPImage = NULL;
FIBITMAP* scaledImage = NULL;
if (!(isRGB24 || isARGB32)) {
if (colorDataType() == Types::ColorTypeCMYK) {
const bool isCmykJpeg = isJpeg(); // Value range inverted
temp24BPPImage = FreeImage_Allocate(sizePixels.width(), sizePixels.height(), 24);
const unsigned int columnsCount = sizePixels.width();
const unsigned int scanlinesCount = sizePixels.height();
for (unsigned int scanline = 0; scanline < scanlinesCount; scanline++) {
const BYTE* const cmykBits = FreeImage_GetScanLine(m_bitmap, scanline);
tagRGBTRIPLE* const rgbBits = (tagRGBTRIPLE *)FreeImage_GetScanLine(temp24BPPImage, scanline);
for (unsigned int column = 0; column < columnsCount; column++) {
const unsigned int cmykColumn = column * 4;
const QColor rgbColor = isCmykJpeg ?
QColor::fromCmyk(255 - cmykBits[cmykColumn], 255 - cmykBits[cmykColumn + 1], 255 - cmykBits[cmykColumn + 2], 255 - cmykBits[cmykColumn + 3])
: QColor::fromCmyk(cmykBits[cmykColumn], cmykBits[cmykColumn + 1], cmykBits[cmykColumn + 2], cmykBits[cmykColumn + 3]);
rgbBits[column].rgbtRed = (BYTE)rgbColor.red();
rgbBits[column].rgbtGreen = (BYTE)rgbColor.green();
rgbBits[column].rgbtBlue = (BYTE)rgbColor.blue();
}
}
} else {
temp24BPPImage = FreeImage_ConvertTo24Bits(originalImage);
}
originalImage = temp24BPPImage;
}
if (resultSize != sizePixels) {
scaledImage = FreeImage_Rescale(originalImage, width, height, FILTER_BOX);
originalImage = scaledImage;
}
for (int scanline = 0; scanline < height; scanline++) {
QRgb *targetData = (QRgb*)result.scanLine(scanline);
if (isARGB32) {
const tagRGBQUAD *sourceRgba = (tagRGBQUAD*)FreeImage_GetScanLine(originalImage, height - scanline - 1);
for (int column = 0; column < width; column++) {
*targetData++ = qRgba(sourceRgba->rgbRed, sourceRgba->rgbGreen, sourceRgba->rgbBlue, sourceRgba->rgbReserved);
sourceRgba++;
}
} else {
const tagRGBTRIPLE *sourceRgb = (tagRGBTRIPLE*)FreeImage_GetScanLine(originalImage, height - scanline - 1);
for (int column = 0; column < width; column++) {
*targetData++ = qRgb(sourceRgb->rgbtRed, sourceRgb->rgbtGreen, sourceRgb->rgbtBlue);
sourceRgb++;
}
}
}
if (temp24BPPImage)
FreeImage_Unload(temp24BPPImage);
if (scaledImage)
FreeImage_Unload(scaledImage);
return result;
}
示例8: result
IddObjectType CurveExponentialSkewNormal::iddObjectType() {
IddObjectType result(IddObjectType::OS_Curve_ExponentialSkewNormal);
return result;
}
示例9: result
Matrix Matrix::operator~() const{
Matrix result(*this);
result.inverse();
return result;
}
示例10: result
IddObjectType CoilCoolingWater::iddObjectType() {
IddObjectType result(IddObjectType::OS_Coil_Cooling_Water);
return result;
}
示例11: estimaterawfee
UniValue estimaterawfee(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"estimaterawfee conf_target (threshold)\n"
"\nWARNING: This interface is unstable and may disappear or change!\n"
"\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
" implementation of fee estimation. The parameters it can be called with\n"
" and the results it returns will change if the internal implementation changes.\n"
"\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
"confirmation within conf_target blocks if possible. Uses virtual transaction size as\n"
"defined in BIP 141 (witness data is discounted).\n"
"\nArguments:\n"
"1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n"
"2. threshold (numeric, optional) The proportion of transactions in a given feerate range that must have been\n"
" confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n"
" lower buckets. Default: 0.95\n"
"\nResult:\n"
"{\n"
" \"short\" : { (json object, optional) estimate for short time horizon\n"
" \"feerate\" : x.x, (numeric, optional) estimate fee-per-kilobyte (in BTC)\n"
" \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n"
" \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n"
" \"pass\" : { (json object, optional) information about the lowest range of feerates to succeed in meeting the threshold\n"
" \"startrange\" : x.x, (numeric) start of feerate range\n"
" \"endrange\" : x.x, (numeric) end of feerate range\n"
" \"withintarget\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed within target\n"
" \"totalconfirmed\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed at any point\n"
" \"inmempool\" : x.x, (numeric) current number of txs in mempool in the feerate range unconfirmed for at least target blocks\n"
" \"leftmempool\" : x.x, (numeric) number of txs over history horizon in the feerate range that left mempool unconfirmed after target\n"
" },\n"
" \"fail\" : { ... }, (json object, optional) information about the highest range of feerates to fail to meet the threshold\n"
" \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
" },\n"
" \"medium\" : { ... }, (json object, optional) estimate for medium time horizon\n"
" \"long\" : { ... } (json object) estimate for long time horizon\n"
"}\n"
"\n"
"Results are returned for any horizon which tracks blocks up to the confirmation target.\n"
"\nExample:\n"
+ HelpExampleCli("estimaterawfee", "6 0.9")
);
RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true);
RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
unsigned int conf_target = ParseConfirmTarget(request.params[0]);
double threshold = 0.95;
if (!request.params[1].isNull()) {
threshold = request.params[1].get_real();
}
if (threshold < 0 || threshold > 1) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold");
}
UniValue result(UniValue::VOBJ);
for (FeeEstimateHorizon horizon : {FeeEstimateHorizon::SHORT_HALFLIFE, FeeEstimateHorizon::MED_HALFLIFE, FeeEstimateHorizon::LONG_HALFLIFE}) {
CFeeRate feeRate;
EstimationResult buckets;
// Only output results for horizons which track the target
if (conf_target > ::feeEstimator.HighestTargetTracked(horizon)) continue;
feeRate = ::feeEstimator.estimateRawFee(conf_target, threshold, horizon, &buckets);
UniValue horizon_result(UniValue::VOBJ);
UniValue errors(UniValue::VARR);
UniValue passbucket(UniValue::VOBJ);
passbucket.push_back(Pair("startrange", round(buckets.pass.start)));
passbucket.push_back(Pair("endrange", round(buckets.pass.end)));
passbucket.push_back(Pair("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0));
passbucket.push_back(Pair("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0));
passbucket.push_back(Pair("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0));
passbucket.push_back(Pair("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0));
UniValue failbucket(UniValue::VOBJ);
failbucket.push_back(Pair("startrange", round(buckets.fail.start)));
failbucket.push_back(Pair("endrange", round(buckets.fail.end)));
failbucket.push_back(Pair("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0));
failbucket.push_back(Pair("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0));
failbucket.push_back(Pair("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0));
failbucket.push_back(Pair("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0));
// CFeeRate(0) is used to indicate error as a return value from estimateRawFee
if (feeRate != CFeeRate(0)) {
horizon_result.push_back(Pair("feerate", ValueFromAmount(feeRate.GetFeePerK())));
horizon_result.push_back(Pair("decay", buckets.decay));
horizon_result.push_back(Pair("scale", (int)buckets.scale));
horizon_result.push_back(Pair("pass", passbucket));
// buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
if (buckets.fail.start != -1) horizon_result.push_back(Pair("fail", failbucket));
} else {
// Output only information that is still meaningful in the event of error
horizon_result.push_back(Pair("decay", buckets.decay));
horizon_result.push_back(Pair("scale", (int)buckets.scale));
horizon_result.push_back(Pair("fail", failbucket));
errors.push_back("Insufficient data or no feerate found which meets threshold");
horizon_result.push_back(Pair("errors",errors));
}
result.push_back(Pair(StringForFeeEstimateHorizon(horizon), horizon_result));
}
return result;
//.........这里部分代码省略.........
示例12: result
IddObjectType SpaceInfiltrationEffectiveLeakageArea::iddObjectType() {
IddObjectType result(IddObjectType::OS_SpaceInfiltration_EffectiveLeakageArea);
return result;
}
示例13: eval
Spectrum eval(const BSDFQueryRecord &bRec, EMeasure measure) const {
Spectrum sigmaA = m_sigmaA->getValue(bRec.its),
sigmaS = m_sigmaS->getValue(bRec.its),
sigmaT = sigmaA + sigmaS,
tauD = sigmaT * m_thickness,
result(0.0f);
if (measure == EDiscrete) {
/* Figure out if the specular transmission is specifically requested */
bool hasSpecularTransmission = (bRec.typeMask & EDeltaTransmission)
&& (bRec.component == -1 || bRec.component == 2);
/* Return the attenuated light if requested */
if (hasSpecularTransmission &&
std::abs(1+dot(bRec.wi, bRec.wo)) < Epsilon)
result = (-tauD/std::abs(Frame::cosTheta(bRec.wi))).exp();
} else if (measure == ESolidAngle) {
/* Sample single scattering events */
bool hasGlossyReflection = (bRec.typeMask & EGlossyReflection)
&& (bRec.component == -1 || bRec.component == 0);
bool hasGlossyTransmission = (bRec.typeMask & EGlossyTransmission)
&& (bRec.component == -1 || bRec.component == 1);
Spectrum albedo;
for (int i = 0; i < SPECTRUM_SAMPLES; i++)
albedo[i] = sigmaT[i] > 0 ? (sigmaS[i]/sigmaT[i]) : (Float) 0;
const Float cosThetaI = Frame::cosTheta(bRec.wi),
cosThetaO = Frame::cosTheta(bRec.wo),
dp = cosThetaI*cosThetaO;
bool reflection = dp > 0, transmission = dp < 0;
/* ==================================================================== */
/* Reflection component */
/* ==================================================================== */
if (hasGlossyReflection && reflection) {
MediumSamplingRecord dummy;
PhaseFunctionQueryRecord pRec(dummy,bRec.wi,bRec.wo);
const Float phaseVal = m_phase->eval(pRec);
result = albedo * (phaseVal*cosThetaI/(cosThetaI+cosThetaO)) *
(Spectrum(1.0f)-((-1.0f/std::abs(cosThetaI)-1.0f/std::abs(cosThetaO)) * tauD).exp());
}
/* ==================================================================== */
/* Transmission component */
/* ==================================================================== */
if (hasGlossyTransmission && transmission
&& m_thickness < std::numeric_limits<Float>::infinity()) {
MediumSamplingRecord dummy;
PhaseFunctionQueryRecord pRec(dummy,bRec.wi,bRec.wo);
const Float phaseVal = m_phase->eval(pRec);
/* Hanrahan etal 93 Single Scattering transmission term */
if (std::abs(cosThetaI + cosThetaO) < Epsilon) {
/* avoid division by zero */
result += albedo * phaseVal*tauD/std::abs(cosThetaO) *
((-tauD/std::abs(cosThetaO)).exp());
} else {
/* Guaranteed to be positive even if |cosThetaO| > |cosThetaI| */
result += albedo * phaseVal*std::abs(cosThetaI)/(std::abs(cosThetaI)-std::abs(cosThetaO)) *
((-tauD/std::abs(cosThetaI)).exp() - (-tauD/std::abs(cosThetaO)).exp());
}
}
return result * std::abs(cosThetaO);
}
return result;
}
示例14: get_req_bin
Test::Result
PK_Encryption_Decryption_Test::run_one_test(const std::string& pad_hdr, const VarMap& vars)
{
const std::vector<uint8_t> plaintext = get_req_bin(vars, "Msg");
const std::vector<uint8_t> ciphertext = get_req_bin(vars, "Ciphertext");
const std::string padding = choose_padding(vars, pad_hdr);
Test::Result result(algo_name() + (padding.empty() ? padding : "/" + padding) + " decryption");
std::unique_ptr<Botan::Private_Key> privkey = load_private_key(vars);
// instead slice the private key to work around elgamal test inputs
//std::unique_ptr<Botan::Public_Key> pubkey(Botan::X509::load_key(Botan::X509::BER_encode(*privkey)));
Botan::Public_Key* pubkey = privkey.get();
std::vector<std::unique_ptr<Botan::PK_Decryptor>> decryptors;
for(auto const& dec_provider : possible_providers(algo_name()))
{
std::unique_ptr<Botan::PK_Decryptor> decryptor;
try
{
decryptor.reset(new Botan::PK_Decryptor_EME(*privkey, Test::rng(), padding, dec_provider));
}
catch(Botan::Lookup_Error&)
{
continue;
}
Botan::secure_vector<uint8_t> decrypted;
try
{
decrypted = decryptor->decrypt(ciphertext);
}
catch(Botan::Exception& e)
{
result.test_failure("Failed to decrypt KAT ciphertext", e.what());
}
result.test_eq(dec_provider, "decryption of KAT", decrypted, plaintext);
check_invalid_ciphertexts(result, *decryptor, plaintext, ciphertext);
}
for(auto const& enc_provider : possible_providers(algo_name()))
{
std::unique_ptr<Botan::PK_Encryptor> encryptor;
try
{
encryptor.reset(new Botan::PK_Encryptor_EME(*pubkey, Test::rng(), padding, enc_provider));
}
catch(Botan::Lookup_Error&)
{
continue;
}
std::unique_ptr<Botan::RandomNumberGenerator> kat_rng;
if(vars.count("Nonce"))
{
kat_rng.reset(test_rng(get_req_bin(vars, "Nonce")));
}
if(padding == "Raw")
{
/*
Hack for RSA with no padding since sometimes one more bit will fit in but maximum_input_size
rounds down to nearest byte
*/
result.test_lte("Input within accepted bounds",
plaintext.size(), encryptor->maximum_input_size() + 1);
}
else
{
result.test_lte("Input within accepted bounds",
plaintext.size(), encryptor->maximum_input_size());
}
const std::vector<uint8_t> generated_ciphertext =
encryptor->encrypt(plaintext, kat_rng ? *kat_rng : Test::rng());
if(enc_provider == "base")
{
result.test_eq(enc_provider, "generated ciphertext matches KAT",
generated_ciphertext, ciphertext);
}
else if(generated_ciphertext != ciphertext)
{
for(std::unique_ptr<Botan::PK_Decryptor>& dec : decryptors)
{
result.test_eq("decryption of generated ciphertext",
dec->decrypt(generated_ciphertext), plaintext);
}
}
}
return result;
}
示例15: algo_name
std::vector<Test::Result> PK_Key_Generation_Test::run()
{
std::vector<Test::Result> results;
for(auto const& param : keygen_params())
{
const std::string report_name = algo_name() + (param.empty() ? param : " " + param);
Test::Result result(report_name + " keygen");
const std::vector<std::string> providers = possible_providers(algo_name());
if(providers.empty())
{
result.note_missing("provider key generation " + algo_name());
}
result.start_timer();
for(auto&& prov : providers)
{
std::unique_ptr<Botan::Private_Key> key_p =
Botan::create_private_key(algo_name(), Test::rng(), param, prov);
const Botan::Private_Key& key = *key_p;
try
{
result.confirm("Key passes self tests", key.check_key(Test::rng(), true));
}
catch(Botan::Lookup_Error&) {}
result.test_gte("Key has reasonable estimated strength (lower)", key.estimated_strength(), 64);
result.test_lt("Key has reasonable estimated strength (upper)", key.estimated_strength(), 512);
// Test PEM public key round trips OK
try
{
Botan::DataSource_Memory data_src(Botan::X509::PEM_encode(key));
std::unique_ptr<Botan::Public_Key> loaded(Botan::X509::load_key(data_src));
result.confirm("recovered public key from private", loaded.get() != nullptr);
result.test_eq("public key has same type", loaded->algo_name(), key.algo_name());
try
{
result.test_eq("public key passes checks", loaded->check_key(Test::rng(), false), true);
}
catch(Botan::Lookup_Error&) {}
}
catch(std::exception& e)
{
result.test_failure("roundtrip PEM public key", e.what());
}
// Test DER public key round trips OK
try
{
Botan::DataSource_Memory data_src(Botan::X509::BER_encode(key));
std::unique_ptr<Botan::Public_Key> loaded(Botan::X509::load_key(data_src));
result.confirm("recovered public key from private", loaded.get() != nullptr);
result.test_eq("public key has same type", loaded->algo_name(), key.algo_name());
try
{
result.confirm("public key passes self tests", loaded->check_key(Test::rng(), true));
}
catch(Botan::Lookup_Error&) {}
}
catch(std::exception& e)
{
result.test_failure("roundtrip BER public key", e.what());
}
// Test PEM private key round trips OK
try
{
Botan::DataSource_Memory data_src(Botan::PKCS8::PEM_encode(key));
std::unique_ptr<Botan::Private_Key> loaded(
Botan::PKCS8::load_key(data_src, Test::rng()));
result.confirm("recovered private key from PEM blob", loaded.get() != nullptr);
result.test_eq("reloaded key has same type", loaded->algo_name(), key.algo_name());
try
{
result.confirm("private key passes self tests", loaded->check_key(Test::rng(), true));
}
catch(Botan::Lookup_Error&) {}
}
catch(std::exception& e)
{
result.test_failure("roundtrip PEM private key", e.what());
}
try
{
Botan::DataSource_Memory data_src(Botan::PKCS8::BER_encode(key));
std::unique_ptr<Botan::Public_Key> loaded(Botan::PKCS8::load_key(data_src, Test::rng()));
//.........这里部分代码省略.........