KiCad PCB EDA Suite
util.h File Reference
#include <cstdint>
#include <limits>
#include <typeinfo>
#include <wx/debug.h>
#include <wx/log.h>

Go to the source code of this file.

Functions

template<typename T >
const T & Clamp (const T &lower, const T &value, const T &upper)
 Function Clamp limits value within the range lower <= value <= upper. More...
 
template<typename fp_type , typename ret_type = int>
constexpr ret_type KiROUND (fp_type v)
 Round a floating point number to an integer using "round halfway cases away from zero". More...
 
template<typename T >
rescale (T aNumerator, T aValue, T aDenominator)
 Function rescale() More...
 
template<typename T >
int sign (T val)
 
template<>
int rescale (int aNumerator, int aValue, int aDenominator)
 
template<>
int64_t rescale (int64_t aNumerator, int64_t aValue, int64_t aDenominator)
 

Function Documentation

◆ Clamp()

template<typename T >
const T& Clamp ( const T &  lower,
const T &  value,
const T &  upper 
)
inline

Function Clamp limits value within the range lower <= value <= upper.

It will work on temporary expressions, since they are evaluated only once, and it should work on most if not all numeric types, string types, or any type for which "operator < ()" is present. The arguments are accepted in this order so you can remember the expression as a memory aid:

result is: lower <= value <= upper

Definition at line 45 of file util.h.

46 {
47  wxASSERT( lower <= upper );
48  if( value < lower )
49  return lower;
50  else if( upper < value )
51  return upper;
52  return value;
53 }

Referenced by LSET::AllCuMask(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), SCH_SEXPR_PARSER::parseFill(), SCH_SEXPR_PARSER::parseStroke(), BRDITEMS_PLOTTER::plotOneDrillMark(), PCB_PLOT_PARAMS::SetSvgPrecision(), and DIALOG_PAGES_SETTINGS::UpdatePageLayoutExample().

◆ KiROUND()

template<typename fp_type , typename ret_type = int>
constexpr ret_type KiROUND ( fp_type  v)

Round a floating point number to an integer using "round halfway cases away from zero".

In Debug build an assert fires if will not fit into the return type.

Definition at line 61 of file util.h.

62 {
63  using max_ret = long long int;
64  fp_type ret = v < 0 ? v - 0.5 : v + 0.5;
65 
66  if( std::numeric_limits<ret_type>::max() < ret ||
67  std::numeric_limits<ret_type>::lowest() > ret )
68  {
69  wxLogDebug
70  ( "Overflow KiROUND converting value %f to %s", double( v ), typeid(ret_type).name() );
71  return 0;
72  }
73 
74  return ret_type( max_ret( ret ) );
75 }
const char * name
Definition: DXF_plotter.cpp:60

References name.

Referenced by ZONE_FILLER::addHatchFillTypeOnZone(), ZONE_FILLER::addKnockout(), PCAD2KICAD::PCB_POLYGON::AddToBoard(), DIMENSION::AdjustDimensionDetails(), GRID_HELPER::Align(), GRID_HELPER::AlignToArc(), GRID_HELPER::AlignToSegment(), EC_45DEGREE::Apply(), PLOTTER::Arc(), HPGL_PLOTTER::Arc(), PDF_PLOTTER::Arc(), SCH_SHEET::AutoplaceFields(), LEGACY_PLUGIN::biuParse(), D_PAD::boundingRadius(), build_pad_testpoints(), BuildCornersList_S_Shape(), DIRECTION_45::BuildInitialTrace(), D_PAD::BuildPadPolygon(), ZONE_FILLER::buildThermalSpokes(), LIB_ARC::CalcEdit(), LIB_ARC::CalcMidPoint(), LIB_ARC::CalcRadiusAngles(), PCAD2KICAD::CalculateTextLengthSize(), KIGFX::WX_VIEW_CONTROLS::CenterOnCursor(), SHAPE_POLY_SET::chamferFilletPolygon(), DRC::checkClearancePadToPad(), DRC_DRILLED_HOLE_TESTER::checkHoles(), EE_INSPECTION_TOOL::checkPart(), Clamp_Text_PenSize(), ClipAndDrawPoly(), computeCenter(), ConfigureHPGLPenSizes(), AM_PRIMITIVE::ConvertShapeToPolygon(), ALTIUM_PARSER::ConvertToKicadUnit(), PCAD2KICAD::CorrectTextPosition(), MICROWAVE_TOOL::createFootprint(), MICROWAVE_TOOL::createMicrowaveInductor(), MICROWAVE_TOOL::createPolygonShape(), LIB_EDIT_TOOL::DeleteItemCursor(), PL_EDIT_TOOL::DeleteItemCursor(), SCH_EDIT_TOOL::DeleteItemCursor(), PCBNEW_CONTROL::DeleteItemCursor(), KIGFX::STROKE_FONT::Draw(), KIGFX::SCH_PAINTER::draw(), AM_PRIMITIVE::DrawBasicShape(), BITMAP_BASE::DrawBitmap(), KIGFX::OPENGL_GAL::DrawGrid(), KIGFX::CAIRO_GAL_BASE::DrawGrid(), DRAWING_TOOL::DrawVia(), GERBER_PLOTTER::emitDcode(), GERBER_FILE_IMAGE::ExecuteRS274XCommand(), EDIT_POINTS::FindPoint(), HPGL_PLOTTER::FlashPadCircle(), HPGL_PLOTTER::FlashPadOval(), HPGL_PLOTTER::FlashPadRect(), HPGL_PLOTTER::FlashPadRoundRect(), FootprintWriteShape(), BM2CMP_FRAME::FormatOutputSize(), formatStroke(), DSN::SPECCTRA_DB::FromSESSION(), gen_arc(), GENDRILL_WRITER_BASE::genDrillMapFile(), C3D_RENDER_OGL_LEGACY::generate_new_3DGrid(), geom_transf(), GERBER_DRAW_ITEM::GetABPosition(), GetArcCenter(), SHAPE_ARC::GetArcMid(), GetArcToSegmentCount(), LIB_PIN::GetBoundingBox(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), WS_DATA_ITEM::GetEndPosUi(), GRID_HELPER::GetGrid(), KIGFX::GAL::GetGridPoint(), EDA_TEXT::GetInterline(), BASE_SCREEN::getNearestGridPosition(), EE_SELECTION_TOOL::GetNode(), IMAGE_SIZE::GetOutputDPI(), SHAPE_ARC::GetP1(), GetPenSizeForBold(), GetPenSizeForNormal(), WS_DATA_ITEM::GetPenSizeUi(), WS_DATA_ITEM_POLYGONS::GetPenSizeUi(), WS_DATA_ITEM_TEXT::GetPenSizeUi(), LIB_CIRCLE::GetRadius(), DRAWSEGMENT::GetRadius(), BITMAP_BASE::GetSize(), D_PAD::GetSolderPasteMargin(), WS_DATA_ITEM::GetStartPosUi(), EDA_TEXT::GetTextBox(), SCH_TEXT::GetTextOffset(), GERBER_DRAW_ITEM::GetXYPosition(), GraphicTextWidth(), GRArc1(), SELECTION_TOOL::GuessSelectionCandidates(), ZONE_CONTAINER::Hatch(), ALTIUM_PCB::HelperCreateBoardOutline(), ALTIUM_PCB::HelperParseDimensions6Leader(), LIB_CIRCLE::HitTest(), LIB_ARC::HitTest(), DRAWSEGMENT::HitTest(), D_PAD::HitTest(), DIALOG_PLOT::init_Dialog(), initializePlotter(), GENERAL_COLLECTOR::Inspect(), TRACK::IsPointOnEnds(), iu_to_d356(), EDA_TEXT::LenSize(), EAGLE_PLUGIN::Load(), SCH_EAGLE_PLUGIN::loadLabel(), EAGLE_PLUGIN::loadPlain(), EAGLE_PLUGIN::loadPolygon(), EAGLE_PLUGIN::loadSignals(), DSN::SPECCTRA_DB::makeIMAGE(), DSN::SPECCTRA_DB::makePADSTACK(), TRANSFORM::MapAngles(), PLOTTER::markerSquare(), Mils2mm(), GERBVIEW_PRINTOUT::milsToIU(), PCBNEW_PRINTOUT::milsToIU(), Mm2mils(), DIALOG_POSITION_RELATIVE::OnOkClick(), BM2CMP_FRAME::OpenProjectFiles(), EAGLE_PLUGIN::orientModuleText(), EAGLE_PLUGIN::packagePad(), EAGLE_PLUGIN::packagePolygon(), EAGLE_PLUGIN::packageText(), PCAD2KICAD::PCB_ARC::Parse(), SCH_SEXPR_PARSER::parseArc(), ALTIUM_PCB::ParseArcs6Data(), PCB_PARSER::parseBoardUnits(), parseInt(), SCH_SEXPR_PARSER::parseInternalUnits(), GPCB_FPL_CACHE::parseMODULE(), DRC_RULES_PARSER::parseValue(), GERBER_PLOTTER::plotArc(), BRDITEMS_PLOTTER::PlotDrawSegment(), BRDITEMS_PLOTTER::PlotFootprintGraphicItem(), PS_PLOTTER::PlotImage(), PDF_PLOTTER::PlotImage(), poly2polyDRC(), poly2segmentDRC(), PSLIKE_PLOTTER::postscriptOverlinePositions(), GERBER_DRAW_ITEM::Print(), GERBER_FILE_IMAGE::ReadIJCoord(), PARAM_CFG_INT_WITH_SCALE::ReadParam(), EXCELLON_IMAGE::readToolInformation(), GERBER_FILE_IMAGE::ReadXYCoord(), PSLIKE_PLOTTER::returnPostscriptTextWidth(), RotatePoint(), rotationFromString(), SCH_SEXPR_PLUGIN::saveSheet(), DSN::scale(), scaletoIU(), PLOTTER::segmentAsOval(), SegmentIntersectsSegment(), PL_SELECTION_TOOL::SelectPoint(), EE_SELECTION_TOOL::SelectPoint(), WS_DATA_ITEM_TEXT::SetConstrainedTextSize(), PCAD2KICAD::SetTextSizeFromStrokeFontHeight(), PCAD2KICAD::SetTextSizeFromTrueTypeFontHeight(), snapAngle(), PS_PLOTTER::StartPlot(), PCAD2KICAD::StrToInt1Units(), PCAD2KICAD::StrToIntUnits(), WS_DATA_ITEM_TEXT::SyncDrawItems(), AR_MATRIX::traceArc(), AR_MATRIX::traceCircle(), AR_MATRIX::TraceFilledRectangle(), PANEL_SETUP_BOARD_STACKUP::transferDataFromUIToStackup(), PANEL_EESCHEMA_DISPLAY_OPTIONS::TransferDataFromWindow(), DIALOG_TEXT_PROPERTIES::TransferDataFromWindow(), DIALOG_EDIT_COMPONENT_IN_LIBRARY::TransferDataFromWindow(), DIALOG_MOVE_EXACT::TransferDataFromWindow(), DIALOG_FOOTPRINT_BOARD_EDITOR::TransferDataFromWindow(), DIALOG_PAD_PRIMITIVES_TRANSFORM::Transform(), TransformOvalToPolygon(), TransformSegmentToPolygon(), D_PAD::TransformShapeWithClearanceToPolygon(), DIALOG_PAGES_SETTINGS::UpdatePageLayoutExample(), KIGFX::ORIGIN_VIEWITEM::ViewDraw(), and EXCELLON_WRITER::writeCoordinates().

◆ rescale() [1/3]

◆ rescale() [2/3]

template<>
int rescale ( int  aNumerator,
int  aValue,
int  aDenominator 
)

Definition at line 32 of file util.cpp.

33 {
34  return (int) ( (int64_t) aNumerator * (int64_t) aValue / (int64_t) aDenominator );
35 }

◆ rescale() [3/3]

template<>
int64_t rescale ( int64_t  aNumerator,
int64_t  aValue,
int64_t  aDenominator 
)

Definition at line 39 of file util.cpp.

40 {
41 #ifdef __x86_64__
42  return ( (__int128_t) aNumerator * (__int128_t) aValue ) / aDenominator;
43 #else
44  int64_t r = 0;
45  int64_t sign = ( ( aNumerator < 0 ) ? -1 : 1 ) * ( aDenominator < 0 ? -1 : 1 ) *
46  ( aValue < 0 ? -1 : 1 );
47 
48  int64_t a = std::abs( aNumerator );
49  int64_t b = std::abs( aValue );
50  int64_t c = std::abs( aDenominator );
51 
52  r = c / 2;
53 
54  if( b <= INT_MAX && c <= INT_MAX )
55  {
56  if( a <= INT_MAX )
57  return sign * ( ( a * b + r ) / c );
58  else
59  return sign * ( a / c * b + ( a % c * b + r ) / c);
60  }
61  else
62  {
63  uint64_t a0 = a & 0xFFFFFFFF;
64  uint64_t a1 = a >> 32;
65  uint64_t b0 = b & 0xFFFFFFFF;
66  uint64_t b1 = b >> 32;
67  uint64_t t1 = a0 * b1 + a1 * b0;
68  uint64_t t1a = t1 << 32;
69  int i;
70 
71  a0 = a0 * b0 + t1a;
72  a1 = a1 * b1 + ( t1 >> 32 ) + ( a0 < t1a );
73  a0 += r;
74  a1 += a0 < (uint64_t)r;
75 
76  for( i = 63; i >= 0; i-- )
77  {
78  a1 += a1 + ( ( a0 >> i ) & 1 );
79  t1 += t1;
80 
81  if( (uint64_t) c <= a1 )
82  {
83  a1 -= c;
84  t1++;
85  }
86  }
87 
88  return t1 * sign;
89  }
90 #endif
91 }
int sign(T val)
Definition: util.h:90

References sign().

◆ sign()